//void IspisRacuna() //{ // if (PrinterSpreman()) // { // SetRacNaslov(); // SetRacStavke(); // SetRacEnd(); // PrintRac(); // SetEndParameters(); // _rowFromTable["P"] = "1"; // //MySql_class.Query("UPDATE Mal_rac SET P = TRUE where ID = '"+ // // _rowFromTable["ID"].ToString()+"' "); // //dataGridView1.SelectedRows[0].Cells[e.ColumnIndex].Value = true; // DialogResult = DialogResult.OK; // this.Close(); // } // else // { // CancelPrintJob(); // MessageBox.Show("Došlo je do greške pri printanju!"); // } // //MessageBox.Show(Naslov+Stavke+End); //} //void BtnPrintClick(object sender, EventArgs e) //{ // if (dataGridView1.Rows.Count > 0) // { // if (txtPrimljeniNovac.Text.Trim(',', '0').Length != 0 && // txtIznosPovrat.Text.Trim(',', '0').Length != 0) // { // IspisRacuna(); // } // else // { // MessageBox.Show("Niste unijeli iznos primljenog novca!"); // } // } // else // { // MessageBox.Show("Niste unijeli artikal!"); // } //} //void BtnPrintStatClick(object sender, EventArgs e) //{ // System.IntPtr lhPrinter = new System.IntPtr(); // PrintThroughDriver.OpenPrinter2("Generic", ref lhPrinter, 0); // PRINTERINFO2 PI = new PRINTERINFO2(); // int Need = 0; // PrintThroughDriver.GetPrinter(lhPrinter, 2, IntPtr.Zero, 0, ref Need); // IntPtr pintStruct = Marshal.AllocCoTaskMem(Need); // int SizeOf = Need; // PrintThroughDriver.GetPrinter(lhPrinter, 2, pintStruct, SizeOf, ref Need); // PI = (PRINTERINFO2)Marshal.PtrToStructure(pintStruct, typeof(PRINTERINFO2)); // MessageBox.Show(PI.Status.ToString()); // // Deallocate the memory. // Marshal.FreeCoTaskMem(pintStruct); // //MessageBox.Show(PrintThroughDriver.GetPrinter(lhPrinter,2,ref PI,Marshal.SizeOf(PI),ref Need).ToString() ); // //MessageBox.Show("Error "+Marshal.GetLastWin32Error()); // PrintThroughDriver.ClosePrinter2(lhPrinter); // // Ovo radi al posalje prvo print i onda javi da ne radi, javlja i windows poruku! // // string set_on_start = (char)27+""+(char)64; // // PrintThroughDriver.SendStringToPrinter(Printer, set_on_start); // // Wmis.GetStatus(); //} public void CancelPrintJob() { string printerName = "Generic"; System.Collections.Specialized.StringCollection printJobCollection = new System.Collections.Specialized.StringCollection(); string searchQuery = "SELECT * FROM Win32_PrintJob WHERE Name like '" + printerName + "%'"; /*searchQuery can also be mentioned with where Attribute, * but this is not working in Windows 2000 / ME / 98 machines * and throws Invalid query error*/ ManagementObjectSearcher searchPrintJobs = new ManagementObjectSearcher(searchQuery); ManagementObjectCollection prntJobCollection = searchPrintJobs.Get(); foreach (ManagementObject prntJob in prntJobCollection) { System.String jobName = prntJob.Properties["Name"].Value.ToString(); //Job name would be of the format [Printer name], [Job ID] char[] splitArr = new char[1]; splitArr[0] = Convert.ToChar(","); string _printerName = jobName.Split(splitArr)[0]; int prntJobID = Convert.ToInt32(jobName.Split(splitArr)[1]); string documentName = prntJob.Properties["Document"].Value.ToString(); if (String.Compare(_printerName, printerName, true) == 0) { printJobCollection.Add(documentName); //performs a action similar to the cancel //operation of windows print console prntJob.Delete(); //isActionPerformed = true; break; } } }
// First Mathematical challenger public static string findPoint(String input) { TextReader reader = Console.In; StringBuilder vs_result = new StringBuilder(); if (!input.Equals(string.Empty)) input = reader.ReadToEnd(); int numberOfTests = Convert.ToInt32(input.Split('\n')[0]); String line = string.Empty; int xFinalPoint = 0; int y1FinalPoint = 0; List<int[]> lst_Matrix = new List<int[]>(); for (int i = 1; i <= numberOfTests; i++) { line = input.Split('\n')[i]; int[] pointP = { Convert.ToInt32(line.Split(' ')[0]), Convert.ToInt32(line.Split(' ')[1]) }; int[] pointQ = { Convert.ToInt32(line.Split(' ')[2]), Convert.ToInt32(line.Split(' ')[3]) }; xFinalPoint = (pointQ[0] * 2) - pointP[0]; y1FinalPoint = (pointQ[1] * 2) - pointP[1]; int[] matrixResult = { xFinalPoint, y1FinalPoint }; lst_Matrix.Add(matrixResult); } int[] vector; for (int i = 0; i < lst_Matrix.Count; i++) { vector = lst_Matrix[i]; vs_result.Append(string.Format("{0} {1}", vector[0], vector[1])); if ((i + 1) < lst_Matrix.Count) vs_result.Append("\n"); } return vs_result.ToString(); }
public PerformerModel AddNewArtist(String artistName) { var dsInsert = new DataSet(); var insertQuery = String.Format("Insert Into Performers (FirstName, LastName, ShortName) Values ('{0}', '{1}', '{0} {1}') Select @@Identity", artistName.Split(' ')[0], artistName.Split(' ')[1]); using (var insertCommand = new SqlCommand(insertQuery, WingtipTicketApp.CreateTenantSqlConnection())) { using (var insertData = new SqlDataAdapter(insertCommand)) { insertData.Fill(dsInsert); if (dsInsert.Tables.Count > 0 && dsInsert.Tables[0].Rows.Count > 0 && dsInsert.Tables[0].Rows[0][0] != DBNull.Value) { return new PerformerModel { PerformerId = Int32.Parse(dsInsert.Tables[0].Rows[0][0].ToString()), ShortName = artistName, FirstName = artistName.Split(' ')[0], LastName = artistName.Split(' ')[1] }; } } } return null; }
public static List<string> IPIStringtoList(String str) { str.Split(new char[] { ';' }); List<String> Res = new List<string>(); Res.AddRange(str.Split(new char[] { ';' })); return Res; }
public void ParseClientInput(String input) { String[] split = input.Split(ssep); switch (split[0].ToLower()) { case "/select": if (split.Length == 2 && split[1][0] == '#') ChangeCurrentChannel(split[1]); break; case "/me": if (CurrentChannel != null & split.Length >= 2) Bot.SendQueue.Add(Message.Action(CurrentChannel, input.Split(ssep,2)[1])); break; case "/notice": if (split.Length >= 3) Bot.SendQueue.Add(Message.Notice(split[1], input.Split(ssep, 3)[2])); break; case "/part": if (split.Length >= 2) Bot.SendQueue.Add("PART " + split[1] + " :leaving"); else if (CurrentChannel != null) Bot.SendQueue.Add("PART " + CurrentChannel + " :leaving"); break; case "/join": if (split.Length == 2) Bot.SendQueue.Add("JOIN " + split[1]); else if (CurrentChannel != null) Bot.SendQueue.Add("JOIN " + CurrentChannel); break; default: if (CurrentChannel != null) Bot.SendQueue.Add(Message.PrivMsg(CurrentChannel, input)); break; } }
// extract column type private static System.Type GetColumnType(System.Type entityType, System.String propName) { System.Reflection.PropertyInfo[] props = entityType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Instance); System.String navEntityName = string.Empty; System.Reflection.PropertyInfo propInfo = null; if (propName.Contains('.')) { navEntityName = propName.Split(new char[] { '.' }, 2)[0]; propName = propName.Split(new char[] { '.' }, 2)[1]; propInfo = props.Where(p => p.Name == navEntityName).FirstOrDefault(); if (propInfo == null) { throw new Exceptions.InvalidExpressionException("Property Not Found"); } return(GetColumnType(propInfo.PropertyType, propName)); } propInfo = props.Where(p => p.Name == propName).FirstOrDefault(); if (propInfo == null) { throw new Exceptions.InvalidExpressionException("Property Not Found"); } if (!IsPrimitiveType(propInfo.PropertyType)) { throw new Exceptions.InvalidExpressionException("Property is not Primitive"); } return(propInfo.PropertyType); }
public static Boolean checkPathValid(String path) { while (true) { String[] pathes = path.Split('/'); if (!"".Equals(pathes[0])) { return false; } path = path.Substring(1); pathes = path.Split('/'); if (!Regex.IsMatch(pathes[0], regexpPathName)) { return false; } if (path.IndexOf("/") < 0) { return true; } path = path.Substring(path.IndexOf("/")); } }
public void ProcessAnswer(String nick, String fullmessage, String[] message, int size) { if (message[3][0] == ':') message[3] = message[3].Substring(1); bool isChannel = message[2][0] == '#'; if (isChannel) { try { ((ITrigger)ChannelTriggers[message[3]]).ProcessTrigger(nick,message[2],fullmessage,message,size); } catch (NullReferenceException nre) { } Bot.Display.WriteLine('[' + message[2] + ']' + '\t' + '<' + nick + '>' + ' ' + fullmessage.Split(separator, 4)[3].Substring(1)); } else { try { ((ITrigger)ChannelTriggers[message[3]]).ProcessTrigger(nick, message[2], fullmessage, message, size); } catch (NullReferenceException nre) { } Bot.Display.WriteLine('[' + "PM" + ']' + ' ' + '<' + nick + '>' + ' ' + fullmessage.Split(separator, 4)[3].Substring(1), ConsoleColor.DarkMagenta, ConsoleColor.DarkGray); } }
public static String interpretCsCode(String csCode, PlayList pl, String path_of_cs_file, Dictionary<String, String> vars) { String interpreted = ""; String[] split_at_instruction = csCode.Split(';'); foreach (String instruction_set in split_at_instruction) { if (instruction_set.Split('(').Length == 2) { String instruction = instruction_set.Split('(')[0]; String args_unparsed = instruction_set.Split('(')[1]; String[] args = args_unparsed.Substring(0, args_unparsed.Length - 1).Trim().Split(','); instruction = instruction.Trim(); String directory = path_of_cs_file.Replace(path_of_cs_file.Split('/')[path_of_cs_file.Split('/').Length - 1], ""); //INSTRUCTIONS: ------------------------------------------------------------------------------------------------------ if (instruction.Equals("genList")) interpreted = genList(pl, directory + args[0].Trim(), args[1].Trim()); else if (instruction.Equals("getVar")) interpreted = vars[args[0].Split('$')[1]]; else continue; //--------------------------------------------------------------------------------------------------------------------- } else continue; } return interpreted; }
public TimeStamp(String str) { try { String[] args = str.Split(':'); if (args.Length <= 2) { int mm = int.Parse(str.Split(':')[0]); int ss = int.Parse(str.Split(':')[1]); this.Hours = 0; this.Minutes = mm; this.Seconds = ss; } else { int hh = int.Parse(args[0]); int mm = int.Parse(args[1]); int ss = int.Parse(args[2]); this.Hours = hh; this.Minutes = mm; this.Seconds = ss; } } catch (Exception e) { this.Hours = 0; this.Minutes = 0; this.Seconds = 0; } }
public EventsLine(String t, TimeStamp s, TimeStamp e, String lastactor) { //not fully implemented. needs to parse original script if (t[0] == '#') { EType = "Comment"; Text = t.Substring(1).Trim(); } else { EType = "Dialogue"; if (t.Contains(':')) { char[] acse = { ':' }; Name = t.Split(acse, 2)[0]; Text = t.Split(acse, 2)[1].Trim(); } else { Name = lastactor; Text = t; } } Layer = 0; Start = s; End = e; Style = "Default"; MarginL = 0; MarginR = 0; MarginV = 0; Effect = ""; }
/// <summary> /// 取消指定任务 /// </summary> /// <param name="printerName">打印机名称</param> /// <param name="printJobID">打印任务ID</param> /// <returns></returns> public static bool CancelPrintJob(string printerName, int printJobID)// cancel the specific job { bool isActionPerformed = false; string searchQuery = "SELECT * FROM Win32_PrintJob"; ManagementObjectSearcher searchPrintJobs = new ManagementObjectSearcher(searchQuery); ManagementObjectCollection prntJobCollection = searchPrintJobs.Get(); foreach (ManagementObject prntJob in prntJobCollection) { System.String jobName = prntJob.Properties["Name"].Value.ToString(); //Job name would be of the format [Printer name], [Job ID] char[] splitArr = new char[1]; splitArr[0] = Convert.ToChar(","); string prnterName = jobName.Split(splitArr)[0]; int prntJobID = Convert.ToInt32(jobName.Split(splitArr)[1]); string documentName = prntJob.Properties["Document"].Value.ToString(); if (String.Compare(prnterName, printerName, true) == 0) { if (prntJobID == printJobID) { //performs a action similar to the cancel //operation of windows print console prntJob.Delete(); isActionPerformed = true; break; } } } return(isActionPerformed); }
public Tape(String initialiser) { mSymbols = new List<char>(); String[] initialiserLines = initialiser.Split('\n'); foreach (String character in initialiserLines[0].Split(',')) { if(String.IsNullOrEmpty(character)) { mSymbols.Add(' '); } else { mSymbols.Add(character[0]); } } mIndex = 0; if (initialiserLines.Length > 1) { string headPosition = initialiser.Split('\n')[1]; if (!String.IsNullOrEmpty(headPosition)) { mIndex = Int32.Parse(headPosition); } } }
//返回IPC中/前的所有字符串加/后的4个字符 public static String DocDbFormatIPC(String ipc) { if (ipc.Trim() == "") { return ipc.Trim(); } else if (!ipc.Contains('/')) { return ipc.Split(' ')[0].Trim(); } else { String[] tem = ipc.Split('/'); String result = ipc.Split('/')[0].Trim() + "/"; if (tem[1].Length > 4)//只取/后的4个字符 { result = result + tem[1].Substring(0, 4).Trim(); } else { result = result + tem[1].Trim(); } return result; } }
private Boolean TimerDayAndTimeCheck(String SettingNameDaysofWeek, String SettingNameHours,String SettingDays) { DateTime _CurrentTime = DateTime.Now; String strDaysofWeek, strHours,strDays; try { strDaysofWeek = SettingNameDaysofWeek; strHours = SettingNameHours; strDays = SettingDays; Boolean k; k = strHours.Split(',').Select(i => Convert.ToString(i)).ToList().Contains(_CurrentTime.Hour.ToString()); if ((strDaysofWeek.Split(',').Select(i => Convert.ToString(i).ToUpper()).ToList().Contains(_CurrentTime.DayOfWeek.ToString().ToUpper()) == true) && (strHours.Split(',').Select(i => Convert.ToString(i)).ToList().Contains(_CurrentTime.Hour.ToString()) == true) && (strDays.Split(',').Select(i => Convert.ToString(i)).ToList().Contains(_CurrentTime.Day.ToString()) == true) ) { return true; } else { return false; } } catch (Exception e) { throw e; } }
public static Molecule ReadNative(System.IO.StreamReader in_Renamed) { Molecule mol = new Molecule(); //UPGRADE_NOTE: Final was removed from the declaration of 'GENERIC_ERROR '. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1003'" System.String GENERIC_ERROR = "Invalid SketchEl file."; try { System.String line = in_Renamed.ReadLine(); if (!line.StartsWith("SketchEl!")) { throw new System.IO.IOException("Not a SketchEl file."); } int p1 = line.IndexOf('('), p2 = line.IndexOf(','), p3 = line.IndexOf(')'); if (p1 == 0 || p2 == 0 || p3 == 0) { throw new System.IO.IOException(GENERIC_ERROR); } int numAtoms = System.Int32.Parse(line.Substring(p1 + 1, (p2) - (p1 + 1)).Trim()); int numBonds = System.Int32.Parse(line.Substring(p2 + 1, (p3) - (p2 + 1)).Trim()); for (int n = 0; n < numAtoms; n++) { line = in_Renamed.ReadLine(); // TODO: verify java's split method syntax: "[\\=\\,\\;]" System.String[] bits = line.Split('=', ',', ';'); if (bits.Length < 5) { throw new System.IO.IOException(GENERIC_ERROR); } int num = mol.AddAtom(bits[0], System.Double.Parse(bits[1].Trim()), System.Double.Parse(bits[2].Trim()), System.Int32.Parse(bits[3].Trim()), System.Int32.Parse(bits[4].Trim())); if (bits.Length >= 6 && bits[5].Length > 0 && bits[5][0] == 'e') { mol.SetAtomHExplicit(num, System.Int32.Parse(bits[5].Substring(1))); } } for (int n = 0; n < numBonds; n++) { line = in_Renamed.ReadLine(); System.String[] bits = line.Split('-', '=', ','); // "[\\-\\=\\,]"); if (bits.Length < 4) { throw new System.IO.IOException(GENERIC_ERROR); } mol.AddBond(System.Int32.Parse(bits[0].Trim()), System.Int32.Parse(bits[1].Trim()), System.Int32.Parse(bits[2].Trim()), System.Int32.Parse(bits[3].Trim())); } line = in_Renamed.ReadLine(); if (String.CompareOrdinal(line, "!End") != 0) { throw new System.IO.IOException(GENERIC_ERROR); } } catch (System.Exception) { throw new System.IO.IOException(GENERIC_ERROR); } return(mol); }
private DateTime getDate(String data) { String[] day = data.Split(' ')[0].Split('/'); String[] time = data.Split(' ')[1].Split(':'); return new DateTime(int.Parse(day[2]), int.Parse(day[1]), int.Parse(day[0]), int.Parse(time[0]), int.Parse(time[1]), int.Parse(time[2])); }
public static IEnumerable<IComponent> GetComponents(String fieldRawText, Context context) { String[] componentStrings = fieldRawText.Split(context.ComponentSeparator); return from item in fieldRawText.Split(context.ComponentSeparator) select ComponentFactory.GetComponent(item, context); }
public void setOvenTemp(String oventemp) { this.oventemp = int.Parse(oventemp.Split()[3]); if (Regex.Match(oventemp, "gas mark").Success) { String mark = oventemp.Split()[8]; this.gasmark = int.Parse(mark.Substring(0, mark.Length - 1)); } }
public static void ProcessCommand(String message) { int distOut; message = message.ToLower().Trim(); Console.WriteLine(message); if (message.Contains("buy") || message.Contains("get") || message.Contains("rush") || message.Contains("purchase")) { Shop.RushItem = Shop.GetItemByName(message); return; } else if (message.StartsWith("distance ")) { String distance = message.Split(" ".ToCharArray())[1].Trim(); int dist = Int32.Parse(distance); Core.MaxDistanceFromCarry = dist; } else if (message.StartsWith("frdm ") || message.StartsWith("freedom ")) { String freedom = message.Split(" ".ToCharArray())[1].Trim(); Console.WriteLine("Setting freedom " + freedom); HeatMap.Frdm = HeatMap.freedomFromString(freedom.ToUpper()); return; } else if (message.StartsWith("pos ")) { String position = message.Split(" ".ToCharArray())[1].Trim(); Console.WriteLine("Setting position " + position); HeatMap.Pos = HeatMap.posFromString(position.ToUpper()); return; } else if (Utility.Map.GetMap().Type == Utility.Map.MapType.SummonersRift && (message == "b" || message.Contains("back") || message.Contains("recall"))) { PingManager.Mode = BehaviourMode.PASSIVE; PingManager.Location = null; PingManager.Target = null; RecallManager.UserRecallRequest = true; return; } else if (Int32.TryParse(message, out distOut) ) { Core.MaxDistanceFromCarry = distOut; } }
// Constructor public Hand(String fileContents) { PlayingCard[] hand = { new PlayingCard(fileContents.Split()[0], fileContents.Split()[1]), new PlayingCard(fileContents.Split()[2], fileContents.Split()[3]), new PlayingCard(fileContents.Split()[4], fileContents.Split()[5]), new PlayingCard(fileContents.Split()[6], fileContents.Split()[7]), new PlayingCard(fileContents.Split()[8], fileContents.Split()[9]) }; this.playingCards = hand; }
private Support getMetricValue(ItemSet val, Metric m) { ItemSet[] splitItems = val.Split(','); if (splitItems.Length == 1) { switch (m) { case Metric.SupportCount: float x = Convert.ToInt32(this._sparseMatrix.Compute("COUNT([" + val + "])", "[" + val + "] = 1")); return(x); case Metric.Support: float y = Convert.ToInt32(this._sparseMatrix.Compute("COUNT([" + val + "])", "[" + val + "] = 1")); return(y / this._sparseMatrix.Rows.Count); case Metric.Confidence: //find support count of whole and divide it by that of the antecedent float supportCountWhole = getMetricValue(val.Replace('#', ','), Metric.SupportCount); float supportCountAntecedent = getMetricValue(val.Split('#')[0], Metric.SupportCount); return(supportCountAntecedent == 0 ? 0 : supportCountWhole / supportCountAntecedent); default: return(0); } } else { switch (m) { case Metric.Support: StringBuilder query = new StringBuilder("["); foreach (ItemSet item in splitItems) { query.Append(item); query.Append("] = 1 AND ["); } query.Remove(query.Length - 5, 5); DataRow[] drColln = _sparseMatrix.Select(query.ToString()); if (drColln.Length > 0) { return((float)drColln.Length / _sparseMatrix.Rows.Count); } else { return(0); } case Metric.Confidence: //find support count of whole and divide it by that of the antecedent float supportCountWhole = getMetricValue(val.Replace('#', ','), Metric.Support); //same as using supportcount because it is a ratio float supportCountAntecedent = getMetricValue(val.Split('#')[0], Metric.Support); //same as using supportcount because it is a ratio return(supportCountAntecedent == 0 ? 0 : supportCountWhole / supportCountAntecedent); default: return(0); } } }
public string[] parseWeatherapi(String message) { String[] divide = { "temp_C", "temp_F" }; string[] words = message.Split(' '); String[] temp = message.Split(divide, StringSplitOptions.RemoveEmptyEntries); return temp; }
// // GET: /OldCoins/Delete/5 public ActionResult CoinsDelete(String coins) { for (int i = 0; i < coins.Split(',').Length; i++) { string coinId = coins.Split(',')[i]; CoinManager.DeleteCoin(Guid.Parse(coinId)); } return RedirectToAction("Index"); }
public Instruction(String Code, VariablesManager Variables) { this.Code = Code; this.Variables = Variables; //special treatment for if statements if (Code.Substring(0,2) == "if") { Type = "if"; Length = 0; Dynamic = true; IfConition = Code.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)[1]; IfInstruction = new Instruction(Code.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)[1], Variables); if (Code.Contains("else")) ElseInstruction = new Instruction(Code.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)[3], Variables); return; } Dynamic = false; Type = Code.Split(new string[] { "->" }, StringSplitOptions.None)[0]; Destinationformula = Code.Split(new string[] { "fill." }, StringSplitOptions.None)[1]; Destination = Destinationformula; foreach (Char c in Arethmitic) Destination = Destination.Split(c)[0]; if (Destinationformula.Contains("(") && Destinationformula.Contains(")")) DestinationConstant = Destinationformula.Split('(')[1].Split(')')[0]; Length = Array.IndexOf(Types, Type); Length = Length < 0 ? Length : Lengths[Length]; if (Type.Contains("@")) { TypeVariable = Type.Split('@')[1]; Type = Type.Split('@')[0]; if (new Regex(@"^\d+$").IsMatch(TypeVariable)) Length = Convert.ToInt32(TypeVariable); else Dynamic = true; } if(Length < 0 && !Dynamic) { //treat as variable TypeVariable = Type; Type = "variable"; Length = 0; } }
public void view (byte[] bytes, String content_type) { String simple_content_type = content_type; Encoding enc = Encoding.Default; if(content_type.Contains(";")) { simple_content_type = content_type.Split(";".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0]; String charset = content_type.Split(new string[]{"charset="}, StringSplitOptions.RemoveEmptyEntries)[1]; if(!string.IsNullOrEmpty(charset)) enc = Encoding.GetEncoding(charset); } textview1.Buffer.Text = format(enc.GetString(bytes), simple_content_type); }
public void AddFunctionIfNotDefined(String signature) { String type = signature.Split()[0]; String name = signature.Split()[1]; bool found = false; foreach (var function in Functions) found |= (function.Name == name); if (!found) Functions.Insert(0, new Function() { Name = name, ReturnType = type, Body = new Block()}); }
public SysLogMessageVO kiwiConvertToSysLogMessageVo(String msg, String sourceip) { SysLogMessageVO msgVo = new SysLogMessageVO(); msgVo.source = sourceip; msgVo.message = msg.Split("\t".ToCharArray())[3]; msgVo.severity = msg.Split("\t".ToCharArray())[1].Split(".".ToCharArray())[1]; msgVo.facility = msg.Split("\t".ToCharArray())[1].Split(".".ToCharArray())[0]; msgVo.date = DateTime.Now.ToString("d"); msgVo.time = DateTime.Now.ToString("t"); msgVo.visible = true; return msgVo; }
/// <summary> /// Hiện thị danh sách các tờ in /// </summary> /// <param name="iID_MaPhuongAn"> phương án chọn</param> /// <param name="KieuIn"> kiểu in 1. Tổng hợp 2, Chi Tiết</param> /// <returns></returns> public static DataTable KeToan_ToIn(String iID_MaPhuongAn, String KieuIn, String iID_MaTrangThaiDuyet) { DataTable dt = new DataTable(); dt.Columns.Add("MaTo", typeof(String)); dt.Columns.Add("TenTo", typeof(String)); dt.Columns.Add("ToSo", typeof(String)); if (KieuIn == "1") { String[] iID_MaTaiKhoan = new String[100]; String[] arrPhuongAn = iID_MaPhuongAn.Split(','); int a = arrPhuongAn.Length % 3; if (a == 1) { iID_MaPhuongAn = iID_MaPhuongAn + ",,"; arrPhuongAn = iID_MaPhuongAn.Split(','); } if (a == 2) { iID_MaPhuongAn = iID_MaPhuongAn + ","; arrPhuongAn = iID_MaPhuongAn.Split(','); } for (int i = 0; i < arrPhuongAn.Length; i = i + 3) { iID_MaTaiKhoan[Convert.ToInt16(i / 3)] += arrPhuongAn[i] + "," + arrPhuongAn[i + 1] + "," + arrPhuongAn[i + 2]; } for (int i = 0; i < (arrPhuongAn.Length / 3); i++) { DataRow R1 = dt.NewRow(); dt.Rows.Add(R1); R1[0] = iID_MaTaiKhoan[i]; R1[1] = "Tờ" + Convert.ToInt16(i + 1) + ": " + iID_MaTaiKhoan[i]; R1[2] = "Tờ " + Convert.ToInt16(i + 1); } dt.Dispose(); } else { String[] iID_MaTaiKhoan = iID_MaPhuongAn.Split(','); String[] TenTaiKhoan = new String[100]; for (int i = 0; i < iID_MaTaiKhoan.Length;i++) { TenTaiKhoan[i] = Convert.ToString(CommonFunction.LayTruong("KT_TaiKhoan", "iID_MaTaiKhoan", iID_MaTaiKhoan[i], "sTen")); } for (int i = 0; i < iID_MaTaiKhoan.Length;i++) { DataRow R1 = dt.NewRow(); dt.Rows.Add(R1); R1[0] = iID_MaTaiKhoan[i]; R1[1] = iID_MaTaiKhoan[i] + " " + TenTaiKhoan[i]; } } return dt; }
public bool CheckUserInGroup(String ntAccount, String GroupName) { string DomainName = (ntAccount.Split('\\'))[0].ToString(); string AccountName = (ntAccount.Split('\\'))[1].ToString(); #region Build WMI query using SelectQuery StringBuilder sBuilder = new StringBuilder("GroupComponent="); sBuilder.Append('"'); sBuilder.Append("Win32_Group.Domain="); sBuilder.Append("'"); sBuilder.Append(DomainName); sBuilder.Append("'"); sBuilder.Append(",Name="); sBuilder.Append("'"); sBuilder.Append(GroupName); sBuilder.Append("'"); sBuilder.Append('"'); sBuilder.Append(" and "); sBuilder.Append("PartComponent="); sBuilder.Append('"'); sBuilder.Append("Win32_UserAccount.Domain="); sBuilder.Append("'"); sBuilder.Append(DomainName); sBuilder.Append("'"); sBuilder.Append(",Name="); sBuilder.Append("'"); sBuilder.Append(AccountName); sBuilder.Append("'"); sBuilder.Append('"'); SelectQuery sQuery = new SelectQuery("Win32_GroupUser", sBuilder.ToString()); #endregion try { ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery); if (mSearcher.Get().Count > 0) { return true; } else { return false; } } catch (Exception ex) { Response.Write(ex.ToString()); return false; } }
/** * Cuts the path down to start at the parsed placeholder */ public static String GetDisplayPath(String path) { int beforeParseCount = path.Split(System.IO.Path.DirectorySeparatorChar).Length; path = GamePlaceholder.ReplacePlaceholders(path); int afterParseCount = path.Split(System.IO.Path.DirectorySeparatorChar).Length; for (int i = 0; i < afterParseCount - beforeParseCount; i++) { path = path.Substring(path.IndexOf(System.IO.Path.DirectorySeparatorChar) + 1); } return path; }
public ContextResolver(String path) { this.Path = new List<string>(); if (path.StartsWith(".")) { this.Path.Add("."); this.Path.AddRange(path.Split('.').Skip(1)); } else { this.Path.AddRange(path.Split('.')); } }
/// <summary> /// 获取文件名 /// </summary> /// <param name="path"></param> /// <returns></returns> public static string GetFileName(String path) { if (path.Contains("\\")) { string[] arr = path.Split('\\'); return arr[arr.Length - 1]; } else { string[] arr = path.Split('/'); return arr[arr.Length - 1]; } }
public ShapeObject(LayerManager layerManager, String filePath) { this.layerManager = layerManager; this.filePath = filePath; this.fileName = filePath.Split('\\')[filePath.Split('\\').Length-1]; this.access = "rb"; this.shapePen = new Pen(layerManager.GetRandomColor(), 1.0f); int i = filePath.LastIndexOf("\\"); name = filePath.Substring(i + 1, filePath.LastIndexOf(".") - i - 1); }
//Connect to server public void Connect(String ip) { try { audioConnection.Connect(IPAddress.Parse(ip.Split(':')[0]), UInt16.Parse(ip.Split(':')[1])); msgConnection.Connect(IPAddress.Parse(ip.Split(':')[0]), UInt16.Parse(ip.Split(':')[1]) - 1); _isConnected = true; OnConnected(); } catch (Exception) { throw new Exception("Server is offline"); } }
private void Button1_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog { InitialDirectory = @"D:\", Title = "Browse PDF Files", CheckFileExists = true, CheckPathExists = true, DefaultExt = "pdf", Filter = "pdf files (*.pdf)|*.pdf", FilterIndex = 2, RestoreDirectory = true, ReadOnlyChecked = true, ShowReadOnly = true }; if (openFileDialog1.ShowDialog() == DialogResult.OK) { textBox1.Text = openFileDialog1.FileName; file_name = textBox1.Text; System.String[] nameList = file_name.Split('\\'); nCnt = nameList.Length; //textBox2.Text = nameList[nCnt - 1]; System.String pdf_name = nameList[nCnt - 1]; excel_name = pdf_name.Replace("pdf", "xls"); textBox2.Text = excel_name; } }
/// <summary> It loads the probability data from the specified file.</summary> /// <param name="fileName">- the path of the file which has the probability data /// </param> /// <throws> IOException </throws> private void init(System.String fileName) { System.IO.StreamReader br = new System.IO.StreamReader(fileName, System.Text.Encoding.UTF8); System.String line = null; System.String[] tokens = null; double[] numbers = null; while ((line = br.ReadLine()) != null) { tokens = line.Split(" "); numbers = new double[tokens.Length - 1]; for (int i = 0; i < tokens.Length - 1; i++) { numbers[i] = System.Double.Parse(tokens[i + 1]); } if (tokens == null || tokens[0] == null || numbers == null) { System.Console.Out.WriteLine("hi"); } table[tokens[0]] = numbers; } br.Close(); }
public System.String get_DatabaseHandle(System.String strSQLLine) { System.String strPartDatabaseSQL = System.String.Empty; System.String strPartDatabase = System.String.Empty; Int32 nIndex = 0; //std::string strSql = databaseConnection->prepareSQLStatement(ALARMRULE_SELECT_1008, string[] splitStrObject = strSQLLine.Split(new Char[] { '=' }); //std::string strSql //databaseConnection->prepareSQLStatement(ALARMRULE_SELECT_1008, strPartDatabaseSQL = splitStrObject[1]; strPartDatabaseSQL = strPartDatabaseSQL.Trim(); nIndex = strPartDatabaseSQL.IndexOf("->"); if (-1 == nIndex) { strPartDatabase = "databaseConnection"; } else { strPartDatabase = strPartDatabaseSQL.Substring(0, nIndex); strPartDatabase = strPartDatabase.Trim(); } return(strPartDatabase); }
public System.String get_AssigenStrSQL(System.String strSQLLine) { System.String strGet = System.String.Empty; System.String strPartAssigen = System.String.Empty; Int32 nIndex = 0; //std::string strSql = databaseConnection->prepareSQLStatement(ALARMRULE_SELECT_1008, string[] splitStrObject = strSQLLine.Split(new Char[] { '=' }); //std::string strSql //databaseConnection->prepareSQLStatement(ALARMRULE_SELECT_1008, strPartAssigen = splitStrObject[0]; strPartAssigen = strPartAssigen.Trim(); nIndex = strPartAssigen.IndexOf(" "); if (-1 == nIndex) { strGet = strPartAssigen; } else { strGet = strPartAssigen.Substring(nIndex + 1); strGet.Trim(); } return(strGet); }
private void OnDataReceived(IAsyncResult asyn) { try { int iRx = 0; iRx = socket.EndReceiveFrom(asyn, ref client); char[] chars = new char[iRx - 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(dataBuffer, 0, iRx - 1, chars, 0); String szData = new System.String(chars); if (szData[0].Equals('*')) { if (szData[1].Equals('C')) { string id = szData.Substring(2); if (!id.Equals(clientID)) { clientID = id; SendData("A\n"); TouchPal.Debug("Client (" + id + ") connected."); manager.ClientConnected(); } } if (szData[1].Equals('R') && manager != null) { manager.ResetControls(); SendData("A\n"); } } else if (manager != null) { string[] controlUpdates = szData.Split(new Char[] { ':' }); foreach (string controlUpdate in controlUpdates) { string[] values = controlUpdate.Split(new Char[] { '=' }); if (values.Count() == 2) { try { int networkID = Convert.ToInt32(values[0]); manager.UpdateControl(networkID, values[1]); SendData("A\n"); } catch (FormatException fe) { TouchPal.Error("Bad network id value (" + values[0] + ") received from client - " + fe.Message); } } } } WaitForData(); } catch (SocketException se) { Console.WriteLine(se.Message); } }
public static StringCollection GetPrintJobsCollection(string printerName)//get print job list of printers { StringCollection printJobCollection = new StringCollection(); string searchQuery = "SELECT * FROM Win32_PrintJob"; /*searchQuery can also be mentioned with where Attribute, * but this is not working in Windows 2000 / ME / 98 machines * and throws Invalid query error*/ ManagementObjectSearcher searchPrintJobs = new ManagementObjectSearcher(searchQuery); ManagementObjectCollection prntJobCollection = searchPrintJobs.Get(); foreach (ManagementObject prntJob in prntJobCollection) { System.String jobName = prntJob.Properties["Name"].Value.ToString(); //Job name's format [Printer name], [Job ID] char[] splitArr = new char[1]; splitArr[0] = Convert.ToChar(","); string prnterName = jobName.Split(splitArr)[0]; string documentName = prntJob.Properties["Document"].Value.ToString(); string jobid = prntJob.Properties["JobId"].Value.ToString(); string status = prntJob.Properties["Status"].Value.ToString(); if (String.Compare(prnterName, printerName, true) == 0) { printJobCollection.Add(status + "<" + jobid + ": " + documentName); // add jobID } } return(printJobCollection); }
protected internal virtual bool isMatch(String filename1, String filename2) { Boolean SHOW_RESULTS = true; System.String result = StringUtil.fileContentsToString(filename1); System.String compare = StringUtil.fileContentsToString(filename2); Boolean equals = result.Equals(compare); if (!equals && SHOW_RESULTS) { Console.Out.WriteLine(filename1 + "/" + filename2 + " :: "); String[] cmp = compare.Split(Environment.NewLine.ToCharArray()); String[] res = result.Split(Environment.NewLine.ToCharArray()); IEnumerator cmpi = cmp.GetEnumerator(); IEnumerator resi = res.GetEnumerator(); Int32 line = 0; while (cmpi.MoveNext() && resi.MoveNext()) { line++; String s1 = resi.Current.ToString().Replace("\t", " ").Trim(); String s2 = cmpi.Current.ToString().Replace("\t", " ").Trim(); if (!s1.Equals(s2)) { Console.Out.WriteLine(line.ToString() + " : " + cmpi.Current.ToString()); Console.Out.WriteLine(line.ToString() + " : " + resi.Current.ToString()); } } } return(equals); }
public int GetPrintJobCount(string printerName) { List <string> printJobCollection = new List <string>(); string searchQuery = "SELECT * FROM Win32_PrintJob"; /*searchQuery can also be mentioned with where Attribute, * but this is not working in Windows 2000 / ME / 98 machines * and throws Invalid query error*/ ManagementObjectSearcher searchPrintJobs = new ManagementObjectSearcher(searchQuery); ManagementObjectCollection prntJobCollection = searchPrintJobs.Get(); foreach (ManagementObject prntJob in prntJobCollection) { System.String jobName = prntJob.Properties["Name"].Value.ToString(); //Job name would be of the format [Printer name], [Job ID] char[] splitArr = new char[1]; splitArr[0] = Convert.ToChar(","); string prnterName = jobName.Split(splitArr)[0]; string documentName = prntJob.Properties["Document"].Value.ToString(); if (String.Compare(prnterName, printerName, true) == 0) { printJobCollection.Add(documentName); } } return(printJobCollection.Count); }
public MapViewLayoutParams(Context context, IAttributeSet attrs) : base(context, attrs) { this.X = attrs.GetAttributeIntValue("http://schemas.mapquest.com/apk/res/mapquest", "x", int.MaxValue); this.Y = attrs.GetAttributeIntValue("http://schemas.mapquest.com/apk/res/mapquest", "x", int.MaxValue); String geoPoint = attrs.GetAttributeValue("http://schemas.mapquest.com/apk/res/mapquest", "geoPoint"); if ((geoPoint.Length > 0)) { String[] arr = geoPoint.Split(new[] { "," }, StringSplitOptions.None); if (arr.Length > 1) { try { double latitude = Double.Parse(arr[0].Trim()); double longitude = Double.Parse(arr[1].Trim()); this.Point = new GeoPoint(latitude, longitude); this.Mode = 0; } catch (NumberFormatException nfe) { Log.Error("mq.android.maps.mapview", "Invalid value for geoPoint attribute : " + geoPoint); } } } }
internal ByArgument(System.String arg) : base(arg) { if (String.IsNullOrEmpty(arg)) { arg = null; } if (CheckNull(Arg(() => arg, arg))) { if (arg.Split(new char[] { Text.DotChar }).Length > 2) { chainException = new QueryTalkException(this, QueryTalkExceptionType.InvalidColumnIdentifier, String.Format("identifier = {0}", arg), Text.Method.Identifier); return; } var pair = new AliasColumnPair(arg); _alias = pair.Alias; _column = pair.Column; if (_column != null) { JoinType = Wall.ByType.NonMappedColumn; } else { JoinType = Wall.ByType.Alias; } } SetArgType(arg); }
public void OnDataReceived(IAsyncResult asyn) { try { int iRx = 0; iRx = _receiverSocket.EndReceive(asyn); char[] chars = new char[iRx]; var decoder = System.Text.Encoding.UTF8.GetDecoder(); int charLen = decoder.GetChars(_buffer, 0, iRx, chars, 0); var szData = new System.String(chars); var splittedCommands = szData.Split(new string[] { _messageTerminator }, StringSplitOptions.RemoveEmptyEntries); foreach (var cmd in splittedCommands) { EnqueReceivedCommand(cmd); } WaitForData(_receiverSocket); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { System.Diagnostics.Debugger.Log(0, "1", se.Message); } }
/// <summary>Init method used by constructors. </summary> private void Init(System.String primary, System.String sub) { // Preliminary checks... if ((primary == null) || (primary.Length <= 0) || (!IsValid(primary))) { throw new MimeTypeException("Invalid Primary Type " + primary); } // Remove optional parameters from the sub type System.String clearedSub = null; if (sub != null) { clearedSub = sub.Split(PARAMS_SEP[0])[0]; } if ((clearedSub == null) || (clearedSub.Length <= 0) || (!IsValid(clearedSub))) { throw new MimeTypeException("Invalid Sub Type " + clearedSub); } // All is ok, assign values this._strName = primary + SEPARATOR + clearedSub; this._strPrimary = primary; this._strSub = clearedSub; this._collExtensions = new System.Collections.ArrayList(); this._collMagics = new System.Collections.ArrayList(); }
/// <summary> /// Parse a rfc 2822 header field with parameters /// </summary> /// <param name="field">field name</param> /// <param name="fieldbody">field body to parse</param> /// <returns>A <see cref="System.Collections.Specialized.StringDictionary" /> from the parsed field body</returns> public static System.Collections.Specialized.StringDictionary parseHeaderFieldBody(System.String field, System.String fieldbody) { if (fieldbody == null) { return(null); } // FIXME: rewrite parseHeaderFieldBody to being regexp based. fieldbody = anmar.SharpMimeTools.SharpMimeTools.uncommentString(fieldbody); System.Collections.Specialized.StringDictionary fieldbodycol = new System.Collections.Specialized.StringDictionary(); System.String[] words = fieldbody.Split(new Char[] { ';' }); if (words.Length > 0) { fieldbodycol.Add(field.ToLower(), words[0].ToLower()); for (int i = 1; i < words.Length; i++) { System.String[] param = words[i].Trim(new Char[] { ' ', '\t' }).Split(new Char[] { '=' }, 2); if (param.Length == 2) { param[0] = param[0].Trim(new Char[] { ' ', '\t' }); param[1] = param[1].Trim(new Char[] { ' ', '\t' }); if (param[1].StartsWith("\"") && !param[1].EndsWith("\"")) { do { param[1] += ";" + words[++i]; } while (!words[i].EndsWith("\"") && i < words.Length); } fieldbodycol.Add(param[0], anmar.SharpMimeTools.SharpMimeTools.parserfc2047Header(param[1].TrimEnd(';').Trim('\"'))); } } } return(fieldbodycol); }
public static void Service() { Debug.Log("Waiting for the Python Script"); // Todo : Find a way to close thread if it is here (blocking call) Socket soc = listener.AcceptSocket(); Debug.Log("Socket found"); while (is_open) { try { Stream s = new NetworkStream(soc); StreamReader sr = new StreamReader(s); System.String str = sr.ReadLine(); if (str != null) { // remove semicolon str = str.Remove(str.Length - 1); // split string[] arr = str.Split("\\".ToCharArray(), System.StringSplitOptions.RemoveEmptyEntries); convert(arr); // print("Accel " + accel[0] + "/" + accel[1] + "/" + accel[2] + // " / Gyro " + gyro[0] + "/" + gyro[1] + "/" + gyro[2] + // "/ Touch " + touch); } } catch (System.Exception e) { Debug.Log(e.Message); } } Debug.Log("Thread Closed"); }
/// <summary> /// AutoSearch /// Calls [usp_autosearch_CustReqPart] /// </summary> public override List <PartDetails> CustReqPart(System.Int32?clientId, System.String partSearch, System.String ids, System.String DateCode) { SqlConnection cn = null; SqlCommand cmd = null; string ManufacturerNo = ""; string ProductNumber = ""; string PackageNumber = ""; string[] values = ids.Split('|');// ids.Split(","); ManufacturerNo = values[0].Trim(); ProductNumber = values[1].Trim(); PackageNumber = values[2].Trim(); try { cn = new SqlConnection(this.ConnectionString); cmd = new SqlCommand("usp_autosearch_CustReqPart", cn); cmd.CommandType = CommandType.StoredProcedure; cmd.CommandTimeout = 60; cmd.Parameters.Add("@ClientId", SqlDbType.Int).Value = clientId; cmd.Parameters.Add("@PartSearch", SqlDbType.NVarChar).Value = partSearch; cmd.Parameters.Add("@ManufacturerNo", SqlDbType.Int).Value = Convert.ToInt32(ManufacturerNo); cmd.Parameters.Add("@ProductNumber", SqlDbType.Int).Value = Convert.ToInt32(ProductNumber); cmd.Parameters.Add("@PackageNumber", SqlDbType.Int).Value = Convert.ToInt32(PackageNumber); cmd.Parameters.Add("@DateCode", SqlDbType.NVarChar).Value = DateCode; cn.Open(); DbDataReader reader = ExecuteReader(cmd); List <PartDetails> lst = new List <PartDetails>(); while (reader.Read()) { PartDetails obj = new PartDetails(); obj.PartNameWithManufacture = GetReaderValue_String(reader, "PartName", ""); obj.PartName = GetReaderValue_String(reader, "Parts", ""); obj.ManufacturerNo = GetReaderValue_Int32(reader, "ManufacturerId", 0); obj.Productname = GetReaderValue_String(reader, "ProductName", ""); obj.Packagename = GetReaderValue_String(reader, "PackageName", ""); obj.DateCode = GetReaderValue_String(reader, "DateCode", ""); obj.ProductNo = GetReaderValue_Int32(reader, "ProductNo", 0); obj.PackageNo = GetReaderValue_Int32(reader, "PackageNo", 0); obj.ManufacturerName = GetReaderValue_String(reader, "ManufacturerName", ""); obj.ROHSNo = GetReaderValue_Int32(reader, "ROHS", 0); lst.Add(obj); obj = null; } return(lst); } catch (SqlException sqlex) { //LogException(sqlex); throw new Exception("Failed to get Parts", sqlex); } finally { cmd.Dispose(); cn.Close(); cn.Dispose(); } }
public void OnDataReceived(IAsyncResult asyn) { try { SocketPacket theSockId = (SocketPacket)asyn.AsyncState; int iRx = theSockId.thisSocket.EndReceive(asyn); char[] chars = new char[iRx]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0); System.String sRecieved = new System.String(chars); string action = sRecieved.Substring(0, 3); string message = ""; if (sRecieved.Length > 8) { message = sRecieved.Substring(8); } string[] s = sRecieved.Split('`'); // Console.WriteLine("|" + action + "|" + sRecieved); switch (action) { case "`0:": break; case "`1:": Invoke(m_AddMessage, new string[] { "Left" }); this.Invoke((MethodInvoker) delegate { // close the form on the forms thread this.Close(); }); break; case "`3:": string[] channelEndPoint = s[3].Split('|'); Invoke(m_AddMessage, new string[] { s[3] }); // string header = "`4:`" + s[2] + "`" + channelEndPoint[1]; string header = "`4:`" + chatWithIndex + "`" + channelEndPoint[1]; SendMessage(header); break; default: Invoke(m_AddMessage, new string[] { sRecieved }); break; } Console.WriteLine(sRecieved); WaitForData(); } catch (ObjectDisposedException) { System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n"); } catch (SocketException se) { Console.WriteLine(se.Message); // chatformStatus.Text = se.Message + " Server Connect failed!"; } }
///<summary> ///Parses the reponse data from a handshake ///</summary> protected System.Boolean ParseHandshake(System.String Data) { /* This function is a rewrite from Last-Exit */ System.String[] Lines = Data.Split(new System.Char[] { '\n' }); System.Boolean Result = false; foreach (System.String Line in Lines) { System.String[] Opts = Line.Split(new System.Char[] { '=' }, 2); switch (Opts[0].ToLower()) { case "session": if (Opts[1].ToLower() == "failed") { Result = false; } else { Result = true; this.SessionID = Opts[1]; } break; case "stream_url": this.StreamURL = Opts[1]; break; case "subscriber": if (Opts[1] == "1") { this.Subscripter = true; } else { this.Subscripter = false; } break; case "framehack": //Don't know what this is for break; case "base_url": this.BaseURL = Opts[1]; break; case "base_path": this.BasePath = Opts[1]; break; default: Console.WriteLine("LastManager.ParseHandshake(): Unknown key: " + Opts[0]); break; } } return(Result); }
public void RemotedExperienceService_Advertise(System.UInt32 Nonce, System.String HostId, System.String ApplicationId, System.String ApplicationVersion, System.String ApplicationData, System.String HostFriendlyName, System.String ExperienceFriendlyName, System.String ExperienceIconUri, System.String ExperienceEndpointUri, System.String ExperienceEndpointData, System.String SignatureAlgorithm, System.String Signature, System.String HostCertificate) { _RES_HostNonce = BitConverter.GetBytes(Nonce); _RES_ApplicationId = ApplicationId; _RES_ApplicationVersion = ApplicationVersion; _RES_ExperienceEndpointUri = ExperienceEndpointUri; _RES_ExperienceEndpointData = ExperienceEndpointData; _RES_SignatureAlgorithm = SignatureAlgorithm; _RES_Signature = Signature; _RES_HostCertificate = HostCertificate; m_logger.LogDebug("RemotedExperienceService_Advertise(" + Nonce.ToString() + HostId.ToString() + ApplicationId.ToString() + ApplicationVersion.ToString() + ApplicationData.ToString() + HostFriendlyName.ToString() + ExperienceFriendlyName.ToString() + ExperienceIconUri.ToString() + ExperienceEndpointUri.ToString() + ExperienceEndpointData.ToString() + SignatureAlgorithm.ToString() + Signature.ToString() + HostCertificate.ToString() + ")"); // parse endpoint data Dictionary <String, String> endpointData = new Dictionary <String, String>(); foreach (String part in ExperienceEndpointData.Split(';')) { String[] nameValuePair = part.Split(new char[] { '=' }, 2); endpointData.Add(nameValuePair[0], nameValuePair[1]); } // decrypt MCX user password with cert's signing key (private key) RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); rsa.FromXmlString(File.ReadAllText(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\Certificates\\SoftSledPrivateKey.xml")); byte[] cryptedPass = Convert.FromBase64String(endpointData["encryptedpassword"]); String rdpPass = ""; try { rdpPass = Encoding.ASCII.GetString(rsa.Decrypt(cryptedPass, true)); } catch (Exception ex) { m_logger.LogError("RSA decryption of encrypted password failed " + ex.Message); m_logger.LogError("Extender Experience Pairing has failed!"); return; } string rdpHost = ExperienceEndpointUri.Substring(6, ExperienceEndpointUri.Length - 12); string rdpUser = endpointData["user"]; m_logger.LogDebug("RDP host: " + rdpHost); m_logger.LogDebug("RDP clear text Password: "******"RDP user: "******"Extender Experience data exchanged!"); }
//public static bool ResumePrintJob(string printerName, int printJobID) /// <summary> /// 继续所有打印任务 /// </summary> /// <param name="printerName">打印机名称</param> /// <param name="printJobID">打印任务ID</param> /// <returns></returns> public static bool ResumePrintJob(string printerName, int printJobID)//resume the paused job { bool isActionPerformed = false; string searchQuery = "SELECT * FROM Win32_PrintJob"; ManagementObjectSearcher searchPrintJobs = new ManagementObjectSearcher(searchQuery); ManagementObjectCollection prntJobCollection = searchPrintJobs.Get(); foreach (ManagementObject prntJob in prntJobCollection) { System.String jobName = prntJob.Properties["Name"].Value.ToString(); System.String JobID = prntJob.Properties["JobID"].Value.ToString(); System.String JobSize = prntJob.Properties["Size"].Value.ToString(); System.String JobPages = prntJob.Properties["TotalPages"].Value.ToString(); System.String JobOwner = prntJob.Properties["Owner"].Value.ToString(); System.String JobName = prntJob.Properties["Document"].Value.ToString(); //Job name would be of the format [Printer name], [Job ID] char[] splitArr = new char[1]; splitArr[0] = Convert.ToChar(","); string prnterName = jobName.Split(splitArr)[0]; int prntJobID = Convert.ToInt32(jobName.Split(splitArr)[1]); string documentName = prntJob.Properties["Document"].Value.ToString(); if (String.Compare(prnterName, printerName, true) == 0) { if (prntJobID == printJobID) { if (prntJob.Properties["Status"].Value.ToString().Equals("Degraded")) { prntJob.InvokeMethod("Resume", null); isActionPerformed = true; break; } } } } return(isActionPerformed); }
private void OnDataReceived(IAsyncResult asyn) { try { int iRx = 0; iRx = clientSocket.EndReceive(asyn); char[] chars = new char[iRx + 1]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); int charLen = d.GetChars(dataBuffer, 0, iRx, chars, 0); String szData = new System.String(chars); if (szData[0].Equals('*')) { if (szData[1].Equals('Q')) { clientSocket.Close(); WaitForConnect(); } else if (szData[1].Equals('R') && manager != null) { manager.ResetControls(); } } else if (manager != null) { string[] controlUpdates = szData.Split(new Char[] { ':' }); foreach (string controlUpdate in controlUpdates) { string[] values = controlUpdate.Split(new Char[] { '=' }); if (values.Count() == 2) { try { int networkID = Convert.ToInt32(values[0]); manager.UpdateControl(networkID, values[1]); } catch (FormatException fe) { TouchPal.Error("Bad network id value (" + values[0] + ") received from client - " + fe.Message); } } } } WaitForData(); } catch (ObjectDisposedException) { WaitForConnect(); } catch (SocketException se) { Console.WriteLine(se.Message); } }
// extract expression tree private static Expression GetExpression(Expression expr, System.Type entityType, System.String propName) { System.Reflection.PropertyInfo[] props = entityType.GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.IgnoreCase | System.Reflection.BindingFlags.Instance); if (propName.Contains('.')) { System.String navEntityName = string.Empty; navEntityName = propName.Split(new char[] { '.' }, 2)[0]; propName = propName.Split(new char[] { '.' }, 2)[1]; System.Type propType = props.Where(p => p.Name == navEntityName).First().PropertyType; return(GetExpression(Expression.Property(expr, navEntityName), propType, propName)); } return(Expression.Property(expr, propName)); }
/// <summary> /// Returns the number of words in the given string object. /// </summary> /// <param name="str">A System.String object.</param> /// <returns>The number of words in the given object.</returns> public static int Words(this System.String str) { return(str.Split(new char[] { ' ', '.', '?', '!', ';' }, StringSplitOptions.RemoveEmptyEntries) .Length); }
/// <summary> /// Convert from DICOM format to Common Data Format. /// </summary> /// <param name="dicomFormat">DICOM format.</param> public override void FromDicomFormat(System.String dicomFormat) { // remove any trailing spaces from the name dicomFormat = dicomFormat.TrimEnd(' '); // split the incoming dicom format into the three component groups System.String[] nameComponentGroups = new System.String[3]; nameComponentGroups = dicomFormat.Split('='); // split the first component group into the five components if (nameComponentGroups.Length > 0) { System.String[] nameComponents = new System.String[5]; nameComponents = nameComponentGroups[0].Split('^'); // save the individual components switch (nameComponents.Length) { case 1: _surname = nameComponents[0]; break; case 2: _surname = nameComponents[0]; _firstName = nameComponents[1]; break; case 3: _surname = nameComponents[0]; _firstName = nameComponents[1]; _middleName = nameComponents[2]; break; case 4: _surname = nameComponents[0]; _firstName = nameComponents[1]; _middleName = nameComponents[2]; _prefix = nameComponents[3]; break; case 5: _surname = nameComponents[0]; _firstName = nameComponents[1]; _middleName = nameComponents[2]; _prefix = nameComponents[3]; _suffix = nameComponents[4]; break; default: break; } } }
// this the call back function which will be invoked when the socket // detects any client writing of data on the stream public void OnDataReceived(IAsyncResult asyn) { try { int iRx = 0; // Complete the BeginReceive() asynchronous call by EndReceive() method // which will return the number of characters written to the stream // by the client iRx = socket.EndReceive(asyn); if (iRx == 0) { // it seems client died parent.RemoveClient(id); return; } char[] chars = new char[iRx]; System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder(); d.GetChars(dataBuffer, 0, iRx, chars, 0); System.String data = new System.String(chars); string[] separators = new string[] { XRefresh.Server.SEPARATOR }; string[] messages = data.Split(separators, StringSplitOptions.None); messages[0] = this.reminder + messages[0]; // TODO: this is wrong, reminder should be extracted before decoding (bug case: packet fragmentation in the middle of UTF8 multichar code sequence) for (int i = 0; i < messages.Length - 1; i++) { string messageJson = messages[i]; messageJson = messageJson.Replace("\0", ""); // HACK to get rid of \0 bytes ClientMessage message = JsonConvert.DeserializeObject <ClientMessage>(messageJson); ProcessMessage(message); } this.reminder = messages[messages.Length - 1]; // continue the waiting for data on the Socket WaitForData(); } catch (ObjectDisposedException e) { Utils.LogException(GetClientFriendlyName() + " closed socket without notice.", e); parent.RemoveClient(id); // TODO: ? } catch (SocketException e) { // fire exception when browser crashed Utils.LogException(GetClientFriendlyName() + " died without saying goodbye (crashed?)", e); parent.RemoveClient(id); // TODO: ? } catch (Exception e) { Utils.LogException(GetClientFriendlyName() + " thrown exception", e); parent.RemoveClient(id); // TODO: ? } }
public MetaInfo(System.String Data) { System.String[] Lines = Data.Split(new System.Char[] { '\n' }); foreach (System.String Line in Lines) { System.String[] Opts = Line.Split(new System.Char[] { '=' }); switch (Opts[0].ToLower()) { case "station": this._Station = Opts[1]; break; case "artist": this._Artist = Opts[1]; break; case "track": this._Track = Opts[1]; break; case "album": this._Album = Opts[1]; break; case "albumcover_small": this._AlbumcoverSmall = Opts[1]; break; case "albumcover_medium": this._AlbumcoverMedium = Opts[1]; break; case "albumcover_large": this._AlbumcoverLarge = Opts[1]; break; case "trackduration": this._Trackduration = Opts[1]; break; case "trackprogress": this._Trackprogress = Opts[1]; break; case "streaming": if (Opts[1].ToLower() == "false") { } break; } } }