public void TryPrint(string zplCommands) { try { // Open connection System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(this.m_IPAddress, this.m_Port); // Write ZPL String to connection System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()); writer.Write(zplCommands); writer.Flush(); // Close Connection writer.Close(); client.Close(); } catch (Exception ex) { this.m_ErrorCount += 1; if(this.m_ErrorCount < 10) { System.Threading.Thread.Sleep(5000); this.TryPrint(zplCommands); } else { throw ex; } } }
public void BuildDungeon() { RDG.Dungeon dungeon = new RDG.Dungeon(80, 80, 80); System.IO.StreamWriter fout = new System.IO.StreamWriter("C:\\Test.txt"); List<RDG.Room> roomList; for (int r = 0; r < dungeon.Height; r++) { for (int c = 0; c < dungeon.Height; c++) { RDG.Dungeon.Coordinates coords = new RDG.Dungeon.Coordinates(r,c); if (dungeon.Map.TryGetValue(coords, out roomList)) { fout.Write(roomList.Count); } else { fout.Write("0"); } } fout.WriteLine(); } fout.Flush(); fout.Close(); }
/// <summary> <p>Creates source code for a Group and returns a GroupDef object that /// describes the Group's name, optionality, repeatability. The source /// code is written under the given directory.</p> /// <p>The structures list may contain [] and {} pairs representing /// nested groups and their optionality and repeastability. In these cases /// this method is called recursively.</p> /// <p>If the given structures list begins and ends with repetition and/or /// optionality markers the repetition and optionality of the returned /// GroupDef are set accordingly.</p> /// </summary> /// <param name="structures">a list of the structures that comprise this group - must /// be at least 2 long /// </param> /// <param name="baseDirectory">the directory to which files should be written /// </param> /// <param name="message">the message to which this group belongs /// </param> /// <throws> HL7Exception if the repetition and optionality markers are not </throws> /// <summary> properly nested. /// </summary> public static NuGenGroupDef writeGroup(NuGenStructureDef[] structures, System.String groupName, System.String baseDirectory, System.String version, System.String message) { //make base directory if (!(baseDirectory.EndsWith("\\") || baseDirectory.EndsWith("/"))) { baseDirectory = baseDirectory + "/"; } System.IO.FileInfo targetDir = NuGenSourceGenerator.makeDirectory(baseDirectory + NuGenSourceGenerator.getVersionPackagePath(version) + "group"); NuGenGroupDef group = getGroupDef(structures, groupName, baseDirectory, version, message); System.IO.StreamWriter out_Renamed = new System.IO.StreamWriter(new System.IO.StreamWriter(targetDir.FullName + "/" + group.Name + ".java", false, System.Text.Encoding.Default).BaseStream, new System.IO.StreamWriter(targetDir.FullName + "/" + group.Name + ".java", false, System.Text.Encoding.Default).Encoding); out_Renamed.Write(makePreamble(group, version)); out_Renamed.Write(makeConstructor(group, version)); NuGenStructureDef[] shallow = group.Structures; for (int i = 0; i < shallow.Length; i++) { out_Renamed.Write(makeAccessor(group, i)); } out_Renamed.Write("}\r\n"); out_Renamed.Flush(); out_Renamed.Close(); return group; }
internal void GetConfig() { lb0: ; if (System.IO.File.Exists(Environment.CurrentDirectory + "\\config.cfg")) { StringBuilder sb = new StringBuilder(1024); GetPrivateProfileString("mssql", "server", "", sb, sb.MaxCapacity, Environment.CurrentDirectory + "\\config.cfg"); ; datasource = sb.ToString(); sb.Clear(); GetPrivateProfileString("mssql", "user", "", sb, sb.MaxCapacity, Environment.CurrentDirectory + "\\config.cfg"); ; userid = sb.ToString(); sb.Clear(); GetPrivateProfileString("mssql", "password", "", sb, sb.MaxCapacity, Environment.CurrentDirectory + "\\config.cfg"); ; password = sb.ToString(); sb.Clear(); } else { System.IO.StreamWriter sw = new System.IO.StreamWriter(Environment.CurrentDirectory + "\\config.cfg", true); sw.Write("[MSSQL]" + Environment.NewLine); sw.Write("server=(local)" + Environment.NewLine); sw.Write("user=sa" + Environment.NewLine); sw.Write("password=" + Environment.NewLine); sw.Close(); goto lb0; } }
// Export to file public void updateInventory(List<List<string>> lst) { inventory = lst; String directory = Environment.CurrentDirectory + "\\productInventory.txt"; System.IO.StreamWriter file2 = new System.IO.StreamWriter(directory); foreach(List<String> lt in inventory) { //prodId file2.Write("{0},", lt[0]); //product name for (int i = 3; i < lt.Count; i++) { if(i == lt.Count - 1) { file2.Write(lt[i]); } else { file2.Write(lt[i] + " "); } } //amount and cost file2.Write(",{0},{1}", lt[1], lt[2]); file2.WriteLine(); } file2.Close(); }
public void WriteToFile() { using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\capstone\output.nex")) { file.WriteLine("#NEXUS"); file.WriteLine("BEGIN TAXA;"); file.WriteLine("Dimensions NTax=" + nexusOb.T.taxa.Count); file.Write("TaxLabels "); foreach (string taxon in nexusOb.T.taxa) { file.Write(taxon + " "); } file.WriteLine(); file.WriteLine("END;"); file.WriteLine("BEGIN CHARACTERS;"); file.WriteLine(@"DIMENSIONS NChar="""); file.WriteLine("MATRIX"); foreach (Sequence s in App.f.C.sequences) { file.WriteLine(s.name + " " + s.characters); } file.WriteLine(";"); file.WriteLine("END;"); } }
static void Main(string[] args) { string nombreFichero = "log_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".txt"; Process[] procesos = null; string wanted = "java"; using (System.IO.StreamWriter fichero = new System.IO.StreamWriter(nombreFichero)) { fichero.WriteLine("=========================================================================================="); fichero.WriteLine("=========================================================================================="); fichero.WriteLine("Fecha y hora de inicio: " + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")); fichero.WriteLine(""); fichero.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tObteniendo listado de procesos."); procesos = Process.GetProcesses(); fichero.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tListado de procesos obtenido."); fichero.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tProceso a buscar: " + wanted); foreach (Process proceso in procesos) { if (proceso.ProcessName.ToLower() == wanted) { fichero.Write(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tProceso " + wanted + " ("+ proceso.Id +") encontrado..."); Process p = Process.GetProcessById(proceso.Id); p.Kill(); fichero.Write(" eliminado.\n"); } } fichero.WriteLine(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "\t\tBúsqueda finalizada."); } }
static void Main(string[] args) { double start = -4; double end = 6; double factor = 65535 / Math.Exp(end); int steps = 100; double step = (end - start) / (steps - 1); int i; int value; System.IO.StreamWriter file = new System.IO.StreamWriter(@"logvec.h"); System.IO.StreamWriter file2 = new System.IO.StreamWriter(@"logvec.txt"); file.Write("static const int logvec[] = { 0x0000,"); for (i = 0; i < 100; i++) { if ((i % 10) == 0) { file.WriteLine(); file.Write("\t"); } value = (int)Math.Floor(Math.Exp(start) * factor); start += step; file2.Write("{0}, ", value); file.Write ("0x{0:X4}, ", value); } file.WriteLine(); file.WriteLine("};"); file.Close(); file2.Close(); }
public void Save(string filename) { //@todo validatoin System.IO.StreamWriter writer = new System.IO.StreamWriter(filename, false, Encoding.ASCII); writer.WriteLine("TITLE " + Title); writer.WriteLine(""); writer.WriteLine("LUT_3D_SIZE " + Dimension.ToString()); writer.WriteLine("DOMAIN_MIN 0.0 0.0 0.0"); writer.WriteLine("DOMAIN_MAX 1.0 1.0 1.0"); writer.WriteLine(""); for (int b = 0; b < Dimension; b++) for (int g = 0; g < Dimension; g++) for (int r = 0; r < Dimension; r++) { writer.Write(string.Format("{0:0.00000}", red[r, g, b])); writer.Write("\t"); writer.Write(string.Format("{0:0.00000}", green[r, g, b])); writer.Write("\t"); writer.Write(string.Format("{0:0.00000}", blue[r, g, b])); writer.WriteLine(""); } writer.Flush(); writer.Close(); }
public static void FlowStatics() { System.IO.StreamWriter sw = new System.IO.StreamWriter("log.txt", false); DataClasses1DataContext mydb = new DataClasses1DataContext(common.connString); var message = mydb.LA_update1.Select(e => e.ip_version_MsgType).Distinct(); Dictionary<string, int> myDic = new Dictionary<string, int>(); foreach (string m in message) { myDic.Add(m, 0); Console.Write(m + "--------------------"); Console.WriteLine(0); sw.Write(m + "--------------------"); sw.WriteLine(0); } sw.Flush(); List<string> startmessage = new List<string>(); startmessage.Add("DTAP MM.Location Updating Request"); startmessage.Add("DTAP MM.CM Service Request"); startmessage.Add("DTAP RR.Paging Response"); startmessage.Add("BSSMAP.Handover Request"); foreach (var start in startmessage) { Dictionary<string, int> newDic = new Dictionary<string, int>(); foreach (KeyValuePair<string, int> pair in myDic) newDic.Add(pair.Key, 0); var a = from p in mydb.LA_update1 where p.ip_version_MsgType == start select p.opcdpcsccp; foreach (var b in a) { foreach (KeyValuePair<string, int> kvp in myDic) { var c = mydb.LA_update1.Where(e => e.opcdpcsccp == b).Where(e => e.ip_version_MsgType == kvp.Key).FirstOrDefault(); if (c != null) newDic[kvp.Key] = newDic[kvp.Key] + 1; } } foreach (var m in newDic.OrderByDescending(e => e.Value)) { Console.Write(m.Key+"--------------------"); Console.WriteLine(m.Value); sw.Write(m.Key + "--------------------"); sw.WriteLine(m.Value); } sw.Flush(); } sw.Close(); }
private void button1_Click(object sender, EventArgs e) { OpenFileDialog o = new OpenFileDialog(); o.ShowDialog(); int p = o.FileName.IndexOf('.'); char[] OutputFilename = new char[o.FileName.Length + 1]; o.FileName.CopyTo(0, OutputFilename, 0, o.FileName.Length - 1); OutputFilename[o.FileName.Length-3] = 'h'; OutputFilename[o.FileName.Length-2] = 'e'; OutputFilename[o.FileName.Length-1] = 'x'; string strOutputFilename = new string(OutputFilename, 0, OutputFilename.Length - 1); System.IO.TextWriter f = new System.IO.StreamWriter(strOutputFilename); System.Drawing.Bitmap bmp = new Bitmap(o.FileName); int r = 0; int c = 0; while (r < bmp.Height) { c = 0; while (c < bmp.Width) { Color rgb = bmp.GetPixel(c, r); /* First character (:) = Start of a record Next two characters = Record length (in this example, 10h) Next four characters = Load address (in this example, 0080h) Next two characters = Record type Remaining characters = Actual data Last two characters = Checksum (i.e., sum of all bytes + checksum = 00) */ int RecordLength = 2; int RecordType = 0; float oatR = ((float)rgb.R )/ 32, oatG = ((float)rgb.G )/ 32, oatB = ((float)rgb.B )/ 32; int intR = (int)oatR + ((oatR - (int)oatR) >= .5 ? 1 : 0), intG = (int)oatG + ((oatG - (int)oatG) >= .5 ? 1 : 0), intB = (int)oatB + ((oatB - (int)oatB) >= .5 ? 1 : 0); intR = intR > 7 ? 7 : intR; intG = intG > 7 ? 7 : intG; intB = intB > 7 ? 7 : intB; int Data = ( (intR << 6) | ( (intG & 7) << 3) | (intB & 7)); int LoadAddress = c + bmp.Width * r; int Checksum = (256 - (RecordLength + (LoadAddress >> 8) + (LoadAddress & 255) + RecordType + (Data >> 8) + Data & 255)) & 0xFF; string strRecordLength = String.Format("{0:X2}", RecordLength), strLoadAddress = String.Format("{0:X4}", LoadAddress), strRecordType = String.Format("{0:X2}", RecordType), strData = String.Format("{0:X4}", Data), strChecksum = String.Format("{0:X2}", Checksum); f.Write(":" + strRecordLength + strLoadAddress + strRecordType + strData + strChecksum + "\n"); ++c; } ++r; } f.Write(":00000001FF"); f.Close(); }
public void escribir_arbol() { escribir = new System.IO.StreamWriter("C:\\Practica1\\ast.dot"); escribir.Write("digraph ast{\n"); graficar_arbol(root); escribir.Write("\n}"); escribir.Close(); generar_arbol(); }
public static void ExportFilteredDataTableToCsv(DataTable targetDataTable, string targetFilePath, string filterString) { using (System.IO.StreamWriter outFile = new System.IO.StreamWriter(targetFilePath, false, Encoding.UTF8)) { for (int i = 0; i < targetDataTable.Columns.Count; i++) { outFile.Write("\""); outFile.Write(targetDataTable.Columns[i].ColumnName.Replace("\"", "\"\"")); outFile.Write("\""); outFile.Write(i == targetDataTable.Columns.Count - 1 ? Environment.NewLine : ","); } foreach (DataRow row in targetDataTable.Select(filterString)) { for (int i = 0; i < targetDataTable.Columns.Count; i++) { outFile.Write("\""); if (targetDataTable.Columns[i].DataType.Equals(typeof(DateTime))) outFile.Write(FormatDateFullTimeStamp((DateTime)row[i])); else outFile.Write(row[i].ToString().Replace("\"", "\"\"")); outFile.Write("\""); outFile.Write(i == targetDataTable.Columns.Count - 1 ? Environment.NewLine : ","); } } } }
public void ExportStudyToCSVOneFile(DatabaseControl db, Study study, string filename) { string header = "StudyName,SubjectID,SessionName,SessionDate,TrialName,SessionSync1.Onset,SessionSync1.Offset,SessionSync2.Onset,SessionSync2.Offset,"; for (int i = 0; i < 15; i++) { header += string.Format("Sensor{0}.ID,Sensor{0}.Time,Sensor{0}.Switch,Sensor{0}.X,Sensor{0}.Y,Sensor{0}.Z,Sensor{0}.Pitch,Sensor{0}.Roll,Sensor{0}.Yaw,Sensor{0}.quality,", i); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(@filename)) { file.Write(header + "\n"); foreach (Subject sub in db.GetSubjects(study)) { foreach (Session sess in db.GetSessions(sub)) { foreach (Trial trial in db.GetTrials(sess)) { Console.WriteLine("Dumping trial : " + trial.name); status = string.Format("{0} - {1} - {2} - {3}", study.name, sub.id, sess.name, trial.name); int total = db.GetSensorReadings(trial).Count(); int count = 0; foreach (SensorReading pt in db.GetSensorReadings(trial)) { count++; percent = Convert.ToInt32(Math.Ceiling((float)count / (float)total * 100.0)); Sensor[] sensors = pt.sensors; // Append study/sub/sess/trial data file.Write(string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", study.name, sub.id, sess.name, sess.tdate, trial.name, sess.sync1_on, sess.sync1_off, sess.sync2_on, sess.sync2_off)); for (int i = 0; i < sensors.Length; i++) { if (sensors[i].active == 1) { // Append sensor data whether sensor is active or not file.Write(string.Format(",{0},{9},{1},{2:0.00},{3:0.00},{4:0.00},{5:0.00},{6:0.00},{7:0.00},{8}", i, sensors[i].button, sensors[i].x, sensors[i].y, sensors[i].z, sensors[i].pitch, sensors[i].roll, sensors[i].yaw, sensors[i].quality, sensors[i].time)); } else { // If the sensor wasn't active then append a blank filler file.Write(",,,,,,,,,,"); } } file.Write("\n"); } percent = 0; } } } } }
public void writeDataAndHeaderIntoFile(string fileName) { using (System.IO.StreamWriter writeFile = new System.IO.StreamWriter(fileName)) { int totalRows = Math.Max(fileData[0].data.Length + 1,headerStrings.Length); for (int i = 0; i < totalRows; i++) { //write header columns if (i <= headerStrings.GetUpperBound(0)) { writeFile.Write(headerStrings[i]); writeFile.Write(","); } else { writeFile.Write(",,"); } //write data if (i == 0) { foreach (singleColData sCol in fileData) { writeFile.Write(sCol.name); writeFile.Write(","); } } else { foreach (singleColData sCol in fileData) { //Write data if the index is still within the array length if ((i - 1) < sCol.data.Length) { double temp = sCol.data[i - 1]; if (temp <= 10000 || temp >= 0.001) { writeFile.Write(temp.ToString("G")); writeFile.Write(","); } else { writeFile.Write(temp.ToString("E")); writeFile.Write(","); } } } } writeFile.WriteLine(); } } }
public void createProblem() { int[][] problem_list = new int[output_num][]; Console.Write(file_name + ":" + output_num + "\r"); for(int i = 0; i < output_num; i++) { int[] problem = new int[64]; for (int j = 0; j < 64; j++) { problem[j] = r.Next(1, 9); } bool isEqual = false; for(int j = 0; j < i; j++) { isEqual = problem_list[j].SequenceEqual(problem); } if (isEqual) { i--; continue; } else { problem_list[i] = problem; } } // ここに問題検査関数を書く try { using (var sw = new System.IO.StreamWriter(file_name + ".csv", false)) { foreach(int[] prob in problem_list) { for(int i = 0; i < 63; i++) { sw.Write(prob[i] + ","); } sw.Write(prob[63] + "\n"); } } } catch (System.Exception e) { System.Console.WriteLine(e.Message); } }
public void SaveData() { var writer = new System.IO.StreamWriter("data.txt"); writer.Write("@ This file was generated by the Leave Wizard. Modifying this file could cause loss of data. @\n"); for (var i = 0; i < Weeks.Count; ++i) { if (String.IsNullOrEmpty(Weeks[i].EffectiveChanges)) continue; writer.Write(i); writer.Write(" "); writer.Write(Weeks[i].EffectiveChanges); writer.WriteLine(";"); } writer.Close(); }
public GistViewableFileViewModel(IApplicationService applicationService, IFilesystemService filesystemService) { GoToFileSourceCommand = ReactiveCommand.Create(); LoadCommand = ReactiveCommand.CreateAsyncTask(async t => { string data; using (var ms = new System.IO.MemoryStream()) { await applicationService.Client.DownloadRawResource(GistFile.RawUrl, ms); ms.Position = 0; var sr = new System.IO.StreamReader(ms); data = sr.ReadToEnd(); } if (GistFile.Language.Equals("Markdown")) data = await applicationService.Client.Markdown.GetMarkdown(data); string path; using (var stream = filesystemService.CreateTempFile(out path, "gist.html")) { using (var fs = new System.IO.StreamWriter(stream)) { fs.Write(data); } } FilePath = path; }); }
/// <summary> /// 将字符串写入文本文件 /// </summary> /// <param name="str">需要写入文本文件的字符串</param> public void Write(string str) { System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\WCF_Log_Reliable.txt", true); sw.Write(str); sw.WriteLine(); sw.Close(); }
public void Save(System.IO.Stream s) { using (var w = new System.IO.StreamWriter(s)) { w.Write(Newtonsoft.Json.JsonConvert.SerializeObject(this, JSS)); } }
/// <summary> /// 创建rdlc的Report /// </summary> /// <param name="documentName"></param> /// <returns></returns> public static string CreateMsReportFile(string documentName) { if (System.IO.File.Exists(documentName)) { return documentName; } else { ResourceContent data = ResourceInfoHelper.ResolveResource(documentName, ResourceType.MsReport); if (data != null) { switch (data.Type) { case ResourceContentType.File: return data.Content.ToString(); case ResourceContentType.Binary: string fileName = System.IO.Path.GetTempFileName(); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName, false)) { sw.Write(data); } return fileName; default: throw new ArgumentException("Invalid Resource Content Type!"); } } else { throw new ArgumentException(string.Format("Can't find resouce of {0}!", documentName)); } } }
static int Main(string[] args) #endif { Type type = null; System.Text.StringBuilder code = new StringBuilder (); try { //if (args.Length >= 1 && args [0].ToLower () == "all") { // if (args.Length == 1) { // GenerateAll (); // return 0; // } else if (args.Length == 2) { // GenerateAll (args [1], false); // return 0; // } //} if (args.Length != 2 && args.Length != 3) { Console.WriteLine("Must supply at least two arguments: "); Console.WriteLine("\t Type to log ('all' to log all overrides and events for all types in System.Windows.Forms.dll)"); Console.WriteLine("\t What to log [overrides|events|overridesevents]"); Console.WriteLine("\t [output filename]"); return 1; } Assembly a = typeof(System.Windows.Forms.Control).Assembly; type = a.GetType (args [0]); if (type == null) throw new Exception (String.Format("Type '{0}' not found.", args[0])); code.Append ("// Automatically generated for assembly: " + a.FullName + Environment.NewLine); code.Append ("// To regenerate:" + Environment.NewLine); code.Append ("// mcs -r:System.Windows.Forms.dll LogGenerator.cs && mono LogGenerator.exe " + type.FullName + " " + args [1] + " " + (args.Length > 2 ? args [2] : " outfile.cs") + Environment.NewLine); if (args[1] == "overrides" || args[1] == "overridesevents") { code.Append (override_logger.GenerateLog (type)); } if (args[1] == "events" || args[1] == "overridesevents") { code.Append (event_logger.GenerateLog (type)); } if (args.Length > 2) { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(args[2], false)) { writer.Write(code); } } else { Console.WriteLine(code); } return 0; } catch (Exception ex) { Console.WriteLine (ex.Message); Console.WriteLine (ex.StackTrace); return 1; } }
public string AddMessagesToQueue(string qName, string oauthToken, string projectId, AddMessageReqPayload addMessageReqPayload) { string uri = string.Format("https://mq-aws-us-east-1.iron.io/1/projects/{0}/queues/{1}", projectId, qName); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.ContentType = "application/json"; request.Headers.Add("Authorization", "OAuth " + oauthToken); request.UserAgent = "IronMQ .Net Client"; request.Method = "POST"; var body = JsonConvert.SerializeObject(addMessageReqPayload); if (body != null) { using (System.IO.StreamWriter write = new System.IO.StreamWriter(request.GetRequestStream())) { write.Write(body); write.Flush(); } } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); string resultVal = "error"; using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream())) { resultVal = reader.ReadToEnd(); } return resultVal; }
/// <summary> /// Prends en parametres le nom et une chaine de caracteres /// Ecrit la chaine de caracteres dans le fichier /// Cree le fichier si il n'existe pas /// </summary> /// <param name="name">Nom du fichier</param> /// <param name="content">Contenu du fichier</param> public static void writeFile(string name, string content) { try { System.IO.StreamWriter outstream = new System.IO.StreamWriter(name); outstream.Write(content); outstream.Close(); } catch (System.IO.DirectoryNotFoundException) { try { System.IO.Directory.CreateDirectory(name); System.IO.Directory.Delete(name); writeFile(name, content); } catch (Exception) { Console.WriteLine("FileStream.writeFile : Erreur lors de la creation du repertoire " + name); } } catch (Exception) { Console.WriteLine("FileStream.writeFile : Erreur lors de l'ecriture dans le fichier " + name); } }
public MessageCreateSuccess CreateIronMQ(string qName, string oauthToken, string projectId) { string uri = string.Format("https://mq-aws-us-east-1.iron.io/1/projects/{0}/queues/{1}", projectId, qName); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.ContentType = "application/json"; request.Headers.Add("Authorization", "OAuth " + oauthToken); request.UserAgent = "IronMQ .Net Client"; request.Method = "POST"; //string body = "{\"push_type\": \"multicast\",\"subscribers\": null}"; MsgQRequestBody body = new MsgQRequestBody(); body.push_type = "multicast"; body.subscribers = null; var bodyStr = JsonConvert.SerializeObject(body); if (bodyStr != null) { using (System.IO.StreamWriter write = new System.IO.StreamWriter(request.GetRequestStream())) { write.Write(bodyStr); write.Flush(); } } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream())) { //return reader.ReadToEnd(); return JsonConvert.DeserializeObject<MessageCreateSuccess>(reader.ReadToEnd()); } }
public static void SaveObjList() { using (var sw = new System.IO.StreamWriter("HerbCache.xml")) { sw.Write(ObjList.ToXml()); } }
private static void SaveResultantXml(string resultantFilename, string resultantXML) { using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(resultantFilename)) { streamWriter.Write(resultantXML); } }
}/* script_new_line */ /* * script_char * * Write a single character to the transscript file. * */ internal static void ScriptChar(zword c) { if (c == CharCodes.ZC_INDENT && ScriptWidth != 0) { c = ' '; } if (c == CharCodes.ZC_INDENT) { ScriptChar(' '); ScriptChar(' '); ScriptChar(' '); return; } if (c == CharCodes.ZC_GAP) { ScriptChar(' '); ScriptChar(' '); return; } if (c > 0xff) { ScriptChar('?'); return; } Sfp?.Write((char)c); ScriptWidth++; }/* script_char */
public static void Error() { IntPtr ptr; Assert.Throws<Exception>(() => DynamicLibrary.Open("NOT_EXISTING")); string failure = "FAILURE"; var fs = new System.IO.StreamWriter(System.IO.File.OpenWrite(failure)); fs.Write("foobar"); fs.Close(); Assert.IsTrue(System.IO.File.Exists(failure)); Assert.Throws<Exception>(() => DynamicLibrary.Open(failure)); System.IO.File.Delete(failure); var dl = DynamicLibrary.Open(DynamicLibrary.Decorate("uv")); Assert.IsTrue(dl.TryGetSymbol("uv_default_loop", out ptr)); Assert.AreNotEqual(ptr, IntPtr.Zero); Assert.IsFalse(dl.TryGetSymbol("NOT_EXISTING", out ptr)); Assert.AreEqual(ptr, IntPtr.Zero); Assert.Throws<Exception>(() => dl.GetSymbol("NOT_EXISTING")); Assert.IsFalse(dl.Closed); dl.Close(); Assert.IsTrue(dl.Closed); }
private void ButtonPhoto_Click(object sender, EventArgs e) { var flickr = new Flickr(Program.ApiKey, Program.SharedSecret, Program.AuthToken); // Referrers DateTime day = DateTime.Today; var statfile = new System.IO.StreamWriter("stats_dom.csv"); var reffile = new System.IO.StreamWriter("stats_referrers.csv"); while (day > Program.LastUpdate) { try { var s = flickr.StatsGetPhotoDomains(day, 1, 100); day -= TimeSpan.FromDays(1); StatusLabel.Text = "Chargement des domaines " + day.ToShortDateString(); Application.DoEvents(); statfile.Write(Utility.toCSV(s, day.ToShortDateString())); foreach (StatDomain dom in s) { var r = flickr.StatsGetPhotoReferrers(day, dom.Name, 1, 100); reffile.Write(Utility.toCSV(r, day.ToShortDateString() + ";" + dom.Name)); } } catch (FlickrApiException ex) { MessageBox.Show("Erreur lors du chargement des domaines référents du " + day.ToShortDateString() + " : " + ex.OriginalMessage, "Erreur", MessageBoxButtons.OK); break; } } statfile.Close(); }
private void SaveBtn_Click(object sender, EventArgs e) { string path = pathText.Text; if (path.Length < 1 || path.Trim().Length < 1) { MessageBox.Show("Invalid path name.", "Invalid path"); return; } foreach (char c in System.IO.Path.GetInvalidFileNameChars()) { if (path.Contains(c)) { MessageBox.Show("Invalid character '" + c + "' in file path.", "Invalid path"); return; } } if (!System.IO.Path.HasExtension(path)) path += ".lua"; if (!overwriteCheckBox.Checked && System.IO.File.Exists(path)) { MessageBox.Show("File '" + path + "' already exists.", "File already exists"); return; } string lua = Derma.GenerateLua(); System.IO.TextWriter file = new System.IO.StreamWriter(path); file.Write(lua); file.Close(); MessageBox.Show("Lua generated to file '" + path + "'.", "Success"); this.Close(); }
private void BtnFTP_Click(object sender, EventArgs e) { //GENERAR ARCHIVO try { con.conectar("DM"); SqlDataAdapter da = new SqlDataAdapter("[CORRECT].[KC_EXPORTADOR]", con.condm); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.Add("@FINI", SqlDbType.DateTime); da.SelectCommand.Parameters.Add("@FFIN", SqlDbType.DateTime); //Calcular inicio de Mes los primeros 5 dias toma tambien los ultimos 5 dias del mes anterior int diaini = 0; if (DateTime.Today.Day <= 5) { diaini = (DateTime.Today.Day + 5) * -1; } else { diaini = (DateTime.Today.Day - 1) * -1; } da.SelectCommand.Parameters["@FINI"].Value = Convert.ToDateTime(DateTime.Today.AddDays(diaini)); da.SelectCommand.Parameters["@FFIN"].Value = Convert.ToDateTime(DateTime.Today); KC.Clear(); da.Fill(KC); con.Desconectar("DM"); } catch (Exception ex) { MessageBox.Show("No se Pudo conectar a la BD Error: " + ex.Message); } StringBuilder csvMemoria = new StringBuilder(); for (int m = 0; m < KC.Rows.Count; m++) { int x = KC.Rows.Count; for (int n = 0; n < KC.Columns.Count; n++) { //si es la última columna no poner el | if (n == KC.Columns.Count - 1) { csvMemoria.Append(String.Format("{0}", KC.Rows[m].ItemArray[n].ToString().Trim())); } else { if (KC.Rows[m].ItemArray[n].GetType() == Type.GetType("System.DateTime")) { csvMemoria.Append(String.Format("{0}|", KC.Rows[m].ItemArray[n].ToString().Substring(0, 10))); } else { if (KC.Rows[m].ItemArray[n].GetType() == Type.GetType("System.Decimal")) { if (KC.Columns[n].Caption.Equals("LONGITUD") || KC.Columns[n].Caption.Equals("LATITUD")) { csvMemoria.Append(String.Format("{0}|", KC.Rows[m].ItemArray[n].ToString().Trim())); } else { csvMemoria.Append(String.Format("{0}|", Math.Round(Convert.ToDecimal(KC.Rows[m].ItemArray[n]), 3).ToString())); } } else { csvMemoria.Append(String.Format("{0}|", KC.Rows[m].ItemArray[n].ToString().Trim())); } } } } csvMemoria.AppendLine(); } //Fecha en formato ddmmyyyy string NArchivo; NArchivo = DateTime.Today.Day.ToString().PadLeft(2, '0') + DateTime.Today.Month.ToString().PadLeft(2, '0') + DateTime.Today.Year.ToString(); string NomredelTXT; NomredelTXT = NArchivo + ".txt"; System.IO.StreamWriter sw = new System.IO.StreamWriter(@"C:\CORRECT\DatosKC" + NomredelTXT, false, System.Text.Encoding.Default); sw.Write(csvMemoria.ToString()); sw.Close(); //CARGAR AL FTP /* Create Object Instance */ ftp ftpClient = new ftp(@"ftp://dt.kcmkt.com/", "*****@*****.**", "Clave1"); /* Upload a File */ ftpClient.upload("/DatosKC" + NomredelTXT, @"C:\CORRECT\DatosKC" + NomredelTXT); MessageBox.Show("Carga Completa"); }
private void Generar_Click(object sender, EventArgs e) { try { con.conectar("DM"); SqlDataAdapter da = new SqlDataAdapter("[CORRECT].[KC_EXPORTADOR]", con.condm); da.SelectCommand.CommandType = CommandType.StoredProcedure; da.SelectCommand.Parameters.Add("@FINI", SqlDbType.DateTime); da.SelectCommand.Parameters.Add("@FFIN", SqlDbType.DateTime); da.SelectCommand.Parameters["@FINI"].Value = Convert.ToDateTime(FechaIni.Value.ToShortDateString()); da.SelectCommand.Parameters["@FFIN"].Value = Convert.ToDateTime(FechaFin.Value.ToShortDateString()); KC.Clear(); da.Fill(KC); this.dataGridView1.DataSource = KC; con.Desconectar("DM"); } catch (Exception ex) { MessageBox.Show("No se Pudo conectar a la BD Error: " + ex.Message); } //Generando Archivo dlGuardar.Filter = "Fichero TXT (*.txt)|*.txt"; dlGuardar.FileName = "DatosKC"; dlGuardar.Title = "Exportar a TxT"; if (dlGuardar.ShowDialog() == DialogResult.OK) { StringBuilder csvMemoria = new StringBuilder(); ////para los títulos de las columnas, encabezado //for (int i = 0; i < dt.Columns.Count; i++) //{ // if (i == dt.Columns.Count - 1) // { // csvMemoria.Append(String.Format("{0}", dt.Columns[i].Caption)); // } // else // { // csvMemoria.Append(String.Format("{0},", dt.Columns[i].Caption)); // } //} // csvMemoria.AppendLine(); // csvMemoria.Append(String.Format("{0}|", dt.Rows[m].ItemArray[n].ToString().Substring(0, dt.Rows[m].ItemArray[n].ToString().Length-4))); this.progressBar1.Value = 0; for (int m = 0; m < KC.Rows.Count; m++) { int x = KC.Rows.Count; this.progressBar1.Increment(Convert.ToInt32((Convert.ToDecimal(m) / Convert.ToDecimal(x)) * 100)); for (int n = 0; n < KC.Columns.Count; n++) { //si es la última columna no poner el | if (n == KC.Columns.Count - 1) { csvMemoria.Append(String.Format("{0}", KC.Rows[m].ItemArray[n].ToString().Trim())); } else { if (KC.Rows[m].ItemArray[n].GetType() == Type.GetType("System.DateTime")) { csvMemoria.Append(String.Format("{0}|", KC.Rows[m].ItemArray[n].ToString().Substring(0, 10))); } else { if (KC.Rows[m].ItemArray[n].GetType() == Type.GetType("System.Decimal")) { if (KC.Columns[n].Caption.Equals("LONGITUD") || KC.Columns[n].Caption.Equals("LATITUD")) { csvMemoria.Append(String.Format("{0}|", KC.Rows[m].ItemArray[n].ToString().Trim())); } else { csvMemoria.Append(String.Format("{0}|", Math.Round(Convert.ToDecimal(KC.Rows[m].ItemArray[n]), 3).ToString())); } } else { csvMemoria.Append(String.Format("{0}|", KC.Rows[m].ItemArray[n].ToString().Trim())); } } } } csvMemoria.AppendLine(); } System.IO.StreamWriter sw = new System.IO.StreamWriter(dlGuardar.FileName, false, System.Text.Encoding.Default); sw.Write(csvMemoria.ToString()); sw.Close(); } }
public static string ParseScript(string sScript) { //converts the script to "real" language //some keywords that need special treatment ArrayList aKeywords = new ArrayList(); aKeywords.Add("do"); aKeywords.Add("goto"); aKeywords.Add("waitms"); aKeywords.Add("waitframe"); aKeywords.Add("waitframes"); aKeywords.Add("interpolate"); aKeywords.Add("rwd"); //TODO: generic waitforevent(object, event) //will probably need some boolean stuff, like //waitforevent("object,event" || ("object,event" && "object,event") ) string sThisObjectName = "Flow"; string sNewScript = ""; sScript = sScript.Replace("\r", ""); sScript = sScript + "\n"; bool bLastLineEmpty = true; while (sScript.Length > 0) { int nEOL = sScript.IndexOf("\n"); string sLine = ""; if (nEOL >= 0) { sLine = sScript.Substring(0, nEOL); sScript = sScript.Remove(0, sLine.Length + 1); } else { sLine = sScript; sScript = ""; } sLine = sLine.Trim(); if (sLine.Length == 0) { if (!bLastLineEmpty) { bLastLineEmpty = true; sNewScript += "}\n"; } continue; } if (bLastLineEmpty) { sLine = sLine.Substring(0, sLine.Length - 1); sNewScript += "\non " + sLine + "()\n{\n"; // bLastLineEmpty = false; continue; } if (sLine.StartsWith("//")) { continue; } if (sLine.StartsWith("*")) { sLine = "do defaultCall(" + sLine.Remove(0, 1) + ")"; } //TODO: find which params are used - declare in function header int nRandomOr = sLine.IndexOf("?"); if (nRandomOr >= 0) { ArrayList aRandomExpressions = new ArrayList(); string sRandom = sLine; //first expression before "?" Match m2 = Regex.Match(sRandom, "[( ,][\"\\w]*[?]"); if (m2.Success) { sRandom = sRandom.Remove(0, m2.Index + m2.Length); aRandomExpressions.Add(m2.Value.Substring(1, m2.Length - 2)); sLine = sLine.Substring(0, m2.Index); //following expressions: while (true) { m2 = Regex.Match(sRandom, "[\"\\w]*[?]"); //[ ,]?[\"\\w]*[?] if (!m2.Success) { break; } sRandom = sRandom.Remove(0, m2.Index + m2.Length); aRandomExpressions.Add(m2.Value.Substring(0, m2.Length - 1)); } //final expression m2 = Regex.Match(sRandom, "[\"\\w]*[\\s\\n);]?"); if (m2.Success) { int nEndIndex = m2.Length; if (m2.Value.EndsWith(";")) { nEndIndex--; } aRandomExpressions.Add(m2.Value.Substring(0, nEndIndex)); } } //do x?y translates to: int _rnd = rnd(2); if (_rnd==0) do x; if (_rnd==1) do y; //o.Play("x"?"y"); to: int _rnd = rnd(2); if (_rnd==0) o.Play("x"); if (_rnd==1) do o.Play("y"); string sBlock = "_rnd = rnd(" + aRandomExpressions.Count.ToString() + ")\n"; for (int nRnd = 0; nRnd < aRandomExpressions.Count; nRnd++) { string s = (string)aRandomExpressions[nRnd]; sBlock += "if (_rnd == " + nRnd.ToString() + ") {\n" + sLine + " " + s + "\n}\n"; } sScript = sBlock + sScript; continue; } Match m = Regex.Match(sLine, "\\w+"); //\\w+ \\w*[\\s^.] if (m.Success && sLine.IndexOf("=") < 0 && m.Index == 0) { string sKeyword = m.Value.Trim(); //Remove(m.Length-1,1); if (aKeywords.Contains(sKeyword)) { bool bAddThisObjectName = true; switch (sKeyword) { case "do": case "goto": sLine = sLine.Remove(0, m.Index + m.Length).Trim(); if (sLine.IndexOf("(") == -1) { sLine += "()"; } if (sKeyword == "goto") { sLine = "_goto(" + sLine + ")"; } else { sLine = "this." + sLine; bAddThisObjectName = false; } break; case "start": //TODO: new player: new(); player.PlayLabel("main") break; case "interpolate": //first value is a property: obj.Vol //change that to GetPropertyInfo(obj, Vol) string sArgs = sLine.Remove(0, m.Index + m.Length); string sProp = sArgs.Substring(1, sArgs.IndexOf(",") - 1); sArgs = sArgs.Remove(0, sProp.Length + 2); sArgs = sArgs.Remove(sArgs.Length - 1, 1); //divide sProp into object and property (e.g. o, "pitch") //Note that Property argument is a string. int nLastIndex = sProp.LastIndexOf("."); if (nLastIndex == -1) { throw new Exception("Need an object and a property for interpolate"); } sProp = sProp.Substring(0, nLastIndex) + ", \"" + sProp.Remove(0, nLastIndex + 1) + "\""; //sLine = m.Value+"(GetPropertyInfo("+sProp+"),"+sArgs+")"; sLine = m.Value + "(" + sProp + "," + sArgs + ")"; break; default: sLine = m.Value + "(" + sLine.Remove(0, m.Index + m.Length) + ")"; break; } if (bAddThisObjectName) { //executer should be sent as argument with all these calls int nIndex = sLine.IndexOf("("); sLine = sLine.Insert(nIndex + 1, "_exec, "); sLine = sThisObjectName + "." + sLine; } } } sNewScript += sLine + ";\n"; } System.IO.StreamWriter wr = new System.IO.StreamWriter("script.txt"); wr.Write(sNewScript.Replace("\n", "\r\n")); wr.Flush(); wr.Close(); return(sNewScript); }
private void button1_Click(object sender, EventArgs e) { try { DataTable dt; using (db mydb = new db(cbProviders.SelectedValue.ToString(), cbConnstr.Text)) { mydb.FillSchema = cbSchema.Checked; dt = mydb.ExecuteDataTableSQL(tbSql.Text, null); if (cbSchema.Checked) { foreach (DataColumn dc in dt.Columns) { dc.ColumnName = dc.DataType + "|" + dc.ColumnName + "|"; } } } if (cbSaveToFile.Checked) { if (saveFileDialog1.ShowDialog() != DialogResult.OK) { return; } string filename = saveFileDialog1.FileName; string separator; if (saveFileDialog1.FilterIndex == 1) { separator = ","; // 1=csv } else { separator = "\t"; // 2=tab } using (System.IO.StreamWriter sw = new System.IO.StreamWriter(filename)) { for (int c = 0; c < dt.Columns.Count; c++) { sw.Write((c == 0 ? string.Empty : separator) + dt.Columns[c].ColumnName); } sw.WriteLine(); foreach (DataRow dr in dt.Rows) { for (int c = 0; c < dt.Columns.Count; c++) { sw.Write((c == 0 ? string.Empty : separator) + dr[c]); } sw.WriteLine(); } } } else { dataGridView1.DataSource = null; // Forget column order dataGridView1.DataSource = dt; } this.Text = "SQL Util - Rows: " + dt.Rows.Count + ", Columns: " + dt.Columns.Count; } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.ToString()); } }
private static void UpdateProjectAndSolution(string slnFile, string sourceDir, string targetDir, string[] emptyDirectories) { // NOTE: The logic in this routine counts on unique GUIDS // Open the file and read project System.IO.StreamReader reader = new System.IO.StreamReader(slnFile); System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument(); System.Xml.XmlNodeList nodes; System.IO.StreamWriter writer; string sln = reader.ReadToEnd(); string[] slnLines; string[] sAttr; string[] fileNames = null; string[][] GUIDLookup = null; //System.IO.Stream stream; string sProj; reader.Close(); slnLines = sln.Split('\n'); foreach (string s in slnLines) { if (s.Trim().ToLower().StartsWith("project(")) { if (GUIDLookup == null) { GUIDLookup = new string[1][]; fileNames = new string[1]; } else { string[][] GUIDLookupTemp = new string[GUIDLookup.GetLength(0) + 1][]; GUIDLookup.CopyTo(GUIDLookupTemp, 0); GUIDLookup = GUIDLookupTemp; //ReDim Preserve GUIDLookup( GUIDLookup.GetUpperBound( 0 ) + 1); string[] fileNamesTemp = new string[fileNames.GetLength(0) + 1]; fileNames.CopyTo(fileNamesTemp, 0); fileNames = fileNamesTemp; //ReDim Preserve fileNames( fileNames.GetUpperBound( 0 ) + 1); } sAttr = s.Split(','); // Second position is file, third is GUID with junk after sAttr[2] = sAttr[2].Substring(sAttr[2].IndexOf("{") + 1); sAttr[2] = sAttr[2].Substring(0, sAttr[2].IndexOf("}")); fileNames[fileNames.GetUpperBound(0)] = sAttr[1].Replace("\"", "").Trim(); GUIDLookup[GUIDLookup.GetUpperBound(0)] = new string[] { new Guid(sAttr[2]).ToString(), Guid.NewGuid().ToString() }; } } sln = ReplaceArray(sln, GUIDLookup); slnFile = System.IO.Path.GetFileName(slnFile); writer = new System.IO.StreamWriter(System.IO.Path.Combine(targetDir, slnFile)); writer.Write(sln); writer.Flush(); writer.Close(); foreach (string fileName in fileNames) { reader = new System.IO.StreamReader(System.IO.Path.Combine(System.IO.Path.Combine(sourceDir, System.IO.Path.GetDirectoryName(slnFile)), fileName)); sProj = reader.ReadToEnd(); reader.Close(); sProj = ReplaceArray(sProj, GUIDLookup); writer = new System.IO.StreamWriter(System.IO.Path.Combine(System.IO.Path.Combine(targetDir, System.IO.Path.GetDirectoryName(slnFile)), fileName)); writer.Write(sProj); writer.Flush(); writer.Close(); xmlDoc.Load(System.IO.Path.Combine(System.IO.Path.Combine(targetDir, System.IO.Path.GetDirectoryName(slnFile)), fileName)); foreach (string exclude in emptyDirectories) { nodes = xmlDoc.SelectNodes("//Files/Include/File[starts-with(@RelPath,'" + exclude + "' )]"); foreach (System.Xml.XmlNode node in nodes) { node.ParentNode.RemoveChild(node); } } xmlDoc.Save(System.IO.Path.Combine(System.IO.Path.Combine(targetDir, System.IO.Path.GetDirectoryName(slnFile)), fileName)); } }
private void buttonExtExcel_Click(object sender, EventArgs e) { Forms.ExportForm frm = new Forms.ExportForm(); frm.Init(new string[] { "All", "Stars only", "Planets only", //2 "Exploration List Stars", //3 "Exploration List Planets", //4 "Sold Exploration Data", // 5 }); if (frm.ShowDialog(FindForm()) == DialogResult.OK) { BaseUtils.CSVWrite csv = new BaseUtils.CSVWrite(); csv.SetCSVDelimiter(frm.Comma); try { using (System.IO.StreamWriter writer = new System.IO.StreamWriter(frm.Path)) { if (frm.SelectedIndex == 5) { int count; List <HistoryEntry> data = HistoryList.FilterByJournalEvent(discoveryform.history.ToList(), "Sell Exploration Data", out count); data = (from he in data where he.EventTimeLocal >= frm.StartTime && he.EventTimeLocal <= frm.EndTime orderby he.EventTimeUTC descending select he).ToList(); List <HistoryEntry> scans = HistoryList.FilterByJournalEvent(discoveryform.history.ToList(), "Scan", out count); if (frm.IncludeHeader) { writer.Write(csv.Format("Time")); writer.Write(csv.Format("System")); writer.Write(csv.Format("Star type")); writer.Write(csv.Format("Planet type", false)); writer.WriteLine(); } foreach (HistoryEntry he in data) { JournalSellExplorationData jsed = he.journalEntry as JournalSellExplorationData; if (jsed == null || jsed.Discovered == null) { continue; } foreach (String system in jsed.Discovered) { writer.Write(csv.Format(jsed.EventTimeLocal)); writer.Write(csv.Format(system)); EDStar star = EDStar.Unknown; EDPlanet planet = EDPlanet.Unknown; foreach (HistoryEntry scanhe in scans) { JournalScan scan = scanhe.journalEntry as JournalScan; if (scan.BodyName.Equals(system, StringComparison.OrdinalIgnoreCase)) { star = scan.StarTypeID; planet = scan.PlanetTypeID; break; } } writer.Write(csv.Format((star != EDStar.Unknown) ? Enum.GetName(typeof(EDStar), star) : "")); writer.Write(csv.Format((planet != EDPlanet.Unknown) ? Enum.GetName(typeof(EDPlanet), planet) : "", false)); writer.WriteLine(); } } } else { List <JournalScan> scans = null; if (frm.SelectedIndex < 3) { var entries = JournalEntry.GetByEventType(JournalTypeEnum.Scan, EDCommander.CurrentCmdrID, frm.StartTime, frm.EndTime); scans = entries.ConvertAll(x => (JournalScan)x); } else { ExplorationSetClass currentExplorationSet = new ExplorationSetClass(); string file = currentExplorationSet.DialogLoad(FindForm()); if (file != null) { scans = new List <JournalScan>(); foreach (string system in currentExplorationSet.Systems) { List <long> edsmidlist = SystemClassDB.GetEdsmIdsFromName(system); if (edsmidlist.Count > 0) { for (int ii = 0; ii < edsmidlist.Count; ii++) { List <JournalScan> sysscans = EDSMClass.GetBodiesList((int)edsmidlist[ii]); if (sysscans != null) { scans.AddRange(sysscans); } } } } } else { return; } } bool ShowStars = frm.SelectedIndex < 2 || frm.SelectedIndex == 3; bool ShowPlanets = frm.SelectedIndex == 0 || frm.SelectedIndex == 2 || frm.SelectedIndex == 4; List <JournalSAAScanComplete> mappings = ShowPlanets ? JournalEntry.GetByEventType(JournalTypeEnum.SAAScanComplete, EDCommander.CurrentCmdrID, frm.StartTime, frm.EndTime) .ConvertAll(x => (JournalSAAScanComplete)x) : null; if (frm.IncludeHeader) { // Write header writer.Write(csv.Format("Time")); writer.Write(csv.Format("BodyName")); writer.Write(csv.Format("Estimated Value")); writer.Write(csv.Format("DistanceFromArrivalLS")); if (ShowStars) { writer.Write(csv.Format("StarType")); writer.Write(csv.Format("StellarMass")); writer.Write(csv.Format("AbsoluteMagnitude")); writer.Write(csv.Format("Age MY")); writer.Write(csv.Format("Luminosity")); } writer.Write(csv.Format("Radius")); writer.Write(csv.Format("RotationPeriod")); writer.Write(csv.Format("SurfaceTemperature")); if (ShowPlanets) { writer.Write(csv.Format("TidalLock")); writer.Write(csv.Format("TerraformState")); writer.Write(csv.Format("PlanetClass")); writer.Write(csv.Format("Atmosphere")); writer.Write(csv.Format("Iron")); writer.Write(csv.Format("Silicates")); writer.Write(csv.Format("SulphurDioxide")); writer.Write(csv.Format("CarbonDioxide")); writer.Write(csv.Format("Nitrogen")); writer.Write(csv.Format("Oxygen")); writer.Write(csv.Format("Water")); writer.Write(csv.Format("Argon")); writer.Write(csv.Format("Ammonia")); writer.Write(csv.Format("Methane")); writer.Write(csv.Format("Hydrogen")); writer.Write(csv.Format("Helium")); writer.Write(csv.Format("Volcanism")); writer.Write(csv.Format("SurfaceGravity")); writer.Write(csv.Format("SurfacePressure")); writer.Write(csv.Format("Landable")); writer.Write(csv.Format("EarthMasses")); writer.Write(csv.Format("IcePercent")); writer.Write(csv.Format("RockPercent")); writer.Write(csv.Format("MetalPercent")); } // Common orbital param writer.Write(csv.Format("SemiMajorAxis")); writer.Write(csv.Format("Eccentricity")); writer.Write(csv.Format("OrbitalInclination")); writer.Write(csv.Format("Periapsis")); writer.Write(csv.Format("OrbitalPeriod")); writer.Write(csv.Format("AxialTilt")); if (ShowPlanets) { writer.Write(csv.Format("Carbon")); writer.Write(csv.Format("Iron")); writer.Write(csv.Format("Nickel")); writer.Write(csv.Format("Phosphorus")); writer.Write(csv.Format("Sulphur")); writer.Write(csv.Format("Arsenic")); writer.Write(csv.Format("Chromium")); writer.Write(csv.Format("Germanium")); writer.Write(csv.Format("Manganese")); writer.Write(csv.Format("Selenium")); writer.Write(csv.Format("Vanadium")); writer.Write(csv.Format("Zinc")); writer.Write(csv.Format("Zirconium")); writer.Write(csv.Format("Cadmium")); writer.Write(csv.Format("Mercury")); writer.Write(csv.Format("Molybdenum")); writer.Write(csv.Format("Niobium")); writer.Write(csv.Format("Tin")); writer.Write(csv.Format("Tungsten")); writer.Write(csv.Format("Antimony")); writer.Write(csv.Format("Polonium")); writer.Write(csv.Format("Ruthenium")); writer.Write(csv.Format("Technetium")); writer.Write(csv.Format("Tellurium")); writer.Write(csv.Format("Yttrium")); } writer.WriteLine(); } foreach (JournalScan je in scans) { JournalScan scan = je as JournalScan; if (ShowPlanets == false) // Then only show stars. { if (String.IsNullOrEmpty(scan.StarType)) { continue; } } if (ShowStars == false) // Then only show planets { if (String.IsNullOrEmpty(scan.PlanetClass)) { continue; } } writer.Write(csv.Format(scan.EventTimeUTC)); writer.Write(csv.Format(scan.BodyName)); writer.Write(csv.Format(scan.EstimatedValue)); writer.Write(csv.Format(scan.DistanceFromArrivalLS)); if (ShowStars) { writer.Write(csv.Format(scan.StarType)); writer.Write(csv.Format((scan.nStellarMass.HasValue) ? scan.nStellarMass.Value : 0)); writer.Write(csv.Format((scan.nAbsoluteMagnitude.HasValue) ? scan.nAbsoluteMagnitude.Value : 0)); writer.Write(csv.Format((scan.nAge.HasValue) ? scan.nAge.Value : 0)); writer.Write(csv.Format(scan.Luminosity)); } writer.Write(csv.Format(scan.nRadius.HasValue ? scan.nRadius.Value : 0)); writer.Write(csv.Format(scan.nRotationPeriod.HasValue ? scan.nRotationPeriod.Value : 0)); writer.Write(csv.Format(scan.nSurfaceTemperature.HasValue ? scan.nSurfaceTemperature.Value : 0)); if (ShowPlanets) { writer.Write(csv.Format(scan.nTidalLock.HasValue ? scan.nTidalLock.Value : false)); writer.Write(csv.Format((scan.TerraformState != null) ? scan.TerraformState : "")); writer.Write(csv.Format((scan.PlanetClass != null) ? scan.PlanetClass : "")); writer.Write(csv.Format((scan.Atmosphere != null) ? scan.Atmosphere : "")); writer.Write(csv.Format(scan.GetAtmosphereComponent("Iron"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Silicates"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("SulphurDioxide"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("CarbonDioxide"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Nitrogen"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Oxygen"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Water"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Argon"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Ammonia"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Methane"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Hydrogen"))); writer.Write(csv.Format(scan.GetAtmosphereComponent("Helium"))); writer.Write(csv.Format((scan.Volcanism != null) ? scan.Volcanism : "")); writer.Write(csv.Format(scan.nSurfaceGravity.HasValue ? scan.nSurfaceGravity.Value : 0)); writer.Write(csv.Format(scan.nSurfacePressure.HasValue ? scan.nSurfacePressure.Value : 0)); writer.Write(csv.Format(scan.nLandable.HasValue ? scan.nLandable.Value : false)); writer.Write(csv.Format((scan.nMassEM.HasValue) ? scan.nMassEM.Value : 0)); writer.Write(csv.Format(scan.GetCompositionPercent("Ice"))); writer.Write(csv.Format(scan.GetCompositionPercent("Rock"))); writer.Write(csv.Format(scan.GetCompositionPercent("Metal"))); } // Common orbital param writer.Write(csv.Format(scan.nSemiMajorAxis.HasValue ? scan.nSemiMajorAxis.Value : 0)); writer.Write(csv.Format(scan.nEccentricity.HasValue ? scan.nEccentricity.Value : 0)); writer.Write(csv.Format(scan.nOrbitalInclination.HasValue ? scan.nOrbitalInclination.Value : 0)); writer.Write(csv.Format(scan.nPeriapsis.HasValue ? scan.nPeriapsis.Value : 0)); writer.Write(csv.Format(scan.nOrbitalPeriod.HasValue ? scan.nOrbitalPeriod.Value : 0)); writer.Write(csv.Format(scan.nAxialTilt.HasValue ? scan.nAxialTilt : null)); if (ShowPlanets) { writer.Write(csv.Format(scan.GetMaterial("Carbon"))); writer.Write(csv.Format(scan.GetMaterial("Iron"))); writer.Write(csv.Format(scan.GetMaterial("Nickel"))); writer.Write(csv.Format(scan.GetMaterial("Phosphorus"))); writer.Write(csv.Format(scan.GetMaterial("Sulphur"))); writer.Write(csv.Format(scan.GetMaterial("Arsenic"))); writer.Write(csv.Format(scan.GetMaterial("Chromium"))); writer.Write(csv.Format(scan.GetMaterial("Germanium"))); writer.Write(csv.Format(scan.GetMaterial("Manganese"))); writer.Write(csv.Format(scan.GetMaterial("Selenium"))); writer.Write(csv.Format(scan.GetMaterial("Vanadium"))); writer.Write(csv.Format(scan.GetMaterial("Zinc"))); writer.Write(csv.Format(scan.GetMaterial("Zirconium"))); writer.Write(csv.Format(scan.GetMaterial("Cadmium"))); writer.Write(csv.Format(scan.GetMaterial("Mercury"))); writer.Write(csv.Format(scan.GetMaterial("Molybdenum"))); writer.Write(csv.Format(scan.GetMaterial("Niobium"))); writer.Write(csv.Format(scan.GetMaterial("Tin"))); writer.Write(csv.Format(scan.GetMaterial("Tungsten"))); writer.Write(csv.Format(scan.GetMaterial("Antimony"))); writer.Write(csv.Format(scan.GetMaterial("Polonium"))); writer.Write(csv.Format(scan.GetMaterial("Ruthenium"))); writer.Write(csv.Format(scan.GetMaterial("Technetium"))); writer.Write(csv.Format(scan.GetMaterial("Tellurium"))); writer.Write(csv.Format(scan.GetMaterial("Yttrium"))); } writer.WriteLine(); } } writer.Close(); if (frm.AutoOpen) { System.Diagnostics.Process.Start(frm.Path); } } } catch { ExtendedControls.MessageBoxTheme.Show(FindForm(), "Failed to write to " + frm.Path, "Export Failed", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } } }
private void InstallModpack() { var modpackinfo = (ModpackInfo)TCAdmin.SDK.Misc.ObjectXml.XmlToObject(this.Arguments.Arguments, typeof(ModpackInfo)); var service = new TCAdmin.GameHosting.SDK.Objects.Service(modpackinfo.ServiceId); var original_status = service.Status; try { if (original_status.ServiceStatus == TCAdmin.Interfaces.Server.ServiceStatus.Running) { service.Stop("Modpack installation"); } var install_data = System.IO.Path.Combine(service.RootDirectory, String.Format("Modpack-{0}.data", modpackinfo.ModpackId)); if (System.IO.File.Exists(install_data)) { UninstallModpack(); } var server = new TCAdmin.GameHosting.SDK.Objects.Server(service.ServerId); var provider = new TCAdminCustomMods.Providers.MinecraftModpacksProvider(); MinecraftModpacksBrowser genericMod = (MinecraftModpacksBrowser)provider.GetMod(modpackinfo.ModpackId.ToString(), Providers.ModSearchType.Id); var filepath = "Shared/bin-extensions/MinecraftModpack-Install-Script.txt"; var script = string.Empty; var utility = service.GetScriptUtility(); utility.ScriptEngineManager.AddVariable("Script.WorkingDirectory", service.RootDirectory); utility.AddObject("ThisModpackInfo", modpackinfo); utility.AddObject("ThisApiInfo", genericMod); utility.AddObject("ThisTaskStep", this); if (System.IO.File.Exists(filepath)) { script = System.IO.File.ReadAllText(filepath); } else { script = PythonScripts.MinecraftModpack_Install_Script; } utility.ScriptEngineManager.SetScript("ipy", script, null); DeleteModpackCmdLines(service); var createdfiles = new List <string>(); using (var filewatcher = new System.IO.FileSystemWatcher(service.RootDirectory, "*")) { filewatcher.InternalBufferSize = 32768; filewatcher.IncludeSubdirectories = true; filewatcher.Created += (object sender, System.IO.FileSystemEventArgs e) => { createdfiles.Add(e.FullPath); }; filewatcher.EnableRaisingEvents = true; utility.ScriptEngineManager.Execute(); provider.PostInstallMod(service, genericMod); } createdfiles.Reverse(); using (var file = System.IO.File.OpenWrite(install_data)) { using (var writer = new System.IO.StreamWriter(file)) { var i = 0; foreach (var createdfile in createdfiles) { i += 1; if (i > 1) { writer.Write("\n"); } writer.Write(TCAdmin.SDK.Misc.Strings.ReplaceCaseInsensitive(createdfile, service.RootDirectory, string.Empty)); } } } //remove current version if it exists foreach (var installed in provider.GetInstalledPlugins(service)) { var packid = int.Parse(installed.Split(':')[0].Replace("MCMP", string.Empty)); if (packid == modpackinfo.ModpackId) { var verid = int.Parse(installed.Split(':')[1]); provider.RemoveInstalledPlugin(service, packid, verid); } } provider.AddInstalledPlugin(service, modpackinfo.ModpackId, modpackinfo.VersionId); //Repair permissions this.WriteLog("Setting file permissions..."); var usercfgfile = string.Format("Services/{0}/User.cfg", service.ServiceId); if (System.IO.File.Exists(usercfgfile)) { var usercfg = new TCAdmin.SDK.Database.XmlField(); usercfg.LoadFromFile(usercfgfile); switch (server.OperatingSystem) { case TCAdmin.SDK.Objects.OperatingSystem.Linux: TCAdmin.SDK.Misc.Linux.SetDirectoryOwner(service.RootDirectory, usercfg["Service.User"].ToString(), true); break; case TCAdmin.SDK.Objects.OperatingSystem.Windows: server.GameHostingUtilitiesService.ConfigureGameAccountPermissions(usercfg["Service.User"].ToString(), service.RootDirectory); break; default: throw new NotImplementedException(server.OperatingSystem.ToString()); } } service.Configure(); var responsedata = new TCAdmin.SDK.Database.XmlField(); responsedata.SetValue("Task.RedirectUrl", modpackinfo.RedirectUrl); responsedata.SetValue("Task.RedirectUrlMvc", modpackinfo.RedirectUrl); this.SetResponse(responsedata.ToString()); this.UpdateProgress(100); } finally { if (original_status.ServiceStatus == TCAdmin.Interfaces.Server.ServiceStatus.Running) { service.Start("Modpack installation"); } } }
private void SaveButton_Click(object sender, EventArgs e) { if (IdTextBox.Text.Trim().Length < 1) { MessageBox.Show("IDを入力してください", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); IdTextBox.Focus(); return; } if (IdTextBox.Text.Contains(",")) { MessageBox.Show("IDにカンマは入力できません", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); IdTextBox.Focus(); return; } if (MailAddressTextBox.Text.Contains(",")) { MessageBox.Show("メールアドレスにカンマは入力できません", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); MailAddressTextBox.Focus(); return; } DialogResult dialogResult = MessageBox.Show( "保存しますか?", "確認", MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (dialogResult == DialogResult.OK) { using (var sw = new System.IO.StreamWriter( "save.csv", true, Encoding.GetEncoding("shift_jis"))) { sw.Write(IdTextBox.Text); sw.Write(","); sw.Write(MailCheckBox.Checked); sw.Write(","); sw.Write(MailAddressTextBox.Text); sw.Write(","); if (BusinessRadioButton.Checked) { sw.Write("1"); } else { sw.Write("0"); } sw.Write(","); sw.Write(EnableComboBox.Text); sw.WriteLine(""); } StatusLabel.Text = "保存しました"; } else { StatusLabel.Text = "キャンセルしました"; } }
private void BtnZaloguj_Click(object sender, RoutedEventArgs e) { //Zczytywanie data z pliku DateTime dataTeraz = DateTime.Now; //pobieram obecną datę w celu porównania z tą w pliku string dataWpliku; //kontener na datę z dokumentu System.IO.StreamReader dataTXT = new System.IO.StreamReader("DataKopii.txt"); //Wskazanie pliku dla StreamReadera MySqlConnectionStringBuilder connString = new MySqlConnectionStringBuilder(); //Obiekt tworzący łańcuch połączeniowy z bazą connString.Server = "DESKTOP-OBR3EBS" /*"LAPTOP-EEGICNKI"*/; //Przekazanie nazwy serwera, connString.Database = "KartotekaAdamPosluszny"; //nazwy bazy danych, string login = txtLogin.Text; if (login.EndsWith("1")) { string[] loginStr = login.Split(' '); connString.UserID = loginStr[0]; blokuj = 1; } else { connString.UserID = login; } connString.Password = pswHaslo.Password; //oraz hasła do łańcucha połączeniowego conn = new MySqlConnection(connString.ConnectionString); //Przekazanie łańcucha do obiektu conn try //Próba nawiązania połączenia z bazą { dataWpliku = dataTXT.ReadLine(); //odczytanie 1 linii z pliku DataKopii.txt dataTXT.Close(); //zamknięcie pliku DateTime dataZpliku = Convert.ToDateTime(dataWpliku); //konwertuję datę z pliku na typ DateTime w celu porównania TimeSpan roznicaDat = dataTeraz - dataZpliku; //tworze TimeSpana żeby zapisać różnicę między datami int dni = roznicaDat.Days; //wyciągam całkowitą liczbę dni pomiędzy Datami conn.Open(); //Otwarcie połączenia z bazą if (dni > 30) //jeżeli od ostatniego backupu minęło więcej niż 30 dni czyli miesiąc { //Tu będzie kod robiący eksport bazy string lokalizacjaKopii = /*NIE ZAPOMNIJ ZMIENIĆ ŚCIEŻKI*/ @"C:\Kartoteka\KopieBazy\" + dataTeraz.ToShortDateString() + "kartoteka.sql"; //ścieżka do pliku po eksporcie using (MySqlCommand polecenie = new MySqlCommand()) { using (MySqlBackup backup = new MySqlBackup(polecenie)) //Był potrzebny pakiet MySqlBackup.Net { polecenie.Connection = conn; backup.ExportToFile(lokalizacjaKopii); } } //i nadpisujący plik DataKopii.txt datą utworzenia System.IO.StreamWriter dataTXTnadpisz = new System.IO.StreamWriter("DataKopii.txt", false); //StreamWriter z parametrem false nadpisuje cały plik dataTXTnadpisz.Write(dataTeraz.ToString()); //Zapisuję nową datę w pliku dataTXTnadpisz.Close(); //zamykam plik MessageBox.Show("Wykonano kopię bazy danych!"); } PacjenciOsobowe pacjenciOsobowe = new PacjenciOsobowe(conn); //Utworzenie nowe obiektu klasy PacjenciOsobowe i przekazanie do niego połączenia conn pacjenciOsobowe.Show(); //Wywołanie metody Show dla obiektu pacjenciOsobowe this.Close(); //Zamknięcie okna logowania metodą Close } catch (MySqlException ex) //Przechwycenie błędu połączenia z bazą { MessageBox.Show(ex.Message); //Wyświetlenie treści błędu } }
private void UpdateAdministration_Load(object sender, EventArgs e) { if (!System.IO.File.Exists("releasekey.xml")) { if (MessageBox.Show("Signature key does not exist, create it?", Application.ProductName, MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) != DialogResult.Yes) { Application.Exit(); return; } System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(); using (System.IO.StreamWriter sw = new System.IO.StreamWriter("releasekey.xml", false)) sw.Write(rsa.ToXmlString(true)); } using (System.IO.StreamReader rd = new System.IO.StreamReader("releasekey.xml")) m_privateKey = rd.ReadToEnd(); List <Update> updates = new List <Update>(); System.Xml.Serialization.XmlSerializer sr = new System.Xml.Serialization.XmlSerializer(typeof(UpdateList)); UpdateList lst = null; if (System.IO.File.Exists(UpdateFile)) { using (System.IO.FileStream fs = new System.IO.FileStream(UpdateFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) lst = (UpdateList)sr.Deserialize(fs); } SortedList <string, string> applicationNames = new SortedList <string, string>(); SortedList <string, string> architectures = new SortedList <string, string>(); if (lst != null && lst.Updates != null) { foreach (Update u in lst.Updates) { listBox1.Items.Add(u); if (!string.IsNullOrEmpty(u.ApplicationName)) { applicationNames[u.ApplicationName.ToLower().Trim()] = u.ApplicationName; } if (!string.IsNullOrEmpty(u.Architecture)) { architectures[u.Architecture.ToLower().Trim()] = u.Architecture; } } } foreach (string s in architectures.Values) { if (UpdateArchitecture.FindString(s) < 0) { UpdateArchitecture.Items.Add(s); } } foreach (string s in applicationNames.Values) { if (UpdateApplication.FindString(s) < 0) { UpdateApplication.Items.Add(s); } } }
private void ModuleWeldBuiness(List <DBAccess.Model.BatteryModuleModel> modList, ref bool isAllComplete) { string weldStr = ""; string reStr = ""; Console.WriteLine("weld当前步骤:" + stepIndex); switch (stepIndex) { case 1: { currWorkMod = null; Console.WriteLine("weld1"); //tag3:SENDED记录数据已发送至焊机,COMPLETE为加工完成 string welderSndFile = string.Format(@"\\{0}\MESReport\DeviceInfoLane{1}.txt", welderIP, channelIndex); // @"\\192.168.0.45\MESReport\DeviceInfoLane1.txt"; if (!System.IO.File.Exists(welderSndFile)) { currentTaskDescribe = string.Format("铝丝焊文件:{0}不存在", welderSndFile); return; } Console.WriteLine("weld2"); for (int i = 0; i < modList.Count; i++) { if (modList[i].tag4.ToUpper() == ENUMWeldStatus.SENDED.ToString() || modList[i].tag4.ToUpper() == ENUMWeldStatus.COMPLETE.ToString()) { continue; } currWorkMod = modList[i]; Console.WriteLine("weld66"); if (GetWeldStr(currWorkMod, ref weldStr, ref reStr) == false) { logRecorder.AddDebugLog(nodeName, string.Format("获取模块焊接加工数据失败:{0}", reStr)); continue; } break; } Console.WriteLine("weld3"); if (currWorkMod == null) { return; } Console.WriteLine("weld4"); System.IO.StreamWriter writter = new System.IO.StreamWriter(welderSndFile, false); StringBuilder strBuild = new StringBuilder(); writter.Write(weldStr); writter.Flush(); writter.Close(); logRecorder.AddDebugLog(nodeName, "写入铝丝焊:" + weldStr); currWorkMod.tag4 = ENUMWeldStatus.SENDED.ToString(); modBll.Update(currWorkMod); Console.WriteLine("weld5"); if (NodeDB2Commit(4 + this.channelIndex, 1, ref reStr) == false) //焊接参数写入完成 { break; } Console.WriteLine("weld6"); stepIndex++; break; } case 2: { if (db2Vals[4 + this.channelIndex] != 2) { currentTaskDescribe = "等待PLC读取MES下发的加工数据完成"; break; } //if (NodeDB2Commit(4 + this.channelIndex, 0, ref reStr) == false)//焊接参数写入完成 //{ // break; //} Console.WriteLine("weld7"); if (this.db2Vals[2 + channelIndex] != 2) //有模块加工完成 { currentTaskDescribe = "等待设备工作完成"; return; } if (this.NodeDB2Commit(2 + channelIndex, 1, ref reStr) == false) //复位读写 { return; } Console.WriteLine("weld8"); Thread uploadMesThread = new Thread(new ParameterizedThreadStart(UploadBatteryModToMes)); uploadMesThread.IsBackground = true; uploadMesThread.Start(currWorkMod); Console.WriteLine("weld10"); currWorkMod.tag4 = ENUMWeldStatus.COMPLETE.ToString(); modBll.Update(currWorkMod); if (IsAllModComplete() == true) { Console.WriteLine("weld11"); currWorkMod.tag4 = ""; modBll.Update(currWorkMod); isAllComplete = true; stepIndex = 0; } else { isAllComplete = false; stepIndex = 1; Console.WriteLine("weld12"); } break; } } }
public void Save() { SortedList <string, DocDefined> mapDefined = new SortedList <string, DocDefined>(this); SortedList <string, DocEnumeration> mapEnum = new SortedList <string, DocEnumeration>(this); SortedList <string, DocSelect> mapSelect = new SortedList <string, DocSelect>(this); SortedList <string, DocEntity> mapEntity = new SortedList <string, DocEntity>(this); SortedList <string, DocFunction> mapFunction = new SortedList <string, DocFunction>(this); SortedList <string, DocGlobalRule> mapRule = new SortedList <string, DocGlobalRule>(this); SortedList <string, DocObject> mapGeneral = new SortedList <string, DocObject>(); foreach (DocSection docSection in this.m_project.Sections) { foreach (DocSchema docSchema in docSection.Schemas) { //if (this.m_schema == null || this.m_schema == docSchema) { if (this.m_included == null || this.m_included.ContainsKey(docSchema)) { foreach (DocType docType in docSchema.Types) { if (this.m_included == null || this.m_included.ContainsKey(docType)) { if (docType is DocDefined) { if (!mapDefined.ContainsKey(docType.Name)) { mapDefined.Add(docType.Name, (DocDefined)docType); } } else if (docType is DocEnumeration) { mapEnum.Add(docType.Name, (DocEnumeration)docType); } else if (docType is DocSelect) { mapSelect.Add(docType.Name, (DocSelect)docType); } if (!mapGeneral.ContainsKey(docType.Name)) { mapGeneral.Add(docType.Name, docType); } } } foreach (DocEntity docEnt in docSchema.Entities) { if (this.m_included == null || this.m_included.ContainsKey(docEnt)) { if (!mapEntity.ContainsKey(docEnt.Name)) { mapEntity.Add(docEnt.Name, docEnt); } if (!mapGeneral.ContainsKey(docEnt.Name)) { mapGeneral.Add(docEnt.Name, docEnt); } } } foreach (DocFunction docFunc in docSchema.Functions) { if ((this.m_included == null || this.m_included.ContainsKey(docFunc)) && !mapFunction.ContainsKey(docFunc.Name)) { mapFunction.Add(docFunc.Name, docFunc); } } foreach (DocGlobalRule docRule in docSchema.GlobalRules) { if (this.m_included == null || this.m_included.ContainsKey(docRule)) { mapRule.Add(docRule.Name, docRule); } } } } } } string dirpath = System.IO.Path.GetDirectoryName(this.m_filename); if (!System.IO.Directory.Exists(dirpath)) { System.IO.Directory.CreateDirectory(dirpath); } using (System.IO.StreamWriter writer = new System.IO.StreamWriter(this.m_filename)) { if (writer.BaseStream.CanSeek) { writer.BaseStream.SetLength(0); } string schemaid = this.m_project.GetSchemaIdentifier(); if (this.m_schema != null) { schemaid = this.m_schema.Name; } string org = "buildingSMART International Limited"; writer.Write("" + "(*\r\n" + "Copyright by:\r\n" + org + ", 1996-" + DateTime.UtcNow.Year + "\r\n" + "\r\n" + "Any technical documentation made available by " + org + "\r\n" + "is the copyrighted work of " + org + " and is owned by the \r\n" + org + ". It may be photocopied, used in software development, \r\n" + "or translated into another computer language without prior written consent from \r\n" + org + " provided that full attribution is given. \r\n" + "Prior written consent is required if changes are made to the technical specification.\r\n" + "\r\n" + "This material is delivered to you as is and " + org + " makes \r\n" + "no warranty of any kind with regard to it, including, but not limited to, the implied \r\n" + "warranties as to its accuracy or fitness for a particular purpose. Any use of the \r\n" + "technical documentation or the information contained therein is at the risk of the user. \r\n" + "Documentation may include technical or other inaccuracies or typographical errors. \r\n" + org + " shall not be liable for errors contained therein or \r\n" + "for incidental consequential damages in connection with the furnishing, performance or use \r\n" + "of the material. The information contained in this document is subject to change without notice.\r\n" + "\r\n" + "Issue date:\r\n" + DateTime.Today.ToLongDateString() + "\r\n" + //"December 27, 2012\r\n" + "\r\n" + "*)\r\n" + "\r\n"); writer.WriteLine("SCHEMA " + schemaid.ToUpper() + ";"); writer.WriteLine(); if (this.m_schema != null) { // references foreach (DocSchemaRef docSchemaRef in this.m_schema.SchemaRefs) { writer.Write("REFERENCE FROM "); writer.WriteLine(docSchemaRef.Name); writer.WriteLine("("); foreach (DocDefinitionRef docDefRef in docSchemaRef.Definitions) { writer.Write(" "); writer.Write(docDefRef.Name); if (docDefRef != docSchemaRef.Definitions[docSchemaRef.Definitions.Count - 1]) { writer.Write(","); } writer.WriteLine(); } writer.WriteLine(");"); writer.WriteLine(); } } // stripped optional applicable if MVD is used if (this.m_included != null) { writer.WriteLine("TYPE IfcStrippedOptional = BOOLEAN;"); writer.WriteLine("END_TYPE;"); writer.WriteLine(); } // defined types foreach (DocDefined docDef in mapDefined.Values) { if (this.m_schema == null || this.m_schema.Types.Contains(docDef)) { writer.Write("TYPE "); writer.Write(docDef.Name); writer.Write(" = "); if (docDef.Aggregation != null) { WriteExpressAggregation(writer, docDef.Aggregation); } writer.Write(docDef.DefinedType); string length = ""; if (docDef.Length > 0) { length = "(" + docDef.Length.ToString() + ")"; } else if (docDef.Length < 0) { int len = -docDef.Length; length = "(" + len.ToString() + ") FIXED"; } writer.Write(length); writer.WriteLine(";"); if (docDef.WhereRules.Count > 0) { writer.WriteLine(" WHERE"); foreach (DocWhereRule where in docDef.WhereRules) { writer.Write("\t"); writer.Write(where.Name); writer.Write(" : "); writer.Write(MakeLongFormExpression(where.Expression, schemaid)); writer.WriteLine(";"); } } writer.WriteLine("END_TYPE;"); writer.WriteLine(); } } // enumerations foreach (DocEnumeration docEnum in mapEnum.Values) { if (this.m_schema == null || this.m_schema.Types.Contains(docEnum)) { writer.Write("TYPE "); writer.Write(docEnum.Name); writer.Write(" = ENUMERATION OF"); writer.WriteLine(); for (int i = 0; i < docEnum.Constants.Count; i++) { DocConstant docConst = docEnum.Constants[i]; if (i == 0) { writer.Write("\t("); } else { writer.Write("\t,"); } writer.Write(docConst.Name); if (i == docEnum.Constants.Count - 1) { writer.WriteLine(");"); } else { writer.WriteLine(); } } writer.WriteLine("END_TYPE;"); writer.WriteLine(); } } // selects foreach (DocSelect docSelect in mapSelect.Values) { if (this.m_schema == null || this.m_schema.Types.Contains(docSelect)) { writer.Write("TYPE "); writer.Write(docSelect.Name); writer.Write(" = SELECT"); writer.WriteLine(); SortedList <string, DocSelectItem> sortSelect = new SortedList <string, DocSelectItem>(this); foreach (DocSelectItem docSelectItem in docSelect.Selects) { if (!sortSelect.ContainsKey(docSelectItem.Name)) { sortSelect.Add(docSelectItem.Name, docSelectItem); } else { this.ToString(); } } int nSelect = 0; for (int i = 0; i < sortSelect.Keys.Count; i++) { DocSelectItem docConst = sortSelect.Values[i]; DocObject docRefEnt = null; if (mapGeneral.TryGetValue(docConst.Name, out docRefEnt)) { if (this.m_included == null || this.m_included.ContainsKey(docRefEnt)) { if (nSelect == 0) { writer.Write("\t("); } else { writer.WriteLine(); writer.Write("\t,"); } nSelect++; writer.Write(docConst.Name); } } } writer.WriteLine(");"); writer.WriteLine("END_TYPE;"); writer.WriteLine(); } } // entities foreach (DocEntity docEntity in mapEntity.Values) { if (this.m_schema == null || this.m_schema.Entities.Contains(docEntity)) { writer.Write("ENTITY "); writer.Write(docEntity.Name); if ((docEntity.IsAbstract())) { writer.WriteLine(); writer.Write(" ABSTRACT"); } // build up list of subtypes from other schemas SortedList <string, DocEntity> subtypes = new SortedList <string, DocEntity>(this); // sort to match Visual Express foreach (DocEntity eachent in mapEntity.Values) { if (eachent.BaseDefinition != null && eachent.BaseDefinition.Equals(docEntity.Name)) { subtypes.Add(eachent.Name, eachent); } } if (subtypes.Count > 0) { StringBuilder sb = new StringBuilder(); // Capture all subtypes, not just those within schema int countsub = 0; foreach (string ds in subtypes.Keys) { DocEntity refent = subtypes[ds]; if (this.m_included == null || this.m_included.ContainsKey(refent)) { countsub++; if (sb.Length != 0) { sb.Append("\r\n ,"); } sb.Append(ds); } } if (!docEntity.IsAbstract()) { writer.WriteLine(); } if (countsub > 1 || this.m_oneof) { writer.Write(" SUPERTYPE OF (ONEOF\r\n (" + sb.ToString() + "))"); } else if (countsub == 1) { writer.Write(" SUPERTYPE OF (" + sb.ToString() + ")"); } } if (docEntity.BaseDefinition != null) { writer.WriteLine(); writer.Write(" SUBTYPE OF ("); writer.Write(docEntity.BaseDefinition); writer.Write(")"); } writer.WriteLine(";"); // direct attributes bool hasinverse = false; bool hasderived = false; foreach (DocAttribute attr in docEntity.Attributes) { if (attr.Inverse == null && attr.Derived == null) { writer.Write("\t"); writer.Write(attr.Name); writer.Write(" : "); if (attr.IsOptional) { writer.Write("OPTIONAL "); } WriteExpressAggregation(writer, attr); if (this.m_included == null || this.m_included.ContainsKey(attr)) { writer.Write(attr.DefinedType); } else { writer.Write("IfcStrippedOptional"); } writer.WriteLine(";"); } else if (attr.Inverse != null && attr.Derived == null) { DocObject docref = null; if (mapGeneral.TryGetValue(attr.DefinedType, out docref)) { if (this.m_included == null || this.m_included.ContainsKey(docref)) { hasinverse = true; } } } else if (attr.Derived != null) { hasderived = true; } } // derived attributes if (hasderived) { writer.WriteLine(" DERIVE"); foreach (DocAttribute attr in docEntity.Attributes) { if (attr.Derived != null) { // determine the superclass having the attribute DocEntity found = null; DocEntity super = docEntity; while (super != null && found == null && super.BaseDefinition != null) { super = mapEntity[super.BaseDefinition] as DocEntity; if (super != null) { foreach (DocAttribute docattr in super.Attributes) { if (docattr.Name.Equals(attr.Name)) { // found class found = super; break; } } } } writer.Write("\t"); if (found != null) { // overridden attribute writer.Write("SELF\\"); writer.Write(found.Name); writer.Write("."); } writer.Write(attr.Name); writer.Write(" : "); WriteExpressAggregation(writer, attr); writer.Write(attr.DefinedType); writer.Write(" := "); writer.Write(attr.Derived); writer.WriteLine(";"); } } } // inverse attributes if (hasinverse) { writer.WriteLine(" INVERSE"); foreach (DocAttribute attr in docEntity.Attributes) { if (attr.Inverse != null && attr.Derived == null) { DocObject docref = null; if (mapGeneral.TryGetValue(attr.DefinedType, out docref)) { if (this.m_included == null || this.m_included.ContainsKey(docref)) { writer.Write("\t"); writer.Write(attr.Name); writer.Write(" : "); WriteExpressAggregation(writer, attr); writer.Write(attr.DefinedType); writer.Write(" FOR "); writer.Write(attr.Inverse); writer.WriteLine(";"); } } } } } // unique rules if (docEntity.UniqueRules.Count > 0) { writer.WriteLine(" UNIQUE"); foreach (DocUniqueRule where in docEntity.UniqueRules) { writer.Write("\t"); writer.Write(where.Name); writer.Write(" : "); foreach (DocUniqueRuleItem ruleitem in where.Items) { if (ruleitem != where.Items[0]) { writer.Write(", "); } writer.Write(ruleitem.Name); } writer.WriteLine(";"); } } // where rules if (docEntity.WhereRules.Count > 0) { writer.WriteLine(" WHERE"); foreach (DocWhereRule where in docEntity.WhereRules) { writer.Write("\t"); writer.Write(where.Name); writer.Write(" : "); writer.Write(MakeLongFormExpression(where.Expression, schemaid)); writer.WriteLine(";"); } } writer.WriteLine("END_ENTITY;"); writer.WriteLine(); } } // functions foreach (DocFunction docFunction in mapFunction.Values) { if (this.m_schema == null || this.m_schema.Functions.Contains(docFunction)) { writer.Write("FUNCTION "); writer.WriteLine(docFunction.Name); writer.WriteLine(MakeLongFormExpression(docFunction.Expression, schemaid)); writer.WriteLine("END_FUNCTION;"); writer.WriteLine(); } } // rules foreach (DocGlobalRule docRule in mapRule.Values) { if (this.m_schema == null || this.m_schema.GlobalRules.Contains(docRule)) { writer.Write("RULE "); writer.Write(docRule.Name); writer.WriteLine(" FOR"); writer.Write("\t("); writer.Write(docRule.ApplicableEntity); writer.WriteLine(");"); writer.WriteLine(docRule.Expression); // where writer.WriteLine(" WHERE"); foreach (DocWhereRule docWhere in docRule.WhereRules) { writer.Write(" "); writer.Write(docWhere.Name); writer.Write(" : "); writer.Write(MakeLongFormExpression(docWhere.Expression, schemaid)); writer.WriteLine(";"); } writer.WriteLine("END_RULE;"); writer.WriteLine(); } } writer.WriteLine("END_SCHEMA;"); } }
private void SaveConfig() { System.IO.StreamWriter sw = new System.IO.StreamWriter(Program.CONFIG_FILE, false); sw.Write(Utility.Global.Config.ToXml()); sw.Close(); }
public void WriteElement(string element, string value) { BeginElement(element, false); wrt.Write(value); EndElement(false); }
public static void RunIRC(string pass) { int port; string buf, nick, owner, server, chan; System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient(); System.IO.TextReader input; System.IO.TextWriter output; //Read .ini file string inifilepath = Application.StartupPath + "\\settings.ini"; INIFile ini = new INIFile(inifilepath); string TUsername = ini.Read("Twitch", "Username"); //-------------- nick = TUsername; owner = TUsername; server = "irc.twitch.tv"; port = 6667; chan = "#" + TUsername; Console.Clear(); //Connect to irc server and get input and output text streams from TcpClient. sock.Connect(server, port); if (!sock.Connected) { Console.WriteLine("Failed to connect!"); return; } else { Console.WriteLine("Conected to " + chan); } input = new System.IO.StreamReader(sock.GetStream()); output = new System.IO.StreamWriter(sock.GetStream()); //Starting USER and NICK login commands output.Write( "USER " + nick + "\n" + "PASS " + pass + "\r\n" + "NICK " + nick + "\r\n" ); output.Flush(); //Process each line received from irc server while ((buf = input.ReadLine()) != null) { //Display received irc message // if (buf != null) { //Console.WriteLine(buf); checkCommands(buf); //Send pong reply to any ping messages if (buf.StartsWith("PING ") || (buf.Contains("PING") && buf.Contains("mwax321"))) { output.Write(buf.Replace("PING", "PONG") + "\r\n"); output.Flush(); } if (buf.Contains("mwax321") && buf.Contains("clear")) { Console.Clear(); } if (buf[0] != ':') { continue; } /* IRC commands come in one of these formats: * :NICK!USER@HOST COMMAND ARGS ... :DATA\r\n * :SERVER COMAND ARGS ... :DATA\r\n */ //After server sends 001 command, we can set mode to bot and join a channel if (buf.Split(' ')[1] == "001") { output.Write( "MODE " + nick + " +B\r\n" + "JOIN " + chan + "\r\n" ); output.Flush(); } } else { Console.WriteLine("Null detected... "); RunIRC(pass); } } Console.WriteLine("Null detected... "); RunIRC(pass); }
void Progress_Click(object sender, EventArgs e) { initializeProgressBar(IOController.getNumFiles(@"Arcanum\")); setStatus("翻訳進捗率の算出中..."); System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); // addでlistにでも情報詰めて集計は後にした方が楽かなー string prog = Path.Xml.ProgressFile; ProgressFile pf = new ProgressFile(); if (System.IO.File.Exists(prog)) { pf = xml.Xml.Read <ProgressFile>(prog); } // listのオーダーが気になるけど書いてないので念のためhashにするよ System.Collections.Hashtable ignore = new System.Collections.Hashtable(); foreach (string f in pf.Ignore) { ignore.Add(f, 0); } foreach (string f in pf.Pending) { ignore.Add(f, 0); } List <ProgressCount> progress = new List <ProgressCount>(); calcProgress(Path.Data.BaseDirectory, progress, ignore); string buff = @""; int num = 0; int total = 0; foreach (ProgressCount count in progress) { if (count.Exist) { buff += @"*"; } if (count.Translated < count.Total) { } else { buff += @"+"; } float rate = 0; if (count.Total > 0) { rate = ( float )count.Translated / count.Total; } buff += count.Name + ": " + count.Translated + " / " + count.Total + " (" + rate.ToString("P0") + ")\r\n"; num += count.Translated; total += count.Total; } if (total > 0) { float totalrate = ( float )num / total; buff = "TOTAL: " + num + " / " + total + " (" + totalrate.ToString("P0") + ")\r\n" + buff; string output = @"progress.txt"; using (System.IO.StreamWriter writer = new System.IO.StreamWriter(output, false, System.Text.Encoding.GetEncoding("shift_jis"))) { //writer.AutoFlush = true; // 即時書き込み writer.Write(buff); runEditor(output); } } completeProgressBar(); watch.Stop(); addStatus("完了: progress.txt" + " (" + watch.ElapsedMilliseconds + "ms)"); // 本とかのチェックにひっかかってるなあ // prefix用とは別関数用意しないと }
/// /// This helper function sends data to the the HubSpot Forms API /// /// HubSpot Portal ID, or 'HUB ID' /// Unique ID for the form /// Dictionary containing all of the field names/values /// UserToken from the visitor's browser /// IP Address of the visitor /// Title of the page they visited /// URL of the page they visited /// /// public bool Post_To_HubSpot_FormsAPI(string intPortalID, string strFormGUID, List <T> progress, string strHubSpotUTK, string propertyField, string strPageTitle, string strPageURL, ref string strMessage) { // Build Endpoint URL string strEndpointURL = string.Format("https://forms.hubspot.com/uploads/form/v2/{0}/{1}", intPortalID, strFormGUID); // Setup HS Context Object Dictionary <string, string> hsContext = new Dictionary <string, string>(); hsContext.Add("hutk", strHubSpotUTK); hsContext.Add("pageUrl", strPageURL); hsContext.Add("ipAddress", HttpContext.Current?.Request.GetOriginalHostAddress()); hsContext.Add("pageName", strPageTitle); string progressValue = HttpUtility.UrlEncode(JsonConvert.SerializeObject(progress)); // Serialize HS Context to JSON (string) var strHubSpotContextJSON = JsonConvert.SerializeObject(hsContext); // Create string with post data string strPostData = ""; // Add dictionary values strPostData += $"{propertyField}={progressValue}&"; // Append HS Context JSON strPostData += "hs_context=" + HttpUtility.UrlEncode(strHubSpotContextJSON); // Create web request object System.Net.HttpWebRequest r = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strEndpointURL); // Set headers for POST r.Method = "POST"; r.ContentType = "application/x-www-form-urlencoded"; r.ContentLength = strPostData.Length; r.KeepAlive = false; // POST data to endpoint using (System.IO.StreamWriter sw = new System.IO.StreamWriter(r.GetRequestStream())) { try { sw.Write(strPostData); } catch (Exception ex) { // POST Request Failed strMessage = ex.Message; return(false); } } return(true); //POST Succeeded }
public void save(string path) { string data = ""; int size = this.Nodes.Count; for (int i = 0; i < size; ++i) { Node node = this.Nodes[i] as Node; if (node != null) { if (node.Type == Node.NodeType.Joint) { data += node.Original; //data += node.Modify; } else { string text = node.Original; // mes,male.female if (node.Editable) { // 不味い文字が入っていないか text = node.Modify.Replace(' ', ' '); // 全角スペースを半角スペースに置換 //if( text.IndexOf( '{' ) > -1 ) { text = text.Replace("{", ""); //} //if( text.IndexOf( '}' ) > -1 ) { text = text.Replace("}", ""); //} } data += "{" + text + "}"; if (node.Editable) { // 変更の反映 // 全部コピーと比較してからコピーはどっちがよい? //node.Original = node.Modify.Clone() as string; node.setOriginal(text, this); // modがまだなくoriginal=modの場合読み直さないとoriginalの表示がおかしくなる // のだがこれをしないと変更チェックが出来ない。 // dirtyフラグにするのか? } } } } System.IO.FileInfo info = new System.IO.FileInfo(path); if (!info.Exists) { } // TODO:拡張子とfiletypeのチェック if (System.IO.Directory.Exists(info.DirectoryName) == false) { System.IO.Directory.CreateDirectory(info.DirectoryName); } using (System.IO.StreamWriter writer = new System.IO.StreamWriter(path, false, System.Text.Encoding.GetEncoding("shift_jis"))) { //writer.AutoFlush = true; // 即時書き込み writer.Write(data); } }
internal static void GenerateBindingInitializeScript(List <string> clsNames, List <Type> valueTypeBinders, string outputPath) { if (!System.IO.Directory.Exists(outputPath)) { System.IO.Directory.CreateDirectory(outputPath); } using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/CLRBindings.cs", false, new UTF8Encoding(false))) { StringBuilder sb = new StringBuilder(); sb.AppendLine(@"using System; using System.Collections.Generic; using System.Reflection; namespace ILRuntime.Runtime.Generated { class CLRBindings {"); if (valueTypeBinders != null) { sb.AppendLine(); foreach (var i in valueTypeBinders) { string clsName, realClsName; bool isByRef; i.GetClassName(out clsName, out realClsName, out isByRef); sb.AppendLine(string.Format(" internal static ILRuntime.Runtime.Enviorment.ValueTypeBinder<{0}> s_{1}_Binder = null;", realClsName, clsName)); } sb.AppendLine(); } sb.AppendLine(@" /// <summary> /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration /// </summary> public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app) {"); if (clsNames != null) { foreach (var i in clsNames) { sb.Append(" "); sb.Append(i); sb.AppendLine(".Register(app);"); } } if (valueTypeBinders != null) { sb.AppendLine(); sb.AppendLine(" ILRuntime.CLR.TypeSystem.CLRType __clrType = null;"); foreach (var i in valueTypeBinders) { string clsName, realClsName; bool isByRef; i.GetClassName(out clsName, out realClsName, out isByRef); sb.AppendLine(string.Format(" __clrType = (ILRuntime.CLR.TypeSystem.CLRType)app.GetType (typeof({0}));", realClsName)); sb.AppendLine(string.Format(" s_{0}_Binder = __clrType.ValueTypeBinder as ILRuntime.Runtime.Enviorment.ValueTypeBinder<{1}>;", clsName, realClsName)); } } sb.AppendLine(@" }"); sb.AppendLine(@" /// <summary> /// Release the CLR binding, please invoke this BEFORE ILRuntime Appdomain destroy /// </summary> public static void Shutdown(ILRuntime.Runtime.Enviorment.AppDomain app) {"); if (valueTypeBinders != null) { foreach (var i in valueTypeBinders) { string clsName, realClsName; bool isByRef; i.GetClassName(out clsName, out realClsName, out isByRef); sb.AppendLine(string.Format(" s_{0}_Binder = null;", clsName)); } } sb.AppendLine(@" }"); sb.AppendLine(@" } }"); sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n")); } }
/// <summary> Encodes the given message and compares it to the given string. Any differences /// are noted in the file [hapi.home]/parse_check.txt. Ignores extra field delimiters. /// </summary> private void checkParse(System.String originalMessageText, Message parsedMessage, Parser parser) { System.String newMessageText = parser.encode(parsedMessage); checkWriter.Write("******************* Comparing Messages ****************\r\n"); checkWriter.Write("Original: " + originalMessageText + "\r\n"); checkWriter.Write("Parsed and Encoded: " + newMessageText + "\r\n"); if (!originalMessageText.Equals(newMessageText)) { //check each segment SupportClass.Tokenizer tok = new SupportClass.Tokenizer(originalMessageText, "\r"); System.Collections.ArrayList one = new System.Collections.ArrayList(); while (tok.HasMoreTokens()) { System.String seg = tok.NextToken(); if (seg.Length > 4) { one.Add(seg); } } tok = new SupportClass.Tokenizer(newMessageText, "\r"); System.Collections.ArrayList two = new System.Collections.ArrayList(); while (tok.HasMoreTokens()) { System.String seg = tok.NextToken(); if (seg.Length > 4) { two.Add(stripExtraDelimiters(seg, seg[3])); } } if (one.Count != two.Count) { checkWriter.Write("Warning: inbound and parsed messages have different numbers of segments: \r\n"); checkWriter.Write("Original: " + originalMessageText + "\r\n"); checkWriter.Write("Parsed: " + newMessageText + "\r\n"); } else { //check each segment for (int i = 0; i < one.Count; i++) { System.String origSeg = (System.String)one[i]; System.String newSeg = (System.String)two[i]; if (!origSeg.Equals(newSeg)) { checkWriter.Write("Warning: inbound and parsed message segment differs: \r\n"); checkWriter.Write("Original: " + origSeg + "\r\n"); checkWriter.Write("Parsed: " + newSeg + "\r\n"); } } } } else { checkWriter.Write("No differences found\r\n"); } checkWriter.Write("******************** End Comparison ******************\r\n"); checkWriter.Flush(); }
/// <summary> Runs the test. /// </summary> public virtual void runTest() { try { assureResultsDirectoryExists(RESULTS_DIR); Configuration c = new Configuration(TEST_CONFIG); System.IO.StreamWriter result = new System.IO.StreamWriter(getFileName(RESULTS_DIR, "output", "res")); message(result, "Testing order of keys ..."); showIterator(result, c.Keys); message(result, "Testing retrieval of CSV values ..."); showVector(result, c.getVector("resource.loader")); message(result, "Testing subset(prefix).getKeys() ..."); Configuration subset = c.subset("file.resource.loader"); showIterator(result, subset.Keys); message(result, "Testing getVector(prefix) ..."); showVector(result, subset.getVector("path")); message(result, "Testing getString(key) ..."); result.write(c.getString("config.string.value")); result.Write("\n\n"); message(result, "Testing getBoolean(key) ..."); //UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Boolean.toString' may return a different value. 'ms-help://MS.VSCC/commoner/redir/redirect.htm?keyword="jlca1043"' result.Write(new Boolean(c.getBoolean("config.boolean.value")).ToString()); result.Write("\n\n"); message(result, "Testing getByte(key) ..."); result.Write(new Byte(c.getByte("config.byte.value")).ToString()); result.Write("\n\n"); message(result, "Testing getShort(key) ..."); result.Write(new Short(c.getShort("config.short.value")).ToString()); result.Write("\n\n"); message(result, "Testing getInt(key) ..."); result.Write(new Integer(c.getInt("config.int.value")).ToString()); result.Write("\n\n"); message(result, "Testing getLong(key) ..."); result.Write(new Long(c.getLong("config.long.value")).ToString()); result.Write("\n\n"); message(result, "Testing getFloat(key) ..."); result.Write(new Float(c.getFloat("config.float.value")).ToString()); result.Write("\n\n"); message(result, "Testing getDouble(key) ..."); result.Write(new Double(c.getDouble("config.double.value")).ToString()); result.Write("\n\n"); message(result, "Testing escaped-comma scalar..."); result.write(c.getString("escape.comma1")); result.Write("\n\n"); message(result, "Testing escaped-comma vector..."); showVector(result, c.getVector("escape.comma2")); result.Write("\n\n"); result.Flush(); result.Close(); if (!isMatch(RESULTS_DIR, COMPARE_DIR, "output", "res", "cmp")) { fail("Output incorrect."); } } catch (System.Exception e) { System.Console.Error.WriteLine("Cannot setup ConfigurationTestCase!"); SupportClass.WriteStackTrace(e, Console.Error); System.Environment.Exit(1); } }
public static void GenerateBindingCode(ILRuntime.Runtime.Enviorment.AppDomain domain, string outputPath, List <Type> valueTypeBinders = null, List <Type> delegateTypes = null) { if (domain == null) { return; } if (!System.IO.Directory.Exists(outputPath)) { System.IO.Directory.CreateDirectory(outputPath); } Dictionary <Type, CLRBindingGenerateInfo> infos = new Dictionary <Type, CLRBindingGenerateInfo>(new ByReferenceKeyComparer <Type>()); CrawlAppdomain(domain, infos); string[] oldFiles = System.IO.Directory.GetFiles(outputPath, "*.cs"); foreach (var i in oldFiles) { System.IO.File.Delete(i); } if (valueTypeBinders == null) { valueTypeBinders = new List <Type>(domain.ValueTypeBinders.Keys); } HashSet <MethodBase> excludeMethods = null; HashSet <FieldInfo> excludeFields = null; HashSet <string> files = new HashSet <string>(); List <string> clsNames = new List <string>(); foreach (var info in infos) { if (!info.Value.NeedGenerate) { continue; } Type i = info.Value.Type; //CLR binding for delegate is important for cross domain invocation,so it should be generated //if (i.BaseType == typeof(MulticastDelegate)) // continue; string clsName, realClsName; bool isByRef; if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0) { continue; } i.GetClassName(out clsName, out realClsName, out isByRef); if (clsNames.Contains(clsName)) { clsName = clsName + "_t"; } clsNames.Add(clsName); string oFileName = outputPath + "/" + clsName; int len = Math.Min(oFileName.Length, 100); if (len < oFileName.Length) { oFileName = oFileName.Substring(0, len) + "_t"; } while (files.Contains(oFileName)) { oFileName = oFileName + "_t"; } files.Add(oFileName); oFileName = oFileName + ".cs"; using (System.IO.StreamWriter sw = new System.IO.StreamWriter(oFileName, false, new UTF8Encoding(false))) { StringBuilder sb = new StringBuilder(); sb.Append(@"using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class "); sb.AppendLine(clsName); sb.Append(@" { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { "); string flagDef = " BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;"; string methodDef = " MethodBase method;"; string fieldDef = " FieldInfo field;"; string argsDef = " Type[] args;"; string typeDef = string.Format(" Type type = typeof({0});", realClsName); MethodInfo[] methods = info.Value.Methods.ToArray(); FieldInfo[] fields = info.Value.Fields.ToArray(); string registerMethodCode = i.GenerateMethodRegisterCode(methods, excludeMethods); string registerFieldCode = fields.Length > 0 ? i.GenerateFieldRegisterCode(fields, excludeFields) : null; string registerValueTypeCode = info.Value.ValueTypeNeeded ? i.GenerateValueTypeRegisterCode(realClsName) : null; string registerMiscCode = i.GenerateMiscRegisterCode(realClsName, info.Value.DefaultInstanceNeeded, info.Value.ArrayNeeded); string commonCode = i.GenerateCommonCode(realClsName); ConstructorInfo[] ctors = info.Value.Constructors.ToArray(); string ctorRegisterCode = i.GenerateConstructorRegisterCode(ctors, excludeMethods); string methodWraperCode = i.GenerateMethodWraperCode(methods, realClsName, excludeMethods, valueTypeBinders); string fieldWraperCode = fields.Length > 0 ? i.GenerateFieldWraperCode(fields, realClsName, excludeFields) : null; string cloneWraperCode = null; if (info.Value.ValueTypeNeeded) { //Memberwise clone should copy all fields var fs = i.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); cloneWraperCode = i.GenerateCloneWraperCode(fs, realClsName); } bool hasMethodCode = !string.IsNullOrEmpty(registerMethodCode); bool hasFieldCode = !string.IsNullOrEmpty(registerFieldCode); bool hasValueTypeCode = !string.IsNullOrEmpty(registerValueTypeCode); bool hasMiscCode = !string.IsNullOrEmpty(registerMiscCode); bool hasCtorCode = !string.IsNullOrEmpty(ctorRegisterCode); bool hasNormalMethod = methods.Where(x => !x.IsGenericMethod).Count() != 0; if ((hasMethodCode && hasNormalMethod) || hasFieldCode || hasCtorCode) { sb.AppendLine(flagDef); } if (hasMethodCode || hasCtorCode) { sb.AppendLine(methodDef); } if (hasFieldCode) { sb.AppendLine(fieldDef); } if (hasMethodCode || hasFieldCode || hasCtorCode) { sb.AppendLine(argsDef); } if (hasMethodCode || hasFieldCode || hasValueTypeCode || hasMiscCode || hasCtorCode) { sb.AppendLine(typeDef); } sb.AppendLine(registerMethodCode); if (fields.Length > 0) { sb.AppendLine(registerFieldCode); } if (info.Value.ValueTypeNeeded) { sb.AppendLine(registerValueTypeCode); } if (!string.IsNullOrEmpty(registerMiscCode)) { sb.AppendLine(registerMiscCode); } sb.AppendLine(ctorRegisterCode); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(commonCode); sb.AppendLine(methodWraperCode); if (fields.Length > 0) { sb.AppendLine(fieldWraperCode); } if (info.Value.ValueTypeNeeded) { sb.AppendLine(cloneWraperCode); } string ctorWraperCode = i.GenerateConstructorWraperCode(ctors, realClsName, excludeMethods, valueTypeBinders); sb.AppendLine(ctorWraperCode); sb.AppendLine(" }"); sb.AppendLine("}"); sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n")); sw.Flush(); } } using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/CLRBindings.cs", false, new UTF8Encoding(false))) { StringBuilder sb = new StringBuilder(); sb.AppendLine(@"using System; using System.Collections.Generic; using System.Reflection; namespace ILRuntime.Runtime.Generated { class CLRBindings { /// <summary> /// Initialize the CLR binding, please invoke this AFTER CLR Redirection registration /// </summary> public static void Initialize(ILRuntime.Runtime.Enviorment.AppDomain app) {"); foreach (var i in clsNames) { sb.Append(" "); sb.Append(i); sb.AppendLine(".Register(app);"); } sb.AppendLine(@" } } }"); sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n")); } var delegateClsNames = GenerateDelegateBinding(delegateTypes, outputPath); clsNames.AddRange(delegateClsNames); GenerateBindingInitializeScript(clsNames, valueTypeBinders, outputPath); }
internal static List <string> GenerateDelegateBinding(List <Type> types, string outputPath) { if (types == null) { types = new List <Type>(0); } List <string> clsNames = new List <string>(); foreach (var i in types) { var mi = i.GetMethod("Invoke"); var miParameters = mi.GetParameters(); if (mi.ReturnType == typeof(void) && miParameters.Length == 0) { continue; } string clsName, realClsName, paramClsName, paramRealClsName; bool isByRef, paramIsByRef; i.GetClassName(out clsName, out realClsName, out isByRef); clsNames.Add(clsName); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/" + clsName + ".cs", false, new UTF8Encoding(false))) { StringBuilder sb = new StringBuilder(); sb.Append(@"using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class "); sb.AppendLine(clsName); sb.AppendLine(@" { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) {"); bool first = true; if (mi.ReturnType != typeof(void)) { sb.Append(" app.DelegateManager.RegisterFunctionDelegate<"); first = true; foreach (var j in miParameters) { if (first) { first = false; } else { sb.Append(", "); } j.ParameterType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef); sb.Append(paramRealClsName); } if (!first) { sb.Append(", "); } mi.ReturnType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef); sb.Append(paramRealClsName); sb.AppendLine("> ();"); } else { sb.Append(" app.DelegateManager.RegisterMethodDelegate<"); first = true; foreach (var j in miParameters) { if (first) { first = false; } else { sb.Append(", "); } j.ParameterType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef); sb.Append(paramRealClsName); } sb.AppendLine("> ();"); } sb.AppendLine(); sb.Append(" app.DelegateManager.RegisterDelegateConvertor<"); sb.Append(realClsName); sb.AppendLine(">((act) =>"); sb.AppendLine(" {"); sb.Append(" return new "); sb.Append(realClsName); sb.Append("(("); first = true; foreach (var j in miParameters) { if (first) { first = false; } else { sb.Append(", "); } sb.Append(j.Name); } sb.AppendLine(") =>"); sb.AppendLine(" {"); if (mi.ReturnType != typeof(void)) { sb.Append(" return ((Func<"); first = true; foreach (var j in miParameters) { if (first) { first = false; } else { sb.Append(", "); } j.ParameterType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef); sb.Append(paramRealClsName); } if (!first) { sb.Append(", "); } mi.ReturnType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef); sb.Append(paramRealClsName); } else { sb.Append(" ((Action<"); first = true; foreach (var j in miParameters) { if (first) { first = false; } else { sb.Append(", "); } j.ParameterType.GetClassName(out paramClsName, out paramRealClsName, out paramIsByRef); sb.Append(paramRealClsName); } } sb.Append(">)act)("); first = true; foreach (var j in miParameters) { if (first) { first = false; } else { sb.Append(", "); } sb.Append(j.Name); } sb.AppendLine(");"); sb.AppendLine(" });"); sb.AppendLine(" });"); sb.AppendLine(" }"); sb.AppendLine(" }"); sb.AppendLine("}"); sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n")); sw.Flush(); } } return(clsNames); }
public override void Write(System.IO.StreamWriter stream) { stream.Write(internalValue); }
public static void GenerateBindingCode(List <Type> types, string outputPath, HashSet <MethodBase> excludeMethods = null, HashSet <FieldInfo> excludeFields = null, List <Type> valueTypeBinders = null, List <Type> delegateTypes = null) { if (!System.IO.Directory.Exists(outputPath)) { System.IO.Directory.CreateDirectory(outputPath); } string[] oldFiles = System.IO.Directory.GetFiles(outputPath, "*.cs"); foreach (var i in oldFiles) { System.IO.File.Delete(i); } List <string> clsNames = new List <string>(); foreach (var i in types) { string clsName, realClsName; bool isByRef; if (i.GetCustomAttributes(typeof(ObsoleteAttribute), true).Length > 0) { continue; } i.GetClassName(out clsName, out realClsName, out isByRef); clsNames.Add(clsName); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(outputPath + "/" + clsName + ".cs", false, new UTF8Encoding(false))) { StringBuilder sb = new StringBuilder(); sb.Append(@"using System; using System.Collections.Generic; using System.Reflection; using System.Runtime.InteropServices; using ILRuntime.CLR.TypeSystem; using ILRuntime.CLR.Method; using ILRuntime.Runtime.Enviorment; using ILRuntime.Runtime.Intepreter; using ILRuntime.Runtime.Stack; using ILRuntime.Reflection; using ILRuntime.CLR.Utils; namespace ILRuntime.Runtime.Generated { unsafe class "); sb.AppendLine(clsName); sb.Append(@" { public static void Register(ILRuntime.Runtime.Enviorment.AppDomain app) { "); string flagDef = " BindingFlags flag = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;"; string methodDef = " MethodBase method;"; string fieldDef = " FieldInfo field;"; string argsDef = " Type[] args;"; string typeDef = string.Format(" Type type = typeof({0});", realClsName); MethodInfo[] methods = i.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); FieldInfo[] fields = i.GetFields(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); string registerMethodCode = i.GenerateMethodRegisterCode(methods, excludeMethods); string registerFieldCode = i.GenerateFieldRegisterCode(fields, excludeFields); string registerValueTypeCode = i.GenerateValueTypeRegisterCode(realClsName); string registerMiscCode = i.GenerateMiscRegisterCode(realClsName, true, true); string commonCode = i.GenerateCommonCode(realClsName); ConstructorInfo[] ctors = i.GetConstructors(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly); string ctorRegisterCode = i.GenerateConstructorRegisterCode(ctors, excludeMethods); string methodWraperCode = i.GenerateMethodWraperCode(methods, realClsName, excludeMethods, valueTypeBinders); string fieldWraperCode = i.GenerateFieldWraperCode(fields, realClsName, excludeFields); string cloneWraperCode = i.GenerateCloneWraperCode(fields, realClsName); string ctorWraperCode = i.GenerateConstructorWraperCode(ctors, realClsName, excludeMethods, valueTypeBinders); bool hasMethodCode = !string.IsNullOrEmpty(registerMethodCode); bool hasFieldCode = !string.IsNullOrEmpty(registerFieldCode); bool hasValueTypeCode = !string.IsNullOrEmpty(registerValueTypeCode); bool hasMiscCode = !string.IsNullOrEmpty(registerMiscCode); bool hasCtorCode = !string.IsNullOrEmpty(ctorRegisterCode); bool hasNormalMethod = methods.Where(x => !x.IsGenericMethod).Count() != 0; if ((hasMethodCode && hasNormalMethod) || hasFieldCode || hasCtorCode) { sb.AppendLine(flagDef); } if (hasMethodCode || hasCtorCode) { sb.AppendLine(methodDef); } if (hasFieldCode) { sb.AppendLine(fieldDef); } if (hasMethodCode || hasFieldCode || hasCtorCode) { sb.AppendLine(argsDef); } if (hasMethodCode || hasFieldCode || hasValueTypeCode || hasMiscCode || hasCtorCode) { sb.AppendLine(typeDef); } sb.AppendLine(registerMethodCode); sb.AppendLine(registerFieldCode); sb.AppendLine(registerValueTypeCode); sb.AppendLine(registerMiscCode); sb.AppendLine(ctorRegisterCode); sb.AppendLine(" }"); sb.AppendLine(); sb.AppendLine(commonCode); sb.AppendLine(methodWraperCode); sb.AppendLine(fieldWraperCode); sb.AppendLine(cloneWraperCode); sb.AppendLine(ctorWraperCode); sb.AppendLine(" }"); sb.AppendLine("}"); sw.Write(Regex.Replace(sb.ToString(), "(?<!\r)\n", "\r\n")); sw.Flush(); } } var delegateClsNames = GenerateDelegateBinding(delegateTypes, outputPath); clsNames.AddRange(delegateClsNames); GenerateBindingInitializeScript(clsNames, valueTypeBinders, outputPath); }
public void Serialize(System.IO.StreamWriter writer) { writer?.Write(JsonConvert.SerializeObject(this)); }
//public const string SAVE_DIR = "results/"; public static void Main(string[] args) { Stopwatch sw = new Stopwatch(); sw.Start(); int gameMode, numGames, numThreads; bool parallel, saveCards; if (args.Length == 6) { //Assuming the input is correct gameMode = Int16.Parse(args[0]); numGames = Int16.Parse(args[1]); parallel = Boolean.Parse(args[2]); numThreads = Int16.Parse(args[3]); saveCards = Boolean.Parse(args[5]); } else { Console.WriteLine("Unspecified parameters. The program will use default parameters."); gameMode = GAMEMODE; numGames = NUMGAMES; parallel = PARALLEL; numThreads = NUM_THREADS; saveCards = SAVE_CARDS; } int firstTeamWins = 0, secondTeamWins = 0, draws = 0, nullGames = 0; //Shared data between threads! List <List <int>[]> cardsPerPlayer = new List <List <int>[]>(numGames); List <int> trumps = new List <int>(numGames); List <int> firstPlayers = new List <int>(numGames); List <int> finalBotTeamPoints = new List <int>(numGames); List <ulong[]> timePerTrick = new List <ulong[]>(numGames); Object allGamesLock = new Object(); Console.WriteLine(""); Console.WriteLine("|||||||||||||||||||| SUECA TEST WAR ||||||||||||||||||||"); Console.WriteLine(""); switch (gameMode) { case 1: Console.WriteLine("Mode 1 (1 RuleBased 3 Random)"); break; case 2: Console.WriteLine("Mode 2 (1 TrickPlayer 3 RuleBased)"); break; case 3: Console.WriteLine("Mode 3 (1 Smart 3 RuleBased)"); break; case 4: Console.WriteLine("Mode 4 (1 TimeLimited 3 RuleBased)"); break; case 5: Console.WriteLine("Mode 5 (1 RBO 3 RuleBased)"); break; case 6: Console.WriteLine("Mode 6 (1 Hybrid 3 RuleBased)"); break; default: break; } Console.WriteLine("#Games: " + numGames); if (parallel) { Parallel.For(0, numGames, new ParallelOptions { MaxDegreeOfParallelism = numThreads }, () => new int[4], (int i, ParallelLoopState state, int[] localCount) => { return(processGames(i, localCount, gameMode, cardsPerPlayer, trumps, firstPlayers, finalBotTeamPoints, timePerTrick, allGamesLock)); }, (int[] localCount) => { draws += localCount[0]; firstTeamWins += localCount[1]; secondTeamWins += localCount[2]; nullGames += localCount[3]; }); } else { for (int i = 0; i < numGames; i++) { int[] localCount = new int[14]; processGames(i, localCount, gameMode, cardsPerPlayer, trumps, firstPlayers, finalBotTeamPoints, timePerTrick, allGamesLock); draws += localCount[0]; firstTeamWins += localCount[1]; secondTeamWins += localCount[2]; nullGames += localCount[3]; } } if (saveCards) { System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo(SAVE_DIR); int count = dir.GetFiles("log*.txt").Length; using (System.IO.StreamWriter file = new System.IO.StreamWriter(SAVE_DIR + "log" + count + ".txt")) { file.WriteLine("Mode: " + GAMEMODE + " #Games: " + numGames); file.WriteLine("p0_0\tp0_1\tp0_2\tp0_3\tp0_4\tp0_5\tp0_6\tp0_7\tp0_8\tp0_9\t" + "p2_0\tp2_1\tp2_2\tp2_3\tp2_4\tp2_5\tp2_6\tp2_7\tp2_8\tp2_9\t" + "trump\tfirst\tfp\t" + "t_t0\tt_t1\tt_t2\tt_t3\tt_t4\tt_t5\tt_t6\tt_t7\tt_t8\tt_t9"); for (int i = 0; i < numGames; i++) { for (int k = 0; k < 4; k = k + 2) { for (int j = 0; j < 10; j++) { file.Write(cardsPerPlayer[i][k][j] + "\t"); } } file.Write(trumps[i] + "\t"); file.Write(firstPlayers[i] + "\t"); file.Write(finalBotTeamPoints[i] + "\t"); for (int l = 0; l < timePerTrick[i].Length; l++) { file.Write(timePerTrick[i][l] + "\t"); } file.WriteLine(""); } } } Console.WriteLine(""); Console.WriteLine("----------------- Summary -----------------"); Console.WriteLine("FirstTeam won " + firstTeamWins + "/" + numGames); Console.WriteLine("SecondTeam 1 won " + secondTeamWins + "/" + numGames); Console.WriteLine("Draws " + draws + "/" + numGames); Console.WriteLine("Null Games " + nullGames); sw.Stop(); Console.WriteLine("Total Time taken by functions is {0} seconds", sw.ElapsedMilliseconds / 1000); //seconds Console.WriteLine("Total Time taken by functions is {0} minutes", sw.ElapsedMilliseconds / 60000); //minutes Console.ReadLine(); }
protected virtual void OnGenerateButtonClicked(object sender, System.EventArgs e) { llum.Core core = llum.Core.getCore(); //System.Collections.Generic.Dictionary<string,string>dic=new System.Collections.Generic.Dictionary<string, string>(); System.Collections.Generic.List <CookComputing.XmlRpc.XmlRpcStruct> list = new System.Collections.Generic.List <CookComputing.XmlRpc.XmlRpcStruct>(); if (studentsRadiobutton.Active) { list = core.xmlrpc.get_students_passwords(); search_mode = 0; } if (teachersRadiobutton.Active) { list = core.xmlrpc.get_teachers_passwords(); //groupsCombobox.Active=0; search_mode = 1; } if (allRadiobutton.Active) { list = core.xmlrpc.get_all_passwords(); //groupsCombobox.Active=0; search_mode = 2; } /* * foreach(string str in dic.Keys) * { * if(!dic[str].Contains("{SSHA}")) * Console.WriteLine(str + ":" + dic[str]); * * } */ string close_html = "</div>\n" + "</body>\n" + "</html>\n"; System.IO.StreamReader stream = new System.IO.StreamReader(core.html_skel); string final_html = stream.ReadToEnd(); stream.Close(); final_html = final_html.Replace("%%NAME%%", Mono.Unix.Catalog.GetString("Name")); final_html = final_html.Replace("%%USER%%", Mono.Unix.Catalog.GetString("User")); final_html = final_html.Replace("%%PASSWORD%%", Mono.Unix.Catalog.GetString("Password")); final_html = final_html.Replace("%%PRINT%%", Mono.Unix.Catalog.GetString("Print")); bool impar = false; foreach (CookComputing.XmlRpc.XmlRpcStruct dic in list) { bool ok = false; if (user_list != null) { if (search_mode == 0) { foreach (LdapUser user in user_list) { if ((string)dic ["uid"] == user.uid) { if (groupsCombobox.Active == 0) { ok = true; break; } else { ok = user.groups.Contains(groupsCombobox.ActiveText); break; } } } } else { ok = true; } } else { ok = true; } if (ok) { if (!impar) { final_html += "\n<div class='row'><div class='left'>\n"; final_html += dic["sn"] + ", " + dic["cn"]; final_html += "\n</div><div class='middle'>\n"; final_html += dic["uid"]; final_html += "\n</div><div class='right'>\n"; final_html += dic["passwd"]; final_html += "\n</div></div>\n"; impar = true; } else { final_html += "\n<div class='row impar'><div class='left'>\n"; final_html += dic["sn"] + ", " + dic["cn"]; final_html += "\n</div><div class='middle'>\n"; final_html += dic["uid"]; final_html += "\n</div><div class='right'>\n"; final_html += dic["passwd"]; final_html += "\n</div></div>\n"; impar = false; } } } final_html += close_html; string file_name = "/tmp/." + RandomString(10) + ".html"; while (System.IO.File.Exists(file_name)) { file_name = "/tmp/." + RandomString(10) + ".html"; } System.IO.StreamWriter sw = new System.IO.StreamWriter(file_name); sw.Write(final_html); sw.Close(); Mono.Unix.Native.Syscall.chmod(file_name, Mono.Unix.Native.FilePermissions.S_IRWXU); System.Threading.ThreadStart start = delegate { System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.FileName = "/usr/share/llum/llum-browser"; p.StartInfo.Arguments = file_name; p.Start(); }; System.Threading.Thread thread = new System.Threading.Thread(start); thread.Start(); }
public bool DianjiaoProcess() { Console.WriteLine("点胶当前步骤:" + stepIndex); switch (stepIndex) { case 1: { List <DBAccess.Model.BatteryModuleModel> modList = modBll.GetModelList(string.Format("palletID='{0}' and palletBinded=1", this.dianjiaoDev.RfidUID)); currWorkMod = null; for (int i = 0; i < modList.Count; i++) { if (modList[i].tag4.ToUpper() == ENUMWeldStatus.SENDED.ToString() || modList[i].tag4.ToUpper() == ENUMWeldStatus.COMPLETE.ToString()) { continue; } currWorkMod = modList[i]; break; } string str = string.Format("{0},{1},", currWorkMod.tag2, this.dianjiaoDev.RfidUID); System.IO.StreamWriter writter = new System.IO.StreamWriter(this.inputPath, false, Encoding.Default); writter.Write(str); writter.Flush(); writter.Close(); this.dianjiaoDev.LogRecorder.AddDebugLog(this.dianjiaoDev.NodeName, "写入点胶文件数据:" + str); if (currWorkMod == null) { return(true); } string downloadStatusAddr = addrDic[this.dianjiaoDev.NodeID]; string posAddr = addrDic[this.dianjiaoDev.NodeID + "-" + currWorkMod.tag2]; if (this.dianjiaoDev.PlcRW.WriteDB(downloadStatusAddr, 1) == false) { this.dianjiaoDev.LogRecorder.AddDebugLog(this.dianjiaoDev.NodeName, "地址:" + downloadStatusAddr + "写入失败!"); break; } if (this.dianjiaoDev.PlcRW.WriteDB(posAddr, 1) == false) { this.dianjiaoDev.LogRecorder.AddDebugLog(this.dianjiaoDev.NodeName, "地址:" + downloadStatusAddr + "写入失败!"); break; } currWorkMod.tag4 = ENUMWeldStatus.SENDED.ToString(); modBll.Update(currWorkMod); this.dianjiaoDev.LogRecorder.AddDebugLog(this.dianjiaoDev.NodeName, "点胶位置" + currWorkMod.tag2 + "数据发送完成,更新数据完成!"); stepIndex++; break; } case 2: { this.dianjiaoDev.currentTaskDescribe = "等待位置" + this.currWorkMod.tag2 + ",加工完成!"; if (this.dianjiaoDev.db2Vals[2 + this.dianjiaoDev.channelIndex] != 2) { break; } currWorkMod.tag4 = ENUMWeldStatus.COMPLETE.ToString(); modBll.Update(currWorkMod); if (IsAllModComplete() == true) { List <DBAccess.Model.BatteryModuleModel> modList = modBll.GetModelList(string.Format("palletID='{0}' and palletBinded=1", this.dianjiaoDev.RfidUID)); foreach (DBAccess.Model.BatteryModuleModel mod in modList) { mod.tag4 = ""; modBll.Update(mod); } stepIndex = 0; this.dianjiaoDev.LogRecorder.AddDebugLog(this.dianjiaoDev.NodeName, "点胶流程完成!"); return(true); } else { stepIndex = 1; this.dianjiaoDev.LogRecorder.AddDebugLog(this.dianjiaoDev.NodeName, "位置" + this.currWorkMod.tag2 + "点胶流程完成,进行下一位置点胶!"); } break; } } return(false); }