/// <summary> /// Constructor /// </summary> Program() { // Set myHandler myHandlerOnExit = new HandlerRoutine(myHandler); SetConsoleCtrlHandler(myHandlerOnExit, true); statusChecker = new StatusChecker(); }
private Program() { // myHandlerメソッドの登録 myHandlerDele = new HandlerRoutine(myHandler); SetConsoleCtrlHandler(myHandlerDele, true); // 里々からのメッセージ受信処理開始 RecvObj.RecvEvt += RecvObj_RecvInfoEvt; RecvObj.Start_GetMsgFromSATORI(); }
public void Start() { if (!Environment.UserInteractive) return; var hr = new HandlerRoutine(ConsoleCtrlCheck); // keep the handler alive because the garbage collector will destroy it after any CTRL event GC.KeepAlive(hr); SetConsoleCtrlHandler(hr, true); }
static void Main(string[] args) { HandlerRoutine hr = new HandlerRoutine(ConsoleCtrlCheck); // we have to keep the handler routine alive during the execution of the program, // because the garbage collector will destroy it after any CTRL event GC.KeepAlive(hr); SetConsoleCtrlHandler(hr, true); Console.WriteLine("Press any key to start measurements"); Console.ReadKey(); VoltageTest(); }
private static void Main(string[] args) { _startColor = Console.ForegroundColor; try { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); _handler = ConsoleCtrlCheck; _processEvent = Program_Exited; SetConsoleCtrlHandler(_handler, true); Process.GetCurrentProcess().Exited += _processEvent; string url = args.Length != 1 ? InputBox.GetUrl() : args[0]; LogSuccess(url); if (string.IsNullOrEmpty(url)) { LogError("No RTSPsource url specified"); return; } bool restart = true; while (restart) { using (_dlg = new VideoStatus()) { _dlg.LoadUrl(url); Application.Run(_dlg); } Thread.Sleep(5000); restart = ViewModel.Get().AutoRestart; } } catch (Exception ex) { LogError("Error: " + ex.Message); LogError("-------------------------------"); LogError("Program Terminating"); } finally { Console.ForegroundColor = _startColor; } if (_dlg != null && !_dlg.IsDisposed) _dlg.Dispose(); LogError("Program ended"); }
public static void RunUntilCtrlC(Func<RunLoopResult> runLoop) { // http://stackoverflow.com/questions/6783561/nullreferenceexception-with-no-stack-trace-when-hooking-setconsolectrlhandler _consoleCtrlHandler = consoleCtrlHandler; SetConsoleCtrlHandler(_consoleCtrlHandler, true); for (;;) { if (_exitAtNextIteration) { break; } if (runLoop() == RunLoopResult.Quit) { break; } } }
public static bool InitConsole() { UnityEngine.Debug.Log("InitConsole"); // if (Application.platform != RuntimePlatform.WindowsPlayer) // return false; AllocConsole(); HandlerRoutine consoleDelegete = new HandlerRoutine(RoutineHandler); SetConsoleCtrlHandler(consoleDelegete, true); StdOutHandle = GetStdHandle(unchecked ((uint)STD_OUTPUT_HANDLE)); StdInHandle = GetStdHandle(unchecked ((uint)STD_INPUT_HANDLE)); // 允许控制台右键菜单 uint dwConsoleMode = 0; GetConsoleMode(StdInHandle, out dwConsoleMode); SetConsoleMode(StdInHandle, ~ENABLE_MOUSE_INPUT & dwConsoleMode); // forbid close IntPtr hWnd = GetConsoleWindow(); IntPtr hMenu = GetSystemMenu(hWnd, 0); RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND); COORD BufferSize = new COORD() { X = 120, Y = 320, }; SMALL_RECT WinRect = new SMALL_RECT() { Left = 0, Top = 0, Right = (short)(BufferSize.X - 1), Bottom = 30, }; IntPtr pBuffer = Marshal.AllocHGlobal(Marshal.SizeOf(BufferSize)); Marshal.StructureToPtr(BufferSize, pBuffer, false); if (!SetConsoleScreenBufferSize(StdOutHandle, pBuffer)) { //return false; } Marshal.FreeHGlobal(pBuffer); IntPtr pWinRect = Marshal.AllocHGlobal(Marshal.SizeOf(WinRect)); Marshal.StructureToPtr(WinRect, pWinRect, false); if (!SetConsoleWindowInfo(StdOutHandle, true, pWinRect)) { //return false; } Marshal.FreeHGlobal(pWinRect); ConsoleAlive = true; Thread th = new Thread(new ThreadStart(WorkingThread)); th.Start(); return(true); }
/// <summary>Registers the ctrl-c handler InterruptHandler.</summary> public WindowsShutdown() { // This is retarded, we have to keep the delegate in memory or it gets // GCed and this will throw a rather nasty exception! _shutdown_callback = ConsoleEventHandler; SetConsoleCtrlHandler(_shutdown_callback, true); }
internal static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, [MarshalAs(UnmanagedType.Bool)] bool addOrRemove);
static extern bool SetConsoleCtrlHandler(HandlerRoutine routine, bool add);
public static extern bool SetConsoleCtrlHandler( HandlerRoutine handlerRoutine, [MarshalAs(UnmanagedType.Bool)] bool add);
static extern bool SetConsoleCtrlHandler(HandlerRoutine HandlerRoutine, bool Add);
internal static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool Add);
static void Main(string[] args) { if (Environment.GetEnvironmentVariable(ENV_HOSTPATH) != null) { _hostsPath = Environment.GetEnvironmentVariable(ENV_HOSTPATH); Console.Write($"Overriding hosts path '{_hostsPath}'"); } if (Environment.GetEnvironmentVariable(ENV_NETWORK) != null) { _listenNetwork = Environment.GetEnvironmentVariable(ENV_NETWORK); Console.Write($"Overriding listen network '{_listenNetwork}'"); } else { Console.WriteLine("Listening to any network"); } if (Environment.GetEnvironmentVariable(ENV_SESSION) != null) { _sessionId = Environment.GetEnvironmentVariable(ENV_SESSION); Console.Write($"Overriding Session Key '{_sessionId}'"); } if (Environment.GetEnvironmentVariable(ENV_TERMMAP) != null) { var mapValue = Environment.GetEnvironmentVariable(ENV_TERMMAP); var mapSets = mapValue.Split('|'); foreach (var mapGroup in mapSets) { var mapSet = mapGroup.Split(":"); if (mapSet.Length != 2) { Console.WriteLine($"Malformed MapSet: '{ mapGroup}'. Expected 'source1,source2:dest'."); continue; } var mapDest = mapSet[1].Trim(); foreach (string mapSource in mapSet[0].Split(",", StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToList()) { if (_termMaps.ContainsKey(mapSource)) { Console.WriteLine($"Skipping DUplicate Source Map '{mapSource}'"); continue; } _termMaps.Add(mapSource.ToLower(), mapDest.ToLower()); } } Console.Write($"Using {_termMaps.Count} termination maps."); } try { _client = GetClient(); } catch (Exception ex) { Log( $"Something went wrong. Likely the Docker engine is not listening at [{_client.Configuration.EndpointBaseUri}] inside of the container."); Log($"You can change that path through environment variable '{ENV_ENDPOINT}'"); Log("Exception is " + ex.Message); Log(ex.StackTrace); if (ex.InnerException != null) { Log("InnerException is " + ex.InnerException.Message); Log(ex.InnerException.StackTrace); } //Exit Gracefully return; } Log("Starting Windows Hosts Writer"); try { _timer = new System.Timers.Timer(_timerPeriod); _timer.Elapsed += (s, e) => { DoUpdate(); }; _timer.Start(); //_timer = new Timer((s) => DoUpdate(), null, 0, _timerPeriod); var shutdown = new ManualResetEvent(false); var complete = new ManualResetEventSlim(); var hr = new HandlerRoutine(type => { Log($"ConsoleCtrlHandler got signal: {type}"); shutdown.Set(); complete.Wait(); return(false); }); SetConsoleCtrlHandler(hr, true); //Hold here until we get that shutdown event shutdown.WaitOne(); Log("Stopping server..."); Exit(); complete.Set(); GC.KeepAlive(hr); } catch (Exception ex) { Log($"Unhandled Exception: {ex.Message}"); Log(ex.StackTrace); if (ex.InnerException != null) { Log("InnerException is " + ex.InnerException.Message); Log(ex.InnerException.StackTrace); } } }
static void Main(string[] args) { if (args.Length == 0) { DisplayHelp(); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Application is running without any arguments. Starting an interactive mode."); Console.ResetColor(); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine("Please enter parameters following this step-by-step procedure:"); Console.ResetColor(); Console.WriteLine(); while (true) { Console.Write("Enter the IP address or the hostname to ping: "); string pingAddress = Console.ReadLine(); if (string.IsNullOrEmpty(pingAddress)) { continue; } if (pingAddress.Contains(" ")) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Wrong address."); Console.ResetColor(); continue; } if (!ValidateAddress.Ip(pingAddress)) { if (!ValidateAddress.HostName(pingAddress)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Cannot resolve the address to IP address."); Console.ResetColor(); continue; } } CommandLineArguments.Address = pingAddress; break; } while (true) { Console.Write("Enter the interval between RTT in ms (default is 500 ms): "); string pingInterval = Console.ReadLine(); if (string.IsNullOrEmpty(pingInterval)) { break; } if (int.TryParse(pingInterval, out int result)) { CommandLineArguments.PingRttInterval = result; } else { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Wrong interval between RTT."); Console.ResetColor(); continue; } break; } while (true) { Console.Write("Do you want to log ping to file (y/n)?: "); string enableLogAnswer = Console.ReadLine(); if (enableLogAnswer != "y" && enableLogAnswer != "n") { continue; } if (enableLogAnswer == "y") { CommandLineArguments.LogEnabled = true; } break; } } if (args.Length > 0) { UtilityArguments arguments = new UtilityArguments(args); if (args[0].StartsWith("/?") || args[0].StartsWith("?")) { DisplayHelp(); Environment.Exit(0); } if (args[0].StartsWith("-")) { DisplayHelp(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Wrong address. Please use the correct address."); Console.ResetColor(); Environment.Exit(0); } else { CommandLineArguments.Address = args[0]; } if (!string.IsNullOrEmpty(arguments.L)) { if (int.TryParse(arguments.L, out int result)) { CommandLineArguments.PacketSize = result; } else { DisplayHelp(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error parsing argument -l"); Console.WriteLine(" Wrong packet payload size."); Console.ResetColor(); Environment.Exit(0); } } if (!string.IsNullOrEmpty(arguments.C)) { if (int.TryParse(arguments.C, out int result)) { CommandLineArguments.PingCount = result; } else { DisplayHelp(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error parsing argument -c"); Console.WriteLine(" Wrong number of ping echo requests."); Console.ResetColor(); Environment.Exit(0); } } if (!string.IsNullOrEmpty(arguments.W)) { if (int.TryParse(arguments.W, out int result)) { CommandLineArguments.PingTimeout = result; } else { DisplayHelp(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error parsing argument -w"); Console.WriteLine(" Wrong timeout."); Console.ResetColor(); Environment.Exit(0); } } if (!string.IsNullOrEmpty(arguments.I)) { if (int.TryParse(arguments.I, out int result)) { CommandLineArguments.PingRttInterval = result; } else { DisplayHelp(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error parsing argument -i"); Console.WriteLine(" Wrong RTT interval."); Console.ResetColor(); Environment.Exit(0); } } if (arguments.T & (string.IsNullOrEmpty(arguments.Tt) || string.IsNullOrEmpty(arguments.Tc))) { DisplayHelp(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Telegram Bot access token and Telegram Chat ID are not defined! Please define them using -tt and -tc arguments."); Console.ResetColor(); Environment.Exit(0); } if (!string.IsNullOrEmpty(arguments.Tt) & string.IsNullOrEmpty(arguments.Tc)) { DisplayHelp(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Telegram Chat ID is not defined! Please define it using -tc argument."); Console.ResetColor(); Environment.Exit(0); } if (!string.IsNullOrEmpty(arguments.Tc) & string.IsNullOrEmpty(arguments.Tt)) { DisplayHelp(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Telegram Bot access token is not defined! Please define it using -tt argument."); Console.ResetColor(); Environment.Exit(0); } if ((arguments.Ta || arguments.Te) & (string.IsNullOrEmpty(arguments.Tt) || string.IsNullOrEmpty(arguments.Tc))) { DisplayHelp(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Telegram Bot access token or Telegram Chat ID is not defined! Please define them using -tt and -tc arguments."); Console.ResetColor(); Environment.Exit(0); } CommandLineArguments.DoNotFragment = arguments.F; CommandLineArguments.FollowTheName = arguments.Follow; CommandLineArguments.LogEnabled = arguments.Log; CommandLineArguments.AddDate = arguments.D; if (!string.IsNullOrEmpty(arguments.Tt) & !string.IsNullOrEmpty(arguments.Tc)) { CommandLineArguments.UsingTelegram = true; } CommandLineArguments.TelegramBotToken = arguments.Tt; CommandLineArguments.TelegramChatId = arguments.Tc; if (arguments.Ta) { CommandLineArguments.TelegramSendAll = arguments.Ta; CommandLineArguments.TelegramSendErrors = false; } if (arguments.Te) { CommandLineArguments.TelegramSendErrors = arguments.Te; } } //validate the address //logic: if address is IP address - continue pinging using the IP address; // if address is name - try to resolve it to IP address and continue pinging using the first IP address from the resolved array of IP's; // if both unsuccessful - terminate the program with the error code -1 bool addressIsIp = ValidateAddress.Ip(CommandLineArguments.Address); if (addressIsIp) { Variables.Address = CommandLineArguments.Address; //disable FollowTheName option and set hostname to empty because using an ip address CommandLineArguments.FollowTheName = false; Variables.HostName = ""; } else { bool addressIsHostName = ValidateAddress.HostName(CommandLineArguments.Address); if (addressIsHostName) { Variables.Address = CommandLineArguments.Address; Variables.HostName = CommandLineArguments.Address; //change the global input address (from Command Line arguments) to the ip address => do not allow the ping module to resolve the hostname to an ip address if (!CommandLineArguments.FollowTheName) { string singleIp = ResolveHostname.GetSingleIp(CommandLineArguments.Address); if (!string.IsNullOrEmpty(singleIp)) { Variables.Address = singleIp; } } } else { string textHostNotFound = "Can't resolve the hostname '" + CommandLineArguments.Address + "' to an IP address."; Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(textHostNotFound); Console.ResetColor(); Environment.Exit(-1); } } //save a reference so it does not get GC'd _consoleHandler = ConsoleCtrlCheck; //set handler that will trap exit SetConsoleCtrlHandler(_consoleHandler, true); Ping ping = new Ping(CommandLineArguments); ping.StartPing(); Result(); Console.WriteLine(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(true); }
static void Main(string[] args) { ConfigEncrypt.ConfigEncrypt.EncryptConfig(); //make sure we only have one.... if (!mutex.WaitOne(TimeSpan.Zero, true)) { Console.WriteLine("Another instance already running"); Thread.Sleep(5000); } Console.Clear(); //save a reference so it does not get GC'd consoleHandler = new HandlerRoutine(ConsoleCtrlCheck); //set our handler here that will trap exit SetConsoleCtrlHandler(consoleHandler, true); Console.Write("CTRL+C to exit or CTRL+BREAK to interrupt the operation\n"); var options = new Options(); if (System.Diagnostics.Debugger.IsAttached & (options.ConnectionString == null | options.DestinationFilePath == null)) { var builder = new SqlConnectionStringBuilder(Properties.Settings.Default.DefaultConn.Decrypt()); options.ConnectionString = builder.ConnectionString; options.DestinationFilePath = Properties.Settings.Default.DefaultFileLocation; options.Database = string.IsNullOrEmpty(builder.InitialCatalog) ? Properties.Settings.Default.DefaultDB : builder.InitialCatalog; options.ExcludeTables = Properties.Settings.Default.DefaultExcludeTables; options.ClassNamespace = Properties.Settings.Default.DefaultClassNamespace; options.References = Properties.Settings.Default.DefaultReferences; options.IndividualTable = Properties.Settings.Default.DefaultIndividualTable; options.SingleClassType = (ObjectType)Properties.Settings.Default.DefaultObjectType; options.SeperateCRUD = Properties.Settings.Default.DefaultSeperateCRUD; } if (CommandLine.Parser.Default.ParseArguments(args, options)) { // Values are available here if (!string.IsNullOrEmpty(options.ConnectionString)) { Console.WriteLine("ConnectionString: {0}", options.ConnectionString); } if (!string.IsNullOrEmpty(options.DestinationFilePath)) { Console.WriteLine("DestinationFilePath: {0}", options.DestinationFilePath); } if (!string.IsNullOrEmpty(options.ClassNamespace)) { Console.WriteLine("ClassNamespace: {0}", options.ClassNamespace); } if (!string.IsNullOrEmpty(options.Database)) { Console.WriteLine("Database: {0}", options.Database); } if (!string.IsNullOrEmpty(options.ExcludeTables)) { Console.WriteLine("ExcludeTables: {0}", options.ExcludeTables); } if (!string.IsNullOrEmpty(options.References)) { Console.WriteLine("References: {0}", options.References); } if (!string.IsNullOrEmpty(options.IndividualTable)) { Console.WriteLine("IndividualTable: {0}", options.IndividualTable); } if (options.SeperateCRUD) { Console.WriteLine("SeperateCRUD: {0}", options.SeperateCRUD); } if (options.SingleClassType != ObjectType.Default) { Console.WriteLine("SingleClass: {0}", options.SingleClassType); } } else { Console.WriteLine("Please provide the required parameters."); if (!System.Diagnostics.Debugger.IsAttached) { return; } } if (string.IsNullOrEmpty(options.DestinationFilePath)) { if (!System.IO.Directory.Exists(options.DestinationFilePath)) { System.IO.Directory.CreateDirectory(options.DestinationFilePath); } } try { new CapsDBClassTools.CreateObjects( options.ConnectionString, options.DestinationFilePath, options.ClassNamespace, options.Database, options.ExcludeTables, options.References, options.IndividualTable, options.SeperateCRUD, options.SingleClassType); } catch (Exception ex) { Console.Write("Error using RefreshClasses: " + ex.Message); } }
static int Main() { handlerRoutine = new HandlerRoutine(ConsoleCtrlCheck); SetConsoleCtrlHandler(handlerRoutine, true); #if DEBUG #else Console.OutputEncoding = Encoding.UTF8; #endif while (doItAll) { try { Debug.Log("Запуск программы"); games = new Dictionary <int, Game>(); TasksMgr.doOtherThreads = true; if (!Params.LoadParams()) { Debug.LogError("Файл настроек не обнаружен - \"params.xml\", создаю новый..."); } if (!Params.LoadUsers()) { Debug.LogError("Файл со списком пользователей не обнаружен - \"users.xml\", создаю новый..."); } if (Params.TelegToken == null || Params.TelegToken.Length < 6) { Debug.LogError("Токен Telegram API не обнаружен, надо ввести его в файле params.xml"); Debug.LogWarning("Завершение работы..."); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); return(-1); } Debug.Log("Нажмите Ctrl + C чтобы сохранить список пользователей"); Debug.Log("Запускаю сервисы Telegram"); Telegram.StartMsgUpd(); TasksMgr.StartLineParsing(); TasksMgr.StartUsersSavingThread(); Thread.Sleep(6 * 3600 * 1000); //ждать 6 часов bool sleepAgain = true; while (sleepAgain) { sleepAgain = false; lock (gamesLocker) { foreach (Game game in games.Values) { //если есть активные алгоритмы sleepAgain |= game.algoritms[0].actived; sleepAgain |= game.algoritms[1].actived; sleepAgain |= game.algoritms[2].actived; sleepAgain |= game.deleteFuncIsActivated; } } if (sleepAgain) { Thread.Sleep(600000); //то подождать ещё 10 мин } } } catch (Exception e) { Debug.LogException(e); } finally { TasksMgr.PrefClosing(); } } return(0); }
} // end _HandlerWrapper /// <summary> /// Installs a control key handler which handles special signals like CTRL-C. /// </summary> /// <remarks> /// N.B. Be careful about blocking the CTRL-handler thread. The handler is /// dispatched on essentially a random threadpool thread, and a lock is held /// while dispatching. So if you block the CTRL-handler thread inside your /// handler, and somebody else tries to install a CTRL handler on a different /// thread (which your handler is dependent on), you will deadlock. /// </remarks> public CtrlCInterceptor(HandlerRoutine replacementHandler) : this(replacementHandler, false) { }
private static extern bool SetConsoleCtrlHandler(HandlerRoutine HandlerRoutine, bool Add);
public SnapOsWindowsExitSignal() { _handlerRoutine = ConsoleCtrlCheck; SetConsoleCtrlHandler(_handlerRoutine, true); }
//////////////////////////////////////////////////////////////////// static void Main(string[] args) { if (args.Length > 0) { targetHost = args[0]; } if (args.Length > 1) { int.TryParse(args[1], out targetPort); } if (args.Length > 2) { long.TryParse(args[2], out pingCount); // Convert.ToInt64(args[2]); } if (args.Length > 3) { logFile = args[3]; } if (logFile == "-") { logFile = ""; } if (targetHost == "/?" || targetHost == "-?" || targetHost == "?" || targetHost == "/h" || targetHost == "-h" || targetHost == "/help" || targetHost == "-help") { Console.Error.WriteLine(); Console.Error.WriteLine("Syntax: ping.net.exe [ipAddr/hostName [port [count [logFile]]]]"); // args[0] args[1] Console.Error.WriteLine("Default: ping.net.exe <defaultGateway> 80 1800 pingsckt.log"); // args[0] args[1] Console.Error.WriteLine(); return; } nicInfo = getNicInfo(); if (targetHost == "") { var m = (new System.Text.RegularExpressions.Regex(@" GW:(\S+)")).Match(nicInfo); targetHost = (m.Success) ? (m.Groups[1]).ToString() : System.Net.IPAddress.Loopback.ToString(); } if (targetHost == "") { targetHost = System.Net.IPAddress.Loopback.ToString(); } println(""); if (nicInfo != "") { println(nicInfo); } //Console.CancelKeyPress += new ConsoleCancelEventHandler(myConsoleCancelEventHandler); myConsoleCtrlHandler = new HandlerRoutine(myConsoleCtrlHandlerCallbackFunction); // will need to keep this in a static var for final garbage collector [ http://stackoverflow.com/questions/6783561/nullreferenceexception-with-no-stack-trace-when-hooking-setconsolectrlhandler ] SetConsoleCtrlHandler(myConsoleCtrlHandler, true); System.Collections.Queue last20Queue = new System.Collections.Queue(); for (i = 0; (pingCount == -1 || i < pingCount); i++) { if (consoleCancelled) { break; } if (i > 0) { System.Threading.Thread.Sleep(1000); } var statusCode = ": "; responseTime = connectSocket(targetHost, targetPort, timeout); if (responseTime > -1) { responseCount++; last20Queue.Enqueue(1); totalResponseTime += responseTime; if (minResponseTime < 0 || responseTime < minResponseTime) { minResponseTime = responseTime; } if (responseTime > maxResponseTime) { maxResponseTime = responseTime; statusCode = "^^"; } if (responseTime > Math.Round((double)totalResponseTime / responseCount)) { statusCode = "^ "; } } else { statusCode = "^^"; last20Queue.Enqueue(0); } if (last20Queue.Count > 20) { last20Queue.Dequeue(); } int last20Pass = 0; foreach (int item in last20Queue) { last20Pass += item; } Console.Write(string.Format("{0:00}{1}", 100 * (last20Queue.Count - last20Pass) / last20Queue.Count, statusCode)); } nicInfo = getNicInfo(); printSummary(); if (consoleCancelled) { try { Console.Error.WriteLine("terminating... press <enter> to exit immediately."); String line = Console.ReadLine(); } catch (Exception e) { var errMsg = e.Message; } } return; } // Main()
public WindowsExitSignal() { m_hr = new HandlerRoutine(ConsoleCtrlCheck); SetConsoleCtrlHandler(m_hr, true); }
public WinExitSignal() { m_hr = new HandlerRoutine(ConsoleCtrlCheck); SetConsoleCtrlHandler(m_hr, true); }
//Main Constructor static void Main(string[] args) { StartTime = DateTime.Now; Log.LogWrite("//////////////////////////PROJECT COMMENCED!\\\\\\\\\\\\\\\\\\\\\\\\\\"); HandlerRoutine handlerRoutine = new HandlerRoutine(ConsoleCtrlCheck); GC.KeepAlive(handlerRoutine); SetConsoleCtrlHandler(handlerRoutine, true); //Check for arguments if (args.Count() > 0 && args[0] == "-?") { ErrorMsg(3); } //Instatiate required objects Initialization initialization = new Initialization(); List <SimpleFileInfo> files = new List <SimpleFileInfo>(); List <string> filteredFiles = new List <string>(); List <string> rawFiles = new List <string>(); //Read config file and set Initialization properties if (File.Exists(initialization.IniFilePath)) { //Get all lines in config file string[] iniData = File.ReadAllLines(initialization.IniFilePath); //Iterate through lines and retreive data, if data is present, ensure it is valid. foreach (string s in iniData) { if (s.Contains(initialization.SourceHeader)) { initialization.DataSource = s.Remove(0, initialization.SourceHeader.Count()); if (!initialization.CheckSourceDestination(initialization.DataSource)) { ErrorMsg(2); } } if (s.Contains(initialization.DestinationHeader)) { initialization.DataDestination = s.Remove(0, initialization.DestinationHeader.Count()); if (!initialization.CheckSourceDestination(initialization.DataDestination)) { ErrorMsg(1); } } if (s.Contains(initialization.SizeHeader)) { initialization.DataSize = Convert.ToDouble(s.Remove(0, initialization.SizeHeader.Count())); if (initialization.DataSize < 210) { ErrorMsg(4); } } if (s.Contains(initialization.ExceptionsHeader)) { string t = s.Remove(0, initialization.ExceptionsHeader.Count()); string[] exceptions; if (t.Contains(",")) { exceptions = t.Split(','); } else if (t.Count() > 0) { exceptions = new string[1] { t } } ; else { exceptions = new string[1] { "" } }; initialization.CheckExceptions(exceptions); } } } //No config file else { ErrorMsg(3); } //Enumerate files and get file info files = GetFileData(initialization.FileExceptions, initialization.CopyDirectories, initialization.WildCardExceptions).ToList(); //Pack files into bins sorted by file size List <Bin> packedBins = PackFiles(files, initialization.DataSize); //Create text files for packed bins CreateOutputFiles(packedBins, initialization.DataDestination); FinishTime = DateTime.Now; Log.LogWrite(String.Format("////////////PROJECT COMPLETE! Elapsed Time = {0:hh\\:mm}\\\\\\\\\\\\", ElapsedTime)); ConsoleCtrlCheck(CtrlTypes.CTRL_CLOSE_EVENT); }
private static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool add);
/// <summary> /// Grab the console and wait for it to close. /// </summary> private void HandleConsole() { // Redirects the 'X' for the console window so we can close the service cleanly. var stopDebugHandler = new HandlerRoutine(OnStop); SetConsoleCtrlHandler(stopDebugHandler, true); // Loop here while the service is running. while (IsRunning) { // Minor delay for process management. Thread.Sleep(50); // Check to see if someone pressed a key. if (Console.KeyAvailable) { // Check to see if the key was a space. if (Console.ReadKey(true).Key != ConsoleKey.Spacebar) { // It was not a space so break the running loop and close the service. break; } // Set the pending trigger flag. This allows the service to break out of a delay. TriggerPending = true; } } // It was not a space so break the running loop and close the service. OnStop(); // If we don't have this the handler will get garbage collected and will result in a // null reference exception when the console windows is closed with the 'X'. GC.KeepAlive(stopDebugHandler); }
public static extern bool SetConsoleCtrlHandler([In][Optional][MarshalAs(UnmanagedType.FunctionPtr)] HandlerRoutine HandlerRoutine, [In][MarshalAs(UnmanagedType.Bool)] bool Add);
public static void RegeditCloseEvent(ref HandlerRoutine handler, bool add) { }
public WinExitSignal() { m_hr = ConsoleCtrlCheck; SetConsoleCtrlHandler(m_hr, true); }
static void Main(string[] args) { //Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress); HandlerRoutine quitHandler = new HandlerRoutine(ConsoleCtrlCheck); GC.KeepAlive(quitHandler); SetConsoleCtrlHandler(quitHandler, true); Program program = new Program(); program.MonitorGames(); }
static extern int SetConsoleCtrlHandler(HandlerRoutine routine, bool add_not_remove);
SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
static extern int SetConsoleCtrlHandler(HandlerRoutine routine, bool add_not_remove);
[DllImport("Kernel32")] public static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool add);
internal static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, [MarshalAs(UnmanagedType.Bool)] bool add);
public void Initialize() { if (initialized) { return; } IntPtr hwnd = LoggerUtils.GetConsoleWindow(); initialized = true; // Console app if (hwnd != IntPtr.Zero) { buffer = LoggerUtils.GetStdHandle(LoggerUtils.STD_OUTPUT_HANDLE); return; } // Windows app bool success = LoggerUtils.AllocConsole(); handleRoutine = new HandlerRoutine(Handler); LoggerUtils.SetConsoleCtrlHandler(handleRoutine, true); this.Visible = false; if (!success) { return; } buffer = LoggerUtils.CreateConsoleScreenBuffer(LoggerUtils.GENERIC_READ | LoggerUtils.GENERIC_WRITE, LoggerUtils.FILE_SHARE_READ | LoggerUtils.FILE_SHARE_WRITE, IntPtr.Zero, LoggerUtils.CONSOLE_TEXTMODE_BUFFER, IntPtr.Zero); bool result = LoggerUtils.SetConsoleActiveScreenBuffer(buffer); //Set console output buffer size IntPtr handle = LoggerUtils.CreateFile( "CONOUT$", // name LoggerUtils.GENERIC_WRITE | LoggerUtils.GENERIC_READ, // desired access LoggerUtils.FILE_SHARE_WRITE | LoggerUtils.FILE_SHARE_READ, // share access null, // no security attributes LoggerUtils.OPEN_EXISTING, // device already exists 0, // no flags or attributes IntPtr.Zero); // no template file. consoleHandle = new SafeFileHandle(handle, true); const UInt16 conWidth = 256; const UInt16 conHeight = 2500; Coord dwSize = new Coord(conWidth, conHeight); LoggerUtils.SetConsoleScreenBufferSize(consoleHandle.DangerousGetHandle(), dwSize); LoggerUtils.SetStdHandle(LoggerUtils.STD_OUTPUT_HANDLE, buffer); LoggerUtils.SetStdHandle(LoggerUtils.STD_ERROR_HANDLE, buffer); Title = "Logger Console"; Stream s = Console.OpenStandardInput(LoggerUtils._DefaultConsoleBufferSize); StreamReader reader = null; if (s == Stream.Null) { reader = StreamReader.Null; } else { reader = new StreamReader(s, Encoding.GetEncoding(LoggerUtils.GetConsoleCP()), false, LoggerUtils._DefaultConsoleBufferSize); } Console.SetIn(reader); // Set up Console.Out StreamWriter writer = null; s = Console.OpenStandardOutput(LoggerUtils._DefaultConsoleBufferSize); if (s == Stream.Null) { writer = StreamWriter.Null; } else { writer = new StreamWriter(s, Encoding.GetEncoding(LoggerUtils.GetConsoleOutputCP()), LoggerUtils._DefaultConsoleBufferSize); writer.AutoFlush = true; } Console.SetOut(writer); s = Console.OpenStandardError(LoggerUtils._DefaultConsoleBufferSize); if (s == Stream.Null) { writer = StreamWriter.Null; } else { writer = new StreamWriter(s, Encoding.GetEncoding(LoggerUtils.GetConsoleOutputCP()), LoggerUtils._DefaultConsoleBufferSize); writer.AutoFlush = true; } Console.SetError(writer); // // Disable Close as this would close the main app also // hwnd = LoggerUtils.GetConsoleWindow(); IntPtr hMenu = LoggerUtils.GetSystemMenu(hwnd, false); LoggerUtils.DeleteMenu(hMenu, LoggerUtils.SC_CLOSE, LoggerUtils.MF_BYCOMMAND); NativeMethods.SetWindowPos(hwnd, new IntPtr(-1), 0, 0, 0, 0, NativeMethods.SWP_NOMOVE | NativeMethods.SWP_NOSIZE); }
public static extern bool SetConsoleCtrlHandler(HandlerRoutine routine, bool add);
unsafe void Run() { myHandlerDele = new HandlerRoutine(myHandler); SetConsoleCtrlHandler(myHandlerDele, true); // retrieve last final datablock DirectoryInfo di = new DirectoryInfo(Directory.GetCurrentDirectory()); var files = di.GetFiles("tc08_*.txt", SearchOption.TopDirectoryOnly); char[] delim = { '.', '_' }; foreach (var file in files) { var fileind = Int32.Parse(file.Name.Split(delim)[1]); blockCount = Math.Max(fileind + 1, blockCount); } if (blockCount > 0) { Console.WriteLine("Continue logging from block index {0]", blockCount); } // get handle handle = Imports.TC08OpenUnit(); if (handle == 0) { Console.WriteLine("Unable to open : {0}", handle); return; } else { Console.WriteLine("Open device : {0}", handle); } // device info var line = new System.Text.StringBuilder(256); Imports.TC08GetFormattedInfo(handle, line, 256); Console.WriteLine("{0}", line); // set channels for (short channel = 0; channel <= USBTC08_MAX_CHANNELS; channel++) { Imports.TC08SetChannel(handle, channel, 'K'); } float[,] data = new float[USBTC08_MAX_CHANNELS + 1, dataBlock]; int dataCount = 0; if (!isStreaming) { // loop single acquire until key hit do { float[] tempbuffer = new float[USBTC08_MAX_CHANNELS]; short overflow; short status = Imports.TC08GetSingle(handle, tempbuffer, &overflow, Imports.TempUnit.USBTC08_UNITS_CENTIGRADE); if (status == PICO_OK) { for (short chan = 1; chan <= USBTC08_MAX_CHANNELS; chan++) { data[chan, dataCount] = tempbuffer[chan]; Console.Write("{0:0.0000} ", tempbuffer[chan]); } Console.WriteLine(); } dataCount++; if (dataCount >= dataBlock) { dataCount = 0; var sw = new StreamWriter("tc08_" + blockCount.ToString() + ".txt"); for (int i = 0; i < dataBlock; i++) { for (int c = 0; c < USBTC08_MAX_CHANNELS + 1; c++) { sw.Write("{0:0.0000}", data[c, i]); if (c == USBTC08_MAX_CHANNELS) { sw.WriteLine(); } else { sw.Write(" "); } } } sw.Close(); blockCount++; } Thread.Sleep(intervalAcquireMs); } while (Win32Interop._kbhit() == 0); Imports.TC08Stop(handle); } else { // streaming acquire until key hit // researve unsafe array float[][] tempbuffer = new float[USBTC08_MAX_CHANNELS + 1][]; int buffer_size = 1024; PinnedArray <float>[] pinned = new PinnedArray <float> [buffer_size]; for (short channel = 0; channel <= USBTC08_MAX_CHANNELS; channel++) { tempbuffer[channel] = new float[buffer_size]; pinned[channel] = new PinnedArray <float>(tempbuffer[channel]); } int[] times_ms_buffer = new int[buffer_size]; short[] overflow = new short[USBTC08_MAX_CHANNELS + 1]; // get interval ms short actual_interval_ms = Imports.TC08Run(handle, Imports.TC08GetMinIntervalMS(handle)); if (actual_interval_ms <= 0) { Console.WriteLine("interval is too short"); } else { do { // acquire int numberOfSamples = 0; for (short chan = 0; chan <= USBTC08_MAX_CHANNELS; chan++) { numberOfSamples = Imports.TC08GetTemp(handle, tempbuffer[chan], times_ms_buffer, buffer_size, out overflow[chan], chan, Imports.TempUnit.USBTC08_UNITS_CENTIGRADE, 0); } if (numberOfSamples > 0) { Console.Write("{0} {1} : ", blockCount, dataCount); for (short chan = 0; chan <= USBTC08_MAX_CHANNELS; chan++) { float ave = 0; for (int i = 0; i < numberOfSamples; i++) { ave += pinned[chan].Target[i]; } ave /= numberOfSamples; data[chan, dataCount] = ave; Console.Write("{0:0.0000} ", ave); } Console.WriteLine(); dataCount++; } if (dataCount >= dataBlock) { dataCount = 0; string filename = "tc08_" + blockCount.ToString() + ".txt"; var sw = new StreamWriter(filename); for (int i = 0; i < dataBlock; i++) { for (int c = 0; c <= USBTC08_MAX_CHANNELS; c++) { sw.Write("{0:0.0000}", data[c, i]); if (c == USBTC08_MAX_CHANNELS) { sw.WriteLine(); } else { sw.Write(" "); } } } sw.Close(); Console.WriteLine("Write " + filename); blockCount++; } Thread.Sleep(intervalAcquireMs); } while (!Console.KeyAvailable); } Imports.TC08Stop(handle); // release arrays foreach (PinnedArray <float> p in pinned) { if (p != null) { p.Dispose(); } } } Imports.TC08CloseUnit(handle); }
static void Main(string[] args) { Console.Title = "IISiteBind"; ConfigurationApply(); //Handler para el exit: Así cuando se cierra la app se mata el proceso handlerRoutine = new HandlerRoutine(OnClose); SetConsoleCtrlHandler(handlerRoutine, true); //Preguntamos por el sitio Log(); Log("---------------------------------------------"); Log("- [SK] IISiteBind"); Log("---------------------------------------------"); Log(); Log(); Log("¿Qué SITE del IIS quieres configurar?"); IIS = new IISManager(); //Validamos la configuración con el usuario string inputName = Ask(); if (!IIS.SiteExists(inputName)) { LogError("El sitio \"" + inputName + "\" no existe en el IIS o no estás ejecutando como administrador."); } string sitePath = IIS.SitePath(inputName); if (!File.Exists(sitePath + "site.config")) { Log("El fichero de site.config no existe, sitePath: " + sitePath); Log("Introduce el path completo si quieres seguir:"); sitePath = Ask(); if (!File.Exists(sitePath + "site.config")) { Log("El fichero de site.config no existe"); } } IDictionary <string, object> conf = JsonConvert.DeserializeObject <IDictionary <string, object> >(File.ReadAllText(@sitePath + "site.config")); string siteName = (string)conf["site"]; IList <IDictionary <string, IList <string> > > conf_bindings = ((JArray)conf["bindings"]).ToObject <IList <IDictionary <string, IList <string> > > >(); if (siteName.ToLower() != inputName.ToLower()) { LogError("El fichero de configuración de \"" + sitePath + "\" indica ser del sitio \"" + siteName + "\". Revísalo."); } Log("¿Configurar " + conf_bindings.Count.ToString() + " certificados en el IIS Site \"" + siteName + "\"?"); AskConfirm(true); //Controlador WINACME if (!File.Exists(conf_path_winacme)) { LogError("El ejecutable de WinACME no está en \"" + conf_path_winacme + "\""); } WinACME = new WAManager(conf_path_winacme); IIS = new IISManager(); //1 Recorremos los paquetes de certificados int countBinding = 0; Log("1. Garantizando certificados"); foreach (IDictionary <string, IList <string> > entry_parent in conf_bindings) { if (entry_parent.Count != 1) { LogError("Error en el fichero de configuración (Bindings con formato invalido)."); } KeyValuePair <string, IList <string> > entry = entry_parent.First(); countBinding++; string ip = entry.Key; Log("2a. Validando " + ip + " con " + entry.Value.Count + " dominios (" + countBinding + "/" + conf_bindings.Count + ")"); List <string> hostNames = new List <string>(); foreach (string hostName in entry.Value) { if ((hostName == "") || (hostName == "*")) { continue; } hostNames.Add(hostName); if (!IIS.SiteHaveBinding(siteName, ip, hostName, false)) { Log("2x. Configurando binding \"" + hostName + "\" de forma temporal para la validacion."); IIS.SiteAddBinding(siteName, ip, hostName); IIS.Commit(); } } if (hostNames.Count == 0) { Log("2d. Ok, 0 domains!"); continue; } //Chequeamos si el paquete ya está creado exactamente como toca byte[] certHash = null; if (hostNames.Count > 0) { certHash = IIS.GetCertHashByHostNameList(hostNames); if (certHash != null) { Log("2d. Certificado ya existe, no se recrea!"); continue; } } Log("2b. Creando el certificado para \"" + string.Join(", ", hostNames) + "\"..."); Log("2b. [NOTA] Si es la primera vez que ejecutas WINACME crea uno (n/4 -no hace falta llegar a hacerlo) y setea mail y acepta tos"); if (!WinACME.CertificateDomainList(siteName, hostNames)) { Program.LogError("No se pudo crear alguno de los certificados por lo que no se puede configurar el IIS."); } WinACME.Stop(); certHash = IIS.GetCertHashByHostNameList(hostNames); if (certHash == null) { LogError("No se pudo crear un certificado que valide todos los dominios."); } Log("2c. Ok!"); } //3 Limpiamos los bidings Log("3. Limpiando Bindings...."); IIS = new IISManager(); IIS.SiteClearBindings(siteName); if (IIS.SitCountBindings(siteName) > 0) { LogError("No se pudieron eliminar los bidings (Permisos?)."); } Log("3. Ok!"); //4. Y ahora se ponen countBinding = 0; Log("4. Configurando Bindings...."); foreach (IDictionary <string, IList <string> > entry_parent in conf_bindings) { KeyValuePair <string, IList <string> > entry = entry_parent.First(); countBinding++; string ip = entry.Key; Log("4a. Configurando " + ip + " con " + entry.Value.Count + " dominios (" + countBinding + "/" + conf_bindings.Count + ")"); List <string> hostNames = new List <string>(); foreach (string hostName in entry.Value) { if ((hostName == "") || (hostName == "*")) { continue; } hostNames.Add(hostName); } byte[] certHash = null; if (hostNames.Count > 0) { certHash = IIS.GetCertHashByHostNameList(hostNames); if (certHash == null) { LogError("No se pudo encontrar un certificado que valide todos los dominios."); } } Log("4b. Configurando..."); foreach (string hostName in entry.Value) { Log("4c. HTTP://" + hostName + "@" + ip); IIS.SiteAddBinding(siteName, ip, hostName); Log("4d. HTTPS://" + hostName + "@" + ip); if ((hostName != "") && (hostName != "*")) { IIS.SiteAddBinding(siteName, ip, hostName, certHash); } } Log("4e. Ok!"); } Log(); Log("5. Commiting..."); while (!IIS.Commit()) { Log("[ERROR] No se puede hacer commit de la configuración, ¿Reintentar?"); AskConfirm(true); } Log("5. Commited OK!"); List <string> inactiveCerts = IIS.GetInactiveCertsHash(); if (inactiveCerts.Count > 0) { Log(); Log(); Log("[ALERT] Non associated certificates availables:"); Log(); foreach (string certificateName in inactiveCerts) { Log("-> " + certificateName); } } Log(); Log(); Log("End!"); KeyToClose(); }
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool State);
private static void Main(string[] args) { // Exit task myHandlerDele = new HandlerRoutine(exitTaskFunc); SetConsoleCtrlHandler(myHandlerDele, true); Console.Title = "FFCrypt Core " + version; Console.WriteLine("\r\n[*] [FFCrypt Core " + version + "]"); EncryptionArgv encArgv = new EncryptionArgv(); long times = 0; try { Console.WriteLine("[*] Analysing arguments...\r\n"); encArgv.SetEncryptionArgvValue(args); showArgvInfo(encArgv); if (encArgv.ShowHelp) { showHelpInfo(); } else if (encArgv.IsEncryption) { Console.Title = Console.Title + " - Encrypting..."; times = startEncryption(encArgv); } else { Console.Title = Console.Title + " - Decrypting..."; times = startDecryption(encArgv); } GC.Collect(); } catch (NoFilePathException) { Console.WriteLine("\r\n[-] Please select the file(s)."); showHelpInfo(); } catch (NoPasswordException) { Console.WriteLine("\r\n[-] Please set the password."); showHelpInfo(); } catch (CreateDirectoryError) { Console.WriteLine("\r\n[-] Could not create directory: '" + encArgv.OutPath + "' "); showHelpInfo(); } if (encArgv.IsEncryption) { Console.WriteLine("\r\n[*] Completed encryption. (" + times + "ms)"); } else { Console.WriteLine("\r\n[*] Completed decryption. (" + times + "ms)"); } taskExited = true; Console.Title = "FFCrypt Core " + version; if (encArgv.WaitForEnterKey) { Console.WriteLine("[*] Press Enter to exit this program..."); Console.ReadLine(); } }
private static void Main(string[] args) { // Subscribing shouldListen = false; hr = new HandlerRoutine(ConsoleCtrlCheck); SetConsoleCtrlHandler(hr, true); using (vhmsg = new VHMsg.Client()) { gazeTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent); string configFile = "config.ini"; if (args.Length > 0) { configFile = args[0]; Console.WriteLine("Reading config file - " + configFile); } ReadConfigFile(configFile); vhmsg.OpenConnection(); Console.WriteLine("VHMSG_SERVER: {0}", vhmsg.Server); Console.WriteLine("VHMSG_SCOPE: {0}", vhmsg.Scope); Console.WriteLine("Press q to quit"); Console.WriteLine("Listening to vrPerception Messages"); vhmsg.MessageEvent += new VHMsg.Client.MessageEventHandler(MessageAction); vhmsg.SubscribeMessage("vrPerception"); vhmsg.SubscribeMessage("vrAllCall"); vhmsg.SubscribeMessage("vrKillComponent"); vhmsg.SubscribeMessage("vrPerceptionApplication"); vhmsg.SendMessage("vrComponent perception-test-application"); while (isRunning) { Thread.Sleep(100); if (_kbhit() != 0) { char c = Console.ReadKey(true).KeyChar; if (c == 'q') { isRunning = false; } } } CleanupBeforeExiting(); } }
static void Run(Options opts, bool haveExistingConsole) { if (!haveExistingConsole && opts.ShowConsole) { AllocConsole(); } HandlerRoutine onCtrlC = (dwCtrlType) => { Console.WriteLine("Received Ctrl-C, exiting"); Environment.Exit(0); return(true); }; if (haveExistingConsole || opts.ShowConsole) { SetConsoleCtrlHandler(onCtrlC, true); var handle = GetStdHandle(STD_INPUT_HANDLE); GetConsoleMode(handle, out var mode); SetConsoleMode(handle, mode | ENABLE_PROCESSED_INPUT | ENABLE_LINE_INPUT); } if (haveExistingConsole) { var thread = new Thread((_) => { IntPtr cw = GetConsoleWindow(); if (cw.ToInt64() != -1) { // Parent process is attached to input buffer, send a key event first so that we can get the next event (with better chance) ThreadPool.QueueUserWorkItem(__ => { Thread.Sleep(1); SendMessage(cw, WM_CHAR, (IntPtr)VK_ENTER, IntPtr.Zero); }); } var key = Console.ReadKey(true); Console.WriteLine("Key pressed, exiting..."); SendMessage(cw, WM_CHAR, (IntPtr)VK_ENTER, IntPtr.Zero); Environment.Exit(0); }); thread.IsBackground = true; thread.Start(); } var mutex = new Mutex(true, Marshal.GetTypeLibGuidForAssembly(Assembly.GetExecutingAssembly()).ToString(), out var isNew); if (!isNew) { Console.WriteLine("Already running"); return; } byte[] audioData; if (!string.IsNullOrEmpty(opts.SoundFile)) { audioData = File.ReadAllBytes(opts.SoundFile); } else { using (var ms = new MemoryStream()) { Assembly.GetExecutingAssembly().GetManifestResourceStream(typeof(Program).Namespace + ".beep.wav").CopyTo(ms); audioData = ms.ToArray(); } } try { new WaveFileReader(new MemoryStream(audioData)); } catch (Exception) { Console.Error.WriteLine("Invalid sound file: {0}", opts.SoundFile); Environment.Exit(1); return; } using (var enumerator = new MMDeviceEnumerator()) { Action <string> addDevice = (id) => { try { var device = enumerator.GetDevice(id); var thread = new Thread(() => ProcessDevice(device, opts, audioData)); thread.IsBackground = true; thread.Start(); } catch (Exception ex) { Console.WriteLine("Failed to handle device {0}:", id); Console.WriteLine(ex); } }; var notifier = new NotificationClient(); notifier.Added += (sender, id) => addDevice(id); enumerator.RegisterEndpointNotificationCallback(notifier); var devices = enumerator.EnumerateAudioEndPoints(DataFlow.Render, DeviceState.All); foreach (var device in devices) { addDevice(device.ID); device.Dispose(); } GC.Collect(2, GCCollectionMode.Forced, true, true); Thread.Sleep(-1); GC.KeepAlive(notifier); } GC.KeepAlive(onCtrlC); GC.KeepAlive(mutex); }
static void Main(string[] args) { // handle closing of the window correctly (see #region cleanup) HandlerRoutine hr = new HandlerRoutine(ConsoleCtrlCheck); SetConsoleCtrlHandler(hr, true); using (var server = new MailslotServer("LagomLitenLedMailSlot")) { try { trinket.open(); // Game lists etc: // read game ini file IniReader games = new IniReader("../../../configuration/Colors.ini"); // supersede allows defining new games or redefining games already in colors.ini to new colors. IniReader supersede = new IniReader("../../../configuration/supersede.ini"); // buttons.ini define which diode goes to which button IniReader buttons = new IniReader("../../../configuration/Buttons.ini"); // colordefinitions.ini have name definitions for different colors. IniReader colors = new IniReader("../../../configuration/ColorDefinitions.ini"); while (!stop) { var msg = server.GetNextMessage(); if (msg != null) // incoming message { var arguments = msg.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (arguments.Length == 1) // one argument means either a game file or an animation { if (arguments[0].Equals("stop")) // time to end this { stop = true; } else if (arguments[0].EndsWith(".lwax", true, null)) // animation, ignore case, default culture { XmlDocument anim = new XmlDocument(); //TODO: add error handling anim.Load(arguments[0]); XmlNodeList intensityList, stateList; intensityList = anim.SelectNodes(".//Intensity[@LedHwType='6']"); // there are more premade animations for LEDWiz stateList = anim.SelectNodes(".//State[@LedHwType='6']"); KeyFrame[] animation = new KeyFrame[stateList.Count]; String currentIntensity = new String("".ToCharArray()); String currentState = new String("".ToCharArray()); for (int i = 0; i < stateList.Count; i++) { XmlElement frameparent = (XmlElement)stateList[i].ParentNode; // find out current intensity setting for (int j = 0; j < intensityList.Count; j++) // index from one, because thats what the animation files do { XmlElement parent = (XmlElement)intensityList[j].ParentNode; if (parent.GetAttribute("Number") == frameparent.GetAttribute("Number")) { XmlElement intensityElement = (XmlElement)intensityList[j]; currentIntensity = intensityElement.GetAttribute("Value"); } } XmlElement stateElement = (XmlElement)stateList[i]; currentState = stateElement.GetAttribute("Value"); // build frame animation[i] = new KeyFrame(int.Parse(frameparent.GetAttribute("Duration")), currentIntensity, currentState); } foreach (KeyFrame frame in animation) { for (int i = 0; i < numberOfDiodes; i++) { trinket.setRed(i, frame.intensity[i * 3]); trinket.setGreen(i, frame.intensity[i * 3 + 1]); trinket.setBlue(i, frame.intensity[i * 3 + 2]); } Thread.Sleep(frame.duration); //trinket.update(); Console.WriteLine(trinket.update().ToString()); } } else //gamefile { // Most games don't use all buttons, so lets paint it black trinket.setToBlack(); // check if the argument matches any of the game files if (games.ContainsSection(arguments[0]) && !supersede.ContainsSection(arguments[0])) // allow supersede to override the colors.ini settings. { setDiodeColorBuffers(games, arguments[0], buttons, colors); } else if (supersede.ContainsSection(arguments[0])) { setDiodeColorBuffers(supersede, arguments[0], buttons, colors); } else { Console.WriteLine("Game file " + arguments[0] + " not found in colors.ini nor in supersede.ini"); } // set system button colors setDiodeColorBuffers(buttons, "SystemButtonColors", buttons, colors); Console.Write(trinket.update().ToString()); } } else if (arguments.Length == 2) // probably keyboardsender sends (Index,KeyboardEventName) { // check buttons.ini if the outputs are grouped (i.e four LEDs for one joystick) foreach (string key in buttons.GetKeys("Diodes"))// expensive going through them all { string[] diodes = buttons.GetValue(key, "Diodes").Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (diodes.Contains(arguments[0])) { foreach (string diode in diodes) { // most cases diodes is only 1 long, in all other cases leds are grouped. // invert color rgb wise (keydown inverts once, keyup on same index will invert back to initial values) int index = int.Parse(diode); byte red = trinket.getRed(index); byte green = trinket.getGreen(index); byte blue = trinket.getBlue(index); trinket.setRed(index, (byte)(255 - red)); trinket.setGreen(index, (byte)(255 - green)); trinket.setBlue(index, (byte)(255 - blue)); } } } Console.Write(trinket.update().ToString()); } else if (arguments.Length == numberOfDiodes) // set colors directly { for (int i = 0; i < numberOfDiodes; i++) { String trimmed = arguments[i]; if (arguments[i].Substring(0, 2) == "0x") trimmed = arguments[i].Substring(2, 6); trinket.setRed(i, byte.Parse(trimmed.Substring(0, 2), System.Globalization.NumberStyles.HexNumber)); trinket.setGreen(i, byte.Parse(trimmed.Substring(2, 2), System.Globalization.NumberStyles.HexNumber)); trinket.setBlue(i, byte.Parse(trimmed.Substring(4, 2), System.Globalization.NumberStyles.HexNumber)); } Console.Write(trinket.update().ToString()); } } Thread.Sleep(1); } } catch (Exception ex) { Console.WriteLine(); Console.WriteLine(ex.Message); Console.ReadKey(); } finally { trinket.close(); } } }
private static extern bool SetConsoleCtrlHandler(HandlerRoutine handler, bool add);
static public void Main(string[] args) { if (args.Length < 10 || args.Length > 11) { show_usage(Process.GetCurrentProcess().ProcessName); return; } string url = args[0]; int broker_id; try { broker_id = Int32.Parse(args[1]); } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } string symbol = args[2]; char side; switch (args[3].ToUpper()) { case "BUY": side = OrderSide.BUY; break; case "SELL": side = OrderSide.SELL; break; case "BOTH": side = default(char); break; default: show_usage(Process.GetCurrentProcess().ProcessName); return; } // ** temporary workaround to support market pegged sell order strategy without plugins ** TradingStrategy.PriceType priceType; switch (args[4].ToUpper()) { case "DEFAULT": case "FIXED": priceType = TradingStrategy.PriceType.FIXED; break; case "PEGGED": case "FLOAT": if (side == OrderSide.SELL) { priceType = TradingStrategy.PriceType.PEGGED; } else { throw new ArgumentException("PEGGED is currently supported only for SELL"); } break; default: show_usage(Process.GetCurrentProcess().ProcessName); return; } ulong maxTradeSize; try { maxTradeSize = (ulong)(Double.Parse(args[5]) * 1e8); if (maxTradeSize < 10000) { throw new ArgumentException("Invalid Trade Size, must be at least 10,000 satoshis"); } } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } // *** ulong buyTargetPrice; try { buyTargetPrice = (ulong)(Double.Parse(args[6]) * 1e8); if (buyTargetPrice < 0) { throw new ArgumentException("Invalid Buy Target Price"); } } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } ulong sellTargetPrice; try { sellTargetPrice = (ulong)(Double.Parse(args[7]) * 1e8); } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } try { if ((side == OrderSide.BUY || side == default(char)) && buyTargetPrice == 0) { throw new ArgumentException("Invalid BUY Target Price"); } if ((side == OrderSide.SELL || side == default(char)) && sellTargetPrice == 0) { throw new ArgumentException("Invalid SELL Target Price"); } if (side == default(char) && buyTargetPrice >= sellTargetPrice) { throw new ArgumentException("Invalid SELL and BUY Price RANGE"); } } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } string user = args[8]; string password = args[9]; string second_factor = args.Length == 11 ? args[10] : null; try { // instantiate the tradeclient object to handle the trading stuff TradingStrategy strategy = new TradingStrategy(maxTradeSize, buyTargetPrice, sellTargetPrice, side, priceType); // instantiate the protocol engine object to handle the blinktrade messaging stuff WebSocketClientProtocolEngine protocolEngine = new WebSocketClientProtocolEngine(); SimpleTradeClient tradeclient = new SimpleTradeClient(broker_id, symbol, strategy, protocolEngine); // tradeclient must subscribe to receive the callback events from the protocol engine protocolEngine.SystemEvent += tradeclient.OnBrokerNotification; protocolEngine.LogStatusEvent += LogStatus; strategy.LogStatusEvent += LogStatus; // workaround (on windows working only in DEBUG) to trap the console application exit // and dump the last state of the Market Data Order Book(s), MiniOMS and Security Status #if (__MonoCS__ || DEBUG) System.AppDomain appDom = System.AppDomain.CurrentDomain; appDom.ProcessExit += new EventHandler(tradeclient.OnApplicationExit); #if __MonoCS__ Thread signal_thread = new Thread(UnixSignalTrap); signal_thread.Start(); #else var consoleHandler = new HandlerRoutine(OnConsoleCtrlCheck); // hold handler to not get GC'd SetConsoleCtrlHandler(consoleHandler, true); #endif #endif // objects to encapsulate and provide user account credentials UserAccountCredentials userAccount = new UserAccountCredentials(broker_id, user, password, second_factor); while (!_userRequestExit) { try { LogStatus(LogStatusType.WARN, "Please Wait..."); // gather and provide the user device data (local ip, external ip etc) UserDevice userDevice = new UserDevice(); // start the connection task to handle the Websocket connectivity and initiate the whole process #if __MonoCS__ Task /*<int>*/ task = WebSocketSharpClientConnection.Start(url, userAccount, userDevice, protocolEngine); #else Task task = WebSocketClientConnection.Start(url, userAccount, userDevice, protocolEngine); #endif /* * Task<int>[] tasks = new Task<int>[2]; * tasks[0] = WebSocketSharpClientConnection.Start (url, userAccount, userDevice, protocolEngine); * //tasks[1] = ... * int index = Task.WaitAny(tasks); * tasks[index].Result; */ task.Wait(); // aguardar até a Task finalizar if (!_userRequestExit) { tradeclient.ResetData(); // must reset tradeclient to refresh whole data after new connection LogStatus(LogStatusType.WARN, "Trying to reconnect in 5 seconds..."); Task.Delay(TimeSpan.FromSeconds(5)).Wait(); } } catch (System.Net.WebException ex) { LogStatus(LogStatusType.ERROR, ex.Message + '\n' + ex.StackTrace); Task.Delay(TimeSpan.FromSeconds(5)).Wait(); continue; } } } catch (Exception ex) { LogStatus(LogStatusType.ERROR, ex.Message + '\n' + ex.StackTrace); return; } /* #if DEBUG * Console.WriteLine("Press any key to exit..."); * Console.ReadKey(); #endif */ }
public static extern Boolean SetConsoleCtrlHandler(HandlerRoutine HandlerRoutine, Boolean Add);
private static void SetEventHandlers() { #if WINDOWS ExitCallback = new HandlerRoutine(ConsoleCtrlCheck); SetConsoleCtrlHandler(ExitCallback, true); #elif UNIX Thread signalThread = new Thread(CheckSignal); signalThread.Start(); #endif }
//Main Constructor static void Main(string[] args) { StartTime = DateTime.Now; Log.LogWrite("//////////////////////////PROJECT COMMENCED!\\\\\\\\\\\\\\\\\\\\\\\\\\"); HandlerRoutine handlerRoutine = new HandlerRoutine(ConsoleCtrlCheck); GC.KeepAlive(handlerRoutine); SetConsoleCtrlHandler(handlerRoutine, true); //Check for arguments if (args.Count() > 0 && args[0] == "-?") ErrorMsg(3); //Instatiate required objects Initialization initialization = new Initialization(); List<SimpleFileInfo> files = new List<SimpleFileInfo>(); List<string> filteredFiles = new List<string>(); List<string> rawFiles = new List<string>(); //Read config file and set Initialization properties if (File.Exists(initialization.IniFilePath)) { //Get all lines in config file string[] iniData = File.ReadAllLines(initialization.IniFilePath); //Iterate through lines and retreive data, if data is present, ensure it is valid. foreach (string s in iniData) { if (s.Contains(initialization.SourceHeader)) { initialization.DataSource = s.Remove(0, initialization.SourceHeader.Count()); if (!initialization.CheckSourceDestination(initialization.DataSource)) ErrorMsg(2); } if (s.Contains(initialization.DestinationHeader)) { initialization.DataDestination = s.Remove(0, initialization.DestinationHeader.Count()); if (!initialization.CheckSourceDestination(initialization.DataDestination)) ErrorMsg(1); } if (s.Contains(initialization.SizeHeader)) { initialization.DataSize = Convert.ToDouble(s.Remove(0, initialization.SizeHeader.Count())); if (initialization.DataSize < 210) ErrorMsg(4); } if (s.Contains(initialization.ExceptionsHeader)) { string t = s.Remove(0, initialization.ExceptionsHeader.Count()); string[] exceptions; if (t.Contains(",")) exceptions = t.Split(','); else if (t.Count() > 0) exceptions = new string[1] { t }; else exceptions = new string[1] { "" }; initialization.CheckExceptions(exceptions); } } } //No config file else ErrorMsg(3); //Enumerate files and get file info files = GetFileData(initialization.FileExceptions, initialization.CopyDirectories, initialization.WildCardExceptions).ToList(); //Pack files into bins sorted by file size List<Bin> packedBins = PackFiles(files, initialization.DataSize); //Create text files for packed bins CreateOutputFiles(packedBins, initialization.DataDestination); FinishTime = DateTime.Now; Log.LogWrite(String.Format("////////////PROJECT COMPLETE! Elapsed Time = {0:hh\\:mm}\\\\\\\\\\\\", ElapsedTime)); ConsoleCtrlCheck(CtrlTypes.CTRL_CLOSE_EVENT); }
static int Main(string[] args) { if (_pipeProxy != null) { Log.WriteSystemEventLog("MCEBuddy engine app already running, cannot start another instance.", EventLogEntryType.Error); return -1; // We can't start engine's } if (!AppProcess.HaveAdministrativeRights()) { Log.WriteSystemEventLog("Start MCEBuddy engine app with Administrative rights.", EventLogEntryType.Information); AppProcess.StartAppWithAdministrativeRights(Application.ExecutablePath); // Engine needs Admin rights for firewall and binding return -2; // Exit, the process will restart with admin rights } // Capture the Window close event if the user manually closes it _controlHandler = new HandlerRoutine(ConsoleCloseCheck); // Setup a static object otherwise on some systems it crashes with null pointer exception due to garbage collection SetConsoleCtrlHandler(_controlHandler, true); // Now that we are running, first Stop the the Windows Service otherwise we don't be able to start (stop before starting the GUI to prevent closure) Log.WriteSystemEventLog("Trying to stop MCEBuddy engine service.", EventLogEntryType.Information); WindowsService.StopService(GlobalDefs.MCEBUDDY_SERVICE_NAME, 10000); //Start MCEBuddy GUI with Normal user rights (just incase this is running admin rights try { if (AppProcess.HaveAdministrativeRights()) { AppProcess.StartAppWithMediumPrivilegeFromUISession(Path.Combine(GlobalDefs.AppPath, "MCEBuddy.GUI.exe"), "", false); } else // Normal user { Process Proc = new Process(); Proc.StartInfo.FileName = Path.Combine(GlobalDefs.AppPath, "MCEBuddy.GUI.exe"); Proc.StartInfo.CreateNoWindow = false; Proc.StartInfo.WindowStyle = ProcessWindowStyle.Normal; Proc.Start(); } } catch (Exception e) { // Sometimes the DLL does not work or is missing or running on wrong windows version, catch it and log it Log.WriteSystemEventLog("MCEBuddy engine app: Unable to start MCEBuddy GUI. Error ->\r\n" + e.ToString(), EventLogEntryType.Warning); } Log.WriteSystemEventLog("Starting MCEBuddy engine app.", EventLogEntryType.Information); MCEBuddyConf.GlobalMCEConfig = new MCEBuddyConf(GlobalDefs.ConfigFile); // Read the settings for global objects MCEBuddyConf.CheckDefaultJobPaths(); // Update paths before we start the engine to it is read _host = new ServiceHost(typeof(Core)); TimeSpan timeoutPeriod = GlobalDefs.PIPE_TIMEOUT; // Create a binding for network SOAP WEB SERVICES string serverString = GlobalDefs.MCEBUDDY_WEB_SOAP_PIPE; serverString = serverString.Replace(GlobalDefs.MCEBUDDY_SERVER_PORT, MCEBuddyConf.GlobalMCEConfig.GeneralOptions.localServerPort.ToString(System.Globalization.CultureInfo.InvariantCulture)); // Update the Server Port with that from the config file BasicHttpBinding ntb = new BasicHttpBinding(GlobalDefs.MCEBUDDY_PIPE_SECURITY); ntb.OpenTimeout = ntb.CloseTimeout = ntb.SendTimeout = ntb.ReceiveTimeout = timeoutPeriod; ntb.TransferMode = TransferMode.Buffered; ntb.MaxReceivedMessageSize = ntb.MaxBufferPoolSize = ntb.MaxBufferSize = Int32.MaxValue; ntb.ReaderQuotas = XmlDictionaryReaderQuotas.Max; ServiceEndpoint soapEndpoint = _host.AddServiceEndpoint(typeof(ICore), ntb, serverString); // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue foreach (OperationDescription operation in soapEndpoint.Contract.Operations) { DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior; if (dataContractBehavior != null) dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue; } // Create a binding for local NAMED PIPES NetNamedPipeBinding npb = new NetNamedPipeBinding(); npb.OpenTimeout = npb.CloseTimeout = npb.SendTimeout = npb.ReceiveTimeout = timeoutPeriod; npb.TransferMode = TransferMode.Buffered; npb.MaxReceivedMessageSize = npb.MaxBufferPoolSize = npb.MaxBufferSize = Int32.MaxValue; npb.ReaderQuotas = XmlDictionaryReaderQuotas.Max; ServiceEndpoint namedPipeEndpoint = _host.AddServiceEndpoint(typeof(ICore), npb, GlobalDefs.MCEBUDDY_LOCAL_NAMED_PIPE); // Increase the max objects allowed in serialization channel otherwise we lose the connection when there more than 5K objects in the queue foreach (OperationDescription operation in namedPipeEndpoint.Contract.Operations) { DataContractSerializerOperationBehavior dataContractBehavior = operation.Behaviors[typeof(DataContractSerializerOperationBehavior)] as DataContractSerializerOperationBehavior; if (dataContractBehavior != null) dataContractBehavior.MaxItemsInObjectGraph = Int32.MaxValue; } _host.CloseTimeout = GlobalDefs.PIPE_TIMEOUT; _host.Open(); _pipeFactory = new ChannelFactory<ICore>(npb, new EndpointAddress(GlobalDefs.MCEBUDDY_LOCAL_NAMED_PIPE)); _pipeProxy = _pipeFactory.CreateChannel(); if (MCEBuddyConf.GlobalMCEConfig.GeneralOptions.engineRunning) _pipeProxy.Start(); // Now that we are up and running SystemEvents.PowerModeChanged += OnPowerChange; // Register for power event changes ConsoleKeyInfo cki; Console.Title = "MCEBuddy 2.x Service Started, Press ESC to stop"; Console.WindowHeight = 15; Console.WindowWidth = 80; int lastNumJobs = 0; bool Shutdown = false; while (!Shutdown) { if (_forceClosed) return 1; // Someone forced the closure, the handler will clean up. Exit now if (Console.KeyAvailable) { cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.Escape) { Log.WriteSystemEventLog("MCEBuddy engine app received user shutdown request.", EventLogEntryType.Information); Shutdown = true; } } try { for (int i = 0, numJobs = _pipeProxy.NumConversionJobs(); i < numJobs; i++) { if (lastNumJobs != numJobs) // The number of conversion jobs has changed Console.Clear(); // Clear the screen string outputStr = ""; outputStr = "Job" + i.ToString(System.Globalization.CultureInfo.InvariantCulture); JobStatus status = _pipeProxy.GetJobStatus(i); if (status != null) { outputStr += " " + status.CurrentAction; if (status.PercentageComplete > 0) outputStr += " " + status.PercentageComplete.ToString("#0.0", System.Globalization.CultureInfo.InvariantCulture) + "%"; else if (-1 == status.PercentageComplete) outputStr += " Working..."; //some processes like ReMuxSupp don't update perc if (!String.IsNullOrEmpty(status.ETA)) outputStr += " ETA=" + status.ETA; if (!String.IsNullOrEmpty(status.SourceFile)) outputStr += " " + Path.GetFileName(status.SourceFile); } else { outputStr += " Idle"; } if (outputStr.Length > 78) outputStr = outputStr.Substring(0, 78); Console.SetCursorPosition(0, i); Console.Write(outputStr.PadRight(78)); lastNumJobs = _pipeProxy.NumConversionJobs(); } } catch (Exception) //while debugging catch Proxy Faulted state and reset it { if (_forceClosed) return 1; if (Shutdown) break; // we are done here _pipeFactory = new ChannelFactory<ICore>(new NetNamedPipeBinding(), new EndpointAddress(GlobalDefs.MCEBUDDY_LOCAL_NAMED_PIPE)); _pipeProxy = _pipeFactory.CreateChannel(); } System.Threading.Thread.Sleep(GlobalDefs.LOCAL_ENGINE_POLL_PERIOD); } ConsoleCloseCheck(ControlSignalType.CTRL_CLOSE_EVENT); // Gracefully shutdown the engine and restart the windows service return 0; // All good }
/********************************************************************************************/ static void Main(string[] args) { if (!mutex.WaitOne(TimeSpan.Zero, true)) { Console.WriteLine("Another instance already running"); Thread.Sleep(5000); return ; } //save a reference so it does not get GC'd consoleHandler = new HandlerRoutine(ConsoleCtrlCheck); //set our handler here that will trap exit SetConsoleCtrlHandler(consoleHandler, true); Migration Test = new Migration(); CssLib.CSMigrationWrapper TestObj; //Account userAccts = new Account(); while (!keepRunning) { if (args.Count() > 0) { if ((args[0].Equals("-Help", StringComparison.CurrentCultureIgnoreCase)) ||(args[0].Equals("-h", StringComparison.CurrentCultureIgnoreCase))) { string builder = "Usage of ZimbraMigrationConsole.exe ConfigxmlFile=C:\\MyConfig.xml Users =C:\\users.csv \n"; builder += "\n"; builder += "ConfigxmlFile= location of the xml file \n"; builder += "\n"; builder += "Users= location of the csv file \n"; builder += "\n"; builder += "MaxThreads= Maximum number of threads by default it uses 4.\n"; builder += "\n"; builder += "MaxErrors= Maximum no of errors allowed for the each migration \n"; builder += "\n"; builder += "MaxWarn= Maximum no of warnings \n"; builder += "\n"; builder += " Profile= UserProfile to be migrated for user migration \n"; builder += "\n"; builder += "DataFile= PST file for the user to be migrated\n"; builder += "\n"; builder += "SourceHost= The Source server hostname \n"; builder += "\n"; builder += "SourceAdminID= The Source AdminID \n"; builder += "\n"; builder += "ZimbraHost= The Zimbra server hostname \n"; builder += "\n"; builder += "ZimbraPort= The Zimbra port \n"; builder += "\n"; builder += " ZimbraID= The Zimbra ID. For server migration it’s the admin id and for user migration it’s the userid on Zimbra\n"; builder += "\n"; builder += " ZimbraPwd= Pwd for Zimbra \n"; builder += "\n"; builder += "ZimbraDomain= The Zimbra Domain name \n"; builder += "\n"; builder += "The Migration Item Options can be specified as Mail=True Calendar=True Contacts=True Sent=True DeletedItems=True Junk=True Tasks=True Rules=True OOO=True \n"; builder += " By default these options are false. Unless specified in the XML or as arguments \n"; builder += "\n"; builder += "Verbose= True|False .This option turns on or off verbose logging \n"; builder += "\n"; builder += "LogLevel= Debug|Info|Trace .This option provides various levels of logging \n"; builder += "\n"; builder += "IsSkipFolders= true|false .This option provides skipping of folders \n"; builder += "\n"; builder += "FoldersToSkip= comma separated folder names to be skipped \n"; builder += "\n"; builder += "IsOnOrAfter= true|false .This option provides the date filter to migration \n"; builder += "\n"; builder += "MigrateOnOrAfter= Date in the format YYYY-MM-DD .Items from this date and after get migrated \n"; builder += "\n"; builder += "IsMaxMessageSize= true|false .This option provides the maxmessagesize filter to migration \n"; builder += "\n"; builder += "MaxMessageSize= a numeric value .Items whose size falls into this category after get migrated \n"; builder += "\n"; builder += "IsSkipPrevMigratedItems= True|false .To skip previously migrated items \n"; builder += "\n"; builder += "LangID= Language/Locale ID of source account e.g. for Spanish Language/Locale ID is 3082. For more information please refer migration documentation \n"; builder += "\n"; builder += "For more information see the help file distributed with the exe. \n"; System.Console.Write(builder); Log.info(builder); keepRunning = true; Console.ReadKey(true); return; } try { CommandLineArgs.I.parseArgs(args, "myStringArg=defaultVal;someLong=12"); // CommandLineArgs.I.parseArgs(vargs, "myStringArg=defaultVal;someLong=12"); //CommandLineArgs.I.parseArgs(args[0] + args[1] +args[2] +args[3], "myStringArg=defaultVal;someLong=12"); } catch (Exception e) { System.Console.WriteLine("Incorrect format of CmdLine arguments" + e.Message); Log.err("Incorrect format of CmdLine arguments" + e.Message); keepRunning = true; if ((CommandLineArgs.I.arg("Silent") != null) &&(CommandLineArgs.I.argAsBool("Silent") == false)) { Console.ReadKey(true); } else if((CommandLineArgs.I.arg("Silent") == null)) Console.ReadKey(true); return; } string ConfigXmlFile = CommandLineArgs.I.argAsString("ConfigxmlFile"); string UserMapFile = CommandLineArgs.I.argAsString("Users"); string MaxWarns = CommandLineArgs.I.argAsString("MaxWarn"); string userid = CommandLineArgs.I.argAsString("Profile"); string Pstfile = CommandLineArgs.I.argAsString("DataFile"); string ZCSHost = CommandLineArgs.I.argAsString("ZimbraHost"); string ZCSPort = CommandLineArgs.I.argAsString("ZimbraPort"); string ZCSID = CommandLineArgs.I.argAsString("ZimbraID"); string ZCSPwd = CommandLineArgs.I.argAsString("ZimbraPwd"); string ZCSDomain = CommandLineArgs.I.argAsString("ZimbraDomain"); string SourceHost = CommandLineArgs.I.argAsString("SourceHost"); string SourceAdmin = CommandLineArgs.I.argAsString("SourceAdminID"); //bool Mail = CommandLineArgs.I.argAsBool("Mail"); bool Mail = false; bool Calendar = false;bool Contacts = false; bool Sent= false;bool DeletedItems = false;bool Junk = false;bool Tasks=false;bool Rules=false;bool OOO = false; bool UseSSL = false; int MaxErrors =0; int MaxThreads =0; string Loglevel = CommandLineArgs.I.argAsString("LogLevel"); bool Datefilter = false; bool SkipFolder = false; bool SkipPreviousMigration = false; bool IsMaxSize = false; string Folderlist = CommandLineArgs.I.argAsString("FoldersToSkip"); string MigrateDate = CommandLineArgs.I.argAsString("MigrateOnOrAfter"); string MaxMessageSize = CommandLineArgs.I.argAsString("MaxMessageSize"); long LangID = 0; bool ServerMigration = false; XmlConfig myXmlConfig = new XmlConfig(); bool Silent = false; if (CommandLineArgs.I.arg("Silent") != null) { Silent = CommandLineArgs.I.argAsBool("Silent"); } else Silent = false; if ((ConfigXmlFile != "") && (File.Exists(ConfigXmlFile))) { //if ((UserMapFile != "") && (File.Exists(UserMapFile))) if (UserMapFile != "") { if (File.Exists(UserMapFile)) { myXmlConfig = new XmlConfig(ConfigXmlFile, UserMapFile); try { myXmlConfig.InitializeConfig(); myXmlConfig.GetUserList(); } catch (Exception e) { Log.err("Exception in initializeconfig/Getuserlist \n" + e.Message); System.Console.WriteLine("Exception in initializeconfig/Getuserlist \n" + e.Message); //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) { Console.ReadKey(true); } return; } } else { Log.err("UserMap file not present.please check the file name or path"); System.Console.WriteLine("UserMap file not present.please check the file name or path"); // if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) { Console.ReadKey(true); } return; } } else { myXmlConfig = new XmlConfig(ConfigXmlFile, ""); try { myXmlConfig.InitializeConfig(); } catch (Exception e) { Log.err("Exception in initializeconfig \n" + e.Message); System.Console.WriteLine("Exception in initializeconfig \n" + e.Message); //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) { Console.ReadKey(true); } return; } } if (myXmlConfig.UserList.Count > 0) { ServerMigration = true; if (userid == "") userid = (myXmlConfig.ConfigObj.SourceServer.AdminID != "") ? myXmlConfig.ConfigObj.SourceServer.AdminID : myXmlConfig.ConfigObj.SourceServer.Profile; if (ZCSID == "") ZCSID = myXmlConfig.ConfigObj.ZimbraServer.AdminID; if (ZCSPwd == "") ZCSPwd = myXmlConfig.ConfigObj.ZimbraServer.AdminPwd; if (ZCSID == "") { if ((myXmlConfig.ConfigObj.SourceServer.Profile != "")) { // if (myXmlConfig.ConfigObj.SourceServer.Hostname == "") { Log.err(" Are you trying Server /User Migration .Check the arguments"); System.Console.WriteLine(" Are you trying Server /User Migration .Check the arguments"); //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) { Console.ReadKey(true); } return; } } } } else { if (userid == "") userid = myXmlConfig.ConfigObj.SourceServer.Profile; if (ZCSID == "") ZCSID = myXmlConfig.ConfigObj.ZimbraServer.UserAccount; if (ZCSPwd == "") ZCSPwd = myXmlConfig.ConfigObj.ZimbraServer.UserPassword; if (Pstfile == "") Pstfile = myXmlConfig.ConfigObj.SourceServer.DataFile; } if ((ZCSHost == "") && (ZCSDomain == "")) { ZCSHost = myXmlConfig.ConfigObj.ZimbraServer.Hostname; ZCSDomain = myXmlConfig.ConfigObj.UserProvision.DestinationDomain; } else { if (ZCSDomain == "") { Log.err("ZimbraHost and ZimbraDomain go together.To override ZimbraHost ,ZimbraDomain has to be overridden as well \n"); System.Console.WriteLine("ZimbraHost and ZimbraDomain go together.To override ZimbraHost ,ZimbraDomain has to be overridden as well \n"); //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) { System.Console.WriteLine("Press any key to return \n"); Console.ReadKey(true); } return; } if (ZCSHost == "") { Log.err("ZimbraHost and ZimbraDomain go together.To override ZimbraDomain ,ZimbraHost has to be overridden as well \n"); System.Console.WriteLine("ZimbraHost and ZimbraDomain go together.To override ZimbraDomain ,ZimbraHost has to be overridden as well \n"); //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) { System.Console.WriteLine("Press any key to return \n"); Console.ReadKey(true); } return; } } if (ZCSPort == "") ZCSPort = myXmlConfig.ConfigObj.ZimbraServer.Port; if (Loglevel == "") Loglevel = myXmlConfig.ConfigObj.GeneralOptions.LogLevel; if (ZCSDomain == "") ZCSDomain = myXmlConfig.ConfigObj.UserProvision.DestinationDomain; /* if (Mail == false) Mail = myXmlConfig.ConfigObj.ImportOptions.Mail;*/ if (CommandLineArgs.I.arg("LangID") != null) LangID = CommandLineArgs.I.argAsLong("LangID"); else LangID = myXmlConfig.ConfigObj.AdvancedImportOptions.LangID; if (CommandLineArgs.I.arg("MaxThreadCount") != null) MaxThreads = CommandLineArgs.I.argAsInt("MaxThreadCount"); else MaxThreads = myXmlConfig.ConfigObj.GeneralOptions.MaxThreadCount; if (MaxThreads == 0) MaxThreads = 4; ; if (CommandLineArgs.I.arg("MaxErrorCount") != null) MaxErrors = CommandLineArgs.I.argAsInt("MaxErrorCount"); else MaxErrors = myXmlConfig.ConfigObj.GeneralOptions.MaxErrorCount; if (CommandLineArgs.I.arg("IsSkipPrevMigratedItems") != null) { SkipPreviousMigration = CommandLineArgs.I.argAsBool("IsSkipPrevMigratedItems"); } else SkipPreviousMigration = myXmlConfig.ConfigObj.AdvancedImportOptions.IsSkipPrevMigratedItems; if (CommandLineArgs.I.arg("IsMaxMessageSize") != null) { IsMaxSize = CommandLineArgs.I.argAsBool("IsMaxMessageSize"); } else IsMaxSize = myXmlConfig.ConfigObj.AdvancedImportOptions.IsMaxMessageSize; if (CommandLineArgs.I.arg("IsSkipFolders") != null) { SkipFolder = CommandLineArgs.I.argAsBool("IsSkipFolders"); } else SkipFolder = myXmlConfig.ConfigObj.AdvancedImportOptions.IsSkipFolders; if (CommandLineArgs.I.arg("IsOnOrAfter") != null) { Datefilter = CommandLineArgs.I.argAsBool("IsOnOrAfter"); } else Datefilter = myXmlConfig.ConfigObj.AdvancedImportOptions.IsOnOrAfter; if (CommandLineArgs.I.arg("UseSSL") != null) { UseSSL = CommandLineArgs.I.argAsBool("UseSSL"); } else UseSSL = myXmlConfig.ConfigObj.ZimbraServer.UseSSL; if (CommandLineArgs.I.arg("Mail") != null) { Mail = CommandLineArgs.I.argAsBool("Mail"); } else Mail = myXmlConfig.ConfigObj.ImportOptions.Mail; if (CommandLineArgs.I.arg("Calendar") != null) { Calendar = CommandLineArgs.I.argAsBool("Calendar"); } else Calendar = myXmlConfig.ConfigObj.ImportOptions.Calendar; if (CommandLineArgs.I.arg("Contacts") != null) { Contacts = CommandLineArgs.I.argAsBool("Contacts"); } else Contacts = myXmlConfig.ConfigObj.ImportOptions.Contacts; if (CommandLineArgs.I.arg("Sent") != null) { Sent = CommandLineArgs.I.argAsBool("Sent"); } else Sent = myXmlConfig.ConfigObj.ImportOptions.Sent; if (CommandLineArgs.I.arg("DeletedItems") != null) { DeletedItems = CommandLineArgs.I.argAsBool("DeletedItems"); } else DeletedItems = myXmlConfig.ConfigObj.ImportOptions.DeletedItems; if (CommandLineArgs.I.arg("Junk") != null) { Junk = CommandLineArgs.I.argAsBool("Junk"); } else Junk = myXmlConfig.ConfigObj.ImportOptions.Junk; if (CommandLineArgs.I.arg("Tasks") != null) { Tasks = CommandLineArgs.I.argAsBool("Tasks"); } else Tasks = myXmlConfig.ConfigObj.ImportOptions.Tasks; if (CommandLineArgs.I.arg("Rules") != null) { Rules = CommandLineArgs.I.argAsBool("Rules"); } else Rules = myXmlConfig.ConfigObj.ImportOptions.Rules; if (CommandLineArgs.I.arg("OOO") != null) { OOO = CommandLineArgs.I.argAsBool("OOO"); } else OOO = myXmlConfig.ConfigObj.ImportOptions.OOO; } else { if (ConfigXmlFile != "") { if (!File.Exists(ConfigXmlFile)) { Log.err("XML file not present.please check the file name or path"); System.Console.WriteLine("XML file not present.please check the file name or path"); //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) { Console.ReadKey(true); } return; } } else { Log.err("Config file or cmdline arguemnts are needed.check the arguments!"); System.Console.WriteLine("Config file or cmdline arguemnts are needed.Check the arguments"); //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) { Console.ReadKey(true); } return; } } MigrationOptions importopts = new MigrationOptions(); ItemsAndFoldersOptions itemFolderFlags = ItemsAndFoldersOptions.None; if (Calendar) { itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Calendar; } if (Contacts) { itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Contacts; } if (Mail) { itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Mail; } if (Sent) { itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Sent; } if (DeletedItems) { itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.DeletedItems; } if (Junk) { itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Junk; } if (Tasks) { itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Tasks; } if (Rules) { itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.Rules; } if (OOO) { itemFolderFlags = itemFolderFlags | ItemsAndFoldersOptions.OOO; } bool verbose = false; if (CommandLineArgs.I.arg("Verbose") != null) { verbose = CommandLineArgs.I.argAsBool("Verbose"); } else verbose = myXmlConfig.ConfigObj.GeneralOptions.Verbose; importopts.ItemsAndFolders = itemFolderFlags; switch(Loglevel.ToLower()) { case"debug": importopts.VerboseOn = LogLevel.Debug; break; case "info": importopts.VerboseOn = LogLevel.Info; break; case "trace": importopts.VerboseOn = LogLevel.Trace; break; default: importopts.VerboseOn = LogLevel.Info; break; } if (verbose) { if (importopts.VerboseOn < LogLevel.Debug) { importopts.VerboseOn = LogLevel.Debug; } } else { /* if (importopts.VerboseOn > LogLevel.Info) { importopts.VerboseOn = LogLevel.Info; }*/ //will fix this later } if (MigrateDate == "") { MigrateDate = myXmlConfig.ConfigObj.AdvancedImportOptions.MigrateOnOrAfter.ToString(); } if (Datefilter) { importopts.DateFilter = MigrateDate; } if (Folderlist == "") { MVVM.ViewModel.OptionsViewModel M = new MVVM.ViewModel.OptionsViewModel(); Folderlist = M.ConvertToCSV(myXmlConfig.ConfigObj.AdvancedImportOptions.FoldersToSkip, ","); } if (SkipFolder) { importopts.SkipFolders = Folderlist; } if (IsMaxSize) { if(MaxMessageSize == "") MaxMessageSize = myXmlConfig.ConfigObj.AdvancedImportOptions.MaxMessageSize; importopts.MessageSizeFilter = MaxMessageSize; } importopts.SkipPrevMigrated = SkipPreviousMigration; if (SourceHost == "") { SourceHost = myXmlConfig.ConfigObj.SourceServer.Hostname; } if (SourceAdmin == "") { SourceAdmin = myXmlConfig.ConfigObj.SourceServer.AdminID; } /* if (MaxErrors == 0) { MaxErrors = myXmlConfig.ConfigObj.GeneralOptions.MaxErrorCount; }*/ importopts.LangID = LangID; importopts.MaxErrorCnt = MaxErrors; //importopts.VerboseOn = Verbose; try { TestObj = new CSMigrationWrapper("MAPI", importopts.VerboseOn); } catch (Exception e) { string error = "Migrationwrapper cannot be initialised ,Migration dll cannot be loaded. "; error += e.Message; System.Console.WriteLine(); System.Console.WriteLine(error); Log.err(error); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, error);*/ System.Console.WriteLine("......... \n"); /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, "");*/ System.Console.WriteLine("......... \n"); // if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) Console.ReadKey(true); return; } System.Console.WriteLine(); System.Console.WriteLine("Migration Initialization "); Log.info("Migration Initialization "); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green, " Migration Initialization ");*/ System.Console.WriteLine("......... \n"); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green, "");*/ System.Console.WriteLine("......... \n"); if (userid != "") { if (Pstfile == "") { string retval = TestObj.GlobalInit(userid, "", ""); if (retval.Length > 0) { System.Console.WriteLine(); // System.Console.WriteLine("Error in Migration Initialization "); Log.err("Error in Migration Initialization "); /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, " Error in Migration Initialization ");*/ System.Console.WriteLine("......... \n"); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, retval);*/ System.Console.WriteLine("......... \n"); System.Console.WriteLine(); return; } } } else { if ((SourceHost != "") && (SourceAdmin != "")) { string retval = TestObj.GlobalInit(SourceHost, SourceAdmin, ""); if (retval.Length > 0) { System.Console.WriteLine(); System.Console.WriteLine("Error in server Migration Initialization "); Log.err("Error in server Migration Initialization "); /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, " Error in Migration Initialization ");*/ System.Console.WriteLine("......... \n"); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, retval);*/ System.Console.WriteLine("......... \n"); System.Console.WriteLine(); return; } } } ZimbraValues.GetZimbraValues().ClientVersion = new MVVM.Model.BuildNum().BUILD_NUM; if (ServerMigration) { foreach (MVVM.Model.Users user in myXmlConfig.UserList) { Account userAcct = new Account(); System.Console.WriteLine(); /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green, "Connecting to to Zimbra Server \n ");*/ System.Console.WriteLine("Connecting to to Zimbra Server \n "); Log.info("Connecting to to Zimbra Server \n "); System.Console.WriteLine(); ZimbraAPI zimbraAPI = new ZimbraAPI(true, importopts.VerboseOn,importopts.SpecialCharRep); /*int stat = zimbraAPI.Logon( myXmlConfig.ConfigObj.zimbraServer.Hostname, myXmlConfig.ConfigObj.zimbraServer.Port, myXmlConfig.ConfigObj.zimbraServer.AdminID, myXmlConfig.ConfigObj.zimbraServer.AdminPwd, true);*/ int stat = zimbraAPI.Logon( ZCSHost, ZCSPort, ZCSID, ZCSPwd, UseSSL, true); if (stat != 0) { zimbraAPI.LastError.Count(); System.Console.WriteLine(); /* string message = "Logon to Zimbra Server for adminAccount " + myXmlConfig.ConfigObj.ZimbraServer.AdminID +"Failed ."+ zimbraAPI.LastError;*/ string message = "Logon to Zimbra Server for adminAccount " + myXmlConfig.ConfigObj.ZimbraServer.AdminID + " Failed. " + System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(zimbraAPI.LastError.ToLower()); System.Console.WriteLine(message); Log.err(message); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, "Logon to to Zimbra Server for adminAccount failed " + myXmlConfig.ConfigObj.ZimbraServer.AdminID);*/ System.Console.WriteLine("......... \n"); System.Console.WriteLine(); // return; } // userAcct.InitializeMigration(myXmlConfig.ConfigObj.zimbraServer.ZimbraHostname, myXmlConfig.ConfigObj.zimbraServer.Port, myXmlConfig.ConfigObj.zimbraServer.ZimbraAdminID,user.UserName); string acctName; if (user.MappedName == "") { acctName = user.UserName + '@' + // (myXmlConfig.ConfigObj.UserProvision.DestinationDomain == "" ? ZCSHost : myXmlConfig.ConfigObj.UserProvision.DestinationDomain); (ZCSDomain == "" ? ZCSHost : ZCSDomain); } else { acctName = user.MappedName + '@' + //(myXmlConfig.ConfigObj.UserProvision.DestinationDomain == "" ? ZCSHost : myXmlConfig.ConfigObj.UserProvision.DestinationDomain); (ZCSDomain == "" ? ZCSHost : ZCSDomain); } if (zimbraAPI.GetAccount(acctName) == 0) { System.Console.WriteLine(); System.Console.WriteLine(); string mesg = "Migration to Zimbra Started for UserAccount " + acctName; System.Console.WriteLine(mesg); Log.info(mesg); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green, " Migration to Zimbra Started for UserAccount " + acctName);*/ System.Console.WriteLine(); System.Console.WriteLine(); user.IsProvisioned = true; } else { System.Console.WriteLine(); string err = "User is not provisioned on Zimbra Server " + acctName; System.Console.WriteLine(err); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Yellow, " User is not provisioned on Zimbra Server " + acctName);*/ Log.info(err); System.Console.WriteLine(); System.Console.WriteLine(); err = "Provisioning user" + acctName; Log.info(err); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green, " Provisioning user" + acctName);*/ string historyfile = Path.GetTempPath() + acctName.Substring(0, acctName.IndexOf('@')) + "history.log"; if (File.Exists(historyfile)) { try { File.Delete(historyfile); } catch (Exception e) { string msg = "exception in deleteing the Histroy file " + e.Message; System.Console.WriteLine(msg); Log.err(msg); } } System.Console.WriteLine(err); System.Console.WriteLine(); System.Console.WriteLine(); string Defaultpwd = ""; /************************************///if csv file has a pwd use it else looks for the pwd in xml file. if ((user.PWDdefault != "")) Defaultpwd = user.PWDdefault; else { Defaultpwd = myXmlConfig.ConfigObj.UserProvision.DefaultPWD; if (Defaultpwd == null) { Defaultpwd = "default"; } } bool mustChangePW = user.ChangePWD; if (zimbraAPI.CreateAccount(acctName, "", "", "", "", Defaultpwd, mustChangePW, myXmlConfig.ConfigObj.UserProvision.COS) == 0) { System.Console.WriteLine(); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green, " Provisioning useraccount success " + acctName);*/ err = "Provisioning useraccount success " + acctName; System.Console.WriteLine(err); System.Console.WriteLine(); System.Console.WriteLine(); Log.info(err); /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Green, " Migration to Zimbra Started for UserAccount " + user.UserName);*/ err = "Migration to Zimbra Started for UserAccount " + user.UserName; System.Console.WriteLine(err); System.Console.WriteLine(); System.Console.WriteLine("......... \n"); Log.info(err); user.IsProvisioned = true; } else { System.Console.WriteLine(); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, " error provisioning user " + acctName);*/ err = "error provisioning user " + acctName + ". " + System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(zimbraAPI.LastError.ToLower()) + "\n"; System.Console.WriteLine(err); Log.err(err); user.IsProvisioned=false; } } string final = user.StatusMessage; } if (myXmlConfig.UserList.Count > 0) { countdownEvent = new CountdownEvent(myXmlConfig.UserList.Count); userAccts.StartMigration(myXmlConfig.UserList, ZCSDomain, importopts, countdownEvent, TestObj, MaxThreads); countdownEvent.Wait(); Console.WriteLine("Finished Migration"); Log.info("Finished Migration"); Console.WriteLine("UNinit Migration"); Log.info("UNinit Migration"); } string retval = TestObj.GlobalUninit(); if (retval.Length > 0) { System.Console.WriteLine(); System.Console.WriteLine("Error in Migration UnInitialization "); Log.err("Error in Migration UnInitialization "); /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, " Error in Migration Initialization ");*/ System.Console.WriteLine("......... \n"); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, retval);*/ System.Console.WriteLine("......... \n"); System.Console.WriteLine(); keepRunning = true; return; } keepRunning = true; } else { if ((userid != "") || (Pstfile != "")) { string accountname = ZCSID; if (!accountname.Contains("@")) { accountname = accountname + "@" + (((ZCSDomain == "") || (ZCSDomain == null)) ? ZCSHost : ZCSDomain); } string accountid = (Pstfile != "") ? Pstfile : userid; ZimbraAPI zimbraAPI = new ZimbraAPI(false, importopts.VerboseOn); System.Console.WriteLine(); /* ProgressUtil.RenderConsoleProgress( 30, '\u2591', ConsoleColor.Green, "Connecting to to Zimbra Server \n ");*/ string err = "Connecting to to Zimbra Server \n "; System.Console.WriteLine(err); System.Console.WriteLine(); Log.info(err); int stat = zimbraAPI.Logon( ZCSHost, ZCSPort, accountname, ZCSPwd, UseSSL, false); if (stat != 0) { zimbraAPI.LastError.Count(); System.Console.WriteLine(); /*ProgressUtil.RenderConsoleProgress( 30, '\u2591', ConsoleColor.Red, "Logon to to Zimbra Server for userAccount failed " + ZCSID);*/ err = "Logon to Zimbra Server for userAccount " + ZCSID + " Failed. " + System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(zimbraAPI.LastError.ToLower()); System.Console.WriteLine(err); Log.err(err); System.Console.WriteLine("......... \n"); System.Console.WriteLine(); //Thread.Sleep(2000); if (Pstfile == "") { string val = TestObj.GlobalUninit(); if (val.Length > 0) { System.Console.WriteLine(); System.Console.WriteLine("Error in Migration UnInitialization "); /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, " Error in Migration Initialization ");*/ System.Console.WriteLine("......... \n"); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, retval);*/ System.Console.WriteLine("......... \n"); Log.err("Error in Migration UnInitialization"); System.Console.WriteLine(); keepRunning = true; return; } } //if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if (!Silent) { Console.ReadKey(true); } keepRunning = true; return; } System.Console.WriteLine(); /* ProgressUtil.RenderConsoleProgress( 30, '\u2591', ConsoleColor.Green, " Migration to Zimbra Started for Profile/PST " + accountid);*/ err = "Migration to Zimbra Started for Profile/PST " + accountid; System.Console.WriteLine(err); Log.info(err); System.Console.WriteLine(); System.Console.WriteLine(); // Test.test(accountname, TestObj, accountid, importopts, false); countdownEvent = new CountdownEvent(1); //Account userAccts = new Account(); MVVM.Model.Users User = new MVVM.Model.Users(); User.UserName = userid; List<MVVM.Model.Users> users = new List<MVVM.Model.Users>(); users.Add(User); userAccts.StartMigration(users, ZCSHost, importopts, countdownEvent, TestObj, MaxThreads, false, accountname, accountid); // Thread.Sleep(129000); countdownEvent.Wait(); Log.info("Finished Migration"); Console.WriteLine(); Console.WriteLine("Finished Migration"); Console.WriteLine("UNinit Migration"); Log.info("UNinit Migration"); if (Pstfile == "") { string retval = TestObj.GlobalUninit(); if (retval.Length > 0) { System.Console.WriteLine(); System.Console.WriteLine("Error in Migration UnInitialization "); Log.err("Error in Migration UnInitialization "); /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, " Error in Migration Initialization ");*/ System.Console.WriteLine("......... \n"); /* ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, retval);*/ System.Console.WriteLine("......... \n"); System.Console.WriteLine(); keepRunning = true; return; } } keepRunning = true; } } } else { System.Console.WriteLine(); /*ProgressUtil.RenderConsoleProgress(30, '\u2591', ConsoleColor.Red, " Make sure the correct arguments (2) are passed \n");*/ System.Console.WriteLine("Make sure the correct arguments (2) are passed . type Help for more information\n"); System.Console.WriteLine(); Log.err("Make sure the correct arguments (2) are passed . type Help for more information\n"); // if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == false)) { Console.ReadKey(true); } else if ((CommandLineArgs.I.arg("Silent") == null)) Console.ReadKey(true); return; } } /// Account userAccts = new Account(); if (_userRequestExit) { keepRunning = true; //set flag to exit loop. Other conditions could cause this too, which is why we use a seperate variable // Console.WriteLine("Shutting down, user requested exit"); } Log.info("Migration finished"); System.Console.WriteLine("Press any key to continue \n"); // if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == true)) if ((CommandLineArgs.I.arg("Silent") != null) && (CommandLineArgs.I.argAsBool("Silent") == false)) { Console.ReadKey(true); } else { if ((CommandLineArgs.I.arg("Silent") == null)) Console.ReadKey(true); } return; }
public static bool SetConsoleCtrlHandler(HandlerRoutine handler, bool add) { return(NativeMethods.SetConsoleCtrlHandler(handler, add)); }
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
public static extern bool SetConsoleCtrlHandler(HandlerRoutine hcb, bool add);