//Extract proxy configuration from commandline private static string GetCommandLine(this System.Diagnostics.Process process) { try { string cmdLine = null; using (var searcher = new System.Management.ManagementObjectSearcher( string.Format("SELECT CommandLine FROM Win32_Process WHERE ProcessId = {0}", process.Id))) { var matchEnum = searcher.Get().GetEnumerator(); if (matchEnum.MoveNext()) { cmdLine = matchEnum.Current["CommandLine"]?.ToString(); } } if (cmdLine != null && cmdLine.Contains("proxy")) { System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(@"proxy-server=[^\s]*"); System.Text.RegularExpressions.Match match = pattern.Match(cmdLine); #if DEBUG Console.WriteLine("\tProxy from cmd: {0}", match.ToString().TrimStart('"').TrimEnd('"')); #endif return(match.ToString().Replace("proxy-server=", "").TrimStart('"').TrimEnd('"')); } } catch (Exception ex) { #if DEBUG Console.WriteLine("[*] An exception occured: {0}", ex.Message); #endif } return(""); }
void ResetFiles(string path) { DirectoryInfo di = new DirectoryInfo(path); FileInfo[] fis = di.GetFiles("*.csv"); tradefiles.Items.Clear(); int newest = 0; foreach (FileInfo fi in fis) { if (fi.Name.Contains(fid)) { tradefiles.Items.Add(fi.Name); System.Text.RegularExpressions.Match datepart = System.Text.RegularExpressions.Regex.Match(fi.Name, "[0-9]{8}", System.Text.RegularExpressions.RegexOptions.None); if (datepart.Success) { int thisdate = Convert.ToInt32(datepart.ToString()); if (thisdate > newest) { newest = thisdate; tradefiles.SelectedIndex = tradefiles.Items.Count - 1; } } else { tradefiles.SelectedIndex = tradefiles.Items.Count - 1; } } } tradefiles_SelectedIndexChanged(null, null); }
private void SearchForRE(string KeyNoteText) { int lastIndex = KeyNoteText.Length; System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(@"(RE:)"); System.Text.RegularExpressions.Match match = pattern.Match(KeyNoteText); string specSection = match.ToString(); int index = match.Index; if (specSection == "RE:") { this.SpecSection = KeyNoteText.Substring(index, lastIndex - index); char c = KeyNoteText[index - 1]; string dash = "-"; char compare = dash[0]; if (c == compare) { this.KeyNoteText = KeyNoteText.Substring(0, index - 1); } else { this.KeyNoteText = KeyNoteText.Substring(0, index - 0); } } else { this.KeyNoteText = KeyNoteText; } }
private bool SpecSectionSearch(string KeyNoteText) { System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex(@"(\d{6})"); System.Text.RegularExpressions.Match match = pattern.Match(KeyNoteText); string specSection = match.ToString(); int index = match.Index; if (specSection.Length == 6) { char c = KeyNoteText[index - 1]; string dash = "-"; char compare = dash[0]; if (c == compare) { this.KeyNoteText = KeyNoteText.Substring(0, index - 1); } else { this.KeyNoteText = KeyNoteText.Substring(0, index - 0); } this.SpecSection = specSection; return(true); } else { return(false); } }
static public string GetManufacturer(string manufacturer) { //http://bit.ly/1UkSs6R //System.Text.RegularExpressions.Regex slowRegex = new System.Text.RegularExpressions.Regex("([a - z] +) *="); //System.Text.RegularExpressions.Match m = slowRegex.Match("Gibson Fender Charvel Taylor Jackson MartinandCompany Dean Epiphone Takamine"); //http://bit.ly/25ZcsEH System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(manufacturer, "\"(([^\\\\\"]*)(\\\\.)?)*\""); return(m.ToString()); }
private bool IsTradingTime(string shareDataTime) { // Trading-time judgement /// Get Hour-Minute System.Text.RegularExpressions.Match timePartMatch = Helper.Regexer_Ex(@"\d{2}", shareDataTime); /// Convert to minutes int currentTime = int.Parse(timePartMatch.ToString()) * 60 + int.Parse(timePartMatch.NextMatch().ToString()); /// Reload Picture only in trading time (or in necessary cases) return((currentTime >= 9 * 60 && currentTime < 11 * 60 + 30) || (currentTime >= 13 * 60 && currentTime < 15 * 60)); }
protected void ValidateName(string aName) { if (String.IsNullOrEmpty(aName)) { throw new ArgumentNullException("Property name can not be null or empty"); } System.Text.RegularExpressions.Match lMatch = System.Text.RegularExpressions.Regex.Match(aName, "[a-zA-Z_]([a-zA-Z0-9_])*"); if (lMatch == null || !lMatch.Success || lMatch.ToString() != aName) { throw new ArgumentException(String.Format("'{0}' is an invalid property name.", aName)); } }
private void UpdatePriceSetting(bool write = false) { // throw new NotImplementedException(); if (write) { string output = ""; if (!Directory.Exists(stockUpDownPriceDirectoryPath)) { Directory.CreateDirectory(stockUpDownPriceDirectoryPath); } foreach (ListViewItem lvi in listView_StockList.Items) { output = ""; output += lvi.SubItems[subitemIndex_UpPrice] + Environment.NewLine; output += lvi.SubItems[subitemIndex_DownPrice] + Environment.NewLine; string code = lvi.Text; using (StreamWriter streamWriter = new StreamWriter(stockUpDownPriceDirectoryPath + @"\" + code)) { streamWriter.Write(output); } } return; } foreach (ListViewItem lvi in listView_StockList.Items) { string code = lvi.Text; string filePath = stockUpDownPriceDirectoryPath + @"\" + code; if (!File.Exists(filePath)) { continue; } using (StreamReader stremReader = new StreamReader(filePath)) { string[] config = stremReader.ReadToEnd().Split('\n'); if (config.Length < 2) { return; } System.Text.RegularExpressions.Match result = Helper.Regexer_Ex("(?<={).+(?=})", config[0]); string upPrice = result.Value.ToString(); result = Helper.Regexer_Ex("(?<={).+(?=})", config[1]); string downPrice = result.ToString(); lvi.SubItems[subitemIndex_UpPrice].Text = upPrice; lvi.SubItems[subitemIndex_DownPrice].Text = downPrice; } } }
public static string UploadImage(string image) { WebClient w = new WebClient(); w.Headers.Add("Authorization", "Client-ID " + ClientId); System.Collections.Specialized.NameValueCollection Keys = new System.Collections.Specialized.NameValueCollection(); try { Keys.Add("image", Convert.ToBase64String(File.ReadAllBytes(image))); byte[] responseArray = w.UploadValues("https://api.imgur.com/3/image", Keys); dynamic result = Encoding.ASCII.GetString(responseArray); System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("link\":\"(.*?)\""); System.Text.RegularExpressions.Match match = reg.Match(result); string url = match.ToString().Replace("link\":\"", "").Replace("\"", "").Replace("\\/", "/"); return(url); } catch { //MessageBox.Show("Something went wrong. " + s.Message); return("0"); } }
private async void postImgur(object sender, PhotoResult e) { string base64String = ""; string baseUrl = "https://api.imgur.com/3/upload.xml"; HttpClient browser = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, baseUrl); HttpResponseMessage result = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError); if (e.TaskResult == TaskResult.OK) { updateTitleBar(AppResources.UploadingText); System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage(); bmp.SetSource(e.ChosenPhoto); byte[] bytearray = null; using (var ms = new System.IO.MemoryStream()) { if (bmp != null) { var wbitmp = new WriteableBitmap((BitmapImage)bmp); wbitmp.SaveJpeg(ms, bmp.PixelWidth, bmp.PixelHeight, 0, 85); bytearray = ms.ToArray(); } } if (bytearray != null) { base64String = Convert.ToBase64String(bytearray); } else { Debug.WriteLine("bytearray was null"); } request.Content = new StringContent(base64String); request.Headers.Add("Authorization", "Client-ID " + AppResources.ImgurApiKey); //make request try { //make request Task <HttpResponseMessage> resultTask = browser.SendAsync(request); result = await resultTask; } catch { updateTitleBar(); return; } Debug.WriteLine("Response: {0}", result.Content.ReadAsStringAsync().Result); System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("<link>(.+?)</link>"); System.Text.RegularExpressions.Match match = reg.Match(result.Content.ReadAsStringAsync().Result); string url = match.ToString().Replace("<link>", "").Replace("</link>", ""); if (messageEntryBox.Text.Length > 0) { messageEntryBox.Text += url; } else { messageEntryBox.Text = url; } //nearly identical regexes :( fix reg = new System.Text.RegularExpressions.Regex("<id>(.+?)</id>"); match = reg.Match(result.Content.ReadAsStringAsync().Result); string id = match.ToString().Replace("<id>", "").Replace("</id>", ""); reg = new System.Text.RegularExpressions.Regex("<deletehash>(.+?)</deletehash>"); match = reg.Match(result.Content.ReadAsStringAsync().Result); string dh = match.ToString().Replace("<deletehash>", "").Replace("</deletehash>", ""); imageList.Add(new ImgurImage(id, url, dh)); appSettings["images"] = imageList; appSettings.Save(); updateTitleBar(); return; } }
static string MatchToUrl(System.Text.RegularExpressions.Match m) { var s = m.ToString(); return(String.Format("<a href='{0}'>{1}</a>", s, s.Replace("_", "__"))); }
public static string parseIssueTag(string s) { System.Text.RegularExpressions.Match part = GlobalShared.regx.Match(s); return(part.ToString()); }
static string[][] ConvertTo2DArray(String Query, String odatastr) { //wc.Headers.Add("Accept", "application/xml"); // EventLog.WriteEntry("Odataquery", "inside convert to 2d "); System.Text.RegularExpressions.Match Match = System.Text.RegularExpressions.Regex.Match(Query, @"\S*select\S*&", System.Text.RegularExpressions.RegexOptions.IgnoreCase); Query = Match.ToString().Replace("&", ""); String fields = Query.Split('=')[Query.Split('=').Length - 1]; string[] splittedfields = fields.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); int NoOfColoumns = splittedfields.Length; //EventLog.WriteEntry("Odataquery", ""+NoOfColoumns); //EventLog.WriteEntry("Odataquery", "before" + odatastr); JObject O = JObject.Parse(odatastr); //EventLog.WriteEntry("Odataquery", "" + odatastr); JArray JO = (JArray)O["value"]; //EventLog.WriteEntry("Odataquery", "after value:" + odatastr); //get the first field string FirstField = ""; if (splittedfields[0].Contains("/")) { FirstField = splittedfields[0].Split('/')[splittedfields[0].Split('/').Length - 1]; } else { FirstField = splittedfields[0]; } //EventLog.WriteEntry("Odataquery", "" + NoOfColoumns); int NoOfRows = JO.Count + 1; //OdataRows.Count + 1; String[][] OdataTable = new String[NoOfRows][]; int i = 0; OdataTable[0] = new string[NoOfColoumns]; foreach (string field in splittedfields) { if (field.Contains("/")) { OdataTable[0][i] = field.Split('/')[field.Split('/').Length - 1]; } else { OdataTable[0][i] = field; } // EventLog.WriteEntry("Odataquery", "" + OdataTable[0][i]); i++; } // EventLog.WriteEntry("Odataquery", "" + NoOfRows); for (int k = 1; k < NoOfRows; k++) { OdataTable[k] = new string[NoOfColoumns]; } int col = 0; //EventLog.WriteEntry("Odataquery","no of rows: "+ NoOfRows); foreach (string field in splittedfields) { string nameField; if (field.Contains("/")) { nameField = field.Replace("/", "."); //field.Split('/')[field.Split('/').Length-1]; } else { nameField = field; } //OdataRows = //OdataFeeds.GetElementsByTagName(("d:" + nameField)); // EventLog.WriteEntry("Odataquery", "before filling .."); for (int j = 1; j <= JO.Count; j++) { OdataTable[j][col] = (string)JO[j - 1].SelectToken(nameField); string s = (string)JO[j - 1].SelectToken(nameField); //EventLog.WriteEntry("Odataquery", s); } col++; } return(OdataTable); }
public static string StrUpper(System.Text.RegularExpressions.Match m) { return(m.ToString().ToUpper()); }
/// <summary> /// Recursive function that finds and /// graphs Wikipedia links /// </summary> /// <param name="g">The graph</param> /// <param name="lookupValue">Name of orgin article</param> /// <param name="hops">How many degrees of separation from the original article</param> private void addLinks(Kitware.VTK.vtkMutableDirectedGraph g, string lookupValue, int hops) { vtkStringArray label = (vtkStringArray)g.GetVertexData().GetAbstractArray("label"); long parent = label.LookupValue(lookupValue); //if lookupValue is not in the graph add it if (parent < 0) { rotateLogo(); parent = g.AddVertex(); label.InsertNextValue(lookupValue); arrListSmall.Add(lookupValue); } //Parse Wikipedia for the lookupValue string underscores = lookupValue.Replace(' ', '_'); System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://en.wikipedia.org/wiki/Special:Export/" + underscores); webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials; webRequest.Accept = "text/xml"; try { System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse(); System.IO.Stream responseStream = webResponse.GetResponseStream(); System.Xml.XmlReader reader = new System.Xml.XmlTextReader(responseStream); String NS = "http://www.mediawiki.org/xml/export-0.4/"; System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(reader); reader.Close(); webResponse.Close(); System.Xml.XPath.XPathNavigator myXPahtNavigator = doc.CreateNavigator(); System.Xml.XPath.XPathNodeIterator nodesText = myXPahtNavigator.SelectDescendants("text", NS, false); String fullText = ""; //Parse the wiki page for links while (nodesText.MoveNext()) { fullText += nodesText.Current.InnerXml + " "; } System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(fullText, "\\[\\[.*?\\]\\]"); int max; try { max = System.Convert.ToInt32(toolStripTextBox2.Text); } catch (Exception) { max = -1; } int count = 0; while (m.Success && ((count < max) || (max < 0))) { String s = m.ToString(); int index = s.IndexOf('|'); String substring = ""; if (index > 0) { substring = s.Substring(2, index - 2); } else { substring = s.Substring(2, s.Length - 4); } //if the new substring is not already there add it long v = label.LookupValue(substring); if (v < 0) { rotateLogo(); v = g.AddVertex(); label.InsertNextValue(substring); arrListSmall.Add(substring); if (hops > 1) { addLinks(g, substring, hops - 1); } } else if (arrListSmall.IndexOf(substring) < 0) { arrListSmall.Add(substring); if (hops > 1) { addLinks(g, substring, hops - 1); } } //Make sure nothing is linked to twice by expanding the graph vtkAdjacentVertexIterator avi = vtkAdjacentVertexIterator.New(); g.GetAdjacentVertices((int)parent, avi); m = m.NextMatch(); ++count; while (avi.HasNext()) { long id = avi.Next(); if (id == v) { return; } } rotateLogo(); g.AddGraphEdge((int)parent, (int)v); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }