private void BuildChangeSetDetails(string history) { using (var reader = new StringReader(history)) { // skip 2 lines reader.ReadLine(); reader.ReadLine(); var regex = new Regex(@"(\d+)\s+.+\s([\w\\]+).+\D(\d{1,2}/\d{1,2}/\d{4}).+"); string line; while ((line = reader.ReadLine()) != null) { var m = regex.Match(line); int changesetId = int.Parse(m.Groups[1].Value); ChangeSetDetails cs; var keyExists = this.csd.TryGetValue(changesetId, out cs); if (!keyExists) { string username = m.Groups[2].Value; string timestamp = m.Groups[3].Value; cs = new ChangeSetDetails(changesetId, timestamp, username); this.csd[changesetId] = cs; } } } }
public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append(Message); int i = 1; foreach (IValidationResult result in ValidationResults) { if (!BoolUtil.IsTrue(result.Passed)) { if (result.Details != null) { foreach (IValidationResultInfo info in result.Details) { sb.Append(Environment.NewLine + i + ": "); StringReader sr = new StringReader(info.ToString()); string s = sr.ReadLine(); bool isFirstLine = true; while (!string.IsNullOrEmpty(s)) { if (!isFirstLine) sb.Append(Environment.NewLine); sb.Append("\t" + s); isFirstLine = false; s = sr.ReadLine(); } sr.Close(); i++; } } } } return sb.ToString(); }
private void GenerateCS() { using (Microsoft.CSharp.CSharpCodeProvider provider = new Microsoft.CSharp.CSharpCodeProvider()) { CodeGeneratorOptions opts = new CodeGeneratorOptions(); StringWriter sw = new StringWriter(); provider.GenerateCodeFromMember(_method, sw, opts); StringReader sr = new StringReader(sw.GetStringBuilder().ToString()); string line = sr.ReadLine(); while (string.IsNullOrEmpty(line)) line = sr.ReadLine(); int idx = line.IndexOf(" " + _method.Name + "("); idx = line.LastIndexOf(' ', idx - 1); if (_method.Statements.Count > 0) { Text = "partial" + line.Remove(0, idx); Text = sw.GetStringBuilder().Replace(line, Text).ToString(); } else { line = "partial" + line.Remove(0, idx); idx = line.LastIndexOf(')'); Text = line.Remove(idx + 1) + ";" + Environment.NewLine; } } }
/// <summary> /// Run given SWAT executable and return the running time /// </summary> /// <param name="swatexe">The path of the executable</param> /// <param name="num">Number of times the executable will be run</param> /// <param name="iprint">The iprint that will be set to file.cio</param> /// <returns></returns> static double RunSWAT(string swatexe, int num, int iprint) { Console.WriteLine(string.Format("Runing {0} with iprint = {1}",swatexe,iprint)); //change the iprint first //find file.cio System.IO.FileInfo info = new FileInfo(swatexe); string cioFile = info.DirectoryName + @"\file.cio"; if (!System.IO.File.Exists(cioFile)) throw new Exception("Couldn't find " + cioFile); //modify file.cio with given output interval, which is located in line 59 string cio = null; using (System.IO.StreamReader reader = new StreamReader(cioFile)) { cio = reader.ReadToEnd(); } using (System.IO.StreamWriter writer = new StreamWriter(cioFile)) { using (System.IO.StringReader reader = new StringReader(cio)) { string oneline = reader.ReadLine(); while (oneline != null) { if (oneline.Contains("IPRINT")) oneline = string.Format("{0} | IPRINT: print code (month, day, year)", iprint); writer.WriteLine(oneline); oneline = reader.ReadLine(); } } } //start to run return RunSWAT(swatexe, num); }
/// <summary> /// Constructor /// </summary> /// <param name="HeaderText">Text for the header</param> public MIMEHeader(string HeaderText) { Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(HeaderText), "HeaderText"); this.Fields = new List<Field>(); StringReader Reader=new StringReader(HeaderText); try { string LineRead=Reader.ReadLine(); string Field=LineRead+"\r\n"; while(!string.IsNullOrEmpty(LineRead)) { LineRead=Reader.ReadLine(); if (!string.IsNullOrEmpty(LineRead) && (LineRead[0].Equals(' ') || LineRead[0].Equals('\t'))) { Field += LineRead + "\r\n"; } else { Fields.Add(new Field(Field)); Field = LineRead + "\r\n"; } } } finally { Reader.Close(); Reader=null; } }
private void TaskAssignmentsInit(string input) { StringReader sr = new StringReader(input); n = Convert.ToInt32(sr.ReadLine()); m = 0; string[] aInputs = sr.ReadLine().Split(new char[]{' '}); a = new int[n]; for (int i = 0; i < n; i++) { a[i] = Convert.ToInt32(aInputs[i]); if (a[i] > m) m = a[i]; } string[] bInputs = sr.ReadLine().Split(new char[] { ' ' }); b = new int[n]; for (int i = 0; i < n; i++) { b[i] = Convert.ToInt32(bInputs[i]); if (b[i] > m) m = b[i]; } mn = m * n; p = new bool[mn+1, mn+1, n+1]; }
public static IEnumerable<string> GetXmlDocLines(StringReader r) { // Find the first non-empty line: string firstLine; do { firstLine = r.ReadLine(); if (firstLine == null) yield break; } while (string.IsNullOrWhiteSpace(firstLine)); string indentation = firstLine.Substring(0, firstLine.Length - firstLine.TrimStart().Length); string line = firstLine; int skippedWhitespaceLines = 0; // Copy all lines from input to output, except for empty lines at the end. while (line != null) { if (string.IsNullOrWhiteSpace(line)) { skippedWhitespaceLines++; } else { while (skippedWhitespaceLines > 0) { yield return string.Empty; skippedWhitespaceLines--; } if (line.StartsWith(indentation, StringComparison.Ordinal)) line = line.Substring(indentation.Length); yield return " " + line; } line = r.ReadLine(); } }
/// <summary> /// Filters a raw stack trace and returns the result. /// </summary> /// <param name="rawTrace">The original stack trace</param> /// <returns>A filtered stack trace</returns> public static string Filter(string rawTrace) { if (rawTrace == null) return null; StringReader sr = new StringReader(rawTrace); StringWriter sw = new StringWriter(); try { string line; // Skip past any Assert or Assume lines while ((line = sr.ReadLine()) != null && assertOrAssumeRegex.IsMatch(line)) /*Skip*/ ; // Copy lines down to the line that invoked the failing method. // This is actually only needed for the compact framework, but // we do it on all platforms for simplicity. Desktop platforms // won't have any System.Reflection lines. while (line != null && line.IndexOf(" System.Reflection.") < 0) { sw.WriteLine(line.Trim()); line = sr.ReadLine(); } } catch (Exception) { return rawTrace; } return sw.ToString(); }
public void HandleException(Exception ex) { StringReader rdr = new StringReader(ex.Message); string report = rdr.ReadLine(); Assert.NotNull(report); string expected = rdr.ReadLine(); if (expected != null && expected.Length > 11) expected = expected.Substring(11); string actual = rdr.ReadLine(); if (actual != null && actual.Length > 11) actual = actual.Substring(11); string line = rdr.ReadLine(); Assert.That(line, Is.Not.Null, "No caret line displayed"); int caret = line.Substring(11).IndexOf('^'); int minLength = Math.Min(expected.Length, actual.Length); int minMatch = Math.Min(caret, minLength); if (caret != minLength) { if (caret > minLength || expected.Substring(0, minMatch) != actual.Substring(0, minMatch) || expected[caret] == actual[caret]) Assert.Fail("Message Error: Caret does not point at first mismatch..." + Env.NewLine + ex.Message); } if (expected.Length > 68 || actual.Length > 68 || caret > 68) Assert.Fail("Message Error: Strings are not truncated..." + Env.NewLine + ex.Message); }
public bool Insert(Range range, string text, bool addNewline) { if (text.Length == 0) { return true; } string fileContents = File.ReadAllText(_filename); using (StringReader reader = new StringReader(fileContents)) using (TextWriter writer = new StreamWriter(File.Open(_filename, FileMode.Create))) { string lineText; if (SeekTo(reader, writer, range, out lineText)) { writer.WriteLine(lineText.Substring(0, range.LineRange.Start) + text + (addNewline ? Environment.NewLine : string.Empty) + lineText.Substring(range.LineRange.Start)); } lineText = reader.ReadLine(); while (lineText != null) { writer.WriteLine(lineText); lineText = reader.ReadLine(); } } return true; }
public bool Delete(Range range) { if (range.LineRange.Length == 0) { return true; } string fileContents = File.ReadAllText(_filename); using (StringReader reader = new StringReader(fileContents)) using (TextWriter writer = new StreamWriter(File.Open(_filename, FileMode.Create))) { string lineText; if (SeekTo(reader, writer, range, out lineText)) { writer.WriteLine(lineText.Substring(0, range.LineRange.Start) + lineText.Substring(range.LineRange.Start + range.LineRange.Length)); } lineText = reader.ReadLine(); while (lineText != null) { writer.WriteLine(lineText); lineText = reader.ReadLine(); } } return true; }
public static object FromScalars(Type t, StringReader r, ContinueAtDelegate c) { var n = Activator.CreateInstance(t); var f = t.GetFields(); var x = r.ReadLine(); while (x != null) { if (x.StartsWith(Indent)) { var i = x.IndexOf(Assignment); var FieldName = x.Substring(Indent.Length, i - Indent.Length); var FieldValue = x.Substring(i + Assignment.Length); t.SetFieldValue(FieldName, n, FieldValue); x = r.ReadLine(); } else { c(x); x = null; } } return n; }
public static Table Parse(IRestResponse response) { Table table = new Table(); StringReader reader = new StringReader(response.Content); string readLine = reader.ReadLine(); if (readLine != null) { string[] collection = readLine.Split(Separator); foreach (string column in collection) { table.Columns.Add(column.TrimStart('"').TrimEnd('"')); } } string line = reader.ReadLine(); while (!string.IsNullOrEmpty(line)) { Row row = new Row(line); table.Rows.Add(row); line = reader.ReadLine(); } return table; }
private List<double> significance_level; //Уровнь значимости //Загружает таблицу критических значений private CriticalPirsonCriterion() { try { using (var sr = new StringReader(Resources.PirsonCritical)) { int k = 1; //Степень свободы string line; //Текущая строка table = new List<Dictionary<double, double>>(); //Парсим первую строку с уровнями значимости line = sr.ReadLine(); significance_level = get_significance_levle(line); //Читаем оставшиеся строки и заполняем таблицу while ((line = sr.ReadLine()) != null) table.Add(get_line_values(line, significance_level)); } } catch(FormatException exp) { throw new Exception("ОШИБКА ФАЙЛА КРИТИЧЕСКИХ ТОЧЕК: значение в файле не является числом"); } catch(IOException exp) { throw new Exception("ОШИБКА ФАЙЛА КРИТИЧЕСКИХ ТОЧЕК: не удается открыть файл"); } catch(Exception exp) { throw exp; } }
public void Write(string format, params object[] args) { string start =format; if(args.Any()) start = String.Format(start, args); using (var reader = new StringReader(start)) { string line = reader.ReadLine(); bool first = true; while (line != null) { if (!first) { _builder.AppendLine(); } else { first = false; } WriteIndent(); _builder.Append(line); line = reader.ReadLine(); } } }
async Task FetchData () { historyCache = new Dictionary<int, IEnumerable<KeyValuePair<DateTime, int>>> (); for (int i = 0; i < 3; i++) { try { var data = await client.GetStringAsync (HistoryApiEndpoint); // If another update was done in the meantime, no need to process it if (!NeedFetching) return; var reader = new StringReader (data); string line = reader.ReadLine (); var times = line.Split ('|').Select (t => DateTime.FromBinary (long.Parse (t))).ToArray (); while ((line = reader.ReadLine ()) != null) { var split = line.Split ('|'); var id = int.Parse (split[0]); var datapoints = split.Skip (1).Select ((v, index) => { var time = times[index]; var num = int.Parse (v); return new KeyValuePair<DateTime, int> (time, num); }).ToArray (); historyCache[id] = datapoints; } lastFetch = DateTime.UtcNow; } catch (Exception e) { e.Data ["method"] = "FetchData"; Xamarin.Insights.Report (e); Android.Util.Log.Error ("HistoryDownloader", e.ToString ()); } } }
/// <summary> /// 转化为markdown格式。 /// </summary> /// <param name="schema"></param> /// <returns></returns> public static string AsMarkdown(JsonSchema schema) { var sb = new StringBuilder(); // 生成表格 sb.AppendLine(AsMarkdown(schema, 1).Trim()); // 生成例子 sb.AppendLine(); sb.AppendLine("例子"); sb.AppendLine(); JToken demoToken = JsonDemoGenerator.Generate(schema); string demo = JsonConvert.SerializeObject(demoToken, Formatting.Indented); // 每一行前+4个空格,以适应markdown的code格式。 var sr = new StringReader(demo); string line = sr.ReadLine(); while (!string.IsNullOrEmpty(line)) { sb.AppendLine(" " + line); line = sr.ReadLine(); } return sb.ToString(); }
public override void Decode(string Input, out byte[] Output) { if (string.IsNullOrEmpty(Input)) { throw new ArgumentNullException("Input can not be null"); } string CurrentLine=""; MemoryStream MemoryStream=new MemoryStream(); StringReader Reader=new StringReader(Input); try { CurrentLine=Reader.ReadLine(); while (!string.IsNullOrEmpty(CurrentLine)) { DecodeOneLine(MemoryStream, CurrentLine); CurrentLine=Reader.ReadLine(); } Output = MemoryStream.ToArray(); } finally { MemoryStream.Close(); MemoryStream = null; Reader.Close(); Reader = null; } }
/// <summary> /// Filters a raw stack trace and returns the result. /// </summary> /// <param name="rawTrace">The original stack trace</param> /// <returns>A filtered stack trace</returns> public static string Filter(string rawTrace) { if (rawTrace == null) return null; StringReader sr = new StringReader(rawTrace); StringWriter sw = new StringWriter(); try { string line; // TODO: Handle Assume and any other verbs // Best way is probably to check first line and // see where the exception was thrown, then // discard all leading lines within the same class. while ((line = sr.ReadLine()) != null && line.IndexOf("at NUnit.Framework.Assert.") >= 0) /*Skip*/ ; while (line != null) { sw.WriteLine(line); line = sr.ReadLine(); } } catch (Exception) { return rawTrace; } return sw.ToString(); }
/// <summary> /// Constructor /// </summary> /// <param name="HeaderText">Text for the header</param> public MIMEHeader(string HeaderText) { if(string.IsNullOrEmpty(HeaderText)) throw new ArgumentNullException("Header text can not be null"); StringReader Reader=new StringReader(HeaderText); try { string LineRead=Reader.ReadLine(); string Field=LineRead+"\r\n"; while(!string.IsNullOrEmpty(LineRead)) { LineRead=Reader.ReadLine(); if (!string.IsNullOrEmpty(LineRead) && (LineRead[0].Equals(' ') || LineRead[0].Equals('\t'))) { Field += LineRead + "\r\n"; } else { Fields.Add(new Field(Field)); Field = LineRead + "\r\n"; } } } finally { Reader.Close(); Reader=null; } }
static void InsertXmlDocumentation(AstNode node, StringReader r) { // Find the first non-empty line: string firstLine; do { firstLine = r.ReadLine(); if (firstLine == null) return; } while (string.IsNullOrWhiteSpace(firstLine)); string indentation = firstLine.Substring(0, firstLine.Length - firstLine.TrimStart().Length); string line = firstLine; int skippedWhitespaceLines = 0; // Copy all lines from input to output, except for empty lines at the end. while (line != null) { if (string.IsNullOrWhiteSpace(line)) { skippedWhitespaceLines++; } else { while (skippedWhitespaceLines > 0) { node.Parent.InsertChildBefore(node, new Comment(string.Empty, CommentType.Documentation), Roles.Comment); skippedWhitespaceLines--; } if (line.StartsWith(indentation, StringComparison.Ordinal)) line = line.Substring(indentation.Length); node.Parent.InsertChildBefore(node, new Comment(" " + line, CommentType.Documentation), Roles.Comment); } line = r.ReadLine(); } }
static List<AssetData> Load() { var assetlist = new List<AssetData>(); var files = Directory.GetFiles("Assets", "ImportPackages*.imp", SearchOption.AllDirectories); foreach( var file in files ){ var text = File.ReadAllText(file); var textReader = new System.IO.StringReader(text); var url = textReader.ReadLine(); var assetData = new AssetData(); assetData.asseturl = url; assetlist.Add(assetData); while( textReader.Peek() > -1 ){ var strs = textReader.ReadLine().Split(','); var guid = strs[1]; var requestFilePath = strs[0]; var filePath = AssetDatabase.GUIDToAssetPath( guid ); if( string.IsNullOrEmpty( filePath ) || File.Exists(filePath) == false ){ assetData.pathList.Add(requestFilePath); } } } return assetlist; }
private void Button_Click(object sender, RoutedEventArgs e) { Button bu=sender as Button; if (bu.Tag.ToString() == "Parse") { string str = textSource.Text; StringBuilder sb = new StringBuilder(); using (StringReader reader = new StringReader(str)) { string line; if (chbCsharpType.IsChecked.Value) { while ((line = reader.ReadLine()) != null) { line = Regex.Replace(line, @"""", "\"\""); line = Regex.Replace(line, @"^\s+(?=[<|\W])", ""); line = Regex.Replace(line, @"\s+$", ""); line = "sb.Append(@\"" + line + "\");"; sb.AppendLine(line); } } if (chbSqlType.IsChecked.Value) { while ((line = reader.ReadLine()) != null) { line = Regex.Replace(line,@"^\s+",""); line = Regex.Replace(line,@"\s+$",""); line = "+N' " + line + " '"; sb.AppendLine(line); } } } textTarget.Text = sb.ToString(); } }
static List <AssetData> Load() { var assetlist = new List <AssetData>(); var files = Directory.GetFiles(".", "ImportPackages*.imp", SearchOption.AllDirectories); foreach (var file in files) { var text = File.ReadAllText(file); var textReader = new System.IO.StringReader(text); var url = textReader.ReadLine(); var assetData = new AssetData(); assetData.asseturl = url; assetlist.Add(assetData); while (textReader.Peek() > -1) { var strs = textReader.ReadLine().Split(','); var guid = strs[1]; var requestFilePath = strs[0]; var filePath = AssetDatabase.GUIDToAssetPath(guid); if (string.IsNullOrEmpty(filePath) || File.Exists(filePath) == false) { assetData.pathList.Add(requestFilePath); } } } return(assetlist); }
public static DatatxtDesc ParseDatatxt(string st) { DatatxtDesc result = new DatatxtDesc(); StringReader sr = new StringReader(st); string line; while ((line = sr.ReadLine()) != null) { if (line.Trim().Length == 0) continue; if (line.Trim() == "<object>") while ((line = sr.ReadLine()) != null) { if (line.Trim() == "<object_end>") break; ObjectInfo of = new ObjectInfo(GetTagAndIntValue(line, "id:"), GetTagAndIntValue(line, "type:"), GetTagAndStrValue(line, "file:")); result.lObject.Add(of); } if (line.Trim() == "<background>") while ((line = sr.ReadLine()) != null) { if (line.Trim() == "<background_end>") break; BackgroundInfo bf = new BackgroundInfo(GetTagAndIntValue(line, "id:"), GetTagAndStrValue(line, "file:")); result.lBackground.Add(bf); } } sr.Close(); return result; }
public static Path3D LoadPath(string file) { StringReader reader = new StringReader(file); Path3D pointList = new Path3D(); using (reader) { string line = reader.ReadLine(); while (line != null) { decimal[] pointCoords = line.Split(',').Select(decimal.Parse).ToArray(); decimal x = pointCoords[0]; decimal y = pointCoords[1]; decimal z = pointCoords[2]; Point3D point = new Point3D(x, y, z); pointList.AddPoint(point); line = reader.ReadLine(); } return pointList; } }
protected IEnumerable<List<string>> EnumerateRecords(string data, params string[] fieldNames) { using (var reader = new StringReader(data)) { var readLine = reader.ReadLine(); if (readLine != null) { var header = readLine; while (string.IsNullOrWhiteSpace(header)) { header = reader.ReadLine(); } header = header.ToLower(); var fields = new List<string>(header.Split(',')); var relevantFields = fieldNames.Select(name => fields.IndexOf(name.ToLower())).ToList(); string line = reader.ReadLine(); while (line != null) { if (!string.IsNullOrWhiteSpace(line)) { var row = ParseRow(line).ToList(); if (row.Count == fields.Count) { yield return new List<string>(relevantFields.Select(index => row[index])); } } line = reader.ReadLine(); } } } }
public static string Filter(string rawTrace) { if (rawTrace == null) return null; StringReader sr = new StringReader(rawTrace); StringWriter sw = new StringWriter(); try { string line; while ((line = sr.ReadLine()) != null && line.IndexOf("NUnit.Framework.Assert") >= 0) /*Skip*/ ; while (line != null) { sw.WriteLine(line); line = sr.ReadLine(); } } catch (Exception) { return rawTrace; } return sw.ToString(); }
/// <summary> /// Initializes a new instance of the <see cref="HttpRequest"/> class. /// </summary> /// <param name="stringRequest"> /// The string request. /// </param> /// <exception cref="ParserException"> /// </exception> public HttpRequest(string stringRequest) { var textReader = new StringReader(stringRequest); var commands = textReader.ReadLine().Split(' '); if (commands.Length != 3) { throw new ParserException( "Invalid format for the first request line. Expected format: [Method] [Uri] HTTP/[Version]"); } this.Method = commands[0]; this.Uri = commands[1]; this.ProtocolVersion = Version.Parse(commands[2].ToLower().Replace("HTTP/".ToLower(), string.Empty)); this.Headers = new SortedDictionary<string, ICollection<string>>(); string line; while ((line = textReader.ReadLine()) != null) { this.AddHeader(line); } this.Action = new ActionDescriptor(this.Uri); }
// ---------- PROPERTIES ---------- // ---------- CONSTRUCTORS ---------- /// <summary> /// Connects the client to SharePoint using the configuration in the specified configuration item. /// </summary> /// <param name="configurationItemDirectoryPath">The physical path to the directory where configuration item files can be found.</param> /// <param name="configurationItemName">The name of the configuration item containing the SharePoint client configuration.</param> public SharePointClient(string configurationItemDirectoryPath, string configurationItemName) { if (!string.IsNullOrWhiteSpace(configurationItemDirectoryPath) && !string.IsNullOrWhiteSpace(configurationItemName)) { // Get the configuration item with the connection data from a file. ConfigurationItem configItem = new ConfigurationItem(configurationItemDirectoryPath, configurationItemName, true); // Read the credentials from the configuration item. if (!string.IsNullOrWhiteSpace(configItem.Value)) { StringReader reader = new StringReader(configItem.Value); userName = reader.ReadLine(); password = reader.ReadLine(); domain = reader.ReadLine(); contextUrl = reader.ReadLine(); } // Initialize the client context. clientContext = new ClientContext(contextUrl) { // Add the credentials to the SharePoint context. Credentials = new NetworkCredential(userName, password, domain) }; } else { throw new ArgumentException("Unable to establish connection to SharePoint."); } }
public PatchInfo(string name, string info) { if (name.Contains("_to_")) { var split = name.Split(new string[] { "_to_" }, StringSplitOptions.None); StartVersion = int.Parse(split[0]); EndVersion = int.Parse(split[1]); } else { StartVersion = 0; EndVersion = int.Parse(new string(name.TakeWhile(c => c != '_').ToArray())); } Files = new List <PatchFileInfo>(); using (var r = new System.IO.StringReader(info)) { r.ReadLine(); // Count while (r.Peek() != -1) { var line = r.ReadLine(); if (string.IsNullOrWhiteSpace(line)) { continue; } var parts = line.Split(new string[] { ", " }, StringSplitOptions.None); Files.Add(new PatchFileInfo(parts[0], int.Parse(parts[1]), parts[2])); } } }
public static string Run(string input) { var sr = new StringReader(input); var gridMaxString = sr.ReadLine(); Parser parser = new Parser(); var gridMax = parser.MaxPosition(gridMaxString); var output = new StringBuilder(); for (; ; ) { var startAsString = sr.ReadLine(); var movementsAsString = sr.ReadLine(); if (string.IsNullOrEmpty(startAsString) || string.IsNullOrEmpty(movementsAsString)) { break; } var start = parser.Start(startAsString); var movements = parser.Movements(movementsAsString); var rover = new Rover(start.Position, start.Direction); rover = movements(rover); output.AppendFormat("{0}{1}", rover, Environment.NewLine); } return output.ToString(); }
/// <summary> /// Method that takes a full message and extract the headers from it. /// </summary> /// <param name="messageContent">The message to extract headers from. Does not need the body part. Needs the empty headers end line.</param> /// <returns>A collection of Name and Value pairs of headers</returns> /// <exception cref="ArgumentNullException">If <paramref name="messageContent"/> is <see langword="null"/></exception> private static NameValueCollection ExtractHeaders(string messageContent) { if (messageContent == null) { throw new ArgumentNullException("messageContent"); } NameValueCollection headers = new NameValueCollection(); using (System.IO.StringReader messageReader = new System.IO.StringReader(messageContent)) { // Read until all headers have ended. // The headers ends when an empty line is encountered // An empty message might actually not have an empty line, in which // case the headers end with null value. string line; while (!string.IsNullOrEmpty(line = messageReader.ReadLine())) { // Split into name and value string[] splittedValue = StringHelper.GetHeadersValue(line); // First index is header name string headerName = splittedValue[0]; // Second index is the header value. // Use a StringBuilder since the header value may be continued on the next line StringBuilder headerValue = new StringBuilder(splittedValue[1]); // Keep reading until we would hit next header // This if for handling multi line headers while (IsMoreLinesInHeaderValue(messageReader)) { // Unfolding is accomplished by simply removing any CRLF // that is immediately followed by WSP // This was done using ReadLine string moreHeaderValue = messageReader.ReadLine(); // If this exception is ever raised, there is an serious algorithm failure // IsMoreLinesInHeaderValue does not return true if the next line does not exist // This check is only included to stop the nagging "possibly null" code analysis hint if (moreHeaderValue == null) { throw new ArgumentException("This will never happen"); } // If a header is continued the first whitespace character is not needed. // It is only there to tell that the header was continued headerValue.Append(moreHeaderValue, 1, moreHeaderValue.Length - 1); } // Now we have the name and full value. Add it headers.Add(headerName, headerValue.ToString()); } } return(headers); }
/// <summary> /// 创蓝通道发送短信 /// </summary> /// <param name="mobileno">目标手机号</param> /// <param name="msg">短信息内容</param> /// <param name="extno">扩展号码,纯数字(1-3位)</param> /// <returns></returns> public FuncResult SendSmsByChuangLan(string mobileno, string smsContent, string extno) { var dic = GetErrorDictionary(); FuncResult result = new FuncResult(); string postStrTpl = "account={0}&pswd={1}&mobile={2}&msg={3}&needstatus=true&product=&extno={4}"; UTF8Encoding encoding = new UTF8Encoding(); byte[] postData = encoding.GetBytes(string.Format(postStrTpl, this._channel.Access_Name, this._channel.Access_Key, mobileno, smsContent, extno)); try { HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(this._channel.Service_Url); myRequest.Method = "POST"; myRequest.ContentType = "application/x-www-form-urlencoded"; myRequest.ContentLength = postData.Length; Stream newStream = myRequest.GetRequestStream(); // Send the data. newStream.Write(postData, 0, postData.Length); newStream.Flush(); newStream.Close(); HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse(); if (myResponse.StatusCode == HttpStatusCode.OK) { StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); string respText = reader.ReadToEnd(); Log.Info(respText); TextReader tr = new System.IO.StringReader(respText); var resText = tr.ReadLine(); var msgid = tr.ReadLine(); var array = resText.Split(','); var isSuccess = array[1] == "0"; this.SendNo = msgid; result.Success = isSuccess; result.Message = dic.ContainsKey(array[1]) ? dic[array[1]] : "发送失败"; result.StatusCode = isSuccess ? 1 : 400; return(result); } result.Success = false; result.Message = "网络链接失败"; result.StatusCode = 503; return(result); } catch (Exception ex) { result.Success = false; result.Message = "连接超时"; result.StatusCode = 500; return(result); } }
private string UpgradeSC1(string sourceCode) { sourceCode = MoveSemiColumnsToPrevLine(sourceCode.Trim()); List <string> sList = new List <string>(); using (System.IO.StringReader reader = new System.IO.StringReader(sourceCode)) { string line = null; while (null != (line = reader.ReadLine())) { if (line.Contains("public ParameterStack Parameters")) { while (!(line = reader.ReadLine()).Contains("new ParameterStack(")) { ; } sList.Add(@"public ParameterStack BuildParameterStack(ParameterStack stackIn)"); sList.Add(@"{"); sList.Add(@" ParameterStackUpdater paramUpdater = new ParameterStackUpdater(stackIn);"); // change AddDoubleParameter / AddIntParameter / AddBoolParameter / AddMultiParameter while (!(line = reader.ReadLine()).Contains("}")) { if (line.Contains("}")) /* do nothing */ } { else if (line.Contains("AddDoubleParameter(")) { string sEndLine = line.Substring(line.IndexOf("(") + 1); sList.Add(@" paramUpdater.CreateDoubleParameter(" + sEndLine); } else if (line.Contains("AddIntParameter")) { string sEndLine = line.Substring(line.IndexOf("(") + 1); sList.Add(@" paramUpdater.CreateIntParameter(" + sEndLine); } else if (line.Contains("AddBoolParameter")) { string sEndLine = line.Substring(line.IndexOf("(") + 1); sList.Add(@" paramUpdater.CreateBoolParameter(" + sEndLine); } else if (line.Contains("AddMultiParameter")) { string sEndLine = line.Substring(line.IndexOf("(") + 1); sList.Add(@" paramUpdater.CreateMultiParameter(" + sEndLine); } } sList.Add(" return paramUpdater.UpdatedStack;"); }
static string IdentText(int tabs, string s, char ident = '\t') { if (tabs == 0) { return(s); } if (s == null) { s = string.Empty; } var sb = new System.Text.StringBuilder(); var tr = new System.IO.StringReader(s); string prefix = string.Empty; for (int i = 0; i < tabs; i++) { prefix += ident; } string line; while ((line = tr.ReadLine()) != null) { if (sb.Length > 0) { sb.AppendLine(); } if (tabs > 0) { sb.Append(prefix); } sb.Append(line); } return(sb.ToString()); }
/// <summary> /// Initializes the mime map from the string. /// </summary> /// <param name="mimeTypes">List of mime types. Uses the format in Apache Mime.Types format. View at http://svn.apache.org/viewvc/httpd/httpd/trunk/docs/conf/mime.types?view=markup.</param> public static void Initialize(string mimeTypes) { using (var sr = new System.IO.StringReader(mimeTypes)) { string line; // all extensions and mime types should be lower case. while ((line = sr.ReadLine()) != null) { line = line.Trim(); if (line.StartsWith("#")) { continue; } var mimeType = Regex.Split(line, @"[ \t]+"); if (mimeType.Length < 2) { continue; // invalid } for (int i = 1; i < mimeType.Length; i++) { RegisterMimeType(mimeType[0], mimeType[i]); } } } }
private List <string> parseTitleList() { var list = new List <string>(); var lines = textBox_down_titles.Text; System.IO.StringReader sr = new System.IO.StringReader(lines); string tmp = null; do { tmp = sr.ReadLine(); if (tmp != null) { tmp = tmp.Trim(); tmp = tmp.Replace("-", ""); if (tmp.Length == 16) { list.Add(tmp); //ShowLog("Title id:" + tmp); } else if (tmp.Length == 0) { } else { ShowLog("Not valid title id:" + tmp); } } } while (tmp != null); return(list); }
static IEnumerable <char> GetUnicodeData() { System.Net.WebClient client = new System.Net.WebClient(); string definedCodePoints = File.ReadAllText("UnicodeData.txt"); //string definedCodePoints = client.DownloadString("http://unicode.org/Public/UNIDATA/UnicodeData.txt"); System.IO.StringReader reader = new System.IO.StringReader(definedCodePoints); System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); while (true) { string line = reader.ReadLine(); if (line == null) { break; } int codePoint = Convert.ToInt32(line.Substring(0, line.IndexOf(";")), 16); if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { //surrogate boundary; not valid codePoint, but listed in the document } else { string utf16 = char.ConvertFromUtf32(codePoint); byte[] utf8 = encoder.GetBytes(utf16); //TODO: something with the UTF-8-encoded character if (Char.TryParse(utf16, out char c)) { yield return(c); } } } }
//------------------------------------------------------------------------------------------- public static string P4GetDirectory(string workingDirectory, string p4Path) { string path = null; string args = "where " + p4Path; P4Result result = P4Command(workingDirectory, args); if (result.resultCode == 0) { if (result.stderr == "") { StringReader strReader = new System.IO.StringReader(result.stdout); string pathString = strReader.ReadLine(); string[] splitPaths = pathString.Split(' '); if (splitPaths.Length == 3) { path = splitPaths[2]; path = path.Trim(new char[] { ' ', '.' }); } } else { //TODO: add some error output here e.g. -- files not in client view } } return(path); }
public Dictionary <String, String> RetrieveFileRelations(string targetPath) { targetPath = Utility.CleanupPath(targetPath); Dictionary <String, String> fileRelations = new Dictionary <string, string>(); String locatedFileIndex = LocateFileIndex(); string[] sourceFiles = locatedFileIndex.Split(new string[] { "SRCSRV: source files ---------------------------------------" }, StringSplitOptions.None); if (sourceFiles.Length == 2) { System.IO.StringReader tester = new System.IO.StringReader(sourceFiles[1].Substring(0, sourceFiles[1].IndexOf("SRCSRV: end ------------------------------------------------")).Trim()); string pdbBodyToParse = null; while ((pdbBodyToParse = tester.ReadLine()) != null) { // Skip all empty lines. if (true == String.IsNullOrEmpty(pdbBodyToParse)) { continue; } String[] processed = BuildKeyValuePairFromString(targetPath, pdbBodyToParse); if (null == processed) { Debug.WriteLine(pdbBodyToParse); } else { fileRelations.Add(processed[0], processed[1]); } } } return(fileRelations); }
public void SetTag() { if (m_comment == null || m_comment == "") { m_line = ""; m_tag = ""; } else { System.IO.StringReader rs = new System.IO.StringReader(m_comment); m_line = rs.ReadLine(); int index = m_line.IndexOf(' '); if (index < 0) { m_tag = m_line; } else { m_tag = m_line.Substring(0, index); } } m_line0 = Util.GetWithoutUselessCharacter(m_line0); m_line1 = Util.GetWithoutUselessCharacter(m_line1); m_line2 = Util.GetWithoutUselessCharacter(m_line2); }
/// <summary> /// Returns all unicode characters /// </summary> /// <returns></returns> public static string GetUnicodeCharacters() { // file from http://unicode.org/Public/UNIDATA/UnicodeData.txt string definedCodePoints = File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UnicodeData.txt")); System.IO.StringReader reader = new System.IO.StringReader(definedCodePoints); System.Text.UTF8Encoding encoder = new System.Text.UTF8Encoding(); StringBuilder sb = new StringBuilder(); while (true) { string line = reader.ReadLine(); if (line == null) { break; } int codePoint = Convert.ToInt32(line.Substring(0, line.IndexOf(";")), 16); if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { //surrogate boundary; not valid codePoint, but listed in the document } else { string utf16 = char.ConvertFromUtf32(codePoint); sb.Append(utf16); byte[] utf8 = encoder.GetBytes(utf16); //TODO: something with the UTF-8-encoded character } } return(sb.ToString()); }
protected bool FindLine(out string output) { string value = (paras[1].isstring) ? paras[1].value : (vars.Exists(paras[1].value) ? vars[paras[1].value] : null); if (value != null) { using (System.IO.TextReader sr = new System.IO.StringReader(vars[paras[0].value])) { string line; while ((line = sr.ReadLine()) != null) { if (line.IndexOf(value, StringComparison.InvariantCultureIgnoreCase) != -1) { output = line; return(true); } } } output = ""; return(true); } else { output = "The variable " + paras[1].value + " does not exist"; } return(false); }
//◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆◆ /// <summary> /// テキストを1行区切でリスト化 /// </summary> /// <param name="str_data">対象文字列</param> /// <param name="str_separator">センサ区切り文字</param> /// <param name="i_data_num">1行内のセンサ数</param> /// <returns></returns> public List <string> mReadLine_String(string str_data, string str_separator, int i_data_num) { string strBuf; List <string> lst_strReturn = new List <string>(); //StreamReader sr = new StreamReader(str_data, Encoding.GetEncoding("SHIFT_JIS")); System.IO.StringReader rs = new System.IO.StringReader(str_data); //num = Character_Figure(str_data, New_Line); while (true) { strBuf = rs.ReadLine(); if (strBuf == null) { break; } else if (i_data_num != Character_Figure(strBuf, str_separator)) { continue; } else { lst_strReturn.Add(strBuf); } } rs.Close(); return(lst_strReturn); }
private void ImportQuestStepChoices_Click(object sender, RoutedEventArgs e) { ChoiceImportDialog inputDialog = new ChoiceImportDialog(); if (inputDialog.ShowDialog() == true) { using (System.IO.StringReader reader = new System.IO.StringReader(inputDialog.ChoicesText)) { string line = reader.ReadLine(); while (line != null) { GameDataViewObject.addNewQuestStepChoiceWithData(line); line = reader.ReadLine(); } } } }
/// <summary> /// Writes attachment to a stream /// </summary> /// <param name="stream">The stream to write the attachmment on</param> public void Write(System.IO.TextWriter stream) { string st = ""; // writes headers #if false foreach (System.Collections.DictionaryEntry s in m_headers) { string v = (string)s.Value; st = s.Key + ":" + v; if (!v.EndsWith("\r\n")) { st += endl; } stream.Write(st); } #else foreach (MimeField m in m_headers) { st = m.Name + ":" + m.Value; if (!st.EndsWith("\r\n")) { st += endl; } stream.Write(st); } #endif // \r\n to end header stream.Write(endl); // write body System.IO.StringReader r = new System.IO.StringReader(m_body.ToString()); string tmp; while ((tmp = r.ReadLine()) != null) { stream.Write(tmp + "\r\n"); } r.Close(); stream.Write(endl); // write attachments if (m_attachments.Count > 0) { stream.Write(m_boundary); stream.Write(endl); foreach (MimeAttachment m in m_attachments) { m.Write(stream); } stream.Write(m_boundary); stream.Write(endl); } }
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()); } }
public static string SERVICE_HASH_REQUEST(string hash_xml_doc_path) { string result; try { HttpWebRequest httpWebRequest = CreateSOAPWebRequest(); XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(hash_xml_doc_path); using (Stream requestStream = httpWebRequest.GetRequestStream()) { xmlDocument.Save(requestStream); } using (WebResponse response = httpWebRequest.GetResponse()) { using (StreamReader streamReader = new StreamReader(response.GetResponseStream())) { string xml = streamReader.ReadToEnd(); XmlDocument xmlDocument2 = new XmlDocument(); xmlDocument2.LoadXml(xml); XmlNamespaceManager xmlNamespaceManager = new XmlNamespaceManager(xmlDocument2.NameTable); xmlNamespaceManager.AddNamespace("m", "http://giccs.gcnet.com/wsdl"); XmlNodeList xmlNodeList = xmlDocument2.SelectNodes("//m:retrieveHashingDataResponse", xmlNamespaceManager); int count = xmlNodeList.Count; string s = null; foreach (XmlNode xmlNode in xmlNodeList) { s = xmlNode["m:return"].InnerText; } List <string> list = new List <string>(); using (System.IO.StringReader stringReader = new System.IO.StringReader(s)) { string item; while ((item = stringReader.ReadLine()) != null) { bool flag = list.Count != 4; if (!flag) { break; } list.Add(item); } } string text = list.Last(); string[] array = text.Split(new char[] { ':' }); result = array[1].Trim(); } } } catch (Exception ex) { result = ex.Message; } return(result); }
/// <summary> /// 解析信息为xaml /// 支持标签[b][/b]粗体 /// </summary> /// <param name="source"></param> /// <returns></returns> public static System.Collections.Generic.List <string> CreateXamlInfo(string source, string color = "Black", int lineHeight = 0, int width = 0, int fontsize = 12) { var lines = new System.Collections.Generic.List <string>(); if (!string.IsNullOrWhiteSpace(source)) { var boldReg = new System.Text.RegularExpressions.Regex(@"\[b\](?<bold>.*)\[\/b\]", System.Text.RegularExpressions.RegexOptions.IgnoreCase); var reader = new System.IO.StringReader(source); var strlineheight = (lineHeight > 0 ? "LineHeight=\"" + lineHeight + "\"" : ""); var strwidth = width > 0 ? "Width=\"" + width + "\"" : ""; for (var line = reader.ReadLine(); line != null; line = reader.ReadLine()) { var ms = boldReg.Matches(line); var temp = string.Empty; var index = 0; foreach (System.Text.RegularExpressions.Match m in ms) { //第一次处理此行 if (m.Index > index) { temp += "<TextBlock HorizontalAlignment=\"Stretch\" Foreground=\"" + color + "\" TextWrapping=\"Wrap\" " + strlineheight + " FontSize=\"" + fontsize + "\" Text=\"" + Text.HtmlHelper.Encode(line.Substring(index, m.Index - index)) + "\" />"; //temp += line.Substring(index, m.Index - index); } temp += "<TextBlock HorizontalAlignment=\"Stretch\" Foreground=\"" + color + "\" FontWeight=\"Bold\" TextWrapping=\"Wrap\" " + strlineheight + " FontSize=\"" + fontsize + "\" Text=\"" + Text.HtmlHelper.Encode(m.Groups["bold"].Value) + "\" />"; //temp+=string.Format("<b>{0}</b>",m.Groups["bold"].Value); index = m.Index + m.Value.Length; } //第一次处理此行 if (string.IsNullOrWhiteSpace(line) || index < line.Length - 1) { temp += "<TextBlock HorizontalAlignment=\"Stretch\" Foreground=\"" + color + "\" FontSize=\"" + fontsize + "\" TextWrapping=\"Wrap\" " + strlineheight + " Text=\"" + (string.IsNullOrWhiteSpace(line) ? " " : Text.HtmlHelper.Encode(line.Substring(index))) + "\" />"; } lines.Add(temp); } } return(lines); }
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()); } }
/// <summary> /// Convert a plain text to an XHTML valid text. /// </summary> public static string FromPlainText(string plainText, PlainTextMode mode) { if (mode == PlainTextMode.CssPlainText) { string htmlEncoded = System.Web.HttpUtility.HtmlEncode(plainText); System.Text.StringBuilder builder = new System.Text.StringBuilder(); builder.Append("<div class=\"plainText\">"); builder.Append(htmlEncoded); builder.Append("</div>"); return(builder.ToString()); } else if (mode == PlainTextMode.XHtmlConversion) { System.Text.StringBuilder builder = new System.Text.StringBuilder(); using (System.IO.StringReader reader = new System.IO.StringReader(plainText)) { string line; while ((line = reader.ReadLine()) != null) { if (line != null && line.Length > 0) { //Replace the space and tab characters at the begind of the line with a nont breaking space for (int col = 0; col < line.Length; col++) { if (line[col] == ' ') { builder.Append(" "); } else if (line[col] == '\t') { builder.Append(" "); } else { string subLine = System.Web.HttpUtility.HtmlEncode(line.Substring(col)); builder.Append(subLine); break; } } } builder.AppendLine("<br />"); } } return(builder.ToString()); } else { throw new BusiBlocksException("Mode not valid"); } }
public void readJson(string filePath) { if (File.Exists(filePath)) { string dataAsJson = File.ReadAllText(filePath); using (System.IO.StringReader reader = new System.IO.StringReader(dataAsJson)) { while (reader.Peek() != -1) { string songInfo = reader.ReadLine(); string chartDataPath1 = reader.ReadLine(); string chartDataPath2 = reader.ReadLine(); string chartDataPath3 = reader.ReadLine(); print(songInfo); print(chartDataPath1); print(chartDataPath2); print(chartDataPath3); Song newSong = JsonUtility.FromJson <Song>(songInfo); Chart newChart1 = JsonUtility.FromJson <Chart>(chartDataPath1); Chart newChart2 = JsonUtility.FromJson <Chart>(chartDataPath2); Chart newChart3 = JsonUtility.FromJson <Chart>(chartDataPath3); newSong.chartDataList.Add(newChart1); newSong.chartDataList.Add(newChart2); newSong.chartDataList.Add(newChart3); songList.Add(newSong); print(newSong.ToString()); print(newChart1.ToString()); print(newChart2.ToString()); print(newChart3.ToString()); } foreach (Song song in songList) { songPlateList.Add(createSongPlate(song)); } } } else { print("Cannot Find Json File"); } }
private void simpleButton2_Click(object sender, EventArgs e) { string text = richTextBox2.Text.Trim(); System.IO.StringReader sr = new System.IO.StringReader(text); bool hasIdInfo = false; int parentId = -1, startId = -1; string parentName = string.Empty, name = string.Empty, sId = string.Empty; List <int> modelIds = new List <int>(); int lineNO = 0; while (true) { string line = sr.ReadLine(); lineNO++; if (line == null) { break; } Console.WriteLine(string.Format("# Line {0}: {1}", lineNO, line)); line = line.Trim(); if (line.Length == 0) { Console.WriteLine("Skip"); continue; } line = line.Trim("/".ToCharArray()); int index = line.LastIndexOf(" "); if (index > -1) { name = line.Substring(0, index).Trim(); sId = line.Substring(index + 1); } else { index = line.LastIndexOf("\t"); if (index > -1) { name = line.Substring(0, index).Trim("\t".ToCharArray()); sId = line.Substring(index + 1); } } if (int.TryParse(sId, out startId)) { Framework.Container.Instance.TaskManager.AddVehicleBrand(name, startId, -1); Console.WriteLine(string.Format("Add brand: name {0}, id {1}", name, startId)); } else { Debug.Assert(false); } } }
/// <summary> /// Scrive informazioni su eccezione /// </summary> /// <param name="e"></param> /// <param name="includeStack"></param> public override void LogException(Exception e, bool includeStack) { if (!this._Active) { return; } //Scrive Exception oException = e; int iIndentEx = 0; int iInnerCount = 0; this.LogMessage(Constants.LOG_SEPARATOR); while (oException != null) { string sIndent = string.Empty.PadRight(iIndentEx); this.LogMessage(@"{0}ECCEZIONE! Livello {1}", sIndent, iInnerCount.ToString()); this.LogMessage(@"{0} + Tipo : {1}", sIndent, oException.GetType().Name); this.LogMessage(@"{0} + Messaggio: {1}", sIndent, oException.Message); //Dati variabili if (!string.IsNullOrEmpty(oException.Source)) { this.LogMessage(@"{0} + Source : {1}", sIndent, oException.Source); } if (oException.TargetSite != null) { this.LogMessage(@"{0} + Classe : {1}", sIndent, oException.TargetSite.DeclaringType.Name); this.LogMessage(@"{0} + Metodo : {1}", sIndent, oException.TargetSite.Name); this.LogMessage(@"{0} + Namespace: {1}", sIndent, oException.TargetSite.DeclaringType.Namespace); } if (oException.StackTrace != null) { this.LogMessage(@"{0} + Stack :", sIndent); using (System.IO.StringReader reader = new System.IO.StringReader(oException.StackTrace)) { string line; while ((line = reader.ReadLine()) != null) { this.LogMessage(@"{0} > {1}", sIndent, line); } } } //Successiva oException = oException.InnerException; iInnerCount++; iIndentEx += 4; } }
public Tuple <int, int, int> getSummary(string output) { try { System.IO.StringReader rs = new System.IO.StringReader(output); string buf = rs.ReadLine(); int count = int.Parse(buf); int move = 0; if (count > problemInfo.allow) { appendLog("選択回数オーバー"); return(null); } List <int> sx = new List <int>(), sy = new List <int>(); List <List <int> > moves = new List <List <int> >(); while (rs.Peek() > -1) { buf = rs.ReadLine(); // さわりはじめの場所 sx.Add(hexToDec(buf[0])); sy.Add(hexToDec(buf[1])); buf = rs.ReadLine(); // 何回続く?(要らない情報) move += int.Parse(buf); buf = rs.ReadLine(); // 実際の操作列 moves.Add(new List <int>()); for (int i = 0; i < buf.Length; i++) { const string table = "URDL"; int idx = table.IndexOf(buf[i]); moves[moves.Count - 1].Add(idx); } } int total = count * problemInfo.selectCost + move * problemInfo.swapCost; return(new Tuple <int, int, int>(count, move, total)); } catch { appendLog("ソルバの出力が異常です。"); return(null); } }
/// <summary> /// Reads the calendar data from the via settings manager specified iCal WebSite. /// </summary> public void FetchCalendarData() { try { if (Calendar != null) { Calendar = null; } // load data from webcal URl System.Net.WebClient client = new System.Net.WebClient(); // validate url if ((_ical_url.Length > 0) && (_ical_url.ToLower().StartsWith("http"))) { System.IO.Stream stream = client.OpenRead(_ical_url); // System.IO.FileStream stream = new System.IO.FileStream("C:\\Temp\\calendar.ics", System.IO.FileMode.Open, System.IO.FileAccess.Read); System.IO.StreamReader reader = new System.IO.StreamReader(stream); string iCalData = reader.ReadToEnd(); string iCalDataNoComments = ""; // remove comment -> not processed by ical library using (var iCalDataReader = new System.IO.StringReader(iCalData)) { for (string line = iCalDataReader.ReadLine(); line != null; line = iCalDataReader.ReadLine()) { if (line.Length == 0) { continue; } if (line[0] != '/') { iCalDataNoComments += line + System.Environment.NewLine; } } } // let parse data from ical calendar Calendar = Ical.Net.Calendar.Load(iCalDataNoComments); //foreach (ical.net.calendarcomponents.calendarevent cal in calendar.children) //{ // data.add("test"); //} } // process new data ConvertICalDataToDataModel(); // publish new data Notify(); } finally { } }
private static void GetNames(string file_path) { //only do this if not done before if (names == null) { TextAsset txt = (TextAsset)Resources.Load("cat_names", typeof(TextAsset)); string allNames = txt.ToString(); names = new List <string>(); using (System.IO.StringReader reader = new System.IO.StringReader(allNames)) { string name; name = reader.ReadLine(); while (name != null) { names.Add(name); name = reader.ReadLine(); } } } }
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()); } }
public async Task <List <FtpListRecord> > ListAsync(string path) { var clientFtp = _ClientFtpCreate(path); clientFtp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails; var ftpList1 = await clientFtp.GetResponseAsync() as System.Net.FtpWebResponse; var regexLineTyped = new System.Text.RegularExpressions.Regex(@"(?<date>.+((?i)am|pm))\s*?(<(?<type>\w+)>)\s*(?<name>.+)"); var regexLineFile = new System.Text.RegularExpressions.Regex(@"(?<date>.+((?i)am|pm))\s*(?<size>\d+)\s*(?<name>.+)"); var r = new List <FtpListRecord>(); using (var ftpList1Sr = new System.IO.StreamReader(ftpList1.GetResponseStream())) { var ftpList1Response = await ftpList1Sr.ReadToEndAsync(); using (var stringReader = new System.IO.StringReader(ftpList1Response)) { while (true) { var line = stringReader.ReadLine(); if (line == null) { break; } var match1 = regexLineTyped.Match(line); if (match1.Success) { r.Add(new FtpListRecord { Date = DateTime.Parse(match1.Groups["date"].Value.Trim()), Name = match1.Groups["name"].Value.Trim(), IsDir = match1.Groups["type"].Value.Trim().ToLower() == "dir", }); } else { var match2 = regexLineFile.Match(line); if (match2.Success) { r.Add(new FtpListRecord { Date = DateTime.Parse(match2.Groups["date"].Value.Trim()), Name = match2.Groups["name"].Value.Trim(), Size = long.Parse(match2.Groups["size"].Value.Trim()), IsDir = false, }); } } } } } return(r); }