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 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(); }
/// <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; }
public static string queue_task(string projectId, string token, string worker) { string uri = "https://worker-aws-us-east-1.iron.io:443/2/projects/" + projectId + "/tasks"; HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri); request.ContentType = "application/json"; request.Headers.Add("Authorization", "OAuth " + token); request.UserAgent = "IronMQ .Net Client"; request.Method = "POST"; // We hand code the JSON payload here. You can automatically convert it, if you prefer string body = "{\"tasks\": [ { \"code_name\": \"" + worker + "\", \"payload\": \"{\\\"key\\\": \\\"value\\\", \\\"fruits\\\": [\\\"apples\\\", \\\"oranges\\\"]}\"} ] }"; if (body != null) { using (System.IO.StreamWriter write = new System.IO.StreamWriter(request.GetRequestStream())) { write.Write(body); write.Flush(); } } HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream())) { return reader.ReadToEnd(); } }
public Plugin_EventXmlLoggerClass() : base("Plugin_EventXmlLogger", "Plugin welches alle Events in einer XML-Datei mitloggt") { if (!System.IO.File.Exists("log\\Plugin_EventXmlLogger.xml")) { // Datei existiert nicht, anlegen using (System.IO.StreamWriter sw = new System.IO.StreamWriter("log\\Plugin_EventXmlLogger.xml", true, Encoding.UTF8)) { sw.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n\r<events>\n\r</events>\n\r"); sw.Flush(); sw.Close(); } } this.xmldoc = new XmlDocument(); try { this.xmldoc.Load("log\\Plugin_EventXmlLogger.xml"); } catch (Exception ex) { // fehlerhaft beim laden System.IO.File.Move("log\\Plugin_EventXmlLogger.xml", "log\\Plugin_EventXmlLogger_corrupt_" + DateTime.Now.Ticks + ".xml"); using (System.IO.StreamWriter sw = new System.IO.StreamWriter("log\\Plugin_EventXmlLogger.xml", true, Encoding.UTF8)) { sw.Write("<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n\r<events>\n\r</events>\n\r"); sw.Flush(); sw.Close(); } } this.xmlroot = xmldoc.DocumentElement; daedalusPluginBase.LogClass.evt_newLogMessage += new daedalusPluginBase.LogClass.evt_newLogMessageHandle(LogClass_evt_newLogMessage); }
/// <summary> /// Saves the colourz /// </summary> public void save() { if (!System.IO.Directory.Exists(Constants.CACHE_PATH)) { System.IO.Directory.CreateDirectory(Constants.CACHE_PATH); } if (!System.IO.Directory.Exists(Constants.CACHE_PATH)) { Console.WriteLine("Created directory"); System.IO.Directory.CreateDirectory(Constants.CACHE_PATH); } System.IO.File.WriteAllBytes(Constants.CACHE_PATH + "Saved Colours.txt", new byte[0]); System.IO.StreamWriter file = new System.IO.StreamWriter(Constants.CACHE_PATH + "Saved Colours.txt", true); string saveText = ""; for(int i = 0; i < stack.Children.Count; i++) { SavedColour s = (SavedColour)stack.Children[i]; if(i != stack.Children.Count) saveText += s.hex + ";"; } file.WriteLine(saveText); file.Flush(); file.Close(); }
public static void Main(string[] args) { Defrag.IFileSystem fileSystem = new Defrag.Win32FileSystem("C:"); Defrag.Optimizer optimizer = new Defrag.Optimizer(fileSystem); Defrag.Win32ChangeWatcher watcher = new Defrag.Win32ChangeWatcher("C:\\"); System.IO.TextWriter log = new System.IO.StreamWriter(System.Console.OpenStandardOutput()); while (true) { String path = watcher.NextFile(); if (path != null) { try { optimizer.DefragFile(path, log); } catch (Win32Exception ex) { log.WriteLine(ex.Message); log.WriteLine("* * Failed! * *"); } finally { log.WriteLine(); log.Flush(); } } else { Thread.Sleep(500); } } }
public static void BugReport(string program, string desc, Exception ex, string data) { try { System.Diagnostics.Process.Start(DeveloperIssuePostURL(program, desc, ex, data)); } catch (Win32Exception) { try { // data passed too small/big System.Diagnostics.Process.Start(DeveloperIssuePostURL(program, program, ex, data, false)); } catch { string report = DeveloperIssuePostURL(program, desc, ex, data); System.IO.StreamWriter sw = new System.IO.StreamWriter("tempreport.txt"); sw.WriteLine(report); sw.Flush(); sw.Close(); System.Diagnostics.Process.Start(Environment.SystemDirectory+"\\notepad.exe tempreport.txt"); System.Diagnostics.Process.Start(DeveloperIssuePostURL(program, desc, null, Environment.NewLine + " PASTE NOTEPAD CONTENTS HERE")); } } }
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; }
static bool SaveId() { try { #if !OOB using (IsolatedStorageFile storageFile = IsolatedStorageFile.GetUserStoreForApplication()) { using (IsolatedStorageFileStream storageStream = new IsolatedStorageFileStream(StorageFileName, System.IO.FileMode.Create, storageFile)) { System.IO.StreamWriter writer = new System.IO.StreamWriter(storageStream); // write settings to isolated storage writer.WriteLine(instanceIdGuid.Value.ToString()); writer.Flush(); } return true; } #else if (IsolatedStorageSettings.ApplicationSettings.Contains(StorageKey)) { IsolatedStorageSettings.ApplicationSettings[StorageKey] = instanceIdGuid.Value.ToString(); } else { IsolatedStorageSettings.ApplicationSettings.Add(StorageKey, instanceIdGuid.Value.ToString()); } return true; #endif } catch { // users can disable isolated storage return false; } }
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()); } }
override protected void Append(LoggingEvent loggingEvent) { if (m_queue == null) { if (MessageQueue.Exists(m_queueName)) { m_queue = new MessageQueue(m_queueName); } else { ErrorHandler.Error("Queue ["+m_queueName+"] not found"); } } if (m_queue != null) { Message message = new Message(); message.Label = RenderLabel(loggingEvent); using(System.IO.MemoryStream stream = new System.IO.MemoryStream()) { System.IO.StreamWriter writer = new System.IO.StreamWriter(stream, new System.Text.UTF8Encoding(false, true)); base.RenderLoggingEvent(writer, loggingEvent); writer.Flush(); stream.Position = 0; message.BodyStream = stream; m_queue.Send(message); } } }
private void buttonSiguiente_Click(object sender, EventArgs e) { if (opcion == 0) { if (textBoxNombre.Text == "" || (radioButtonMasculino.Checked == false && radioButtonFemenino.Checked == false)) MessageBox.Show("Es necesario llenar los campos de Nombre y Sexo"); else { string sexo = ""; if (radioButtonMasculino.Checked == true) sexo = "Masculino"; if (radioButtonFemenino.Checked == true) sexo = "Femenino"; string text = usuario + "|" + textBoxNombre.Text + "|" + textBoxCURP.Text + "|" + textBoxRFC.Text + "|" + textBoxCelular.Text + "|" + textBoxTelefono.Text + "|" + textBoxDireccion.Text + "|" + sexo.ToString() + "|" + textBoxLugarDeNacimiento.Text + "|" + textBoxNacFecha1.Text + "|" + textBoxNacFecha2.Text + "|" + textBoxNacFecha3.Text + "|" + textBoxEdad.Text + "|" + textBoxEmailLaboral.Text + "|" + textBoxEmailPersonal.Text + "|" + textBoxTipoDeSangre.Text + "|" + textBoxNumeroDeEmergencia.Text + "|" + textBoxContactoDeEmergencia.Text + "|" + textBoxParentesco.Text + "|" + textBoxDireccionDelContacto.Text + "|" + textBoxOtrasOcupaciones.Text + "|" + textBoxOtrasOcupaciones.Text + "|" + textBoxEstadoCivil.Text + "|" + textBoxStatusFamiliar.Text + "|"; System.IO.StreamWriter file = new System.IO.StreamWriter("BDP_ELYON.elyon", true); file.WriteLine(text); file.Flush(); file.Close(); this.Close(); } } if (opcion == 1) { string sexo = ""; if (radioButtonMasculino.Checked == true) sexo = "Masculino"; if (radioButtonFemenino.Checked == true) sexo = "Femenino"; string text = usuario + "|" + textBoxNombre.Text + "|" + textBoxCURP.Text + "|" + textBoxRFC.Text + "|" + textBoxCelular.Text + "|" + textBoxTelefono.Text + "|" + textBoxDireccion.Text + "|" + sexo.ToString() + "|" + textBoxLugarDeNacimiento.Text + "|" + textBoxNacFecha1.Text + "|" + textBoxNacFecha2.Text + "|" + textBoxNacFecha3.Text + "|" + textBoxEdad.Text + "|" + textBoxEmailLaboral.Text + "|" + textBoxEmailPersonal.Text + "|" + textBoxTipoDeSangre.Text + "|" + textBoxNumeroDeEmergencia.Text + "|" + textBoxContactoDeEmergencia.Text + "|" + textBoxParentesco.Text + "|" + textBoxDireccionDelContacto.Text + "|" + textBoxOtrasOcupaciones.Text + "|" + textBoxOtrasOcupaciones.Text + "|" + textBoxEstadoCivil.Text + "|" + textBoxStatusFamiliar.Text + "|"; editarArchivo(1, text); this.Close(); } }
private void btnSave_Click(object sender, RoutedEventArgs e) { SaveFileDialog dialog = new SaveFileDialog(); try { dialog.DefaultExt = ".txt"; dialog.Filter = "Text Files|*.txt"; //dialog.FilterIndex = 0; bool? dialogResult = dialog.ShowDialog(); if (dialogResult == false) return; System.IO.Stream fileStream = dialog.OpenFile(); System.IO.StreamWriter sw = new System.IO.StreamWriter(fileStream); foreach (StatusItem item in ViewModel.Current.Status.StatusItems) { sw.WriteLine(item.FormattedMesage ); } sw.Flush(); sw.Close(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
private void processLog(Object state) { _readWriteLock.EnterWriteLock(); while (queue.Count != 0) { string msg = String.Empty; lock (_Lock) { if(queue.Count > 0) msg = queue.Dequeue(); } lock (_LockFile) { DateTime data = DateTime.Now; file = new System.IO.StreamWriter(name + ".log", true); if (file.BaseStream.Length > 1000000) { System.IO.File.Copy(name + ".log", name + "-" + data.ToString("ddMMyyyy HHmm") + ".log"); file.Flush(); file.Close(); //fechando arquivo para deletar System.IO.File.Delete(name + ".log"); file = new System.IO.StreamWriter(name + ".log", true); } file.WriteLine(data.ToString(System.Globalization.CultureInfo.InvariantCulture) + " :" + msg); file.Flush(); file.Close(); } } _readWriteLock.ExitWriteLock(); }
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(); }
public static string connect(String server,int port,String ouath) { System.Net.Sockets.TcpClient sock = new System.Net.Sockets.TcpClient (); sock.Connect (server, port); if (!sock.Connected) { Console.Write ("not working hoe"); } System.IO.TextWriter output; System.IO.TextReader input; output = new System.IO.StreamWriter (sock.GetStream ()); input = new System.IO.StreamReader (sock.GetStream ()); output.Write ( "PASS " + ouath + "\r\n" + "NICK " + "Sail338" + "\r\n" + "USER " + "Sail338" + "\r\n" + "JOIN " + "#sail338" + "" + "\r\n" ); output.Flush (); for (String rep = input.ReadLine ();; rep = input.ReadLine ()) { string[] splitted = rep.Split (':'); if (splitted.Length > 2) { string potentialVote = splitted [2]; if (Array.Exists (validVotes, vote => vote.Equals(potentialVote))) return potentialVote; } } }
public static void WriteToLog(string logText, bool writeToLog) { try { if (writeToLog) { string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string path = System.IO.Path.Combine(myDocs, "pubnubmessaging.log"); lock (_logLock) { using (System.IO.TextWriter writer = new System.IO.StreamWriter(path, true)) { writer.WriteLine(logText); writer.Flush(); writer.Close(); } } } } catch (Exception ex) { try { string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.Personal); string path = System.IO.Path.Combine(myDocs, "pubnubcrash.log"); using (System.IO.TextWriter writer = new System.IO.StreamWriter(path, true)) { writer.WriteLine(ex.ToString()); writer.Flush(); writer.Close(); } } catch { } } }
public static void filter_min_exp(string [] args) { if(args.Length!=4) { ConsoleLog.WriteLine("checkbanned list out_list minexp"); return; } string[] Bots=System.IO.File.ReadAllLines(args[1]); System.IO.TextWriter outs=new System.IO.StreamWriter(args[2],true); //System.Net.WebClient client=new System.Net.WebClient(); NerZul.Core.Network.HttpClient client=new NerZul.Core.Network.HttpClient(); int cnt=1; foreach (string Bot in Bots) { ConsoleLog.WriteLine("["+cnt.ToString()+"/"+Bots.Length.ToString()+"] "+ "Checking "+Bot.Split('|')[0]); cnt++; string botinfo=Bot.Split('|')[0].Replace(" ","%20"); botinfo="http://api.erepublik.com/v1/feeds/citizens/"+botinfo+"?by_username=true"; botinfo=client.DownloadString(botinfo); botinfo=System.Text.RegularExpressions.Regex. Match(botinfo,@"\<experience-points\>(\w+)\<").Groups[1].Value; if (int.Parse(botinfo)>=int.Parse(args[3])) { outs.WriteLine(Bot); outs.Flush(); ConsoleLog.WriteLine("OK"); } System.Threading.Thread.Sleep(3000); }; }
public void Save(string filename) { var cols = columns.OrderBy(kv => kv.Value).Select(kv => kv.Key).ToList(); using (var o = new System.IO.StreamWriter(filename)) { // write header { var header = ""; var mid = ""; foreach (var col in cols) { header += mid+Escape(col); mid = ";"; } o.WriteLine(header); } // then rows foreach (var row in rows) { var line = ""; var mid = ""; foreach (var col in cols) { var val = ""; if (row.ContainsKey(col)) val = row[col].ToString(); line += mid + Escape(val); mid = ";"; } o.WriteLine(line); } o.Flush(); o.Close(); } }
private void printButton_Click(object sender, EventArgs e) { // Printer IP Address and communication port string ipAddress = printerIpText.Text; int port = 9100; try { // Open connection System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(); client.Connect(ipAddress, port); // Write ZPL String to connection System.IO.StreamWriter writer = new System.IO.StreamWriter(client.GetStream()); writer.Write(zplCode); writer.Flush(); // Close Connection writer.Close(); client.Close(); MessageBox.Show("Print Successful!", "Success"); this.Close(); } catch (Exception ex) { Console.WriteLine("Error: {0}", ex); MessageBox.Show("No printer installed corresponds to the IP address given", "No response"); } }
private void buttonSiguiente_Click(object sender, EventArgs e) { if (opcion == 0) { System.IO.StreamWriter file = new System.IO.StreamWriter("BDL_ELYON.elyon", true); file.WriteLine(obtenerDatos()); file.Flush(); file.Close(); string seguridad = ""; if (radioButtonSeguridadAlto.Checked == true) seguridad = "Alto"; if (radioButtonSeguridadMedio.Checked == true) seguridad = "Medio"; if (radioButtonSeguridadBajo.Checked == true) seguridad = "Bajo"; string text2 = textBoxUsuario.Text + "|" + textBoxContraseña.Text + "|" + textBoxNombre.Text + "|" + seguridad.ToString() + "|"; System.IO.StreamWriter file2 = new System.IO.StreamWriter("USU_ELYON.elyon", true); file2.WriteLine(text2); file2.Flush(); file2.Close(); PanelDatosPersonal panel = new PanelDatosPersonal(opcion,textBoxUsuario.Text, textBoxNombre.Text, textBoxEmailLaboral.Text, textBoxEmailPersonal.Text); panel.Show(); this.Close(); } if (opcion == 1) { editarArchivo(0, obtenerDatos()); PanelDatosPersonal panel = new PanelDatosPersonal(opcion, textBoxUsuario.Text, textBoxNombre.Text, textBoxEmailLaboral.Text, textBoxEmailPersonal.Text); panel.Show(); this.Close(); } }
public MainWindow() { log_file = new System.IO.FileStream("log3.txt", System.IO.FileMode.Append); log_sw = new System.IO.StreamWriter(log_file); InitializeComponent(); ac_m = new ArchiveControl(); Console.SetOut(log_sw); _LogTimer.Interval = System.TimeSpan.FromSeconds(5); _LogTimer.Tick += flushLog; _LogTimer.Start(); Console.WriteLine("========================================"); Console.WriteLine("MainWindow()"); Console.WriteLine(DateTime.Now.ToString()); log_sw.Flush(); write.mainWindow = this; try { button_NP_Click(null, null); button_NS_Click(null, null); } catch { } TabItem1.Visibility = Visibility.Hidden; TabItem2.Visibility = Visibility.Hidden; TabItem3.Visibility = Visibility.Hidden; TabItem4.Visibility = Visibility.Hidden; // mainWindow = this; ac_m.count(); }
private void init() { logTimer.Elapsed += new System.Timers.ElapsedEventHandler((object sender, System.Timers.ElapsedEventArgs e) => { try { fs = new System.IO.FileStream(LogFile, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); sw = new System.IO.StreamWriter(fs); sw.BaseStream.Seek(0, System.IO.SeekOrigin.End); lock(buffer) { foreach(String str in buffer) { sw.Write("[" + DateTime.Now.ToString() + "] "); //sw.Flush(); sw.WriteLine(str); sw.Flush(); } buffer.Clear(); } sw.Close(); fs.Close(); } catch (Exception ex) { System.Windows.MessageBox.Show(ex.Message); } }); logTimer.AutoReset = true; //每到指定时间Elapsed事件是触发一次(false),还是一直触发(true) logTimer.Enabled = true; //是否触发Elapsed事件 logTimer.Start(); }
public static void addLog(string s) { System.Diagnostics.Debug.WriteLine(s); if (bDoLogging) { try { if (System.IO.File.Exists(LogFilename)) { System.IO.FileInfo fi = new System.IO.FileInfo(LogFilename); if (fi.Length > maxFileSize) { //create backup file System.IO.File.Copy(LogFilename, LogFilename + "bak", true); System.IO.File.Delete(LogFilename); } } System.IO.StreamWriter sw = new System.IO.StreamWriter(LogFilename, true); sw.WriteLine(DateTime.Now.ToShortDateString()+ " " + DateTime.Now.ToShortTimeString() + "\t" + s); sw.Flush(); sw.Close(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Exception in addLog FileWrite: " + ex.Message); } } }
public writeReadFile() { //Create a try catch block to make sure that that memory is recoverted. try { //Tell the user about writing a new file. Console.WriteLine("Press any key to write a random double file to the same directory."); Console.ReadKey(); using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter("fileOfGarbage.txt")) { //Create a new random double. Random randGarbageDouble = new Random(); //Write random generated numbers to the text file for (int countToGarbageTotalNumber = 0; countToGarbageTotalNumber < 10000000; countToGarbageTotalNumber++) { streamWriter.WriteLine((randGarbageDouble.NextDouble() * (99999999999.999999 - 1) + 1).ToString()); } showMemoryUsage(); //Flush, dispose, and Close the stream writer. streamWriter.Flush(); streamWriter.Dispose(); streamWriter.Close(); showMemoryUsage(); } showMemoryUsage(); Console.WriteLine("Press any key to read the random double file in the same directory."); Console.ReadKey(); //Create a new double to be collected. double[] garbageArrayString = new double[10000000]; //Read everything that was written into an array. using (System.IO.StreamReader streamReader = new System.IO.StreamReader("fileOfGarbage.txt")) { //Create a string to hold the line string line; //create an int to hold the linecount int countOfGarbageLine = 0; while ((line = streamReader.ReadLine()) != null) { garbageArrayString[countOfGarbageLine++] = double.Parse(line); } showMemoryUsage(); //Flush, dispose, and Close the stream writer. streamReader.Dispose(); streamReader.Close(); //Nullify the garbage array string for collection. garbageArrayString = null; countOfGarbageLine = 0; showMemoryUsage(); } } //Finally is not needed as variables are cleared in the using statements. finally { //Run garbage collection to be sure. GC.Collect(); showMemoryUsage(); } }
public void buildLog(String str) { System.IO.FileStream fs = new System.IO.FileStream(@"d:\keylog.txt", System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write); System.IO.StreamWriter sw = new System.IO.StreamWriter(fs); sw.BaseStream.Seek(0, System.IO.SeekOrigin.End); sw.Write("[" + DateTime.Now.ToString() + "]");//Write LINE LINE sw.Flush(); //foreach (String str in keyLogCol) { sw.WriteLine("[" + str + "] "); sw.Flush(); } sw.Close(); fs.Close(); //keyLogCol.Clear(); }
public void error(Exception msg) { DateTime dat1 = DateTime.Now; file = new System.IO.StreamWriter("SatServerApp.log", true); file.WriteLine(dat1.ToString(System.Globalization.CultureInfo.InvariantCulture) + " :" + msg.StackTrace); file.Flush(); file.Close(); }
/// <summary> Stores profile in persistent storage with given ID.</summary> public virtual void persistProfile(System.String ID, System.String profile) { System.IO.FileInfo dest = new System.IO.FileInfo(getFileName(ID)); System.IO.StreamWriter out_Renamed = new System.IO.StreamWriter(new System.IO.StreamWriter(dest.FullName, false, System.Text.Encoding.Default).BaseStream, new System.IO.StreamWriter(dest.FullName, false, System.Text.Encoding.Default).Encoding); out_Renamed.Write(profile); out_Renamed.Flush(); out_Renamed.Close(); }
public void WriteLine(string line) { lock (s_lock) { _logFile?.WriteLine(line); _logFile?.Flush(); LogCallback?.Invoke(line); } }
public void Save(string fileName) { using (var writer = new System.IO.StreamWriter(fileName)) { var serializer = new XmlSerializer(this.GetType()); serializer.Serialize(writer, this); writer.Flush(); } }
public static void ssh_test2() { SshUserData data1 = new SshUserData(); data1.user = "******"; data1.host = "tkynt2.phys.s.u-tokyo.ac.jp"; data1.port = 22; data1.pass = ""; System.Collections.Hashtable config = new System.Collections.Hashtable(); config["StrictHostKeyChecking"] = "no"; SshfsMessage mess1 = new SshfsMessage("[]"); jsch::JSch jsch = new Tamir.SharpSsh.jsch.JSch(); jsch::Session sess1 = jsch.getSession(data1.user, data1.host, data1.port); sess1.setConfig(config); //sess1.setUserInfo(new DokanSSHFS.DokanUserInfo(data1.pass,null)); sess1.setUserInfo(new SshLoginInfo(mess1, data1)); sess1.setPassword(data1.pass); sess1.connect(); //MyProx proxy=new MyProx(sess1); //SshUserData data2=new SshUserData(); //data2.user="******"; //data2.host="127.0.0.1"; //data2.port=50022; //data2.pass=""; //jsch::Session sess2=jsch.getSession(data2.user,data2.host,data2.port); //sess2.setConfig(config); //sess2.setUserInfo(new mwg.Sshfs.SshLoginInfo(mess1,data2)); //sess2.setPassword(data2.pass); //sess2.setProxy(proxy); //sess2.connect(); System.Console.WriteLine("cat"); jsch::ChannelExec ch_e = (jsch::ChannelExec)sess1.openChannel("exec"); ch_e.setCommand("cat"); ch_e.setOutputStream(System.Console.OpenStandardOutput(), true); System.IO.Stream ins = ch_e.getOutputStream(); ch_e.connect(); System.Threading.Thread.Sleep(2000); System.Console.WriteLine("hello"); ins.WriteByte((byte)'h'); ins.WriteByte((byte)'e'); ins.WriteByte((byte)'l'); ins.WriteByte((byte)'l'); ins.WriteByte((byte)'o'); ins.WriteByte((byte)'\n'); ins.Flush(); //System.Threading.Thread.Sleep(2000); System.Threading.Thread.Sleep(2000); System.IO.StreamWriter sw = new System.IO.StreamWriter(ins); System.Console.WriteLine("test"); sw.WriteLine("test"); sw.Flush(); System.Threading.Thread.Sleep(2000); System.Console.WriteLine("world"); sw.WriteLine("world"); sw.Flush(); System.Threading.Thread.Sleep(2000); for (int i = 0; i < 5; i++) { System.Console.WriteLine("count={0}", i); sw.WriteLine("count={0}", i); sw.Flush(); System.Threading.Thread.Sleep(2000); } for (int i = 5; i < 20; i++) { System.Console.WriteLine("count={0}", i); sw.WriteLine("count={0}", i); sw.Flush(); } System.Threading.Thread.Sleep(2000); sw.Close(); ins.Close(); System.Console.WriteLine("comp."); ch_e.disconnect(); //sess2.disconnect(); sess1.disconnect(); }
public static void DumpDetails(string value) { s_WriterDetails.Write(value); s_WriterDetails.Flush(); }
//If you've UTF-8 characters in your XML, you should use this //method to output the XML. public void Write(string stringForOutput) { writer.Write(stringForOutput); writer.Flush(); }
/// <summary> Writes any buffered data from the print() and println() methods to the /// device. /// /// /// /// </summary> public virtual void flush() { out_Renamed.Flush(); }
protected internal virtual void Transmit(string eventLabel) { writer.WriteLine(eventLabel); writer.Flush(); Ack(); }
public static void ImpEtiquetaLayout(decimal Codigo, string Produto, string Cod_barra, decimal Vl_preco, int Qtd_etiqueta, string Porta, CamadaDados.Diversos.TRegistro_CadTerminal rTerminal, bool sobra = false) { if (!System.IO.Directory.Exists("c:\\aliance.net")) { System.IO.Directory.CreateDirectory("c:\\aliance.net"); } System.IO.FileInfo f = new System.IO.FileInfo("c:\\aliance.net\\etiqueta.txt"); System.IO.StreamWriter w = f.CreateText(); decimal falta = decimal.Zero; try { TList_CadLayoutEtiqueta lLyaout = new TList_CadLayoutEtiqueta(); if (rTerminal.Id_layout != decimal.Zero) { lLyaout = TCN_CadLayoutEtiqueta.Busca(rTerminal.Id_layout.ToString(), string.Empty, null); } lLyaout.ForEach(p => { p.lCampos = TCN_CamposLayout.Busca(string.Empty, p.Id_layoutstr, string.Empty, null); }); decimal qtidade = decimal.Zero; decimal qtd = decimal.Zero; if (!string.IsNullOrEmpty(Qtd_etiqueta.ToString())) { qtidade = Convert.ToDecimal(Qtd_etiqueta.ToString()); } lLyaout.ForEach(p => { qtd = decimal.Divide(qtidade, p.nr_Coluna); String[] str = qtd.ToString().Split(','); if (str.Length > 1) { if (Convert.ToDecimal(str[0]) > 1) { qtd = Convert.ToDecimal(str[0]); } else { qtd = 1; } //{ //} } falta = Qtd_etiqueta - qtd * p.nr_Coluna; w.WriteLine("I8,A,001"); w.WriteLine(); w.WriteLine(); w.WriteLine("Q" + p.alturaetiqueta.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0" + p.larguraetiqueta.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true))); // altura espaco 176,024 w.WriteLine("rN"); w.WriteLine("S4"); w.WriteLine("D7"); w.WriteLine("ZT"); w.WriteLine("JF"); w.WriteLine("OD"); w.WriteLine("f100"); w.WriteLine("N"); TList_CamposEtiqueta lcamp = new TList_CamposEtiqueta(); //if (sobra) //{ p.lCampos.ForEach(o => { if (o.coluna <= Qtd_etiqueta) { lcamp.Add(o); } }); //} //else //{ // p.lCampos.ForEach(o => // { // lcamp.Add(o); // }); //} int cont = 0; string prod1 = string.Empty; string prod2 = string.Empty; string prod3 = Produto; if (Produto.Trim().Length > 20) { prod1 = Produto.Trim().Substring(0, 20); Produto = Produto.Remove(0, 20); if (Produto.Trim().Length > 20) { prod2 = Produto.Trim().Substring(0, 20); Produto = Produto.Remove(0, 20); //if (Produto.Trim().Length > 20) //{ // prod3 = Produto.Trim().Substring(0, 20); // Produto = Produto.Remove(0, 20); //} //else prod3 = Produto; } else { prod2 = Produto; // f } } else { prod1 = Produto; } Produto = prod3; lcamp.ForEach(o => { string tp = string.Empty; if (o.Status.Equals("CAMPO")) { tp = "A"; } else { tp = "B"; } cont = 0; //string prod1 = string.Empty; //string prod2 = string.Empty; //string prod3 = string.Empty; //if (Produto.Trim().Length > 20) //{ // prod1 = Produto.Trim().Substring(0, 20); // Produto = Produto.Remove(0, 20); // if (Produto.Trim().Length > 20) // { // cont = 1; // prod2 = Produto.Trim().Substring(0, 20); // Produto = Produto.Remove(0, 20); // if (Produto.Trim().Length > 20) // { // prod3 = Produto.Trim().Substring(0, 20); // Produto = Produto.Remove(0, 20); // } // else prod3 = Produto; // } // else prod2 = Produto; // f //} //else prod1 = Produto; cont++; if (o.ds_campo.Equals("DESCRICAO")) { w.WriteLine(tp + o.posx.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + "," + o.posy.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0," + o.Tp_Fonte + ",1,1,N,\"" + prod1.Trim() + "\""); //A24,8 //w.WriteLine("A304,8,0,2,1,1,N,\"" + prod1.Trim() + "\""); //w.WriteLine("A584,8,0,2,1,1,N,\"" + prod1.Trim() + "\""); } if (o.ds_campo.Equals("DESCRICAO2")) { w.WriteLine(tp + o.posx.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + "," + o.posy.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0," + o.Tp_Fonte + ",1,1,N,\"" + prod2.Trim() + "\""); //A24,32 cont = 0; //w.WriteLine("A304,32,0,2,1,1,N,\"" + prod2.Trim() + "\""); //w.WriteLine("A584,32,0,2,1,1,N,\"" + prod2.Trim() + "\""); } else if (o.ds_campo.Equals("VALOR")) { w.WriteLine(tp + o.posx.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + "," + o.posy.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0," + o.Tp_Fonte + ",1,1,N,\"" //A24,56 + Vl_preco.ToString("C2", new System.Globalization.CultureInfo("pt-BR", true)) + " Cd:" + Codigo.ToString() + "\""); } else if (o.ds_campo.Equals("COD_BAR")) { w.WriteLine(tp + o.posx.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + "," + o.posy.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0,E30,2," + o.Tp_Fonte + ",56,B,\"" + Cod_barra.Trim() + "\"");//B40,88 } }); }); w.WriteLine("P" + qtd); w.Flush(); f.CopyTo(Porta.Trim()); } finally { w.Dispose(); f = null; } try { if (falta > decimal.Zero) { ImpEtiquetaLayout(Codigo, Produto, Cod_barra, Vl_preco, Convert.ToInt32(falta.ToString("N0", new System.Globalization.CultureInfo("en-US"))), Porta, rTerminal, true); } } finally { } }
public void Produce(object arg) { Params p = (Params)arg; using (produce_outputfile = new System.IO.StreamWriter(p.Path + "\\produce.txt")) { produce_outputfile.WriteLine("Database: " + Program.Database + "\t Variables: " + p.Variables + "\t Iterations: " + p.Iterations + "\t WriteFrequency: " + p.writefrequency + "\t InitIterations: " + p.inititerations); produce_outputfile.WriteLine("Insert duration\tFinal duration\tRead back\tSpeed"); telemetry_p = new Telemetry(Program.VmName, p.Path, p.Variables, adapter); telemetry_p.InitTelemetryCollection("produce"); System.Diagnostics.Stopwatch onevariable_watch = new System.Diagnostics.Stopwatch(); var w_mock = new System.Diagnostics.Stopwatch(); int sleep = (int)((1.0f / (double)p.writefrequency) * 1000); while (p_mRunning) { System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); var startime = System.DateTime.Now; var endtime = startime.Add(p.timeSpan); while (System.DateTime.Now.Subtract(endtime).TotalSeconds <= 0) { if (!p_mRunning) { break; } sw.Restart(); adapter.PrepareWriteData(p.Variables); adapter.Send(ref onevariable_watch); sw.Stop(); int wait = sleep - (int)sw.ElapsedMilliseconds; if (wait > 0) { System.Threading.Thread.Sleep(wait); } } while (p.Variables < max_var) { var percent = p.Iterations / 100; for (int j = 0; j < p.Iterations; j++) { if (!p_mRunning) { break; } sw.Restart(); if (p.writefrequency > 1) { for (int i = 1; i < p.writefrequency; i++) { var st0 = System.Diagnostics.Stopwatch.StartNew(); adapter.PrepareWriteData(p.Variables); adapter.Send(ref w_mock); double elap0 = st0.Elapsed.TotalSeconds; int wait0 = sleep - (int)(elap0 * 1000); if (wait0 > 0) { System.Threading.Thread.Sleep(wait0); } } } adapter.PrepareWriteData(p.Variables); adapter.Send(ref onevariable_watch); var check1 = sw.Elapsed.TotalSeconds; while (true) { bool x = adapter.CheckInsert(); if (x) { break; } if (!p_mRunning) { break; } } onevariable_watch.Stop(); sw.Stop(); double elap = sw.Elapsed.TotalSeconds; float speed = (float)(p.Variables / elap); try { produce_outputfile.WriteLine(check1 + "\t" + elap + "\t" + onevariable_watch.Elapsed.TotalSeconds + "\t" + speed); } catch (System.ObjectDisposedException) { } onevariable_watch.Reset(); if (j % percent == 0) { System.Console.WriteLine("Producer: " + j / percent + "% progress"); } int wait = sleep - (int)sw.ElapsedMilliseconds; if (wait > 0) { System.Threading.Thread.Sleep(wait); } } if (p_mRunning) { p.Variables += increament; //Increase updated variable count telemetry_p.CollectVariableRunTelemetry(p.Variables); if (p.Variables >= max_var) { p_mRunning = false; break; } try { produce_outputfile.WriteLine("New Variable count: " + p.Variables + "\t"); } catch (System.ObjectDisposedException) { } } } p_done = true; System.Console.WriteLine("Producer iterations finished"); telemetry_p.CollectVariableRunTelemetry(p.Variables); telemetry_p.mRunning = false; produce_outputfile.Flush(); produce_outputfile.Close(); produce_outputfile.Dispose(); System.Console.WriteLine("Producer start fill"); while (p_mRunning) { sw.Restart(); adapter.PrepareWriteData(p.Variables); adapter.Send(ref onevariable_watch); sw.Stop(); int wait = sleep - (int)(sw.ElapsedMilliseconds); if (wait > 0) { System.Threading.Thread.Sleep(wait); } } System.Console.WriteLine("Producer fill finished"); break; } System.Console.WriteLine("Producer ending"); } }
public static void LogUsageInformation() { if (MinerWars.AppCode.Game.Missions.MyMissions.ActiveMission == null) { return; } m_counts = new Dictionary <MyModelsEnum, int>(); m_wrong_models = new List <WLentry>(); foreach (MyEntity e in MyEntities.GetEntities()) { if (MyModelsStatisticsConstants.MODEL_STATISTICS_WRONG_LODS_ONLY) { if (e.ModelLod0 != null && e.ModelLod1 != null && e.ModelLod0.GetTrianglesCount() < e.ModelLod1.GetTrianglesCount() * 2) { bool founded = false; foreach (WLentry entry in m_wrong_models) { if (entry.lod1Asset == e.ModelLod1.AssetName && entry.lod0Asset == e.ModelLod0.AssetName) { founded = true; break; } } if (!founded) { WLentry entry = new WLentry(); entry.lod1Asset = e.ModelLod1.AssetName; entry.lod1Triangles = MyModels.m_modelsByAssertName[e.ModelLod1.AssetName].GetTrianglesCount().ToString(); entry.lod1Type = "LOD1"; entry.lod0Asset = e.ModelLod0.AssetName; entry.lod0Triangles = MyModels.m_modelsByAssertName[e.ModelLod0.AssetName].GetTrianglesCount().ToString(); entry.lod0Type = "LOD0"; m_wrong_models.Add(entry); } } if (e.ModelLod1 != null && e.ModelLod2 != null && e.ModelLod1.GetTrianglesCount() < e.ModelLod2.GetTrianglesCount() * 2) { bool founded = false; foreach (WLentry entry in m_wrong_models) { if (entry.lod1Asset == e.ModelLod2.AssetName && entry.lod0Asset == e.ModelLod1.AssetName) { founded = true; break; } } if (!founded) { WLentry entry = new WLentry(); entry.lod1Asset = e.ModelLod2.AssetName; entry.lod1Triangles = MyModels.m_modelsByAssertName[e.ModelLod2.AssetName].GetTrianglesCount().ToString(); entry.lod1Type = "LOD2"; entry.lod0Asset = e.ModelLod1.AssetName; entry.lod0Triangles = MyModels.m_modelsByAssertName[e.ModelLod1.AssetName].GetTrianglesCount().ToString(); entry.lod0Type = "LOD1"; m_wrong_models.Add(entry); } } if (e.ModelLod0 != null && e.ModelCollision != null && e.ModelLod0.GetTrianglesCount() < e.ModelCollision.GetTrianglesCount() * 2) { bool founded = false; foreach (WLentry entry in m_wrong_models) { if (entry.lod1Asset == e.ModelCollision.AssetName && entry.lod0Asset == e.ModelLod0.AssetName) { founded = true; break; } } if (!founded) { WLentry entry = new WLentry(); entry.lod1Asset = e.ModelCollision.AssetName; entry.lod1Triangles = MyModels.m_modelsByAssertName[e.ModelCollision.AssetName].GetTrianglesCount().ToString(); entry.lod1Type = "COL"; entry.lod0Asset = e.ModelLod0.AssetName; entry.lod0Triangles = MyModels.m_modelsByAssertName[e.ModelLod0.AssetName].GetTrianglesCount().ToString(); entry.lod0Type = "LOD0"; m_wrong_models.Add(entry); } } } if (e.ModelLod0 != null) { MyModelsEnum en = e.ModelLod0.ModelEnum; if (m_counts.ContainsKey(en)) { ++m_counts[en]; } else { m_counts[en] = 1; } } if (e.ModelLod1 != null) { MyModelsEnum en = e.ModelLod1.ModelEnum; if (m_counts.ContainsKey(en)) { ++m_counts[en]; } else { m_counts[en] = 1; } } if (e.ModelLod2 != null) { MyModelsEnum en = e.ModelLod2.ModelEnum; if (m_counts.ContainsKey(en)) { ++m_counts[en]; } else { m_counts[en] = 1; } } if (e.ModelCollision != null) { MyModelsEnum en = e.ModelCollision.ModelEnum; if (m_counts.ContainsKey(en)) { ++m_counts[en]; } else { m_counts[en] = 1; } } ParseEntityChildrensForLog(e.Children); } foreach (MyModel m in MyModels.m_models) { if (!m_counts.ContainsKey(m.ModelEnum)) { m_counts[m.ModelEnum] = 0; } } string activeMissionName = MinerWars.AppCode.Game.Missions.MyMissions.ActiveMission != null?MinerWars.AppCode.Game.Missions.MyMissions.ActiveMission.DebugName.ToString() : MyModelsStatisticsConstants.ACTUAL_MISSION_FOR_MODEL_STATISTICS.ToString(); activeMissionName = activeMissionName.Replace(' ', '-').ToString().ToLower(); if (MyModelsStatisticsConstants.MODEL_STATISTICS_WRONG_LODS_ONLY) { using (System.IO.StreamWriter output = new System.IO.StreamWriter(System.IO.File.Open("models-usage-statistics-WL_" + activeMissionName + ".csv", System.IO.FileMode.Create))) { output.WriteLine("lodX AssetName" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "lodX Triangles" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "lodX Type" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "lodX-1 AssetName" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "lodX-1 Triangles" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "lodX-1 Type"); foreach (WLentry entry in m_wrong_models) { output.WriteLine(entry.lod1Asset + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + entry.lod1Triangles + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + entry.lod1Type + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + entry.lod0Asset + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + entry.lod0Triangles + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + entry.lod0Type); } output.Flush(); output.Close(); } } using (System.IO.StreamWriter output = new System.IO.StreamWriter(System.IO.File.Open("models-usage-statistics-N_" + activeMissionName + ".csv", System.IO.FileMode.Create))) { output.WriteLine("Model name" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "Used X-times" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "VB size [MB]" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "IB size [MB]" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "LoadData/LoadContent"); foreach (KeyValuePair <MyModelsEnum, int> kvp in m_counts) { string assetName = MyModels.GetModelAssetName(kvp.Key); string LS; if (!MyModels.m_modelsByAssertName[assetName].LoadedData) { continue; LS = "X"; } else { if (!MyModels.m_modelsByAssertName[assetName].LoadedContent) { LS = "LD"; } else { LS = "LC"; } } output.WriteLine(assetName + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + kvp.Value.ToString() + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + Math.Round(MyModels.m_modelsByAssertName[assetName].GetVBSize / 1024.0 / 1024.0, 4).ToString() + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + Math.Round(MyModels.m_modelsByAssertName[assetName].GetIBSize / 1024.0 / 1024.0, 4).ToString() + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + LS); } output.Flush(); output.Close(); } m_counts = null; GC.Collect(); if (MyModelsStatisticsConstants.GET_MODEL_STATISTICS_AUTOMATICALLY && MyModelsStatisticsConstants.MISSIONS_TO_GET_MODEL_STATISTICS_FROM.Length > (++MyModelsStatisticsConstants.ACTUAL_MISSION_FOR_MODEL_STATISTICS + 1)) { GUI.MyGuiScreenMainMenu.StartMission(MyModelsStatisticsConstants.MISSIONS_TO_GET_MODEL_STATISTICS_FROM[MyModelsStatisticsConstants.ACTUAL_MISSION_FOR_MODEL_STATISTICS]); } else { MergeLogFiles(); } }
/// <summary> /// Runs a program and redirects the standard output and error to the console /// This procedure blocks until the program is finished running /// </summary> /// <param name="program">The path to the program to run</param> /// <param name="arguments">Any arguments to run the program with</param> /// <param name="StdInput">Any Input to send to the program</param> /// /// <exception cref="System.Exception"></exception> public static ProgramReturnValues RunProgram(String program, String arguments, String StdInput) { ProgramReturnValues retval; if (program == null || program == String.Empty) { throw new ArgumentNullException("program"); } if (arguments == null) { arguments = ""; } if (StdInput == null) { StdInput = ""; } System.Diagnostics.Process p = new System.Diagnostics.Process(); p.StartInfo.Arguments = arguments; p.StartInfo.FileName = program; p.StartInfo.UseShellExecute = false; p.StartInfo.ErrorDialog = false; p.StartInfo.RedirectStandardOutput = true; if (StdInput != "") { p.StartInfo.RedirectStandardInput = true; } System.IO.StreamReader sro = null; System.IO.StreamWriter swi = null; try { p.Start(); if (StdInput != "") { swi = p.StandardInput; swi.Write(StdInput); swi.Flush(); swi.Close(); swi.Dispose(); swi = null; } sro = p.StandardOutput; p.WaitForExit(); retval.StdOutput = sro.ReadToEnd(); retval.ExitCode = p.ExitCode; } catch (Exception ex) { throw ex; } finally { if (swi != null) { swi.Close(); swi.Dispose(); } if (sro != null) { sro.Close(); sro.Dispose(); } p.Close(); p.Dispose(); } return(retval); }
public static void Main(System.String[] args) { if (args.Length < 2) { ExitWithUsage(); } System.Type stemClass = System.Type.GetType("SF.Snowball.Ext." + args[0] + "Stemmer"); SnowballProgram stemmer = (SnowballProgram)System.Activator.CreateInstance(stemClass); System.Reflection.MethodInfo stemMethod = stemClass.GetMethod("stem", (new System.Type[0] == null)?new System.Type[0]:(System.Type[]) new System.Type[0]); System.IO.StreamReader reader; reader = new System.IO.StreamReader(new System.IO.FileStream(args[1], System.IO.FileMode.Open, System.IO.FileAccess.Read), System.Text.Encoding.Default); reader = new System.IO.StreamReader(reader.BaseStream, reader.CurrentEncoding); System.Text.StringBuilder input = new System.Text.StringBuilder(); System.IO.Stream outstream = System.Console.OpenStandardOutput(); if (args.Length > 2 && args[2].Equals("-o")) { outstream = new System.IO.FileStream(args[3], System.IO.FileMode.Create); } else if (args.Length > 2) { ExitWithUsage(); } System.IO.StreamWriter output = new System.IO.StreamWriter(outstream, System.Text.Encoding.Default); output = new System.IO.StreamWriter(output.BaseStream, output.Encoding); int repeat = 1; if (args.Length > 4) { repeat = System.Int32.Parse(args[4]); } System.Object[] emptyArgs = new System.Object[0]; int character; while ((character = reader.Read()) != -1) { char ch = (char)character; if (System.Char.IsWhiteSpace(ch)) { if (input.Length > 0) { stemmer.SetCurrent(input.ToString()); for (int i = repeat; i != 0; i--) { stemMethod.Invoke(stemmer, (System.Object[])emptyArgs); } output.Write(stemmer.GetCurrent()); output.Write('\n'); input.Remove(0, input.Length - 0); } } else { input.Append(System.Char.ToLower(ch)); } } output.Flush(); }
static void engine_ExpressivEmoStateUpdated(object sender, EmoStateUpdatedEventArgs e) { EmoState es = e.emoState; Single timeFromStart = es.GetTimeFromStart(); EdkDll.EE_ExpressivAlgo_t[] expAlgoList = { EdkDll.EE_ExpressivAlgo_t.EXP_BLINK, EdkDll.EE_ExpressivAlgo_t.EXP_CLENCH, EdkDll.EE_ExpressivAlgo_t.EXP_EYEBROW, EdkDll.EE_ExpressivAlgo_t.EXP_FURROW, EdkDll.EE_ExpressivAlgo_t.EXP_HORIEYE, EdkDll.EE_ExpressivAlgo_t.EXP_LAUGH, EdkDll.EE_ExpressivAlgo_t.EXP_NEUTRAL, EdkDll.EE_ExpressivAlgo_t.EXP_SMILE, EdkDll.EE_ExpressivAlgo_t.EXP_SMIRK_LEFT, EdkDll.EE_ExpressivAlgo_t.EXP_SMIRK_RIGHT, EdkDll.EE_ExpressivAlgo_t.EXP_WINK_LEFT, EdkDll.EE_ExpressivAlgo_t.EXP_WINK_RIGHT }; Boolean[] isExpActiveList = new Boolean[expAlgoList.Length]; Boolean isBlink = es.ExpressivIsBlink(); Boolean isLeftWink = es.ExpressivIsLeftWink(); Boolean isRightWink = es.ExpressivIsRightWink(); Boolean isEyesOpen = es.ExpressivIsEyesOpen(); Boolean isLookingUp = es.ExpressivIsLookingUp(); Boolean isLookingDown = es.ExpressivIsLookingDown(); Boolean isLookingLeft = es.ExpressivIsLookingLeft(); Boolean isLookingRight = es.ExpressivIsLookingRight(); Single leftEye = 0.0F; Single rightEye = 0.0F; Single x = 0.0F; Single y = 0.0F; es.ExpressivGetEyelidState(out leftEye, out rightEye); es.ExpressivGetEyeLocation(out x, out y); Single eyebrowExtent = es.ExpressivGetEyebrowExtent(); Single smileExtent = es.ExpressivGetSmileExtent(); Single clenchExtent = es.ExpressivGetClenchExtent(); EdkDll.EE_ExpressivAlgo_t upperFaceAction = es.ExpressivGetUpperFaceAction(); Single upperFacePower = es.ExpressivGetUpperFaceActionPower(); EdkDll.EE_ExpressivAlgo_t lowerFaceAction = es.ExpressivGetLowerFaceAction(); Single lowerFacePower = es.ExpressivGetLowerFaceActionPower(); for (int i = 0; i < expAlgoList.Length; ++i) { isExpActiveList[i] = es.ExpressivIsActive(expAlgoList[i]); } expLog.Write( "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14},{15},{16},{17},{18},", timeFromStart, isBlink, isLeftWink, isRightWink, isEyesOpen, isLookingUp, isLookingDown, isLookingLeft, isLookingRight, leftEye, rightEye, x, y, eyebrowExtent, smileExtent, upperFaceAction, upperFacePower, lowerFaceAction, lowerFacePower); for (int i = 0; i < expAlgoList.Length; ++i) { expLog.Write("{0},", isExpActiveList[i]); } expLog.WriteLine(""); expLog.Flush(); }
partial void NAVExportPressed(NSButton sender) { string filePath = "/Users/" + Environment.UserName + "/Documents/Professional/Resilience/CashflowReportNAV"; filePath += "_" + this.startDate.ToString("yyyyMMdd"); filePath += "_" + this.endDate.ToString("yyyyMMdd"); filePath += ".csv"; this.showAll = true; this.ScenarioButton.State = NSCellStateValue.On; this.OutflowsOnlyButton.State = NSCellStateValue.Off; this.ScheduledOnlyButton.State = NSCellStateValue.Off; this.showFullDetail = false; this.FullDetailCheckBox.State = NSCellStateValue.Off; this.RefreshTable(); System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(filePath); // titles streamWriter.WriteLine("Date,Amount,Type,Description"); // data for (int i = 0; i < this.dataSource.Cashflows.Count; i++) { int loanID = this.dataSource.Cashflows[i].LoanID(); streamWriter.Write(this.dataSource.Cashflows[i].PayDate().ToString("MM/dd/yyyy")); streamWriter.Write(","); streamWriter.Write(this.dataSource.Cashflows[i].Amount().ToString("#0.00")); streamWriter.Write(","); streamWriter.Write(this.dataSource.Cashflows[i].TypeID().ToString()); streamWriter.Write(","); if (loanID >= 0) { streamWriter.Write(new clsLoan(loanID).Property().Address()); } else { switch (this.dataSource.Cashflows[i].TypeID()) { case clsCashflow.Type.AccountingFees: streamWriter.Write("RSM"); break; case clsCashflow.Type.BankFees: streamWriter.Write("Huntington"); break; case clsCashflow.Type.LegalFees: streamWriter.Write("Dykema"); break; case clsCashflow.Type.ManagementFee: case clsCashflow.Type.PromoteFee: streamWriter.Write("Adaptation"); break; default: streamWriter.Write("N/A"); break; } } streamWriter.WriteLine(); streamWriter.Flush(); } streamWriter.Close(); }
private void button5_Click(object sender, EventArgs e) { //Export the presentation if (System.IO.Directory.Exists(textBox1.Text) == true) { bool good = true; foreach (string file in listBox1.Items) { good = System.IO.File.Exists(file); } if (good == true) { try { //Good to export the project if (textBox1.Text.TrimEnd().EndsWith("\\")) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(textBox1.Text + "Presentation.nopres")) { sw.Write(_CODE); sw.Flush(); sw.Close(); } //Copy each of the files in the resources list foreach (string file in listBox1.Items) { System.IO.FileInfo fl = new System.IO.FileInfo(file); System.IO.File.Copy(file, textBox1.Text + fl.Name); } } else { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(textBox1.Text + "\\Presentation.nopres")) { sw.Write(_CODE); sw.Flush(); sw.Close(); } //Copy each of the files in the resources list foreach (string file in listBox1.Items) { System.IO.FileInfo fl = new System.IO.FileInfo(file); System.IO.File.Copy(file, textBox1.Text + "\\" + fl.Name); } } if (MessageBox.Show("The project / presentation has been successfully exported. Do you want to preview it in the explorer?", "Ninponix Office 2017", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { System.Diagnostics.Process.Start("explorer", textBox1.Text); Close(); } else { Close(); } } catch (Exception) { MessageBox.Show("The project export failed to proceed", "Ninponix Office 2017", MessageBoxButtons.OK, MessageBoxIcon.Error); } } else { Message m = new Message("Ninponix Office 2017", "Ninponix Office cannot find the resources that you have mentioned in the list.", MessageIcon.MessageIconType.Error, MessageIcon.MessageMode.Presentation); m.ShowDialog(); } } else { Message m = new Message("Ninponix Office 2017", "Ninponix Office cannot find the directory that you have mentioned", MessageIcon.MessageIconType.Error, MessageIcon.MessageMode.Presentation); m.ShowDialog(); } }
public mmria.common.model.couchdb.document_put_response Post() { //bool valid_login = false; mmria.common.metadata.app metadata = null; string object_string = null; mmria.common.model.couchdb.document_put_response result = new mmria.common.model.couchdb.document_put_response(); try { System.IO.Stream dataStream0 = this.Request.Content.ReadAsStreamAsync().Result; // Open the stream using a StreamReader for easy access. //dataStream0.Seek(0, System.IO.SeekOrigin.Begin); System.IO.StreamReader reader0 = new System.IO.StreamReader(dataStream0); // Read the content. string temp = reader0.ReadToEnd(); metadata = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.metadata.app>(temp); //System.Dynamic.ExpandoObject json_result = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Dynamic.ExpandoObject>(result, new Newtonsoft.Json.Converters.ExpandoObjectConverter()); //string metadata = DecodeUrlString(temp); } catch (Exception ex) { Console.WriteLine(ex); } try { Newtonsoft.Json.JsonSerializerSettings settings = new Newtonsoft.Json.JsonSerializerSettings(); settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; object_string = Newtonsoft.Json.JsonConvert.SerializeObject(metadata, settings); string metadata_url = this.get_couch_db_url() + "/metadata/" + metadata._id; System.Net.WebRequest request = System.Net.WebRequest.Create(new System.Uri(metadata_url)); request.Method = "PUT"; request.ContentType = "application/json"; request.ContentLength = object_string.Length; request.PreAuthenticate = false; if (this.Request.Headers.Contains("Cookie") && this.Request.Headers.GetValues("Cookie").Count() > 0) { string[] cookie_set = this.Request.Headers.GetValues("Cookie").First().Split(';'); for (int i = 0; i < cookie_set.Length; i++) { string[] auth_session_token = cookie_set[i].Split('='); if (auth_session_token[0].Trim() == "AuthSession") { request.Headers.Add("Cookie", "AuthSession=" + auth_session_token[1]); request.Headers.Add("X-CouchDB-WWW-Authenticate", auth_session_token[1]); break; } } } using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(request.GetRequestStream())) { try { streamWriter.Write(object_string); streamWriter.Flush(); streamWriter.Close(); System.Net.WebResponse response = (System.Net.HttpWebResponse)request.GetResponse(); System.IO.Stream dataStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); result = Newtonsoft.Json.JsonConvert.DeserializeObject <mmria.common.model.couchdb.document_put_response>(responseFromServer); if (response.Headers["Set-Cookie"] != null) { string[] set_cookie = response.Headers["Set-Cookie"].Split(';'); string[] auth_array = set_cookie[0].Split('='); if (auth_array.Length > 1) { string auth_session_token = auth_array[1]; result.auth_session = auth_session_token; } else { result.auth_session = ""; } } System.Threading.Tasks.Task.Run(new Action(() => { var f = new GenerateSwaggerFile(); System.IO.File.WriteAllText(file_root_folder + "/api-docs/api.json", f.generate(metadata)); })); } catch (Exception ex) { Console.WriteLine(ex); } } if (!result.ok) { } } catch (Exception ex) { Console.WriteLine(ex); } return(result); }
/// <summary> /// Send the raw text data to router by socket. /// </summary> /// <param name="text">raw text to be sent</param> /// <returns>Send result</returns> private bool Send(string text) { //UnityEngine.Debug.Log ("Sending raw text to router: " + text); if (_clientSocket == null) { return(false); } lock (_clientSocket) { //FIXME [RACE]: I want to describe a race condition whereby, SOMETIMES // by having Disconnect print it is disconnecting, I slowed down execution enough that Send() does not fire off // the erroneously proced error message that we disconnected midSend (while the whole game is shutting down). //obviously this is not ideal at all, but I have documented it here. //SO! I am trying out ways to make sure 'LogError' doesn't run IF the game is shutting down. //enabled didn't work. _isEstablished may be too much- but it DOES seem to work. I will keep the FixMe around //a little longer... if (!this._isEstablished) { UnityEngine.Debug.Log(OCLogSymbol.CONNECTION + "OCNetworkElement is shutting down; not sending message."); _isEstablished = false; _clientSocket = null; return(false); } //UnityEngine.Debug.Log ("Are we even connected, we need to be connected to send something right..."); if (!_clientSocket.Connected) { UnityEngine.Debug.LogError(OCLogSymbol.ERROR + "We lost connection while sending!"); _isEstablished = false; _clientSocket = null; return(false); } //else //UnityEngine.Debug.Log ("Seems we're connected..."); //TODO: Delete this, I'm using it as a reference /*bool canSend = true; * while(canSend) * { * if(!_clientSocket.Pending()) * { * //UnityEngine.Debug.Log (System.DateTime.Now.ToString ("HH:mm:ss.fff") + ": Nope, not pending..."); * if (_shouldStop) * UnityEngine.Debug.LogError(OCLogSymbol.IMPOSSIBLE_ERROR + "OCServerListener.Listener() has TCPListener.Pending() reporting false. Which is funny, because IT SHOULDN'T BE HERE BECAUSE _shouldStop IS TRUE!!"); * // If listener is not pending, sleep for a while to relax the CPU. * yield return new UnityEngine.WaitForSeconds(0.5f); * } */ try { System.IO.Stream s = new System.Net.Sockets.NetworkStream(_clientSocket); System.IO.StreamWriter sw = new System.IO.StreamWriter(s); sw.Write(text); sw.Flush(); //byte[] byteArr = Encoding.UTF8.GetBytes(message); //this.socket.Send(byteArr); sw.Close(); s.Close(); //UnityEngine.Debug.Log ("OCNetworkElement::Send was succesful!"); } catch (System.Exception e) { UnityEngine.Debug.LogError(OCLogSymbol.ERROR + "Something went wrong in OCNetworkElement::Send: " + e.Message); return(false); } } return(true); }
public void Consume(object arg) { Params p = (Params)arg; using (consume_outputfile = new System.IO.StreamWriter(p.Path + "\\consume.txt")) { consume_outputfile.WriteLine("Database: " + Program.Database + "\t Variables: " + p.Variables + "\t Iterations: " + p.Iterations + "\t Timespan: " + p.timeSpan + "\t WriteFrequency: " + p.writefrequency + "\t InitIterations: " + p.inititerations); consume_outputfile.WriteLine("Variables\tDuration(ms)\tReadCount"); int variables = p.Variables; TimeSpan variabletimespanTS = p.timeSpan; telemetry_c = new Telemetry(Program.VmName, p.Path, variables, adapter); telemetry_c.SetID("consume"); telemetry_c.InitTelemetryCollection("consume"); bool ex = false; while (c_mRunning) { System.Diagnostics.Stopwatch sww = new System.Diagnostics.Stopwatch(); for (int ii = 0; ii < p.inititerations; ii++) { if (!c_mRunning) { break; } sww.Restart(); adapter.PrepareReadMultipleLatest(variables, variabletimespanTS); adapter.ReadStatic(variables, variabletimespanTS); sww.Stop(); int wait = 1000 - (int)sww.ElapsedMilliseconds; if (wait > 0) { System.Threading.Thread.Sleep(wait); } } var percent = p.Iterations / 100; for (int i = 0; i < p.Iterations; i++) { if (!c_mRunning) { break; } adapter.PrepareReadMultipleLatest(variables, variabletimespanTS); var sw = System.Diagnostics.Stopwatch.StartNew(); try { adapter.ReadStatic(variables, variabletimespanTS); }catch (System.NullReferenceException e) { ex = true; continue; } sw.Stop(); if (ex) { System.Console.WriteLine("Consumer: OK"); ex = false; } double elap = sw.Elapsed.TotalMilliseconds; try { consume_outputfile.WriteLine(variables + "\t" + elap + "\t" + adapter.GetStaticReadCount()); } catch (System.ObjectDisposedException) { } if (i % percent == 0) { System.Console.WriteLine("Consumer: " + i / percent + "% progress"); } int sleep = 1000 - (int)elap; if (sleep > 0) { System.Threading.Thread.Sleep(sleep); } } while (!p_done) { if (!c_mRunning) { break; } adapter.PrepareReadMultipleLatest(variables, variabletimespanTS); try { adapter.ReadStatic(variables, variabletimespanTS); } catch (System.NullReferenceException e) { ex = true; continue; } } break; } System.Console.WriteLine("Consumer ending"); telemetry_c.CollectVariableRunTelemetry(variables); telemetry_c.mRunning = false; consume_outputfile.Flush(); consume_outputfile.Close(); consume_outputfile.Dispose(); } }
/// <summary> /// Constructs a new SingleInstance object /// </summary> /// <param name="basefolder">The folder in which the control file structure is placed</param> /// public SingleInstance(string basefolder) { if (!System.IO.Directory.Exists(basefolder)) { System.IO.Directory.CreateDirectory(basefolder); } m_controldir = System.IO.Path.Combine(basefolder, CONTROL_DIR); if (!System.IO.Directory.Exists(m_controldir)) { System.IO.Directory.CreateDirectory(m_controldir); } m_lockfilename = System.IO.Path.Combine(m_controldir, CONTROL_FILE); m_file = null; System.IO.Stream temp_fs = null; try { if (Platform.IsClientPosix) { temp_fs = UnixSupport.File.OpenExclusive(m_lockfilename, System.IO.FileAccess.Write); } else { temp_fs = System.IO.File.Open(m_lockfilename, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None); } if (temp_fs != null) { System.IO.StreamWriter sw = new System.IO.StreamWriter(temp_fs); sw.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Id); sw.Flush(); //Do not dispose sw as that would dispose the stream m_file = temp_fs; } } catch { if (temp_fs != null) { try { temp_fs.Dispose(); } catch {} } } //If we have write access if (m_file != null) { m_filewatcher = new System.IO.FileSystemWatcher(m_controldir); m_filewatcher.Created += new System.IO.FileSystemEventHandler(m_filewatcher_Created); m_filewatcher.EnableRaisingEvents = true; DateTime startup = System.IO.File.GetLastWriteTime(m_lockfilename); //Clean up any files that were created before the app launched foreach (string s in SystemIO.IO_OS.GetFiles(m_controldir)) { if (s != m_lockfilename && System.IO.File.GetCreationTime(s) < startup) { try { System.IO.File.Delete(s); } catch { } } } } else { //Wait for the initial process to signal that the filewatcher is activated int retrycount = 5; while (retrycount > 0 && new System.IO.FileInfo(m_lockfilename).Length == 0) { System.Threading.Thread.Sleep(500); retrycount--; } //HACK: the unix file lock does not allow us to read the file length when the file is locked if (new System.IO.FileInfo(m_lockfilename).Length == 0) { if (!Platform.IsClientPosix) { throw new Exception("The file was locked, but had no data"); } } //Notify the other process that we have started string filename = System.IO.Path.Combine(m_controldir, COMM_FILE_PREFIX + Guid.NewGuid().ToString()); //Write out the commandline arguments string[] cmdargs = System.Environment.GetCommandLineArgs(); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(Platform.IsClientPosix ? UnixSupport.File.OpenExclusive(filename, System.IO.FileAccess.Write) : new System.IO.FileStream(filename, System.IO.FileMode.CreateNew, System.IO.FileAccess.Write, System.IO.FileShare.None))) for (int i = 1; i < cmdargs.Length; i++) //Skip the first, as that is the filename { sw.WriteLine(cmdargs[i]); } //Wait for the other process to delete the file, indicating that it is processed retrycount = 5; while (retrycount > 0 && System.IO.File.Exists(filename)) { System.Threading.Thread.Sleep(500); retrycount--; } //This may happen if the other process is closing as we write the command if (System.IO.File.Exists(filename)) { //Try to clean up, so the other process does not spuriously show this try { System.IO.File.Delete(filename); } catch { } throw new Exception("The lock file was locked, but the locking process did not respond to the start command"); } } }
public static void CheckAllModels() { Dictionary <string, MyModel> modelsLod0 = new Dictionary <string, MyModel>(); Dictionary <string, MyModel> modelsLod1 = new Dictionary <string, MyModel>(); Dictionary <string, MyModel> modelsCol = new Dictionary <string, MyModel>(); foreach (MyModel model in m_models) { model.LoadOnlyModelInfo(); string smallAsset = model.AssetName; if (smallAsset.EndsWith("_COL")) { modelsCol.Add(smallAsset.Substring(0, smallAsset.Length - 4), model); } else if (smallAsset.EndsWith("_LOD1")) { modelsLod1.Add(smallAsset.Substring(0, smallAsset.Length - 5), model); } else { modelsLod0.Add(smallAsset, model); } } using (System.IO.StreamWriter output = new System.IO.StreamWriter(System.IO.File.Open("All_models.csv", System.IO.FileMode.Create))) { output.WriteLine("lod0 AssetName" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "LOD0 Triangles" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "LOD1 AssetName" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "LOD1 Triangles" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "COL AssetName" + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + "COL Triangles"); foreach (KeyValuePair <string, MyModel> lod0 in modelsLod0) { string part2 = MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR.ToString(), part3 = MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR.ToString(); if (modelsLod1.ContainsKey(lod0.Key)) { MyModel lod1 = modelsLod1[lod0.Key]; if (lod0.Value.ModelInfo.TrianglesCount < lod1.ModelInfo.TrianglesCount * 4 && lod1.ModelInfo.TrianglesCount > 50) { part2 = lod1.AssetName + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + lod1.ModelInfo.TrianglesCount; } } if (modelsCol.ContainsKey(lod0.Key)) { MyModel col = modelsCol[lod0.Key]; if (lod0.Value.ModelInfo.TrianglesCount < col.ModelInfo.TrianglesCount * 4 && col.ModelInfo.TrianglesCount > 50) { part3 = col.AssetName + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + col.ModelInfo.TrianglesCount; } } if (part2 != MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR.ToString() || part3 != MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR.ToString()) { output.WriteLine(lod0.Value.AssetName + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + lod0.Value.ModelInfo.TrianglesCount + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + part2 + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + part3); } } output.WriteLine(); foreach (KeyValuePair <string, MyModel> lod0 in modelsLod0) { if ((!modelsLod1.ContainsKey(lod0.Key) || !modelsCol.ContainsKey(lod0.Key)) && lod0.Value.ModelInfo.TrianglesCount > 50) { if (lod0.Value.AssetName.Contains("Prefab")) { output.WriteLine(lod0.Value.AssetName + MyModelsStatisticsConstants.MODEL_STATISTICS_CSV_SEPARATOR + lod0.Value.ModelInfo.TrianglesCount); } } } output.Flush(); output.Close(); } }
/// <summary> /// 遍历动态循环 /// </summary> public void Cycle(SoraApi api) { if (api == null) { return; } var path = "config.json"; string jsonString; using (System.IO.StreamReader file = System.IO.File.OpenText(path)) { using (JsonTextReader reader = new JsonTextReader(file)) { JObject o = (JObject)JToken.ReadFrom(reader); //遍历up for (int i = 0; i < o["up"].Count(); i++) { var up = o["up"][i]; int id = 0; int.TryParse(up["id"].ToString(), out id); if (id > 0) { // 获取entity var entity = moment.GetMoment(id).Result; if (entity.feedList == null || entity.feedList.Length == 0) { continue; } var entity1 = entity.feedList.First(); //判断是否有更新 bool isUpdated = false; try { isUpdated = (int.Parse(up["newmomentid"].ToString()) < int.Parse(entity1.moment.momentId)); } catch (Exception e) { Console.WriteLine(e.Message); } if (isUpdated) { long uid = 0; object[] msg = GetMessages(entity1); //对每个提醒qq发送消息 foreach (var notifyqq in up["notifyqq"]) { long.TryParse(notifyqq.ToString(), out uid); if (uid > 0) { api.SendPrivateMessage(uid, msg); } } //对每个提醒qq群发送消息 foreach (var notifygroup in up["notifygroup"]) { long.TryParse(notifygroup.ToString(), out uid); if (uid > 0) { api.SendPrivateMessage(uid, msg); } } //回写entityid o["up"][i]["newmomentid"] = entity1.moment.momentId; } //撤回消息 bool isCalceled = (int.Parse(up["newmomentid"].ToString()) > int.Parse(entity1.moment.momentId)); if (isCalceled) { //回写entityid o["up"][i]["newmomentid"] = entity1.moment.momentId; } } } //修改后存入字符串 jsonString = JsonConvert.SerializeObject(o); } } //回写config using (System.IO.StreamWriter writer = new System.IO.StreamWriter(path)) { writer.WriteLine(jsonString); writer.Flush(); } }
/// <summary> /// 输出一条日志信息。 /// </summary> /// <param name="log">日志实体。</param> private void WriteLog(LogEntity log) { if (log == null) { return; } if (this._OutLogEvent != null && (this.OutputType & LogOutputType.LogEvent) == LogOutputType.LogEvent) { this._OutLogEvent(log); } if ((this.OutputType & LogOutputType.Debugger) == LogOutputType.Debugger) { System.Diagnostics.Debug.Write(this.Log2String(log, this.LogFormat)); } if ((this.OutputType & LogOutputType.Console) == LogOutputType.Console) { System.Console.Write(this.Log2String(log, this.LogFormat)); } if ((this.OutputType & LogOutputType.LogFile) == LogOutputType.LogFile) { lock (this.LockThis) { string f = this.GetCurrentLogFile(); System.IO.FileStream fs = new System.IO.FileStream(f, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.Read); try { System.IO.StreamWriter sw = new System.IO.StreamWriter(fs, System.Text.Encoding.UTF8); try { if (this.LogFormat == LogFormatType.XML) { if (sw.BaseStream.Length == 0) //如果是一个新的日志文件,则写入 XML 说明。 { sw.Write(XMLDocBeginTag); } else //如果是一个已经存在的日志文件,则将新日志数据写入位置定位到最后一条日志信息末尾。 { sw.BaseStream.Seek(0 - XMLDocEndTag.Length, System.IO.SeekOrigin.End); } } else { sw.BaseStream.Seek(0, System.IO.SeekOrigin.End); //定位文件指针到文件末尾。 } if (this.OutputType != LogOutputType.LogFile) //如果日志还输出到其他的位置(不仅限于日志文件)。 { sw.Write(this.Log2String(log, this.LogFormat)); sw.Flush(); } else { do { sw.Write(this.Log2String(log, this.LogFormat)); sw.Flush(); log = null; #region 处理多条日志写入操作,避免重复打开文件耗时操作。 if (this.wqLog.Count > 0 && fs.Length < this.MaxLogFileSize * 1024) //检查是否还有需要写入的日志,如果没有则关闭日志文件,否则继续写入下一条日志信息。 { log = this.wqLog.Get(0); } #endregion }while (log != null); } } finally { if (this.LogFormat == LogFormatType.XML) { sw.Write(XMLDocEndTag); } sw.Flush(); sw.Close(); } } finally { fs.Close(); fs.Dispose(); } } } }
private static void Send(string text, ref System.IO.StreamWriter w) { w.Write(text + "\r\n"); w.Flush(); }
private void btnSurnameSearch_Click(object sender, EventArgs e) { try { // throw new IndexOutOfRangeException(); string _Connectionstring = @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\MitchellMusicDB.mdf;Integrated Security=True"; frmAddStudent add = new frmAddStudent(); using (SqlConnection connection = new SqlConnection(_Connectionstring)) { connection.Open(); if (tb_Name.Text == "") { string sqlQuery = string.Format("SELECT * FROM tbl_Student WHERE Student_Surname LIKE '{0}'", tb_Surname.Text); SqlCommand insertCommand = new SqlCommand(sqlQuery, connection); SqlDataReader rdr = insertCommand.ExecuteReader(); // if (rdr.Read()) { this.tb_ID.Enabled = false; this.tb_ID.Text = rdr[0].ToString(); this.tb_Name.Text = rdr[1].ToString(); this.tb_Surname.Text = rdr[2].ToString(); this.tb_Address1.Text = rdr[3].ToString(); this.tb_Address2.Text = rdr[4].ToString(); this.tb_Postcode.Text = rdr[5].ToString(); this.tb_Tel.Text = rdr[6].ToString(); this.tb_Instrument.Text = rdr[7].ToString(); this.tb_Tutor.Text = rdr[8].ToString(); this.cbo_Status.Text = rdr[9].ToString(); this.cboClass.Text = rdr[11].ToString(); this.checkBox1.Checked = Convert.ToBoolean(rdr[12].ToString()); this.cboLevel.Text = rdr[13].ToString(); rdr.Close(); } else { add.showBalloonTip("Unsuccessful", "Could Not find Data!"); rdr.Close(); } } else { string sqlQuery = string.Format("SELECT * FROM tbl_Student WHERE Student_Surname LIKE '{0}' and Student_Name LIKE '{1}'", tb_Surname.Text, tb_Name.Text); SqlCommand insertCommand = new SqlCommand(sqlQuery, connection); SqlDataReader rdr = insertCommand.ExecuteReader(); if (rdr.Read()) { this.tb_ID.Enabled = false; this.tb_ID.Text = rdr[0].ToString(); this.tb_Name.Text = rdr[1].ToString(); this.tb_Surname.Text = rdr[2].ToString(); this.tb_Address1.Text = rdr[3].ToString(); this.tb_Address2.Text = rdr[4].ToString(); this.tb_Postcode.Text = rdr[5].ToString(); this.tb_Tel.Text = rdr[6].ToString(); this.tb_Instrument.Text = rdr[7].ToString(); this.tb_Tutor.Text = rdr[8].ToString(); this.cbo_Status.Text = rdr[9].ToString(); this.cboClass.Text = rdr[11].ToString(); this.checkBox1.Checked = Convert.ToBoolean(rdr[12].ToString()); this.cboLevel.Text = rdr[13].ToString(); rdr.Close(); } else { add.showBalloonTip("Unsuccessful", "Could Not find Data!"); rdr.Close(); } } connection.Dispose(); connection.Close(); } } catch (Exception ex) { if (count2 < 1) { add.showBalloonTip("Error", "Something Went Wrong"); } System.IO.StreamWriter writer = new System.IO.StreamWriter("../../ErrorLog.txt", true); writer.WriteLine("- " + DateTime.Now + " " + ex.Message, true); writer.Flush(); writer.Close(); count2++; } }
public static void ImpEtiquetaLayout(List <TRegistro_Objeto> obj, string Porta, CamadaDados.Diversos.TRegistro_CadTerminal rTerminal, bool sobra = false) { if (!System.IO.Directory.Exists("c:\\aliance.net")) { System.IO.Directory.CreateDirectory("c:\\aliance.net"); } //carrega layouts TList_CadLayoutEtiqueta lLyaout = new TList_CadLayoutEtiqueta(); if (rTerminal.Id_layout != decimal.Zero) { lLyaout = TCN_CadLayoutEtiqueta.Busca(rTerminal.Id_layout.ToString(), string.Empty, null); } if (lLyaout.Count <= 0) { return; } lLyaout.ForEach(p => { p.lCampos = TCN_CamposLayout.Busca(string.Empty, p.Id_layoutstr, string.Empty, null); }); decimal total_etiqueta = obj.Sum(p => p.Qtd_etiqueta); //desagrupar quantidades e definir posicoes List <TRegistro_Objeto> prod_un = new List <TRegistro_Objeto>(); int pos = 0; obj.ForEach(p => { for (int i = 1; i <= p.Qtd_etiqueta; i++) { pos++; prod_un.Add(new TRegistro_Objeto() { Codigo = p.Codigo, Cod_barra = p.Cod_barra, Produto = p.Produto, Vl_preco = p.Vl_preco, posicao = pos }); //1 1 2 if (pos == 3) //2 2 3 { pos = 0; //3 3 3 } } }); decimal total_imprimido = decimal.Zero; //lista de impressao StringBuilder w = new StringBuilder(); lLyaout.ForEach(p => { TList_CamposEtiqueta lcamp = new TList_CamposEtiqueta(); p.lCampos.ForEach(o => { lcamp.Add(o); }); pos = 0; prod_un.ForEach(pro => { pos++; if (string.IsNullOrEmpty(w.ToString())) { w.AppendLine("I8,A,001"); w.AppendLine(); w.AppendLine(); w.AppendLine("Q" + p.alturaetiqueta.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0" + p.larguraetiqueta.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true))); w.AppendLine("rN"); w.AppendLine("S4"); w.AppendLine("D7"); w.AppendLine("ZT"); w.AppendLine("JF"); w.AppendLine("OD"); w.AppendLine("f100"); w.AppendLine("N"); } string prod1 = string.Empty; string prod2 = string.Empty; string prod3 = pro.Produto; if (pro.Produto.Trim().Length > 20) { prod1 = pro.Produto.Trim().Substring(0, 20); pro.Produto = pro.Produto.Remove(0, 20); if (pro.Produto.Trim().Length > 20) { prod2 = pro.Produto.Trim().Substring(0, 20); pro.Produto = pro.Produto.Remove(0, 20); } else { prod2 = pro.Produto; } } else { prod1 = pro.Produto; } pro.Produto = prod3; lcamp.ForEach(o => { string tp = string.Empty; if (o.Status.Equals("CAMPO")) { tp = "A"; } else { tp = "B"; } if (o.ds_campo.Equals("DESCRICAO") && o.coluna.Equals(pro.posicao)) { w.AppendLine(tp + o.posx.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + "," + o.posy.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0,2,1,1,N,\"" + prod1.Trim() + "\""); } if (o.ds_campo.Equals("DESCRICAO2") && o.coluna.Equals(pro.posicao)) { w.AppendLine(tp + o.posx.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + "," + o.posy.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0,2,1,1,N,\"" + prod2.Trim() + "\""); } else if (o.ds_campo.Equals("VALOR") && o.coluna.Equals(pro.posicao)) { w.AppendLine(tp + o.posx.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + "," + o.posy.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0,2,1,1,N,\"" //A24,56 + " Cd:" + pro.Codigo.ToString() + "\""); //+ pro.Vl_preco.ToString("C2", new System.Globalization.CultureInfo("pt-BR", true)) + " Cd:" + pro.Codigo.ToString() + "\""); } else if (o.ds_campo.Equals("COD_BAR") && o.coluna.Equals(pro.posicao)) { w.AppendLine(tp + o.posx.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + "," + o.posy.ToString("N0", new System.Globalization.CultureInfo("pt-BR", true)) + ",0,E30,2,4,56,B,\"" + pro.Cod_barra.Trim() + "\"");//B40,88 } }); if (pos == 3 || (decimal.Subtract(total_etiqueta, decimal.Add(total_imprimido, pos)) == decimal.Zero)) { System.IO.FileInfo f = new System.IO.FileInfo("c:\\aliance.net\\etiqueta.txt"); System.IO.StreamWriter we = f.CreateText(); try { w.AppendLine("P1"); we.WriteLine(w.ToString()); } finally { we.Flush(); we.Dispose(); f.CopyTo(Porta.Trim()); pos = 0; w.Clear(); total_imprimido += 3; } } }); }); }
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 static void Log(this System.IO.StreamWriter logStream, string log) { logStream.WriteLine(System.DateTime.Now.ToString() + ": " + log); logStream.Flush(); }
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 methodsDef = " MethodInfo[] methods = type.GetMethods(flag).Where(t => !t.IsGenericMethod).ToArray();"; string fieldDef = " FieldInfo field;"; string argsDef = " Type[] args;"; string typeDef = string.Format(" Type type = typeof({0});", realClsName); bool needMethods; 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, out needMethods); 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, null); string fieldWraperCode = i.GenerateFieldWraperCode(fields, realClsName, excludeFields, valueTypeBinders, null); 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); } if (needMethods) { sb.AppendLine(methodsDef); } 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 static void GenerateBindingCode(ILRuntime.Runtime.Enviorment.AppDomain domain, string outputPath, List <Type> valueTypeBinders = null, List <Type> delegateTypes = null, params string[] excludeFiles) { 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>(); FileNameEqualityComparer fileNameEqualityComparer = new FileNameEqualityComparer(); 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 (excludeFiles.Contains(clsName)) { continue; } int extraClsNameIndex = 0; string oClsName = clsName; while (clsNames.Contains(oClsName)) { extraClsNameIndex++; oClsName = clsName + "_t" + extraClsNameIndex; } clsNames.Add(oClsName); clsName = oClsName; //File path length limit string oriFileName = outputPath + "/" + clsName; int len = Math.Min(oriFileName.Length, 100); if (len < oriFileName.Length) { oriFileName = oriFileName.Substring(0, len); } int extraNameIndex = 0; string oFileName = oriFileName; while (files.Contains(oFileName, fileNameEqualityComparer)) { extraNameIndex++; oFileName = oriFileName + "_t" + extraNameIndex; } 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.Linq; 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 methodsDef = " MethodInfo[] methods = type.GetMethods(flag).Where(t => !t.IsGenericMethod).ToArray();"; string fieldDef = " FieldInfo field;"; string argsDef = " Type[] args;"; string typeDef = string.Format(" Type type = typeof({0});", realClsName); bool needMethods; MethodInfo[] methods = info.Value.Methods.ToArray(); FieldInfo[] fields = info.Value.Fields.ToArray(); string registerMethodCode = i.GenerateMethodRegisterCode(methods, excludeMethods, out needMethods); 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, domain); string fieldWraperCode = fields.Length > 0 ? i.GenerateFieldWraperCode(fields, realClsName, excludeFields, valueTypeBinders, domain) : 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); } if (needMethods) { sb.AppendLine(methodsDef); } 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 {"); sb.Append(SmartBindText); sb.Append(@" /// <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); }
static void engine_AffectivEmoStateUpdated(object sender, EmoStateUpdatedEventArgs e) { EmoState es = e.emoState; Single timeFromStart = es.GetTimeFromStart(); EdkDll.EE_AffectivAlgo_t[] affAlgoList = { EdkDll.EE_AffectivAlgo_t.AFF_ENGAGEMENT_BOREDOM, EdkDll.EE_AffectivAlgo_t.AFF_EXCITEMENT, EdkDll.EE_AffectivAlgo_t.AFF_FRUSTRATION, EdkDll.EE_AffectivAlgo_t.AFF_MEDITATION, }; Boolean[] isAffActiveList = new Boolean[affAlgoList.Length]; Single longTermExcitementScore = es.AffectivGetExcitementLongTermScore(); Single shortTermExcitementScore = es.AffectivGetExcitementShortTermScore(); for (int i = 0; i < affAlgoList.Length; ++i) { isAffActiveList[i] = es.AffectivIsActive(affAlgoList[i]); } Single meditationScore = es.AffectivGetMeditationScore(); Single frustrationScore = es.AffectivGetFrustrationScore(); Single boredomScore = es.AffectivGetEngagementBoredomScore(); double rawScoreEc = 0, rawScoreMd = 0, rawScoreFt = 0, rawScoreEg = 0; double minScaleEc = 0, minScaleMd = 0, minScaleFt = 0, minScaleEg = 0; double maxScaleEc = 0, maxScaleMd = 0, maxScaleFt = 0, maxScaleEg = 0; double scaledScoreEc = 0, scaledScoreMd = 0, scaledScoreFt = 0, scaledScoreEg = 0; es.AffectivGetExcitementShortTermModelParams(out rawScoreEc, out minScaleEc, out maxScaleEc); if (minScaleEc != maxScaleEc) { if (rawScoreEc < minScaleEc) { scaledScoreEc = 0; } else if (rawScoreEc > maxScaleEc) { scaledScoreEc = 1; } else { scaledScoreEc = (rawScoreEc - minScaleEc) / (maxScaleEc - minScaleEc); } Console.WriteLine("Affectiv Short Excitement: Raw Score {0:f5} Min Scale {1:f5} max Scale {2:f5} Scaled Score {3:f5}\n", rawScoreEc, minScaleEc, maxScaleEc, scaledScoreEc); } es.AffectivGetEngagementBoredomModelParams(out rawScoreEg, out minScaleEg, out maxScaleEg); if (minScaleEg != maxScaleEg) { if (rawScoreEg < minScaleEg) { scaledScoreEg = 0; } else if (rawScoreEg > maxScaleEg) { scaledScoreEg = 1; } else { scaledScoreEg = (rawScoreEg - minScaleEg) / (maxScaleEg - minScaleEg); } Console.WriteLine("Affectiv Engagement : Raw Score {0:f5} Min Scale {1:f5} max Scale {2:f5} Scaled Score {3:f5}\n", rawScoreEg, minScaleEg, maxScaleEg, scaledScoreEg); } es.AffectivGetMeditationModelParams(out rawScoreMd, out minScaleMd, out maxScaleMd); if (minScaleMd != maxScaleMd) { if (rawScoreMd < minScaleMd) { scaledScoreMd = 0; } else if (rawScoreMd > maxScaleMd) { scaledScoreMd = 1; } else { scaledScoreMd = (rawScoreMd - minScaleMd) / (maxScaleMd - minScaleMd); } Console.WriteLine("Affectiv Meditation : Raw Score {0:f5} Min Scale {1:f5} max Scale {2:f5} Scaled Score {3:f5}\n", rawScoreMd, minScaleMd, maxScaleMd, scaledScoreMd); } es.AffectivGetFrustrationModelParams(out rawScoreFt, out minScaleFt, out maxScaleFt); if (maxScaleFt != minScaleFt) { if (rawScoreFt < minScaleFt) { scaledScoreFt = 0; } else if (rawScoreFt > maxScaleFt) { scaledScoreFt = 1; } else { scaledScoreFt = (rawScoreFt - minScaleFt) / (maxScaleFt - minScaleFt); } Console.WriteLine("Affectiv Frustration : Raw Score {0:f5} Min Scale {1:f5} max Scale {2:f5} Scaled Score {3:f5}\n", rawScoreFt, minScaleFt, maxScaleFt, scaledScoreFt); } affLog.Write( "{0},{1},{2},{3},{4},{5},", timeFromStart, longTermExcitementScore, shortTermExcitementScore, meditationScore, frustrationScore, boredomScore); for (int i = 0; i < affAlgoList.Length; ++i) { affLog.Write("{0},", isAffActiveList[i]); } affLog.WriteLine(""); affLog.Flush(); }
private WLID_FolderItem FindFolders(bool autocreate) { var folders = (m_rootfolder + '/' + m_prefix).Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (folders.Length == 0) { var url = string.Format("{0}/{1}?access_token={2}", WLID_SERVER, ROOT_FOLDER_ID, Library.Utility.Uri.UrlEncode(AccessToken)); return(GetJSONData <WLID_FolderItem>(url)); } WLID_FolderItem cur = null; foreach (var f in folders) { var n = FindFolder(f, cur == null ? null : cur.id); if (n == null) { if (autocreate) { var url = string.Format("{0}/{1}?access_token={2}", WLID_SERVER, cur == null ? ROOT_FOLDER_ID : cur.id, Library.Utility.Uri.UrlEncode(AccessToken)); var req = (HttpWebRequest)WebRequest.Create(url); req.UserAgent = USER_AGENT; req.Method = "POST"; var areq = new Utility.AsyncHttpRequest(req); using (var ms = new System.IO.MemoryStream()) using (var sw = new System.IO.StreamWriter(ms)) { new Newtonsoft.Json.JsonSerializer().Serialize(sw, new WLID_CreateFolderData() { name = f, description = LC.L("Autocreated folder") }); sw.Flush(); ms.Position = 0; req.ContentLength = ms.Length; req.ContentType = "application/json"; using (var reqs = areq.GetRequestStream()) Utility.Utility.CopyStream(ms, reqs); } using (var resp = (HttpWebResponse)areq.GetResponse()) using (var rs = areq.GetResponseStream()) using (var tr = new System.IO.StreamReader(rs)) using (var jr = new Newtonsoft.Json.JsonTextReader(tr)) { if ((int)resp.StatusCode < 200 || (int)resp.StatusCode > 299) { throw new ProtocolViolationException(string.Format(LC.L("Unexpected error code: {0} - {1}"), resp.StatusCode, resp.StatusDescription)); } cur = new Newtonsoft.Json.JsonSerializer().Deserialize <WLID_FolderItem>(jr); } } else { throw new FolderMissingException(LC.L("Missing the folder: {0}", f)); } } else { cur = n; } } return(cur); }