public void SetWindowState(SW State) { ShowWindowAsync(Handle, (int)State); }
public static extern bool ShowWindowAsync(IntPtr hWnd, SW nCmdShow);
/// <summary> /// Helper method to print the response in a readable format /// </summary> /// <returns> /// return string formatted response /// </returns> public override string ToString() { return("ApduResponse SW=" + SW.ToString("X4") + " (" + SWTranslation + ")" + ((ResponseData != null && ResponseData.Length > 0) ? (",Data=" + BitConverter.ToString(ResponseData).Replace("-", "")) : "")); }
public static extern IntPtr ShellExecute( IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, SW nShowCmd);
public SNROutputFile(string dirName) : base(dirName, "snrs.csv") { SW.WriteLine("Movie,ZMW,Channel,SNR"); }
internal static extern bool ShowWindow(IntPtr hwnd, SW nCmdShow);
public virtual void SyncLanguages(string lang1, string lang2) { using (var x = SW.Measure()) { string[] types = new string[] { "Columns", "Words", "Pages", "Messages" }; foreach (string type in types) { string resLang1 = Path.Combine(_paths.LocalizationRoot, "Localization", type + "." + lang1 + ".resx"); string resLang2 = Path.Combine(_paths.LocalizationRoot, "Localization", type + "." + lang2 + ".resx"); ResxXmlReader reader = new ResxXmlReader(); var data1 = new List <DataItem>(); var data2 = new List <DataItem>(); var headers1 = new ResHeaderItem[0]; var headers2 = new ResHeaderItem[0]; if (reader.TryRead(resLang1, out ResourceContainer cont1)) { cont1.DataItems = cont1.DataItems ?? new DataItem[0]; Out.WriteLine("Found " + type + "." + lang1 + ".resx with " + cont1.DataItems.Length + " items"); headers1 = cont1.Headers; data1 = new List <DataItem>(); data1.AddRange(cont1.DataItems); } if (reader.TryRead(resLang2, out ResourceContainer cont2)) { cont2.DataItems = cont2.DataItems ?? new DataItem[0]; Out.WriteLine("Found " + type + "." + lang2 + ".resx with " + cont2.DataItems.Length + " items"); headers2 = cont2.Headers; data2 = new List <DataItem>(); data2.AddRange(cont2.DataItems); } int i = 0; foreach (var item in data1) { if (!data2.Any(d => d.Name == item.Name)) { data2.Add(new DataItem { Name = item.Name, Value = "", Space = item.Space }); i++; } } Out.WriteLine($"{lang1} --> {lang2} : Added {i} Entries.."); i = 0; foreach (var item in data2) { if (!data1.Any(d => d.Name == item.Name)) { data1.Add(new DataItem { Name = item.Name, Value = type == "Messages" ? LangUtils.IdToPhrase(item.Name) : "", Space = item.Space }); i++; } } Out.WriteLine($"{lang2} --> {lang1} : Added {i} Entries.."); reader.Save(resLang1, new ResourceContainer { DataItems = data1.ToArray(), Headers = headers1 }); reader.Save(resLang2, new ResourceContainer { DataItems = data2.ToArray(), Headers = headers2 }); } WriteSuccess(x.Elapsed); } }
/// <summary> /// /// </summary> /// <param name="hwnd"></param> /// <param name="nCmdShow"></param> /// <returns></returns> public static bool ShowWindow(IntPtr hwnd, SW nCmdShow) { return NativeMethods.ShowWindow(hwnd, nCmdShow); }
public static extern bool ShowWindow(IntPtr handle, SW nCmdShow);
public void TruncateLogFile(string sLogPath) { if (m_logquotaformat == elogquotaformat.no_restriction) { return; } long nfileSize = 0; long i = 0; long j = 0; if (!File.Exists(sLogPath)) { return; } switch (m_logquotaformat) { case elogquotaformat.kbytes: try { FileInfo info = new FileInfo(sLogPath); nfileSize = info.Length; } catch (Exception x) { System.Console.WriteLine("Error:" + x.Message); nfileSize = 0; } if (nfileSize < (m_logsizemax * 1024)) { return; } break; case elogquotaformat.rows: using (StreamReader sr = new StreamReader(sLogPath)) { String line; while ((line = sr.ReadLine()) != null) { i++; } if (i < m_logsizemax) { return; } } break; } File.Delete(sLogPath + ".new"); StreamWriter SW; SW = File.AppendText(sLogPath + ".new"); using (StreamReader sr = new StreamReader(sLogPath)) { switch (m_logquotaformat) { case elogquotaformat.kbytes: char[] c = null; long bufsize = 1024; //should match streams natural buffer size. long kb = 1024; j = (long)((m_logsizemax * kb) * .9); while (sr.Peek() >= 0) { c = new char[bufsize]; sr.Read(c, 0, c.Length); i++; if ((i * bufsize) > j) { for (i = 0; i < c.Length; i++) { if (c[i] == '\r' && c[i + 1] == '\n') { //write out the remaining part of the last line. char[] c2 = new char[i + 2]; Array.Copy(c, 0, c2, 0, i + 2); SW.Write(c2); break; } } break; } else { SW.Write(c); } } break; case elogquotaformat.rows: String line; j = (long)(m_logsizemax * .9); //reduce by 10% below max. while ((line = sr.ReadLine()) != null) { SW.WriteLine(line); i++; if (i > j) { break; } } break; } } SW.Close(); File.Delete(sLogPath); File.Move(sLogPath + ".new", sLogPath); }
public Rw(string fileNameTXT, string fileLogName) { conf Config = new conf(); FileStream fs = new FileStream(fileNameTXT, FileMode.Open, FileAccess.ReadWrite); DataTable docNames = new DataTable(); docNames.Columns.Add("WZ", typeof(string)); String[] documents; string pdfName = fileNameTXT.Replace(".txt", ".pdf"); StreamReader sr = new StreamReader(fs); while (!sr.EndOfStream) { string text = sr.ReadLine().Replace(" ", ""); if ( text.Contains("rk") && text.Contains("us") && text.Contains("LP/") || text.Contains("Ar") && text.Contains("k") && text.Contains("s") ) { compilerDocName.Rw RwName = new ocr_wz.compilerDocName.Rw(); RwName.RWfirst(text); documents = RwName.resultRW.Split(';'); foreach (var document in documents) { if (document.Contains("LP_")) { RwName.LP(document); if (RwName.resultRW != null) { docNames.Rows.Add(RwName.resultRW); } } else if (document.Contains("RW_")) { RwName.RW(document); if (RwName.resultRW != null) { docNames.Rows.Add(RwName.resultRW); } } } } } if (docNames.Rows.Count == 0) { string docName = pdfName.Replace(Config.inPath + "\\!ocr\\po_ocr\\", ""); Copy CopyNewName = new Copy(pdfName, "0", docName, fileLogName); CopyNewName.CopyOther(); } else { var UniqueRows = docNames.AsEnumerable().Distinct(DataRowComparer.Default); DataTable uniqDocNames = UniqueRows.CopyToDataTable(); StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("Tablica dokumentów:"); SW.Close(); int rw = 0; int lp = 0; foreach (DataRow row in uniqDocNames.Rows) { StreamWriter SW1; SW1 = File.AppendText(fileLogName); SW1.WriteLine(row.Field <string>(0)); SW1.Close(); if (row.Field <string>(0).Contains("LP_")) { lp++; yearDocs yearOut = new yearDocs(row.Field <string>(0)); yearOut.yearLP(); year = yearOut.year; } else if (row.Field <string>(0).Contains("RW_")) { rw++; } } if (rw == lp || rw > lp) { foreach (DataRow row in uniqDocNames.Rows) { if (row.Field <string>(0).Contains("RW_")) { Copy CopyNewName = new Copy(pdfName, year, row.Field <string>(0), fileLogName); CopyNewName.CopyRW(); } } } else { foreach (DataRow row in uniqDocNames.Rows) { if (row.Field <string>(0).Contains("LP_")) { Copy CopyNewName = new Copy(pdfName, year, row.Field <string>(0), fileLogName); CopyNewName.CopyRW(); } } } fs.Close(); } }
public static string RunExeGetOutput(string folderPath, string fileOutExePath, string[] inputs) { string Output = string.Empty; ProcessStartInfo startInfo = new ProcessStartInfo(); Process myprocess = new Process(); try { startInfo.WorkingDirectory = folderPath; startInfo.FileName = fileOutExePath; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; startInfo.UseShellExecute = false; //'required to redirect startInfo.CreateNoWindow = true; // '<---- creates no window, obviously startInfo.Verb = "runas"; myprocess.StartInfo = startInfo; myprocess.Start(); System.IO.StreamReader SR; System.IO.StreamWriter SW; Thread.Sleep(200); SR = myprocess.StandardOutput; SW = myprocess.StandardInput; Thread.Sleep(200); for (int i = 0; i < inputs.Length; i++) { SW.WriteLine(inputs[i]); Thread.Sleep(200); } SW.WriteLine("exit"); // 'exits program prompt window SW.WriteLine("exit"); // 'exits command prompt window myprocess.WaitForExit(5000); if (!myprocess.HasExited) { myprocess.Kill(); } while (!myprocess.StandardOutput.EndOfStream) { string outs = myprocess.StandardOutput.ReadLine(); Output += outs + Environment.NewLine; } SW.Close(); SR.Close(); return(Output.TrimEnd()); } catch (Exception e) { if (myprocess != null && (!myprocess.HasExited)) { myprocess.Kill(); } //while (!myprocess.StandardError.EndOfStream) //{ // Output = "Error: " + myprocess.StandardError.ReadLine() + Environment.NewLine; //} throw e; } }
public static extern BOOL ShowWindow( [In] HWND hWnd, [In] SW nCmdShow );
static void Main(string[] args) { string folder = ""; NeatGenome seedGenome = null; string filename = null; string shape = "triangle"; bool isMulti = false; for (int j = 0; j < args.Length; j++) { if (j <= args.Length - 2) { switch (args[j]) { case "-seed": filename = args[++j]; Console.WriteLine("Attempting to use seed from file " + filename); break; case "-folder": folder = args[++j]; Console.WriteLine("Attempting to output to folder " + folder); break; case "-shape": shape = args[++j]; Console.WriteLine("Attempting to do experiment with shape " + shape); break; case "-multi": isMulti = Boolean.Parse(args[++j]); Console.WriteLine("Experiment is heterogeneous? " + isMulti); break; } } } if (filename != null) { try { XmlDocument document = new XmlDocument(); document.Load(filename); seedGenome = XmlNeatGenomeReaderStatic.Read(document); } catch (Exception e) { System.Console.WriteLine("Problem loading genome. \n" + e.Message); } } double maxFitness = 0; int maxGenerations = 1000; int populationSize = 150; int inputs = 4; IExperiment exp = new SkirmishExperiment(inputs, 1, isMulti, shape); StreamWriter SW; SW = File.CreateText(folder + "logfile.txt"); XmlDocument doc; FileInfo oFileInfo; IdGenerator idgen; EvolutionAlgorithm ea; if (seedGenome == null) { idgen = new IdGenerator(); ea = new EvolutionAlgorithm(new Population(idgen, GenomeFactory.CreateGenomeList(exp.DefaultNeatParameters, idgen, exp.InputNeuronCount, exp.OutputNeuronCount, exp.DefaultNeatParameters.pInitialPopulationInterconnections, populationSize)), exp.PopulationEvaluator, exp.DefaultNeatParameters); } else { idgen = new IdGeneratorFactory().CreateIdGenerator(seedGenome); ea = new EvolutionAlgorithm(new Population(idgen, GenomeFactory.CreateGenomeList(seedGenome, populationSize, exp.DefaultNeatParameters, idgen)), exp.PopulationEvaluator, exp.DefaultNeatParameters); } for (int j = 0; j < maxGenerations; j++) { DateTime dt = DateTime.Now; ea.PerformOneGeneration(); if (ea.BestGenome.Fitness > maxFitness) { maxFitness = ea.BestGenome.Fitness; doc = new XmlDocument(); XmlGenomeWriterStatic.Write(doc, (NeatGenome)ea.BestGenome); oFileInfo = new FileInfo(folder + "bestGenome" + j.ToString() + ".xml"); doc.Save(oFileInfo.FullName); // This will output the substrate, uncomment if you want that /* doc = new XmlDocument(); * XmlGenomeWriterStatic.Write(doc, (NeatGenome) SkirmishNetworkEvaluator.substrate.generateMultiGenomeModulus(ea.BestGenome.Decode(null),5)); * oFileInfo = new FileInfo(folder + "bestNetwork" + j.ToString() + ".xml"); * doc.Save(oFileInfo.FullName); */ } Console.WriteLine(ea.Generation.ToString() + " " + ea.BestGenome.Fitness + " " + (DateTime.Now.Subtract(dt))); //Do any post-hoc stuff here SW.WriteLine(ea.Generation.ToString() + " " + (maxFitness).ToString()); } SW.Close(); doc = new XmlDocument(); XmlGenomeWriterStatic.Write(doc, (NeatGenome)ea.BestGenome, ActivationFunctionFactory.GetActivationFunction("NullFn")); oFileInfo = new FileInfo(folder + "bestGenome.xml"); doc.Save(oFileInfo.FullName); }
public static void ShowWindow(IntPtr hWnd, SW flags) { NativeMethods.ShowWindow(hWnd, (int)flags); }
public string SaveXslt(string fileName, string oldName, string fileContents, bool ignoreDebugging) { fileName = fileName.CleanForXss(); if (AuthorizeRequest(DefaultApps.developer.ToString())) { IOHelper.EnsurePathExists(SystemDirectories.Xslt); // validate file IOHelper.ValidateEditPath(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName), SystemDirectories.Xslt); // validate extension IOHelper.ValidateFileExtension(IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName), new List <string>() { "xsl", "xslt" }); StreamWriter SW; string tempFileName = IOHelper.MapPath(SystemDirectories.Xslt + "/" + DateTime.Now.Ticks + "_temp.xslt"); SW = File.CreateText(tempFileName); SW.Write(fileContents); SW.Close(); // Test the xslt string errorMessage = ""; if (!ignoreDebugging) { try { // Check if there's any documents yet string xpath = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "/root/node" : "/root/*"; if (content.Instance.XmlContent.SelectNodes(xpath).Count > 0) { var macroXML = new XmlDocument(); macroXML.LoadXml("<macro/>"); var macroXSLT = new XslCompiledTransform(); var umbPage = new page(content.Instance.XmlContent.SelectSingleNode("//* [@parentID = -1]")); var xslArgs = macro.AddMacroXsltExtensions(); var lib = new library(umbPage); xslArgs.AddExtensionObject("urn:umbraco.library", lib); HttpContext.Current.Trace.Write("umbracoMacro", "After adding extensions"); // Add the current node xslArgs.AddParam("currentPage", "", library.GetXmlNodeById(umbPage.PageID.ToString())); HttpContext.Current.Trace.Write("umbracoMacro", "Before performing transformation"); // Create reader and load XSL file // We need to allow custom DTD's, useful for defining an ENTITY var readerSettings = new XmlReaderSettings(); readerSettings.ProhibitDtd = false; using (var xmlReader = XmlReader.Create(tempFileName, readerSettings)) { var xslResolver = new XmlUrlResolver(); xslResolver.Credentials = CredentialCache.DefaultCredentials; macroXSLT.Load(xmlReader, XsltSettings.TrustedXslt, xslResolver); xmlReader.Close(); // Try to execute the transformation var macroResult = new HtmlTextWriter(new StringWriter()); macroXSLT.Transform(macroXML, xslArgs, macroResult); macroResult.Close(); File.Delete(tempFileName); } } else { //errorMessage = ui.Text("developer", "xsltErrorNoNodesPublished"); File.Delete(tempFileName); //base.speechBubble(speechBubbleIcon.info, ui.Text("errors", "xsltErrorHeader", base.getUser()), "Unable to validate xslt as no published content nodes exist."); } } catch (Exception errorXslt) { File.Delete(tempFileName); errorMessage = (errorXslt.InnerException ?? errorXslt).ToString(); // Full error message errorMessage = errorMessage.Replace("\n", "<br/>\n"); //closeErrorMessage.Visible = true; // Find error var m = Regex.Matches(errorMessage, @"\d*[^,],\d[^\)]", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace); foreach (Match mm in m) { string[] errorLine = mm.Value.Split(','); if (errorLine.Length > 0) { var theErrorLine = int.Parse(errorLine[0]); var theErrorChar = int.Parse(errorLine[1]); errorMessage = "Error in XSLT at line " + errorLine[0] + ", char " + errorLine[1] + "<br/>"; errorMessage += "<span style=\"font-family: courier; font-size: 11px;\">"; var xsltText = fileContents.Split("\n".ToCharArray()); for (var i = 0; i < xsltText.Length; i++) { if (i >= theErrorLine - 3 && i <= theErrorLine + 1) { if (i + 1 == theErrorLine) { errorMessage += "<b>" + (i + 1) + ": >>> " + Server.HtmlEncode(xsltText[i].Substring(0, theErrorChar)); errorMessage += "<span style=\"text-decoration: underline; border-bottom: 1px solid red\">" + Server.HtmlEncode( xsltText[i].Substring(theErrorChar, xsltText[i].Length - theErrorChar)). Trim() + "</span>"; errorMessage += " <<<</b><br/>"; } else { errorMessage += (i + 1) + ": " + Server.HtmlEncode(xsltText[i]) + "<br/>"; } } } errorMessage += "</span>"; } } } } if (errorMessage == "" && fileName.ToLower().EndsWith(".xslt")) { //Hardcoded security-check... only allow saving files in xslt directory... var savePath = IOHelper.MapPath(SystemDirectories.Xslt + "/" + fileName); if (savePath.StartsWith(IOHelper.MapPath(SystemDirectories.Xslt + "/"))) { //deletes the old xslt file if (fileName != oldName) { var p = IOHelper.MapPath(SystemDirectories.Xslt + "/" + oldName); if (File.Exists(p)) { File.Delete(p); } } SW = File.CreateText(savePath); SW.Write(fileContents); SW.Close(); errorMessage = "true"; } else { errorMessage = "Illegal path"; } } File.Delete(tempFileName); return(errorMessage); } return("false"); }
public static bool ShowWindowAsync(IntPtr handle, SW showState) { return NativeMethods.ShowWindowAsync((int)handle, (int)showState); }
/// <summary> /// To generate excel file. /// </summary> /// <param name="oDataTable"></param> /// <param name="directoryPath"></param> /// <param name="fileName"></param> /// <returns></returns> public string Convert(DataTable oDataTable, string directoryPath, string fileName) { string fullpath = ""; if (directoryPath.Substring(directoryPath.Length - 1, 1) == @"\" || directoryPath.Substring(directoryPath.Length - 1, 1) == "/") { fullpath = directoryPath + fileName; } else { fullpath = directoryPath + @"\" + fileName; } StreamWriter SW; SW = File.CreateText(fullpath); StringBuilder oStringBuilder = new StringBuilder(); /******************************************************** * Start, check for border width * ******************************************************/ int borderWidth = 0; if (_ShowExcelTableBorder) { borderWidth = 1; } /******************************************************** * End, Check for border width * ******************************************************/ /******************************************************** * Start, Check for bold heading * ******************************************************/ string boldTagStart = ""; string boldTagEnd = ""; if (_ExcelHeaderBold) { boldTagStart = "<B>"; boldTagEnd = "</B>"; } /******************************************************** * End,Check for bold heading * ******************************************************/ oStringBuilder.Append("<Table border=" + borderWidth + ">"); /******************************************************************* * Start, Creating table header * *****************************************************************/ oStringBuilder.Append("<TR>"); foreach (DataColumn oDataColumn in oDataTable.Columns) { oStringBuilder.Append("<TD>" + boldTagStart + oDataColumn.ColumnName + boldTagEnd + "</TD>"); } oStringBuilder.Append("</TR>"); /******************************************************************* * End, Creating table header * *****************************************************************/ /******************************************************************* * Start, Creating rows * *****************************************************************/ foreach (DataRow oDataRow in oDataTable.Rows) { oStringBuilder.Append("<TR>"); foreach (DataColumn oDataColumn in oDataTable.Columns) { if (oDataRow[oDataColumn.ColumnName] is long) { oStringBuilder.Append("<TD align=right>" + oDataRow[oDataColumn.ColumnName] + "</TD>"); } else { oStringBuilder.Append("<TD>" + oDataRow[oDataColumn.ColumnName] + "</TD>"); } } oStringBuilder.Append("</TR>"); } /******************************************************************* * End, Creating rows * *****************************************************************/ oStringBuilder.Append("</Table>"); SW.WriteLine(oStringBuilder.ToString()); SW.Close(); return(fullpath); }
internal static extern BOOL ShowWindow(IntPtr hWnd, SW nCmdShow);
public static partial BOOL ShowWindow(IntPtr hWnd, SW nCmdShow);
static void Main(string[] args) { string IP = "152.78.241.226"; int port = 2525; HighBidTurn ST1 = new HighBidTurn(); Coordinate TestC; //coordinateSIT TestC; //This is to create a directory which records the MySQL results in a time and date folder String Todaysdate = DateTime.Now.ToString("dd-MM-yyyy-HH.mm"); string ResultsDirectory = @"C:\Documents and Settings\Siemens\Desktop\Andrew's Work\Paramics Models\Poole Junction\Paramics 2010.1 Version\Cabot Lane Poole V3\Results\" + Todaysdate; if (!Directory.Exists(ResultsDirectory)) { Directory.CreateDirectory(ResultsDirectory); } string ResultsDir = ResultsDirectory; ResultsDir = ResultsDirectory.Replace("'", "''"); //This is because MySQL uses an apostrophe (') as it's delimiter ResultsDir = ResultsDir.Replace("\\", "//"); //How many times would you like the program to run int NumberOfRuns = 1; int Counter = 0; while (Counter < NumberOfRuns) { if (args.Length == 0) { //string[] fnames = new string[] { "TrainedTriJ1H7.csv", "TrainedTriJ2H7.csv", "TrainedTriJ3H7.csv" }; //string[] sigNs = new string[] { "1", "0", "2" }; //TestC = new coordinateSIT("JunctionDesignTriC.XML", ST1, IP, port); // <--- Simon used this one 05/11/12 //TestC = new Coordinate("JunctionDesignMillbrook.XML", ST1, IP, port); //<--- Simon used this one 20/11/12 //TestC = new Coordinate("JunctionDesignSimpleCrossroads.XML", ST1, IP, port); //Andrew's attempt on Simple Crossroads 20/11/12 //TestC = new Coordinate("JunctionDesignSimpleCrossroads3Lane.XML", ST1, IP, port); //Andrew's Simple Crossroads - 3 lane 02/09/13 //TestC = new Coordinate("JunctionDesignPooleJunction.XML", ST1, IP, port); //Stages are same as existing stages - 4 stage solution //TestC = new Coordinate("JunctionDesignPooleJunction - WithTurningIntention.XML", ST1, IP, port); //Stages are adapted to 8 stage solution TestC = new Coordinate("JunctionDesignSopersLane.XML", ST1, IP, port); //Stages are adapted to 8 stage solution //TestC = new coordinateSIT("JunctionDesignSimpleCrossroads3Lane.XML", ST1, IP, port); //Andrew's Simple Crossroads - 3 lane 04/12/13 //TestC = new Coordinate("JunctionDesignSimpleCrossroads2LaneStraightBoth.XML", ST1, IP, port); //Andrew's Simple Crossroads - 2 lane - Both Straight Ahead 04/12/13 //TestC = new Coordinate("JunctionDesignSimpleCrossroads2LaneStraightLeft.XML", ST1, IP, port); //Andrew's Simple Crossroads - 2 lane - Straight and Left Lane Together, Dedicated Right 04/12/13 //TestC = new Coordinate("JunctionDesignSimpleCrossroads2LaneStraightRight.XML", ST1, IP, port); //Andrew's Simple Crossroads - 2 lane - Straight and Right Lane Together, Dedicated Left 04/12/13 ParamicsPuppetMaster.EditConfig ECG = new ParamicsPuppetMaster.EditConfig(TestC.ParamicsPath); ECG.SetDemandRate(100); //ECG.SetStartTime(07); //ParamicsPuppetMaster.EditDemands EDM = new ParamicsPuppetMaster.EditDemands(TestC.ParamicsPath, A.Demands); } else { TestC = new Coordinate("JunctionDesignOrigV2flat.xml", ST1, IP, port); } try { //ParaESVstarter StartParamicsModel = new ParaESVstarter(TestC.ParamicsPath); ParaBSMstarter StartParamicsModel = new ParaBSMstarter(TestC.ParamicsPath); StartParamicsModel.LauncParamics(); TestC.ConnectToParamics(); Thread.Sleep(2000); Runner Run = new Runner(TestC); Run.SynchRun(5400); //AH added this function to save the biddata and linkturningmovements tables after a run TestC.SaveTables(Counter, ResultsDir); } catch (Exception e) { StreamWriter SW; SW = File.AppendText(@"C:\Documents and Settings\Siemens\Desktop\Andrew's Work\C# Code\ParamicsSNMPcontrolV3\BigRunLog.txt"); SW.WriteLine("G = {0:G}", DateTime.Now); foreach (string s in args) { SW.WriteLine(s); } SW.WriteLine(e.Message); SW.WriteLine("*******************************"); SW.WriteLine(""); SW.WriteLine(""); SW.Close(); } Counter++; } }
public void addPoint(Player p, string foundPath, string additional = "", string extra = "10", string more = "2") { string[] allLines; try { allLines = File.ReadAllLines("bots/" + foundPath); } catch { allLines = new string[1]; } StreamWriter SW; try { if (!File.Exists("bots/" + foundPath)) { Player.SendMessage(p, "Created new bot AI: &b" + foundPath); SW = new StreamWriter(File.Create("bots/" + foundPath)); SW.WriteLine("#Version 2"); } else if (allLines[0] != "#Version 2") { Player.SendMessage(p, "File found is out-of-date. Overwriting"); SW = new StreamWriter(File.Create("bots/" + foundPath)); SW.WriteLine("#Version 2"); } else { Player.SendMessage(p, "Appended to bot AI: &b" + foundPath); SW = new StreamWriter("bots/" + foundPath, true); } } catch { Player.SendMessage(p, "An error occurred when accessing the files. You may need to delete it."); return; } try { switch (additional.ToLower()) { case "": case "walk": SW.WriteLine("walk " + p.pos[0] + " " + p.pos[1] + " " + p.pos[2] + " " + p.rot[0] + " " + p.rot[1]); break; case "teleport": case "tp": SW.WriteLine("teleport " + p.pos[0] + " " + p.pos[1] + " " + p.pos[2] + " " + p.rot[0] + " " + p.rot[1]); break; case "wait": SW.WriteLine("wait " + int.Parse(extra)); break; case "nod": SW.WriteLine("nod " + int.Parse(extra) + " " + int.Parse(more)); break; case "speed": SW.WriteLine("speed " + int.Parse(extra)); break; case "remove": SW.WriteLine("remove"); break; case "reset": SW.WriteLine("reset"); break; case "spin": SW.WriteLine("spin " + int.Parse(extra) + " " + int.Parse(more)); break; case "reverse": for (int i = allLines.Length - 1; i > 0; i--) { if (allLines[i][0] != '#' && allLines[i] != "") { SW.WriteLine(allLines[i]); } } break; case "linkscript": if (extra != "10") { SW.WriteLine("linkscript " + extra); } else { Player.SendMessage(p, "Linkscript requires a script as a parameter"); } break; case "jump": SW.WriteLine("jump"); break; default: Player.SendMessage(p, "Could not find \"" + additional + "\""); break; } SW.Flush(); SW.Close(); SW.Dispose(); } catch { Player.SendMessage(p, "Invalid parameter"); SW.Close(); } }
public void getAgent(ref SW agent, int id) { agent = agents_[id]; }
public static extern bool ShowWindow(IntPtr hwnd, SW nCmdShow);
public void setAgent(ref SW agent, int id) { agents_[id] = agent; }
public static extern bool ShowWindow(HWND hWnd, SW nCmdShow);
void ResetAgents() { agents_.Clear(); foreach (var wa in walkerAgents_) { Destroy(wa); } walkerAgents_.Clear(); foreach (var tar in targetAgents_) { Destroy(tar); } targetAgents_.Clear(); for (int i = 0; i < numAgents_; i++) { float hue = (float)i / numAgents_; Color newColor = Color.HSVToRGB(hue, 1f, 1f); Color newColorDark = Color.HSVToRGB(hue, 1f, 0.5f); Vector3 pos = new Vector3(Random.Range(minBound_.x, maxBound_.x), 0.5f, Random.Range(minBound_.z, maxBound_.z)); Vector3 tar = new Vector3(Random.Range(minBound_.x, maxBound_.x), 0.5f, Random.Range(minBound_.z, maxBound_.z)); SW S = new SW(); S.init(pos, tar); agents_.Add(S); GameObject walkerClone = Instantiate(walkerPrefab_, pos, Quaternion.identity); walkerClone.GetComponent <MeshRenderer>().material.color = newColor; GameObject targetClone = Instantiate(targetPrefab_, tar, Quaternion.identity); targetClone.GetComponent <MeshRenderer>().material.color = newColorDark; if (imitationLearning) { if (i == 0) { walkerClone.GetComponent <SWAgent>().GiveBrain(TeacherBrain_.GetComponent <Brain>()); } else { walkerClone.GetComponent <SWAgent>().GiveBrain(StudentBrain_.GetComponent <Brain>()); } } else { walkerClone.GetComponent <SWAgent>().GiveBrain(SocialWalkerBrain_.GetComponent <Brain>()); } walkerClone.GetComponent <SWAgent>().sw_id = i; walkerClone.GetComponent <SWAgent>().target_ = targetClone; walkerAgents_.Add(walkerClone); targetAgents_.Add(targetClone); agentActive_.Add(true); } }
static void Main(string[] args) { string msgLog = ""; string _arquivo = args[0]; if (!_arquivo) { msgLog += "\rNome de arquivo não informado..."; } else if (!File.Exists(_arquivo)) { msgLog += "\rArquivo {0} inexistente..." + _arquivo; } else { //Console.Write("URI a ser assinada (Ex.: infCanc, infNFe, infInut, etc.) :"); //string _uri = Console.ReadLine(); string _uri = args[1]; //"LoteRps"; if (_uri == null) { msgLog += "\rURI não informada..."; } else { // // le o arquivo xml // StreamReader SR; string _stringXml; SR = File.OpenText(_arquivo); _stringXml = RemoverCaracteresEspeciais(RemoverAcentos(SR.ReadToEnd())); //_stringXml = SR.ReadToEnd(); SR.Close(); // // realiza assinatura // AssinaturaDigital AD = new AssinaturaDigital(); // // cria cert // X509Certificate2 cert = new X509Certificate2(); // // seleciona certificado do repositório MY do windows // //Certificado certificado = new Certificado(); //string nroSerieCertificado = Convert.ToString(ConfigurationManager.AppSettings["nroSerieCertificado"]); //cert = certificado.BuscaNroSerie(nroSerieCertificado); int resultado = AD.Assinar(_stringXml, _uri, args[2], args[3]); if (resultado == 0) { // // grava arquivo assinado // StreamWriter SW; SW = File.CreateText(_arquivo.Replace(".xml", "_ass.xml").Trim()); SW.Write(AD.XMLStringAssinado); SW.Close(); /* * XmlTextWriter writer = new XmlTextWriter(_arquivo.Replace(".xml", "_ass.xml").Trim(), null); * writer.Formatting = Formatting.Indented; * AD.XMLDocAssinado.Save(writer); */ } msgLog += AD.mensagemResultado; // // grava arquivo de log // StreamWriter Log; Log = File.CreateText(_arquivo.Replace(".xml", "_log.txt").Trim()); Log.Write(msgLog); Log.Close(); } } }
public ActionResult Index(HttpPostedFileBase file, int?value) { if (file != null) { int tamaño = 0; int final = 0; //String PathP = System.Configuration.ConfigurationManager.AppSettings["Path"].ToString(); String PathP = Request.MapPath("~/ReportesXLS"); string CodeString = ""; String FileName = file.FileName; String Extention = Path.GetExtension(file.FileName); var root = Path.Combine(PathP, "Analytics"); try { if (System.IO.Directory.Exists(root)) { root = Path.Combine(root, FileName); file.SaveAs(root); } else { Directory.CreateDirectory(root); root = Path.Combine(root, FileName); file.SaveAs(root); } } catch (Exception e) { String msg = e.Message; return(Json(msg, JsonRequestBehavior.AllowGet)); } string path = root; DirectoryInfo directory = new DirectoryInfo(path); FileInfo item = new FileInfo(path); string allcontent = getContent(item.FullName); allcontent = ReplaceContent(allcontent); if (value == 1) { allcontent = CreateCad(allcontent); //String conexion = "data source=195.192.2.249;initial catalog=PLMClients 20160913;user id=sa;password=t0m$0nl@t1n@"; String conexion = System.Configuration.ConfigurationManager.AppSettings["Conexion"].ToString(); SqlConnection cnn = new SqlConnection(conexion); cnn.Open(); try { String consulta = "select distinct ClientId from plm_vwClientsByApplication where CodeString in (" + allcontent + ")" + " "; SqlCommand cmd = new SqlCommand(consulta, cnn); SqlDataReader read = cmd.ExecuteReader(); if (read.HasRows == true) { while (read.Read()) { CodeString = CodeString + read.GetValue(0).ToString() + ","; } } allcontent = CodeString.Trim(); } catch (Exception e) { } } tamaño = allcontent.Length; final = tamaño - 1; allcontent = allcontent.Substring(0, final); StreamWriter SW; SW = System.IO.File.CreateText(PathP + @"\Content.txt"); root = Path.Combine(root, "Content.txt"); SW.Write(allcontent); SW.Close(); SW.Dispose(); return(View()); } return(View()); }
public ReadTxt(string fileNameTXT, string fileLogName) { try { if (File.Exists(fileNameTXT)) { FileStream fs = new FileStream(fileNameTXT, FileMode.Open, FileAccess.ReadWrite); StreamReader sr = new StreamReader(fs); int wz = 0; int ww = 0; int fv = 0; int rw = 0; int raben = 0; int schenker = 0; while (!sr.EndOfStream) { string text1 = sr.ReadLine().Replace(" ", ""); compilerDocName.All allCompiler = new ocr_wz.compilerDocName.All(text1); string text = allCompiler.resultText; if (text.Contains("FAKTURA") && !text.Contains("KORYGUJ") && text.Contains("F/")) { fv++; } else if (((text.Contains("yda") || text.Contains("ani")) && text.Contains("mer")) && (text.Contains("WZ") || text.Contains("WŻ") || text.Contains("wz") || text.Contains("Wz") || text.Contains("W2/") || text.Contains("WZ/"))) { wz++; } else if (text.Contains("yda") && text.Contains("mer") && text.Contains("WW")) { ww++; } else if (text.Contains("rku") && text.Contains("LP/")) { rw++; } else if ((text.Contains("ZA") && text.Contains("CZO") && text.Contains("DOKU")) || text.Contains("Raben")) { raben++; } else if ((text.Contains("oku") && text.Contains("nt") && text.Contains("WZ"))) { schenker++; } } fs.Close(); if (wz > 0) { if (ww > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się dokumenty WZ i dokument WW"); SW.Close(); documents.Wz Wz = new documents.Wz(fileNameTXT, fileLogName); documents.Ww Ww = new documents.Ww(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else if (fv > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się dokumenty WZ i FV"); SW.Close(); documents.Wz Wz = new documents.Wz(fileNameTXT, fileLogName); documents.Fv Fv = new documents.Fv(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else if (rw > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się dokumenty WZ i RW"); documents.Wz Wz = new documents.Wz(fileNameTXT, fileLogName); documents.Rw Rw = new documents.Rw(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else if (raben > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się dokumenty WZ i dokument dostawy Raben"); SW.Close(); documents.Wz Wz = new documents.Wz(fileNameTXT, fileLogName); documents.Raben Raben = new documents.Raben(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else if (schenker > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się dokumenty WZ i dokument dostawy Schenker"); SW.Close(); documents.Wz Wz = new documents.Wz(fileNameTXT, fileLogName); documents.Schenker Schenker = new documents.Schenker(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się tylko dokumenty WZ"); SW.Close(); documents.Wz Wz = new ocr_wz.documents.Wz(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } } else if (fv < 1 && wz < 1 && ww < 1 && rw < 1 && raben < 1 && schenker < 1) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!! Nie mogę odczytać dokumentu !!! dokument nazwany ZAS"); SW.Close(); documents.Zas Zas = new ocr_wz.documents.Zas(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else if (wz < 1) { if (ww > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się tylko dokumenty WW"); SW.Close(); documents.Ww Ww = new ocr_wz.documents.Ww(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else if (fv > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się tylko dokumenty FV"); SW.Close(); documents.Fv Fv = new ocr_wz.documents.Fv(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else if (raben > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się tylko dokumenty dostawy Raben"); SW.Close(); documents.Raben Raben = new ocr_wz.documents.Raben(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else if (schenker > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się tylko dokumenty dostawy Schenker"); SW.Close(); documents.Schenker Schenker = new ocr_wz.documents.Schenker(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } else if (rw > 0) { try { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("W pliku znajdują się tylko dokumenty RW"); SW.Close(); documents.Rw RW = new ocr_wz.documents.Rw(fileNameTXT, fileLogName); PdfOcrDone pdfDone = new PdfOcrDone(fileNameTXT); } catch { StreamWriter SW; SW = File.AppendText(fileLogName); SW.WriteLine("!!Przetwarzanie zakończono błędem!!"); SW.Close(); } } } } } catch (Exception ex) { Console.WriteLine("Nie odnaleziono pliku txt!" + ex); } }
public JsonResult XML(string file) { int count = 0; int final = 0; String conexion = "data source=195.192.2.249;initial catalog=Medinet 20170721;user id=sa;password=t0m$0nl@t1n@"; SqlConnection cnn = new SqlConnection(conexion); cnn.Open(); try { List <GetXML> GetXML_Result = new List <GetXML>(); String consulta = "select * from FXML where XMLContent is not null"; SqlCommand cmd = new SqlCommand(consulta, cnn); SqlDataReader read = cmd.ExecuteReader(); String PathP = System.Configuration.ConfigurationManager.AppSettings["Path"].ToString(); if (read.HasRows == true) { while (read.Read()) { GetXML GetXML = new GetXML(); GetXML.NameXML = read.GetValue(9).ToString(); GetXML.XMLContent = read.GetValue(10).ToString(); GetXML_Result.Add(GetXML); var root = Path.Combine(PathP, "XML"); GetXML.NameXML = ReplaceContent(GetXML.NameXML); if (System.IO.File.Exists(root + @"\" + GetXML.NameXML)) { GetXML.NameXML = GetXML.NameXML + "_1"; } StreamWriter SW; SW = System.IO.File.CreateText(root + @"\" + GetXML.NameXML); root = Path.Combine(root, GetXML.NameXML); SW.Write(GetXML.XMLContent); SW.Close(); SW.Dispose(); count = count + 1; } } else { string men = "No hay datos"; } //return View(GetClient_Result); final = count; return(Json(true, JsonRequestBehavior.AllowGet)); } catch (Exception e) { string message = e.Message; return(Json(false, JsonRequestBehavior.AllowGet)); } }
} // selection public void crossover() { int numberOfGenerations = 0; setAveFitAndStdDev(); while (numberOfGenerations < NUMGENERATIONS) { List <Chromosome> parents = selection(); List <Chromosome> newPopulation = new List <Chromosome>(); List <Gene> parent1; List <Gene> parent2; Console.WriteLine("Generation " + numberOfGenerations + " average fitness = " + averagePopulationFitness); while (newPopulation.Count < POPSIZE) { parent1 = parents[random.Next(parents.Count)].getGenes(); parent2 = parents[random.Next(parents.Count)].getGenes(); Chromosome child = new Chromosome(); /* schedule any fixed events first */ List <Gene> fixedEvents = (from g in parent1 where g.getCannotChange() == true select g).ToList(); foreach (Gene g in fixedEvents) { child.add(g.getSlot(), g.getEvent(), g.getRoom(), g.getCannotChange()); } /* schedule any lunch events next */ int[] days = { 1, 2, 4, 5 }; foreach (int day in days) { List <Gene> lunchEvents = (from g in parent1 where g.getEvent().getCourse() == "Lunch" && g.getSlot().getDay() == day select g).ToList(); lunchEvents.AddRange(from g in parent2 where g.getEvent().getCourse() == "Lunch" && g.getSlot().getDay() == day select g); foreach (string grp in Program.groups) { List <Gene> slotsForGroup = (from g in lunchEvents where g.getEvent().getGroups().Contains(grp) select g).ToList(); Gene selectedLunchSlot = slotsForGroup[0]; /* Might have to put a check in here to ensure that not all of the groups * (or at least a majority) have lunch at the same time */ if (slotsForGroup.Count > 1) { // check that there aren't any clashes (this might occur for groups with external events bool slotFound = false; int i = 0; while ((i < slotsForGroup.Count) && (!slotFound)) { if (!child.doClashesExist(slotsForGroup[i].getSlot(), slotsForGroup[i].getEvent(), slotsForGroup[i].getRoom())) { slotFound = true; selectedLunchSlot = slotsForGroup[i]; } i++; } } if (!child.hasLunchBeenScheduled(selectedLunchSlot.getSlot(), selectedLunchSlot.getEvent())) { child.add(Program.slots[Program.slots.IndexOf(selectedLunchSlot.getSlot())], selectedLunchSlot.getEvent(), selectedLunchSlot.getRoom(), selectedLunchSlot.getCannotChange()); child.add(Program.slots[Program.slots.IndexOf(child.getCorrespondingSlot(selectedLunchSlot.getSlot()))], selectedLunchSlot.getEvent(), selectedLunchSlot.getRoom(), selectedLunchSlot.getCannotChange()); } } } /* choose a random point from which to start going through the timetable */ Slot startSlot = Program.slots[random.Next(Program.slots.Count)]; int startPoint = Program.slots.IndexOf(startSlot); for (int i = startPoint; i < Program.slots.Count; i++) { Slot s = Program.slots[i]; List <Gene> p1GenesWeekly = (from g in parent1 where (g.getSlot() == s) select g).ToList(); List <Gene> p2GenesWeekly = (from g in parent2 where (g.getSlot() == s) select g).ToList(); scheduleLists(s, p1GenesWeekly, p2GenesWeekly, child); } for (int i = 0; i < startPoint; i++) { Slot s = Program.slots[i]; List <Gene> p1GenesWeekly = (from g in parent1 where (g.getSlot() == s) select g).ToList(); List <Gene> p2GenesWeekly = (from g in parent2 where (g.getSlot() == s) select g).ToList(); scheduleLists(s, p1GenesWeekly, p2GenesWeekly, child); } if (random.NextDouble() < MUTATION) { child.mutate(); } newPopulation.Add(child); } population = newPopulation; numberOfGenerations++; } // output 100th gen fitness to file StreamWriter SW; SW = File.AppendText("C:\\Users\\Stu\\Desktop\\Constant analysis\\Mutation " + MUTATION + ".txt"); SW.WriteLine(averagePopulationFitness); SW.Close(); //Console.WriteLine("Text Appended Successfully"); sortPopulation(); //Console.WriteLine("\n\n" + population[0]); } // crossover
public static extern BOOL ShowWindow(IntPtr hWnd, SW nCmdShow);
public static void PerformUpdate(bool oldrevision) { try { StreamWriter SW; if (!Server.mono) { if (!File.Exists("Update.bat")) { SW = new StreamWriter(File.Create("Update.bat")); } else { if (File.ReadAllLines("Update.bat")[0] != "::Version 3") { SW = new StreamWriter(File.Create("Update.bat")); } else { SW = new StreamWriter(File.Create("Update_generated.bat")); } } SW.WriteLine("::Version 3"); SW.WriteLine("TASKKILL /pid %2 /F"); SW.WriteLine("if exist MCPink_.dll.backup (erase MCPink_.dll.backup)"); SW.WriteLine("if exist MCPink_.dll (rename MCPink_.dll MCPink_.dll.backup)"); SW.WriteLine("if exist MCPink.new (rename MCPink.new MCPink_.dll)"); SW.WriteLine("start MCPink.exe"); } else { if (!File.Exists("Update.sh")) { SW = new StreamWriter(File.Create("Update.sh")); } else { if (File.ReadAllLines("Update.sh")[0] != "#Version 2") { SW = new StreamWriter(File.Create("Update.sh")); } else { SW = new StreamWriter(File.Create("Update_generated.sh")); } } SW.WriteLine("#Version 2"); SW.WriteLine("#!/bin/bash"); SW.WriteLine("kill $2"); SW.WriteLine("rm MCPink_.dll.backup"); SW.WriteLine("mv MCPink_.dll MCPink.dll_.backup"); SW.WriteLine("wget http://mclawl.tk/MCLawl_.dll"); SW.WriteLine("mono MCPink.exe"); } SW.Flush(); SW.Close(); SW.Dispose(); string filelocation = ""; string verscheck = ""; Process proc = Process.GetCurrentProcess(); string assemblyname = proc.ProcessName + ".exe"; if (!oldrevision) { WebClient client = new WebClient(); Server.selectedrevision = client.DownloadString("http://www.mclawl.tk/curversion.txt"); client.Dispose(); } verscheck = Server.selectedrevision.TrimStart('r'); int vers = int.Parse(verscheck.Split('.')[0]); if (oldrevision) { filelocation = ("http://www.mclawl.tk/archives/exe/" + Server.selectedrevision + ".exe"); } if (!oldrevision) { filelocation = ("http://www.mclawl.tk/MCLawl_.dll"); } WebClient Client = new WebClient(); Client.DownloadFile(filelocation, "MCPink.new"); Client.DownloadFile("http://www.mclawl.tk/changelog.txt", "extra/Changelog.txt"); foreach (Level l in Server.levels) { l.Save(); } foreach (Player pl in Player.players) { pl.save(); } string fileName; if (!Server.mono) { fileName = "Update.bat"; } else { fileName = "Update.sh"; } try { if (MCPink.Gui.Window.thisWindow.notifyIcon1 != null) { MCPink.Gui.Window.thisWindow.notifyIcon1.Icon = null; MCPink.Gui.Window.thisWindow.notifyIcon1.Visible = false; } } catch { } Process p = Process.Start(fileName, "main " + System.Diagnostics.Process.GetCurrentProcess().Id.ToString()); p.WaitForExit(); } catch (Exception e) { Server.ErrorLog(e); } }
public static extern Int32 ShowWindow(IntPtr hwnd, SW command);