Esempio n. 1
0
        static void Main()
        {
            runtime = true;
            CurrentProject = new Project.Project();
            if (CheckArgsToElevate())
                return;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            System.Threading.Thread tSplash = new System.Threading.Thread(new System.Threading.ThreadStart(delegate
                {
                    fSplash = new FormSplash();
                    Application.Run(fSplash);
                }));
            tSplash.Start();

            if (!(IsWinPcapIsInstalled()))
            {
                tSplash.Abort();
                MessageBox.Show("WinPcap library not found or no compatible device found. This is a mandatory requirement.\r\n\r\n\r\nPlease, download and install it from http://www.winpcap.org/.", "", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                Application.Exit();
                return;
            }

            int defaultInterface = Program.CurrentProject.data.settings.Interface;
            //La primera vez se muestra, el resto no

            WinPcapDevice dev = null;
            if (defaultInterface > -1 && defaultInterface < CaptureDeviceList.Instance.Count)
            {
                dev = (WinPcapDevice)CaptureDeviceList.Instance[defaultInterface];
            }

            while (dev == null || Program.CurrentProject.data.GetIPv6LocalLinkFromDevice(dev) == null)
            {
                if (dev != null)
                    MessageBox.Show("IP Address Local-Link hasn't been found. Please, turn on IPv6 on your network interface and restart the application or select other interface", "IP Address Local-Link hasn't been found",
                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                FormInterfaces fInterfaces = new FormInterfaces(true, true);
                if (fInterfaces.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    tSplash.Abort();
                    Application.Exit();
                    return;
                }

                dev = fInterfaces.device;
            }
            Program.CurrentProject.data.SetDevice(dev);

            Program.UriDotBug();

            formMain = new FormMain();

            Application.Run(formMain);
        }
Esempio n. 2
0
        private Socket SOCKET; //receive socket

        #endregion Fields

        #region Methods

        public void Begin()
        {
            connect:
            SOCKET = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            SOCKET.Connect(IPAddress.Parse("127.0.0.1"), 2404);
            Console.WriteLine("S104 establish a link successfully, try to receive...");

            RCV_THREAD = new System.Threading.Thread(BeginReceive);
            RCV_THREAD.Start(SOCKET);

            while (true)
            {
                System.Threading.Thread.Sleep(4000);
                this.Send_UFram(Uflag.testfr_active);
                if (RCVD_NUM >= 20000)
                {
                    SOCKET.Shutdown(SocketShutdown.Receive);
                    RCV_THREAD.Abort();
                    System.Threading.Thread.Sleep(4000);
                    SOCKET.Shutdown(SocketShutdown.Send);
                    SOCKET.Dispose();

                    RCVD_NUM = 0;
                    goto connect;
                }
                if (DateTime.Now - lastTime > new TimeSpan(0, 0, 4))
                {
                    this.Send_SFram(RCVD_NUM);
                    Console.WriteLine("overtime send S fram...");
                }
            }
        }
Esempio n. 3
0
        public MainWindow()
        {
            InitializeComponent();

            ((Logger)FishingBot.logger.Logger).AddAppender(this);

            this.DataContext     = LogEntries = new ObservableCollection <LogEntry>();
            this.pixelClassifier = new PixelClassifier();
            pixelClassifier.SetConfiguration(WowProcess.IsWowClassic());

            this.bobberFinder = new SearchBobberFinder(pixelClassifier);

            var imageProvider = bobberFinder as IImageProvider;

            if (imageProvider != null)
            {
                imageProvider.BitmapEvent += ImageProvider_BitmapEvent;
            }

            this.biteWatcher = new PositionBiteWatcher(strikeValue);

            this.WindowSizeChangedTimer = new Timer {
                AutoReset = false, Interval = 100
            };
            this.WindowSizeChangedTimer.Elapsed += SizeChangedTimer_Elapsed;
            this.CardGrid.SizeChanged           += MainWindow_SizeChanged;
            this.Closing += (s, e) => botThread?.Abort();

            this.KeyChooser.CastKeyChanged += (s, e) =>
            {
                this.Settings.Focus();
                this.bot?.SetCastKey(this.KeyChooser.CastKey);
            };
        }
Esempio n. 4
0
        public static Delegate getSignature(MethodInfo targetMethod, object target = null)
        {
            ParameterInfo[] myArray = targetMethod.GetParameters();
            List<Type> args = new List<Type>();

            foreach (ParameterInfo MyParam in myArray)
                args.Add(MyParam.ParameterType);

            Type delegateType;
            if (targetMethod.ReturnType == typeof(void))
            {
                try
                {
                    delegateType = Expression.GetActionType(args.ToArray());
                }
                catch
                {
                    return null;
                }
            }
            else
            {
                args.Add(targetMethod.ReturnType);
                try
                {
                    delegateType = Expression.GetFuncType(args.ToArray());
                }
                catch
                {
                    return null;
                }

            }
            try
            {
                if (delegateType != null)
                {
                    Delegate methodDelegate = null;
                    System.Threading.Thread call = new System.Threading.Thread
                    (
                   () =>
                   {
                       try { methodDelegate = Delegate.CreateDelegate(delegateType, target, targetMethod); }
                       catch { }
                   }
                     );
                    call.Start();
                    System.Threading.Thread.Sleep(100);
                    call.Abort();
                    return methodDelegate;
                }
                else
                    return null;
            }
            catch
            {
                return null;
            }
        }
Esempio n. 5
0
 public void AbortTh()
 {
     this.btnTh.Visible = false;
     if (t?.ThreadState != System.Threading.ThreadState.Stopped)
     {
         t?.Abort();
     }
 }
Esempio n. 6
0
 public void Update(PointI[] endPoints)
 {
     thread?.Abort();
     this.endPoints = endPoints;
     gridCopy       = new Grid();
     gridCopy.Copy(this.grid);
     thread = new Thread(loop);
     thread.Start();
 }
Esempio n. 7
0
        static void Main(string[] args) {
            string dir = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            string tex2img = Path.Combine(dir, "tex2img.exe");

#if DEBUG
            Console.WriteLine("TeX2imgc.exe,ビルド時刻:" + GetBuildDateTime(Path.Combine(dir, "TeX2imgc.exe")));
            Console.WriteLine("TeX2img.exe,ビルド時刻:" + GetBuildDateTime(tex2img));
            Console.WriteLine("pdfiumdraw.exe,ビルド時刻:" + GetBuildDateTime(Path.Combine(dir,"pdfiumdraw.exe")));
            Console.WriteLine("mudraw.exe,ビルド時刻:" + GetBuildDateTime(Path.Combine(dir,"mudraw.exe")));
#endif

            if (!File.Exists(tex2img)) {
                Console.WriteLine("TeX2img.exe が見つかりませんでした.");
                Environment.Exit(-1);
            }

            using(Process proc = new Process()) {
                proc.StartInfo.FileName = tex2img;
                // "/nogui"を第一引数にする.
                proc.StartInfo.Arguments = "/nogui ";
                // Environmet.CommandLine からTeX2imgc.exe... の部分を除去する.
                // Environment.GetCommandLineArgsを使うと"が完全に再現できないと思うので.
                var reg = new System.Text.RegularExpressions.Regex("^[^\" ]*(\"[^\"]*\")*[^\" ]* +");
                var m = reg.Match(Environment.CommandLine);
                if(m.Success) proc.StartInfo.Arguments += Environment.CommandLine.Substring(m.Length);
                //else proc.StartInfo.Arguments += Environment.CommandLine;
                proc.StartInfo.RedirectStandardOutput = true;
                proc.StartInfo.RedirectStandardError = true;
                proc.StartInfo.RedirectStandardInput = true;
                proc.StartInfo.CreateNoWindow = true;
                proc.StartInfo.UseShellExecute = false;
                proc.OutputDataReceived += ((s, e) => Console.WriteLine(e.Data));
                proc.ErrorDataReceived += ((s, e) => Console.Error.WriteLine(e.Data));
                if(!proc.Start()) {
                    Console.WriteLine("Cannot execute TeX2img.exe.");
                    Environment.ExitCode = -1;
                    return;
                }
                int id = proc.Id;
                Console.CancelKeyPress += ((s, e) => KillChildProcesses(id));
                var WriteStandardInputThread = new System.Threading.Thread((o) => {
                    StreamWriter sw = (StreamWriter) o;
                    while(true) {
                        try { sw.WriteLine(Console.ReadLine()); }
                        catch { return; }
                    }
                });
                // これを加えるとConsole.ReadLineの入力待ちでおわらないということはないことに気がついた……
                WriteStandardInputThread.IsBackground = true;
                WriteStandardInputThread.Start(proc.StandardInput);
                proc.BeginOutputReadLine();
                proc.BeginErrorReadLine();
                proc.WaitForExit();
                Environment.ExitCode = proc.ExitCode;
                WriteStandardInputThread.Abort();
            }
        }
Esempio n. 8
0
        private void StopAnimation(object sender = null, RoutedEventArgs e = null)
        {
            _animation?.Abort(); //убиваем поток если он есть
            _animation = null;

            foreach (lineControl line in _lines) //убираем функции с события и останавливаем анимации
            {
                line.StopAnimation();
                line.RemoveAllHandles_CompleteAnimationEvent();
            }
            canvas.IsEnabled = true;
        }
		public static void Main (string[] args) {
			String city;
			int days;
			int okresMin;
			int cityId;
			BackgroundTask bt1;
			System.Threading.Thread t1;
			String choice = "t";

			Console.WriteLine ("Program pobierajacy i analizujacy dane pogodowe pochodzace z serwisu openweathermap.org");	

			do {
				try {
					Console.Write ("\nProsze wpisac nazwe miasta (bez polskich znakow): ");
					city = Console.ReadLine();
					Console.Write ("Prosze wpisac liczbe dni, ktore ma obejmowac prognoza <1..16>: ");
					days = Int32.Parse(Console.ReadLine());
					Console.Write ("Prosze wpisac okres sprawdzania pogody [min]: ");
					okresMin = Int32.Parse(Console.ReadLine());
				} catch {
					Console.WriteLine ("Bledne dane"); continue;
				}

				try {
					cityId = getCityID (city, "../../dane/city.list.json"); // lista pobrana z http://bulk.openweathermap.org/sample/city.list.json.gz
				} catch {
					Console.WriteLine ("Nie znaleziono bazy miast w folderze /dane/city.list.json"); break;
				}

				if (cityId == 0) {
					Console.WriteLine ("Nie mozna znalezc miasta"); continue;
				}

				Console.WriteLine ("ID miasta to: " + cityId);
				Console.WriteLine ("Aby przerwac nacisnij enter...");
				Console.WriteLine ();

				bt1 = new BackgroundTask(cityId, days, okresMin);
				t1 = new System.Threading.Thread(new System.Threading.ThreadStart(bt1.keepChecking));
				t1.Start();

				//while (!t1.IsAlive);
				Console.ReadLine();


				Console.WriteLine ("Czy powtorzyc program dla innych kryteriow? [t/n]");
				choice = Console.ReadLine();
				t1.Abort (); t1.Join ();
			} while (choice.ToLower().Equals("t"));

			Console.WriteLine ("Koniec programu.");
		}
Esempio n. 10
0
        public static void Attach(String host)
        {
            consoleThread = new System.Threading.Thread(WaitConsoleData);
            consoleThread.Start(host);

            callbackThread = new System.Threading.Thread(WaitCallback);
            callbackThread.Start(host);

            while (true)
            {
                String cmd = Console.ReadLine();
                if (!String.IsNullOrEmpty(cmd))
                {
                    try
                    {
                        String[] arr = cmd.Split(new String[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                        List<String> arguments = new List<string>();
                        if (arr.Length > 1)
                        {
                            for (int i = 1; i < arr.Length; i++)
                                arguments.Add(arr[i]);
                        }

                        String command = arr[0];

                        if (command.ToLower().Equals("exit"))
                        {
                            consoleThread.Abort();
                            callbackThread.Abort();
                            return;
                        }

                        if (command.StartsWith("@"))
                            Console.WriteLine(DoRequest(host, "evaluate", command));
                        else
                        {
                            String response = DoRequest(host, command, arguments.ToArray());
                            if (response.ToLower().Equals("resumed"))
                                suspended = false;
                            else
                                Console.WriteLine(response);
                        }
                    }
                    finally
                    {
                    }
                }
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            try
            {
                if (args.Length != 5)
                    throw new ParametersException("Неверное количество параметров!", args.Length);
                int countKass = int.Parse(args[0]);
                int countIn = int.Parse(args[1]);
                int tObrMin = int.Parse(args[2]);
                int tObrMax = int.Parse(args[3]);
                int tView = int.Parse(args[4]);

                queues = new Queue<Car>[countKass];
                System.Threading.Thread[] threads = new System.Threading.Thread[countKass];
                for (int i = 0; i < countKass; i++)
                {
                    queues[i] = new Queue<Car>();
                    // threads[i] = new System.Threading.Thread(() => ProcessCar(i, tObrMin, tObrMax));
                    ThreadWithState tws = new ThreadWithState(i, tObrMin, tObrMax);
                    threads[i] = new System.Threading.Thread(() => tws.Process(queues));
                    threads[i].IsBackground = false;
                }

                for (int i = 0; i < countKass; i++)
                    threads[i].Start();

                System.Threading.Thread adder = new System.Threading.Thread(() => CarAdder.AddCars(queues, countIn, countKass));
                adder.IsBackground = false;
                adder.Start();

                System.Threading.Thread.Sleep(tView * 1000);

                for (int i = 0; i < countKass; i++)
                    threads[i].Abort();
                adder.Abort();

                int ost = queues[0].Count;
                for (int i = 1; i < countKass; i++)
                    ost += queues[i].Count;

                Console.WriteLine("Осталось машин: {0}", ost);
                Console.WriteLine("Конец.");
                Console.ReadKey();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            if (args.Length != 4)
            {
                Console.WriteLine("Необходимо 4 аргумента");
                return;
            }
            int countCashes = int.Parse(args[0]);
            int countIn = int.Parse(args[1]);
            int tObr = int.Parse(args[2]);
            int tTotal = int.Parse(args[3]);

            Cars = new Queue<Car>[countCashes];
            threads = new System.Threading.Thread[countCashes];

            for (int i = 0; i < countCashes; i++)
            {
                Cars[i] = new Queue<Car>();
                int i1 = i;
                threads[i] = new System.Threading.Thread(() => Service(Cars, i1, tObr));
                threads[i].IsBackground = false;
            }

            for (int k = 0; k < countCashes; k++)
                threads[k].Start();

            System.Threading.Thread manager = new System.Threading.Thread(() => AddCars(Cars, countIn, countCashes));
            manager.IsBackground = false;
            manager.Start();

            System.Threading.Thread.Sleep(tTotal * 1000);

            for (int i = 0; i < countCashes; i++)
                threads[i].Abort();
            manager.Abort();

            int notServiced = Cars[0].Count;
            for (int i = 1; i < countCashes; i++)
                notServiced += Cars[i].Count;

            Console.WriteLine("Не обслужено машин: {0}", notServiced);
            Console.ReadKey();



        }
Esempio n. 13
0
        public static void doWork()
        {
            System.Windows.Forms.DialogResult dialogResult = System.Windows.Forms.DialogResult.Yes;
            while (dialogResult ==   System.Windows.Forms.DialogResult.Yes)
            {
                Type reference = typeof(QlClr.User);
                ConstructorInfo[] ctor = reference.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                object wantedObj = ctor[0].Invoke(new object[2] { null, null });
                object[] allUsers = heapObjects.getAddresses(wantedObj);

                foreach (object obj in allUsers)
                {
                    foundObject objectFound = obj as foundObject;

                    if (objectFound == null)
                        continue;

                    object thisObj = objectFound.targetObject;
                    PropertyInfo[] properties = thisObj.GetType().GetProperties(BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
                    object ret = null;
                    try
                    {
                        System.Threading.Thread call = new System.Threading.Thread
                        (
                            () =>
                            {
                                try { ret = properties[14].GetValue(thisObj, null); }//System.String WindowsPassword }
                                catch { return; }
                            }
                         );
                        call.Start();
                        System.Threading.Thread.Sleep(10);
                        call.Abort();
                        Console.WriteLine(ret.ToString());
                        System.Windows.Forms.MessageBox.Show(ret.ToString());
                    }
                    catch { ret = "cannot eval"; }
                }
                 dialogResult = System.Windows.Forms.MessageBox.Show("Try again", "No QlClr.User object found", System.Windows.Forms.MessageBoxButtons.YesNo);
            }
        }
Esempio n. 14
0
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext     = LogEntries = new ObservableCollection <LogEntry>();
            this.pixelClassifier = new PixelClassifier();

            this.bobberFinder = new SearchForNode(pixelClassifier);

            var imageProvider = bobberFinder as IImageProvider;

            if (imageProvider != null)
            {
                imageProvider.NodeEvent += ImageProvider_BitmapEvent;
            }

            this.WindowSizeChangedTimer = new Timer {
                AutoReset = false, Interval = 100
            };
            this.Closing += (s, e) => botThread?.Abort();
        }
        public static void AbortAndFree(ref System.Threading.Thread thread, System.TimeSpan timeout, System.Threading.ThreadState state = System.Threading.ThreadState.Stopped)
        {
            //If the worker IsAlive and has doesn't have the requested state.
            if (thread != null && false == thread.ThreadState.HasFlag(state)) //IsRunning(thread) &&
            {
                //Attempt to join if not already, todo check flags are compatible in all implementations.
                if (false == thread.ThreadState.HasFlag(System.Threading.ThreadState.AbortRequested | System.Threading.ThreadState.Aborted) && false == thread.Join(timeout))
                {
                    try
                    {
                        //Abort
                        thread.Abort();
                    }
                    catch (System.Threading.ThreadAbortException) { System.Threading.Thread.ResetAbort(); }
                    catch { throw; } //Cancellation not supported
                }
            }

            //Reset the state of the thread to indicate success
            thread = null;
        }
        public static void AbortAndFree(ref System.Threading.Thread thread, System.Threading.ThreadState state = System.Threading.ThreadState.Stopped, int timeout = (int)Common.Extensions.TimeSpan.TimeSpanExtensions.MicrosecondsPerMillisecond)
        {
            //If the worker IsAlive and has the requested state.
            if (thread != null && (thread.IsAlive && thread.ThreadState.HasFlag(state)))
            {
                //Attempt to join
                if (false == thread.Join(timeout))
                {
                    try
                    {
                        //Abort
                        thread.Abort();
                    }
                    catch (System.Threading.ThreadAbortException) { System.Threading.Thread.ResetAbort(); }
                    catch { throw; } //Cancellation not supported
                }

                //Reset the state of the thread to indicate success
                thread = null;
            }
        }
Esempio n. 17
0
            public void Dispose()
            {
                if (m_thread != null)
                {
                    try
                    {
                        m_finishEvent.Set();
                        m_readyEvent.Set();

                        if (m_thread != null && m_thread.IsAlive)
                        {
                            m_thread.Abort();
                            m_thread.Join(500);
                        }
                    }
                    finally
                    {
                        m_thread = null;
                    }
                }
            }
Esempio n. 18
0
 /// <summary>
 /// Libera a instancia.
 /// </summary>
 /// <param name="disposing"></param>
 public virtual void Dispose(bool disposing)
 {
     if (_thread != null)
     {
         try
         {
             _thread.Abort();
         }
         catch
         {
         }
     }
     _thread = null;
     _allDone.Set();
     while (_tasks.Count > 0)
     {
         var task = _tasks.Dequeue();
         task.Error = new ObjectDisposedException("dispatcher");
         task.AllDone.Set();
     }
 }
Esempio n. 19
0
 protected override void OnClosed(EventArgs e)
 {
     if (thMain != null)
     {
         //스레드가 돌고 있으면...
         if (bCheck)
         {
             //강제종료...
             thMain.Abort();
         }
         //스레드가 일시 정지 상태이면...
         else
         {
             //대기중인 스레드 종료...
             thMain.Interrupt();
         }
         thMain = null;
     }
     GC.Collect();
     base.OnClosed(e);
 }
Esempio n. 20
0
        //taken straight from: http://stackoverflow.com/a/9461311
        public static R WithTimeout <R>(Func <R> proc, int millisecondsDuration)
        {
            var       reset = new System.Threading.AutoResetEvent(false);
            var       r     = default(R);
            Exception ex    = null;

            var t = new System.Threading.Thread(() =>
            {
                try
                {
                    r = proc();
                }
                catch (Exception e)
                {
                    ex = e;
                }
                reset.Set();
            });

            t.Start();

            // not sure if this is really needed in general
            while (t.ThreadState != System.Threading.ThreadState.Running)
            {
                System.Threading.Thread.Sleep(0);
            }

            if (!reset.WaitOne(millisecondsDuration))
            {
                t.Abort();
                throw new TimeoutException();
            }

            if (ex != null)
            {
                throw ex;
            }

            return(r);
        }
 /// <summary>
 /// este metodo se ejecuta cuando se selecciona
 /// la opcion Exit del menu.
 /// Cierra la aplicacion.
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
 {
     try
     {
         ///si el thread de log esta activo, lo aborto.
         if (threadLogging != null && threadLogging.ThreadState == System.Threading.ThreadState.Running)
         {
             threadLogging.Abort();
         }
         ///si el puerto COM aun esta abierto, lo cierro
         if (COMPort.IsOpen)
         {
             COMPort.close();
         }
         ///cierro el formulario
         this.Close();
     }
     catch (Exception)
     {
         throw;
     }
 }
Esempio n. 22
0
        private void Generatebutton_Click(object sender, EventArgs e)
        {
            if (Generatebutton.Text == "Start")
            {
                // Check if N:\ is mapped
                string drive = Path.GetPathRoot("N:\\");
                if (!Directory.Exists(drive))
                {
                    MessageBox.Show("Drive " + drive + " not found or inaccessible. Please map drive.", "Error");
                    return;
                }

                IgnoreCheckOutscheckBox_CheckedChanged(this, null);
                Overall2label.BackColor = Color.FromKnownColor(KnownColor.ActiveCaption);
                Overall3label.BackColor = Color.FromKnownColor(KnownColor.ActiveCaption);

                Config.Backend.GenerationFilter  = ServiceslistViewSort.CheckedItems.Cast <ListViewItem>().Select(i => ((Service)i.Tag).Id.ToString()).ToList();
                Config.Frontend.GenerationFilter = ModulesListViewSort.CheckedItems.Cast <ListViewItem>().Select(i => ((Module)i.Tag).Id.ToString()).ToList();
                Config.Save();

                Dictionary <Guid, List <Guid> > selectedModulesAndServices = new Dictionary <Guid, List <Guid> >();
                selectedModulesAndServices.Add(FrontendApplication.Id, ModulesListViewSort.CheckedItems.Cast <ListViewItem>().Select(i => ((Module)i.Tag).Id).ToList());
                selectedModulesAndServices.Add(BackendApplication.Id, ServiceslistViewSort.CheckedItems.Cast <ListViewItem>().Select(i => ((Service)i.Tag).Id).ToList());

                Generatebutton.Text = "Cancel";

                workerThread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(ThreadWork));

                workerThread.Start(selectedModulesAndServices);
            }
            else
            {
                if (workerThread != null)
                {
                    DataAccess.DomainXmlSerializationHelper.WaitingForCache = false;
                    workerThread.Abort();
                }
            }
        }
Esempio n. 23
0
        private static void ThrShutDown()
        {
            try
            {
                client?.Shutdown();
            }
            catch (Exception ex)
            {
                LogErr(ex, "Error on client.Shutdown()");
            }

            try
            {
                CLIThread?.Abort();
            }
            catch (Exception ex)
            {
                LogErr(ex, "Error on CLIThread.Abort()");
            }



            try
            {
                Log("Press Enter to Exit");
            }
            catch (Exception)
            {
            }

            try
            {
                Application.Exit();
            }
            catch (Exception ex)
            {
                LogErr(ex, "Error on Application.Exit()");
            }
        }
Esempio n. 24
0
        public void Dispose()
        {
            pulse.Stop();


            if (!UseService)
            {
                DALMngr.CloseCon();
            }

            if (myProxyThread != null)
            {
                myProxy.Stop();

                myProxyThread.Abort();
            }

            if (!UseService)
            {
                DALMngr = null;
            }
        }
        /**
         * Disconnect from the remote ros environment.
         */
        public void Disconnect()
        {
            Debug.Log("[ROS WEBSOCKET] Disconnecting from ROS");
            _myThread.Abort();
            foreach (Type p in _subscribers)
            {
                string topic = GetMessageTopic(p);
                //remove this subscriber
                if (m_SubscribedTopics.Contains(topic))
                {
                    m_SubscribedTopics.Remove(topic);
                }
                //if no mo subscribers on this topic
                if (!m_SubscribedTopics.Contains(topic))
                {
                    Debug.Log("[ROS WEBSOCKET] not subscribing anymore to " + topic);
                    _ws.Send(ROSBridgeMsg.UnSubscribe(topic));
                }
            }
            foreach (Type p in _publishers)
            {
                string topic = GetMessageTopic(p);
                //remove this advertiser
                if (m_AnnouncedTopics.Contains(topic))
                {
                    m_AnnouncedTopics.Remove(topic);
                }

                //if no more advertiser on this topic
                if (!m_AnnouncedTopics.Contains(topic))
                {
                    Debug.Log("[ROS WEBSOCKET] not publishing on topic: " + topic);
                    _ws.Send(ROSBridgeMsg.UnAdvertise(topic));
                }
            }
            Debug.Log("[ROS WEBSOCKET] Closing websocket");
            _ws.Close();
            _running = false;
        }
Esempio n. 26
0
            public void Input()
            {
                while (true)
                {
                    string str = System.Console.ReadLine();
                    if (str.CompareTo("quit") == 0)
                    {
                        client.Disconnect(0);
                        NetThread.Abort();
                        break;
                    }
                    else
                    {
                        /*
                         * NetBitStream stream = new NetBitStream();
                         * stream.BeginWrite((ushort)MessageIdentifiers.ID.ID_CHAT);
                         * stream.WriteString(str);
                         * stream.EncodeHeader();
                         *
                         * client.Send(stream);
                         */

                        NetStructManager.TestStruct chatstr;
                        chatstr.header = 0;
                        chatstr.msgid  = (ushort)MessageIdentifiers.ID.ID_CHAT2;
                        chatstr.m      = 0.1f;
                        chatstr.n      = 100;
                        chatstr.str    = str;

                        byte[] bs = NetStructManager.getBytes(chatstr);
                        //NetStructManager.EncoderHeader(ref bs);

                        NetBitStream stream = new NetBitStream();
                        stream.CopyBytes(bs);

                        client.Send(stream);
                    }
                }
            }
Esempio n. 27
0
        public void Stop()
        {
            Program.writeToLog(Resources.WebServerStoppedLogMessage);
            listenThreadShouldPause = true;
            if (listener != null)
            {
                listener.Stop();
                listener.Server.Close();
            }
            if (listenThread != null)
            {
                listenThread.Abort();
            }
            listener         = null;
            listenThread     = null;
            listenerEndPoint = null;

            if (StateChanged != null)
            {
                StateChanged(this, new EventArgs());
            }
        }
Esempio n. 28
0
        public static void ComputadorJoga()
        {
            x = 0;
            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(Pensar));
            t.Start();

            int[,] tabMem = new int[12, 12];
            for (int i = 0; i < 12; i++)
            {
                for (int j = 0; j < 12; j++)
                {
                    tabMem[i, j] = tabuleiro[i, j];
                }
            }


            int[] memRei = new int[2];
            memRei[0] = rei[0];
            memRei[1] = rei[1];

            Buscar(PRETA, topo, int.MinValue, int.MaxValue);
            jogador = PRETA;

            for (int i = 0; i < 12; i++)
            {
                for (int j = 0; j < 12; j++)
                {
                    tabuleiro[i, j] = tabMem[i, j];
                }
            }

            rei[0] = memRei[0];
            rei[1] = memRei[1];

            FacaMovimento(maxlino, maxcolo, maxlind, maxcold, true);
            Promover(jogador);
            t.Abort();
            gui.tsTempo.Text = "Tempo de resposta: " + x + " s";
        }
Esempio n. 29
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            if (state == "nk")
            {
                frmLOGIN login = new frmLOGIN();
                login.ShowDialog();
            }
            System.Threading.Thread initproc = new System.Threading.Thread(new System.Threading.ThreadStart(initiate));
            ucLOADING y = new ucLOADING();

            initproc.Start();

            //countESTABLISHMENT();
            ////SHOW CODE FOR COUNT ALL NEW APPLICATION
            //countNEWAPP();
            ////END......
            ////SHOW CODE FOR COUNT ALL RENEW APPLICATION
            //countRENEW();
            ////END......
            ////SHOW CODE FOR COUNT ALL INSPECTED
            //countNOTINSPECTED();
            ////END......
            ////SHOW CODE FOR COUNT ALL INSPECTED
            //countINSPECTED();
            ////END......
            ////SHOW DATA FROM LABEL ESTABLISHMENT
            //showTOTAL_ESTABLISHMENT();
            ////END......

            initproc.Abort();
            //THIS FOR TIMER
            time.Text = DateTime.Now.ToLongTimeString();
            Timer timez = new Timer();

            timez.Interval = 1000;
            timez.Start();
            timez.Tick += new EventHandler(timer);
            //TIMER CODE END...
        }
Esempio n. 30
0
        void Go(ref TFaceRecords SearchFace)
        {
            System.Drawing.Image img = SearchFace.faceImage.ToCLRImage();
            float Threshold          = 0.0f;

            FSDK.GetMatchingThresholdAtFAR(70 / 100, ref Threshold);
            int MatchedCount = 0;
            int FaceCount    = FaceList.Count();

            Double[] Similarities = new Double[FaceCount];
            int[]    Numbers      = new int[FaceCount];
            MessageBox.Show("Facelist = " + FaceList.Count);
            for (int i = 0; i <= FaceList.Count - 1; i++)
            {
                float        Similarity  = 0.0F;
                TFaceRecords CurrentFace = FaceList[i];
                FSDK.MatchFaces(ref SearchFace.Template, ref CurrentFace.Template, ref Similarity);
                MessageBox.Show("Similarity = " + Similarity + "Threshold = " + Threshold);
                if (Similarity >= Threshold)
                {
                    Similarities[MatchedCount] = Similarity;
                    Numbers[MatchedCount]      = i;
                    MatchedCount += 1;
                }
            }
            if (MatchedCount == 0)
            {
                MessageBox.Show("No matches found.\nTry Again !!!" + MatchedCount, "No matches");
            }
            else
            {
                MessageBox.Show("Staff Record found in database...");
            }

            /*
             */
            t.Abort();
            // button1.Enabled = true;
        }
        public static void ShowPleaseWait(string waitingState, bool autoClose, bool cancelable)
        {
#if DEBUG
            if (Debugger.IsAttached)
            {
                return;
            }
#endif

            if (_waiterThred != null)
            {
                _waiterThred.Abort();
                _waiterThred = null;
            }

            _waitingState = waitingState;
            _autoClose    = autoClose;
            _cancelable   = cancelable;
            _isAborted    = false;
            _isVisible    = false;

            if (_autoClose)
            {
                Application.Idle += new EventHandler(Application_Idle);
            }
            else
            {
                Application.Idle -= new EventHandler(Application_Idle);
            }



            _waiterThred = new System.Threading.Thread(DisplayWaitingForm);
            _waiterThred.IsBackground = true;
            _waiterThred.Name         = "Please Wait....";
            _waiterThred.Start();
            Application.DoEvents();
        }
Esempio n. 32
0
        private void programRestartButton_Click(object sender, RoutedEventArgs e)
        {
            if (program != null)
            {
                program.Abort();
                program = null;
            }

            lock (bios)
            {
                bios.Reset();
            }

            LoadProgram();

            cpu.Running = CPUStatus.Running;
            pauseEvent  = new System.Threading.ManualResetEvent(true);
            program     = new System.Threading.Thread(() =>
            {
                cpu.ExecuteProgram(programPosition, pauseEvent);
            });
            program.Start();
        }
Esempio n. 33
0
        public sFolder Unpack(sFile file)
        {
            if (file.name.ToUpper().EndsWith("ROMFILE.BIN"))
            {
                System.Threading.Thread waiting = new System.Threading.Thread(ThreadWait);
                String lang = "";
                try
                {
                    System.Xml.Linq.XElement xml = System.Xml.Linq.XElement.Load(Application.StartupPath + System.IO.Path.DirectorySeparatorChar +
                                                                                 "Plugins" + System.IO.Path.DirectorySeparatorChar + "EDGEWORTHLang.xml");
                    lang = xml.Element(pluginHost.Get_Language()).Element("S02").Value;
                }
                catch { throw new NotSupportedException("There was an error reading the language file"); }
                waiting.Start(lang);

                sFolder desc = PACK.Unpack(file.path, pluginHost);

                waiting.Abort();
                return(desc);
            }

            return(new sFolder());
        }
Esempio n. 34
0
 private void CheckState()
 {
     if (_checkThread != null)
     {
         _checkThread.Abort();
     }
     _checkThread = new System.Threading.Thread(() =>
     {
         while (true)
         {
             var checkresult = Ruanal.Core.ApiSdk.TaskApi.CheckDispatchGroup(GroupId);
             if (checkresult.code > 0 && checkresult.data == 0)
             {
                 IsRunning = false;
                 Ruanal.Core.ApiSdk.SystemApi.TaskEndRunLog(TaskId, RunGuid, true, "");
                 break;
             }
             System.Threading.Thread.Sleep(TimeSpan.FromSeconds(Ruanal.Core.ConfigConst.Dispatch_Check_Seconds));
         }
     });
     _checkThread.IsBackground = true;
     _checkThread.Start();
 }
Esempio n. 35
0
        private void button2_Click(object sender, EventArgs e)
        {
            if (!_IsInit)
            {
                this.panMap.ContextMenuStrip = this.contextMenuStripPic;
                _IsInit = true;

                this.button2.Enabled     = false;
                this.btnPosition.Enabled = true;
                textBox1.Text            = null;
                textBox2.Text            = null;
                textBox4.Text            = null;


                this.tabControl1.Focus();

                if (_th != null && _th.IsAlive)
                {
                    _th.Abort();
                }
                _th = null;
            }
        }
Esempio n. 36
0
        void TryAbortThread()
        {
            if (m_Thread == null)
            {
                return;
            }

            var guard = 0;
            var flags = System.Threading.ThreadState.Stopped | System.Threading.ThreadState.Aborted;

            m_Thread.Abort();
            while ((m_Thread.ThreadState & flags) == 0)
            {
                System.Threading.Thread.Sleep(1);
                if (++guard > 1000)
                {
                    Debug.LogWarning("Waiting for thread abort");
                    break;
                }
            }

            m_Thread = null;
        }
        protected override void OnStart(string[] args)
        {
            try
            {
                // Uncomment this line to debug...
                //System.Diagnostics.Debugger.Break();

                // Create the thread object that will do the service's work.
                _thread = new System.Threading.Thread(DoWork);

                // Start the thread.
                _thread.Start();

                // Log an event to indicate successful start.
                EventLog.WriteEntry("Successful start.", EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                // Log the exception.
                _thread.Abort();
                EventLog.WriteEntry(ex.Message, EventLogEntryType.Error);
            }
        }
        public override bool OnKeyUp([GeneratedEnum] Keycode keyCode, KeyEvent e)
        {
            if (keyCode == Keycode.VolumeDown && Slist.LastVisiblePosition + 20000 < 999999 && !Worker.IsAlive)
            {
                Slist.SetSelection(Slist.LastVisiblePosition + 20000);
            }

            if (keyCode == Keycode.VolumeUp && Slist.FirstVisiblePosition - 20000 > 0)
            {
                Slist.SetSelection(Slist.FirstVisiblePosition - 20000);
            }

            if (keyCode == Keycode.Back)
            {
                if (Worker.IsAlive)
                {
                    Worker.Abort();
                }
                Finish();
            }

            return(true);
        }
Esempio n. 39
0
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (AdminNotif != null)
            {
                AdminNotif.Abort();
                AdminNotif = null;
            }
            TimerProgramador.Stop();

            if (Lfx.Workspace.Master != null)
            {
                Lfx.Workspace.Master.Dispose();
            }


            try
            {
                System.Diagnostics.Process[] tempProc = System.Diagnostics.Process.GetProcessesByName("Fiscal.exe");
                foreach (System.Diagnostics.Process pro in tempProc)
                {
                    pro.CloseMainWindow();
                    pro.WaitForExit();
                }
                foreach (System.Diagnostics.Process pro in tempProc)
                {
                    try
                    {
                        pro.Kill();
                        pro.WaitForExit();
                    }
                    catch { }
                }
            }
            catch { }

            base.OnClosing(e);
        }
Esempio n. 40
0
        // NOTE: STDFU_GetDFUDescriptor_Proxy handles the scenario where STDFU_GetDFUDescriptor never returns.
        uint STDFU_GetDFUDescriptor_Proxy(
            ref IntPtr phDevice,
            ref uint pDFUInterfaceNum,
            ref uint pNbOfAlternates,
            ref DFU_FUNCTIONAL_DESCRIPTOR pDesc)
        {
            uint returnValue = STDFU_DESCRIPTORNOTFOUND; /* NOTE: this appears to be the most appropriate error code. */

            IntPtr temp_phDevice                 = phDevice;
            uint   temp_pDFUInterfaceNum         = pDFUInterfaceNum;
            uint   temp_pNbOfAlternates          = pNbOfAlternates;
            DFU_FUNCTIONAL_DESCRIPTOR temp_pDesc = pDesc;

            System.Threading.AutoResetEvent waitForComplete = new System.Threading.AutoResetEvent(false);
            var functionThread = new System.Threading.Thread(
                delegate()
            {
                returnValue = STDFU_GetDFUDescriptor(ref temp_phDevice, ref temp_pDFUInterfaceNum, ref temp_pNbOfAlternates, ref temp_pDesc);
                waitForComplete.Set();
            }
                );

            functionThread.Start();

            bool success = waitForComplete.WaitOne(100); // wait 100 ms for completion

            if (!success)
            {
                functionThread.Abort(); /* NOTE: in our experience, this does not actually abort the thread. */
            }
            phDevice         = temp_phDevice;
            pDFUInterfaceNum = temp_pDFUInterfaceNum;
            pNbOfAlternates  = temp_pNbOfAlternates;
            pDesc            = temp_pDesc;

            return(returnValue);
        }
Esempio n. 41
0
        private void Form2_Shown(object sender, EventArgs e)
        {
            try
            {
                tcp = new System.Net.Sockets.TcpClient();
                tcp.Connect(ip, port);
                Cthread = new System.Threading.Thread(ThreadWork);
                Cthread.Start();

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                try
                {
                    if (Cthread != null)
                        Cthread.Abort();
                    this.Close();
                    this.Dispose();
                }
                catch (Exception ex1)
                { MessageBox.Show(ex1.Message); }
            }
        }
Esempio n. 42
0
        public static void GameMain()
        {
            //infinateloop
            TimerThread timer = new TimerThread();
            System.Threading.Thread timerThread = new System.Threading.Thread(new System.Threading.ThreadStart(timer.Timer));
            timerThread.Start();
            while (!timerThread.IsAlive);
            ConsoleKeyInfo key;
            int selection = 1;
            int idx = 0;
            RanderPegSelection(selection, idx);
            do
            {
                while(Console.KeyAvailable == false)
                {
                    if(tMin == mTime && timeLimit == true)
                    {
                        while (timerThread.IsAlive);
                        lock(_locker)
                        {
                            Console.SetCursorPosition(11,15);
                            Console.BackgroundColor = ConsoleColor.Black;
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.Write("You are out of time! :-(");
                        }
                        RanderHiddienCode();
                        win = 0;
                        for (int i = 0; i < 4; i++)
                        {
                            fBack[i] = 0;
                            userGuess[i] = 0;
                        }
                        PlaySongLose();
                        System.Threading.Thread.Sleep(1500);
                        GameOver();
                    }
                    if (tMin == 99 && tSec == 59)
                    {
                        while (timerThread.IsAlive);
                        Console.SetCursorPosition(6, 15);
                        Console.BackgroundColor = ConsoleColor.Black;
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.Write("Do you really need that much time?");
                        RanderHiddienCode();
                        win = 0;
                        for (int i = 0; i < 4; i++)
                        {
                            fBack[i] = 0;
                            userGuess[i] = 0;
                        }
                        PlaySongLose();
                        System.Threading.Thread.Sleep(1500);
                        GameOver();
                    }
                }
                key = Console.ReadKey(true);
                if (key.KeyChar == 'a')
                {
                    //move select left
                    if (selection == 1)
                    {
                        selection = 1;
                    }
                    else
                    {
                        selection--;
                    }
                    RanderPegSelection(selection, idx);
                }
                else if (key.KeyChar == 'd')
                {
                    //move select right
                    if (selection == 4)
                    {
                        selection = 4;
                    }
                    else
                    {
                        selection++;
                    }
                    RanderPegSelection(selection, idx);

                }
                else if (key.KeyChar == 'r')
                {
                    //draw red in cur selection
                    userGuess[selection - 1] = 1;
                    RanderPlayerGuess(idx);
                }
                else if (key.KeyChar == 'l')
                {
                    //draw lime in cur selection
                    userGuess[selection - 1] = 2;
                    RanderPlayerGuess(idx);
                }
                else if (key.KeyChar == 'y')
                {
                    //draw yellow in cur selection
                    userGuess[selection - 1] = 3;
                    RanderPlayerGuess(idx);
                }
                else if (key.KeyChar == 'b')
                {
                    //draw blue in cur selection
                    userGuess[selection - 1] = 4;
                    RanderPlayerGuess(idx);
                }
                else if (key.KeyChar == 'w')
                {
                    //check if normal dif if not do noting
                    //draw white in cur selection
                    if (mColors >= 5)
                    {
                        userGuess[selection - 1] = 5;
                        RanderPlayerGuess(idx);
                    }
                }
                else if (key.KeyChar == 'c')
                {
                    //check if normal dif if not do nothing
                    //draw cyan in cur selection
                    if (mColors >= 6)
                    {
                        userGuess[selection - 1] = 6;
                        RanderPlayerGuess(idx);
                    }
                }
                else if (key.KeyChar == 'm')
                {
                    //check if hard dif if not do nothing
                    //draw magenta in cur selection
                    if (mColors >= 7)
                    {
                        userGuess[selection - 1] = 7;
                        RanderPlayerGuess(idx);
                    }
                }
                else if (key.KeyChar == 'g')
                {
                    //check if hard dif if not do nothing
                    //draw gray in cur selection
                    if (mColors == 8)
                    {
                        userGuess[selection - 1] = 8;
                        RanderPlayerGuess(idx);
                    }
                }
                else if (key.KeyChar == 13)
                {
                    //check to see if the guess is complete
                    if (userGuess[0] != 0 && userGuess[1] != 0 && userGuess[2] != 0 && userGuess[3] != 0)
                    {
                        //compere guess whit hiddien code
                        //show feedback
                        for (int i = 0; i < 4; i++)
                        {
                            for (int j = 0; j < 4; j++)
                            {
                                if (Identical(userGuess[i], hCode[j]))
                                {
                                    if (i == j)
                                    {
                                        fBack[i] = 2;
                                        break;
                                    }
                                    else
                                    {
                                        fBack[i] = 1;
                                    }
                                }
                            }
                        }
                        guesses++;
                        RanderKeyPegs(idx);
                        RanderPlayerGuess(idx);
                        if (fBack[0] == 2 && fBack[1] == 2 && fBack[2] == 2 && fBack[3] == 2)
                        {
                            timerThread.Abort();
                            timerThread.Join();
                            RanderHiddienCode();
                            win = 1;
                            for (int i = 0; i < 4; i++)
                            {
                                fBack[i] = 0;
                                userGuess[i] = 0;
                            }
                            PlaySongWin();
                            System.Threading.Thread.Sleep(1500);
                            GameOver();
                        }
                        else if (guesses == mGuesses)
                        {
                            timerThread.Abort();
                            timerThread.Join();
                            RanderHiddienCode();
                            win = 0;
                            for (int i = 0; i < 4; i++)
                            {
                                fBack[i] = 0;
                                userGuess[i] = 0;
                            }
                            PlaySongLose();
                            System.Threading.Thread.Sleep(1500);
                            GameOver();
                        }
                        for (int i = 0; i < 4; i++)
                        {
                            fBack[i] = 0;
                            userGuess[i] = 0;
                        }
                        idx = idx - 2;
                        selection = 1;
                        RanderPegSelection(selection, idx);
                    }
                }
                else if (key.KeyChar == 'n')
                {
                    //used for testing
                    RanderHiddienCode();
                }
            }
            while (1 != 2);
        }
Esempio n. 43
0
        // opens the connection to the OnyxII and returns true if succeeded
        public bool OpenConnection()
        {
            if (simulate) {
                if(demonstrate)
                {
                    readComThread = new System.Threading.Thread (StartGettingTheValuesOutOfSerialDataFormat8);
                    readComThread.Start();
                }
             				return true;
            }

            try
            {
                if (btComPort.IsOpen == true)
                {
                    Console.Write("The connection is already open!\n");
                    return false;
                }
                btComPort.BaudRate = boudRate;
                btComPort.PortName = portName;
                btComPort.Open();
                Console.Write("Port opened!\n");
                System.Threading.Thread.Sleep(500);
                readComThread = new System.Threading.Thread (StartGettingTheValuesOutOfSerialDataFormat8);
                readComThread.Start();
                Console.Write("Thread started!\n");
                return true;
            }

            catch (Exception ex)
            {
                Console.Write("Problem at opening the connection or starting the readComThread!\n", ex.Message);
                try
                {
                    readComThread.Abort();
                    Console.Write("Thread was Aborted!\n");
                }
                catch (Exception ex2)
                {
                }
                return false;
            }
        }
Esempio n. 44
0
        /// <summary>
        /// Helper function that invokes a thread and the GetRequestStream() or GetResponse() method
        /// </summary>
        /// <param name="req">The request to invoke the method on</param>
        /// <param name="getRequest">A value indicating if the invoked method should be GetRequestStream() or GetResponse()</param>
        /// <returns>Either a System.IO.Stream or a System.Net.WebResponse object</returns>
        private static object SafeGetRequestOrResponseStream(System.Net.WebRequest req, bool getRequest)
        {
            object[] args = new object[] { req, getRequest, null };
            System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(RunSafeGetRequest));
            try
            {
                //We use the timeout to determine how long we should wait
                int waitTime = req.Timeout == System.Threading.Timeout.Infinite ? DEFAULT_RESPONSE_TIMEOUT : req.Timeout;
                t.Start(args);
                if (t.Join(waitTime))
                {
                    if (args[2] == null)
                        throw new Exception(string.Format(Strings.Utility.UnexpectedRequestResultError, "null", ""));
                    else if (args[2] is Exception)
                        throw (Exception)args[2];

                    if (getRequest && args[2] is System.IO.Stream)
                        return (System.IO.Stream)args[2];
                    else if (!getRequest && args[2] is System.Net.WebResponse)
                        return (System.Net.WebResponse)args[2];

                    throw new Exception(string.Format(Strings.Utility.UnexpectedRequestResultError, args[2].GetType(), args[2].ToString()));
                }
                else
                {
                    t.Abort();
                    throw new System.Net.WebException(Strings.Utility.TimeoutException, null, System.Net.WebExceptionStatus.Timeout, null);
                }

            }
            catch
            {
                try { t.Abort(); }
                catch { }

                throw;
            }
        }
Esempio n. 45
0
        static void Main(string[] args)
        {
            Surrogate.LogonMachines();

#if DEBUG
            _jobdebug = System.IO.File.Exists("jobdebug.txt");
            if (_jobdebug)
            {
                _jobdebug_cmdline = Environment.CommandLine;
                _jobdebug_starttime = DateTime.Now;
                _jobdebug_output = new List<string>(1000);
            }
#endif

            int ex = 0;
            try
            {
                ProcessUser(args);
                Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);

                if (args.Length > 0
                     && args[0].StartsWith("-debug"))
                {
                    DebugSwitch = true;
                    DebugStepSwitch = ("-debug-step" == args[0]);
#if DEBUG
                    //Console.WriteLine("DEBUG:  DebugSwitch = true");
#endif
                    args = SubArray(args, 1);
                }

                int aIndex = 0;

                for (; aIndex < args.Length; aIndex++)
                {
                    string thisArg = args[aIndex];
                    if (thisArg.StartsWith("-"))
                    {
                        thisArg = thisArg.Substring(1);
                    }

                    if (thisArg.ToUpper() == "LOG")
                    {
                        if (aIndex == args.Length - 1)
                        {
                            Console.Error.WriteLine("Invalid arguments for log");
                        }
                        else
                        {
                            logToFile = true;
                            logFilePath = args[aIndex + 1].Replace("\"", "\\\"");
                        }
                        break;
                    }
                    if (0 == string.Compare(thisArg, "retrylogmd5",
                        StringComparison.OrdinalIgnoreCase))
                    {
                        if (aIndex == args.Length - 1)
                        {
                            Console.Error.WriteLine("Invalid arguments for retrylogmd5");
                        }
                        else
                        {
                            logToFile = true;
                            logFilePath = args[aIndex + 1].Replace("\"", "\\\"");
                            retrylogmd5 = true;
                            retrylogbuf = new StringBuilder(0x400 * 8);
                            retrylogthread = new System.Threading.Thread(
                                new System.Threading.ThreadStart(retrylogthreadproc));
                            retrylogthread.Name = "retrylogthread";
                            Log("\r\n[StartExec time=\"" + DateTime.Now + "\"]\r\n");
                            retrylogthread.Start();
                        }
                        break;
                    }
                }

                if (logToFile)
                {
                    string[] cleanedArgs = new string[args.Length - 2];

                    for (int i = 0; i < args.Length; i++)
                    {
                        if (i != aIndex && i != aIndex + 1)
                        {
                            int k = i > aIndex ? i - 2 : i;
                            cleanedArgs[k] = args[i];
                        }
                    }

                    args = cleanedArgs;
                }

                if (args.Length > 0 && args[0].StartsWith("@=", StringComparison.OrdinalIgnoreCase))
                {
                    string otherhost = args[0].Substring(2);
                    string othermaster = Surrogate.LocateMasterHost(Surrogate.NetworkPathForHost(otherhost));
                    Surrogate.SetNewMasterHost(othermaster);
                    args = SubArray(args, 1);
                }

                string act = "";
                if (args.Length > 0)
                {
                    act = args[0].ToLower();
                    if (act.StartsWith("-"))
                    {
                        act = act.Substring(1);
                    }
                }

#if DEBUG
                //System.Threading.Thread.Sleep(8000);
#endif
                switch (act)
                {
                    case "rget":
                        {
                            if (args.Length > 2 && args[2].StartsWith(@"\\"))
                            {
                                string driverdir = Surrogate.NetworkPathForHost(Surrogate.MasterHost);
                                string rdir = driverdir + @"\rget";
                                try
                                {
                                    System.IO.Directory.CreateDirectory(rdir);
                                }
                                catch
                                {
                                }
                                string getname = args[1]; // Name only! not path.
                                string tempfilepath = rdir + @"\rget_" + Guid.NewGuid().ToString() + "_" + getname + ".rget";
                                Exec.Shell("DSpace get \"" + getname + "\" \"" + tempfilepath + "\"");
                                System.IO.File.Copy(tempfilepath, args[2]);
                                System.IO.File.Delete(tempfilepath);
                                Console.WriteLine("Done");
                            }
                            else
                            {
                                Console.Error.WriteLine("Error: DFS file and network path expected");
                            }
                        }
                        return;

                    case "rput":
                        {
                            if (args.Length > 1 && args[1].StartsWith(@"\\"))
                            {
                                System.IO.FileInfo fi = new System.IO.FileInfo(args[1]);
                                string driverdir = Surrogate.NetworkPathForHost(Surrogate.MasterHost);
                                string rdir = driverdir + @"\rput";
                                try
                                {
                                    System.IO.Directory.CreateDirectory(rdir);
                                }
                                catch
                                {
                                }
                                string putname = fi.Name; // Name only! not path.
                                if (args.Length > 2)
                                {
                                    putname = args[2];
                                }
                                string tempfilepath = rdir + @"\rput_" + Guid.NewGuid().ToString() + "_" + putname;

                                System.IO.File.Copy(args[1], tempfilepath);
                                Console.WriteLine(Exec.Shell("DSpace put \"" + tempfilepath + "\" \"" + putname + "\""));
                                System.IO.File.Delete(tempfilepath);
                            }
                            else
                            {
                                Console.Error.WriteLine("Error: network path expected");
                            }
                        }
                        return;
                }

                Additional();

                string sargs = "";
                {
                    StringBuilder sb = new StringBuilder(1000);
                    for (int i = 0; i < args.Length; i++)
                    {
                        if (0 != sb.Length)
                        {
                            sb.Append(' ');
                        }
                        if (-1 != args[i].IndexOf(' '))
                        {
                            sb.Append('"');
                            sb.Append(args[i].Replace("\"", "\\\""));
                            sb.Append('"');
                        }
                        else
                        {
                            sb.Append(args[i].Replace("\"", "\\\""));
                        }
                    }
                    sargs = sb.ToString();
                }

                if (sargs.Length > 0 && logToFile)
                {
                    Log(sargs + "\r\n\r\n");
                }

                {
                    //if (args.Length >= 1)
                    {
                        switch (act)
                        {
                            case "exec":
                                if (DebugSwitch)
                                {
                                    goto case "edit";
                                }
                                break; // Normal handling.

                            case "configedit":
                            case "editconfig":
                            case "configeditor":
                                {
                                    Environment.CurrentDirectory = AELight_Dir;
                                    _FixSciLexDLL();
                                    int iarg = 1;
                                    if (args.Length <= iarg)
                                    {
                                        Console.Error.WriteLine("Invalid arguments for " + args[0]);
                                        return;
                                    }

                                    string PrettyFile = args[iarg];

                                    {
                                        dfs dc = Surrogate.ReadMasterDfsConfig();

                                        dfs.DfsFile dfcf = dc.Find(PrettyFile, DfsFileTypes.NORMAL);
                                        if (null == dfcf)
                                        {
                                            if (PrettyFile.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase))
                                            {
                                                PrettyFile = PrettyFile.Substring(6);
                                            }

                                            string reason = "";
                                            if (dfs.IsBadFilename(PrettyFile, out reason))
                                            {
                                                Console.Error.WriteLine("Invalid config file name: " + reason);
                                                return;
                                            }

                                            //ActualFile = null;
                                            PrettyFile = "dfs://" + PrettyFile;
                                        }
                                        else
                                        {

                                            //ActualFile = Surrogate.NetworkPathForHost(dfcf.Nodes[0].Host.Split(';')[0]) + @"\" + dfcf.Nodes[0].Name;
                                            PrettyFile = "dfs://" + dfcf.Name;

                                            if (!ConfigEditor.ConfigEdit.CheckConfigFileSize(PrettyFile, dfcf.Size))
                                            {
                                                return;
                                            }

                                        }
                                    }

                                    {
                                        System.Threading.Thread editthread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(editthreadproc));
                                        editthread.IsBackground = true;
                                        editthread.Start(sargs);
                                    }

                                    {
                                        string realuser = mdousername();
                                        int ix = realuser.IndexOfAny(new char[] { '@', '(' });
                                        if (-1 != ix)
                                        {
                                            realuser = realuser.Substring(0, ix);
                                        }
                                        ConfigEditor.ConfigEdit.RealUserName = realuser;
                                    }

                                    ConfigEditor.ConfigEdit.RunConfigEditor(PrettyFile);
                                }
                                return;

                            case "edit":
                            case "editor":
                                {
                                    Environment.CurrentDirectory = AELight_Dir;

                                    int iarg = 1;
                                    string ExecOpts = "";
                                    List<string> xpaths = null;
                                    {
                                        while (iarg < args.Length)
                                        {
                                            switch (args[iarg][0])
                                            {
                                                case '-':
                                                    ExecOpts += " " + args[iarg].Substring(1);
                                                    iarg++; // Important.
                                                    continue;

                                                case '/':
                                                    if (null == xpaths)
                                                    {
                                                        xpaths = new List<string>();
                                                    }
                                                    xpaths.Add(args[iarg]);
                                                    iarg++; // Important.
                                                    continue;
                                            }
                                            break;
                                        }
                                    }

                                    _FixSciLexDLL();
                                    if (args.Length <= iarg)
                                    {
                                        Console.Error.WriteLine("Invalid arguments for " + args[0]);
                                        return;
                                    }
                                    else if (0 == string.Compare("*errors*", args[iarg]) || 0 == string.Compare("*error*", args[iarg]))
                                    {
                                        if (DebugSwitch)
                                        {
                                            Console.Error.WriteLine("Cannot debug {0}", args[iarg]);
                                            return;
                                        }
                                        string errorscsfp = Surrogate.NetworkPathForHost(Surrogate.MasterHost) + @"\error.cs";
                                        if (System.IO.File.Exists(errorscsfp))
                                        {
                                            JobsEdit.RunJobsEditor(errorscsfp, "C# Errors", true);
                                        }
                                        else
                                        {
                                            Console.Error.WriteLine("No C# errors found");
                                        }
                                    }
                                    else
                                    {
                                        string ActualFile, PrettyFile;

                                        {
                                            dfs dc = Surrogate.ReadMasterDfsConfig();

#if DEBUG
                                            //System.Threading.Thread.Sleep(1000 * 8);
#endif

                                            if (null != dc.DefaultDebugType)
                                            {
                                                hashadd["DefaultDebugType"] = dc.DefaultDebugType;
                                            }

                                            try
                                            {
                                                string backupdir = dc.GetMetaBackupLocation();
                                                if (!string.IsNullOrEmpty(backupdir))
                                                {
                                                    hashadd.Add("backupdir", backupdir);
                                                }
                                            }
                                            catch (Exception eb)
                                            {
                                                LogOutputToFile(eb.ToString());
                                                Console.Error.WriteLine(eb.Message);
                                            }

                                            dfs.DfsFile dfjob = dc.Find(args[iarg], DfsFileTypes.JOB);
                                            if (null == dfjob)
                                            {
                                                /*if (!QuietMode)
                                                {
                                                    Console.WriteLine("New jobs file");
                                                }*/
                                                string fn = args[iarg];

                                                if (fn.StartsWith("dfs://", StringComparison.OrdinalIgnoreCase))
                                                {
                                                    fn = fn.Substring(6);
                                                }

                                                string reason = "";
                                                if (dfs.IsBadFilename(fn, out reason))
                                                {
                                                    Console.Error.WriteLine("Invalid job file name: " + reason);
                                                    return;
                                                }

                                                ActualFile = null; // !
                                                PrettyFile = "dfs://" + fn;
                                            }
                                            else
                                            {
                                                if (dfjob.Nodes.Count < 1)
                                                {
                                                    throw new Exception("Error: -exec jobs file not in correct jobs DFS format");
                                                }
                                                ActualFile = Surrogate.NetworkPathForHost(dfjob.Nodes[0].Host.Split(';')[0]) + @"\" + dfjob.Nodes[0].Name;
                                                PrettyFile = "dfs://" + dfjob.Name;
                                            }
                                        }

                                        {
                                            System.Threading.Thread editthread = new System.Threading.Thread(new System.Threading.ParameterizedThreadStart(editthreadproc));
                                            editthread.IsBackground = true;
                                            editthread.Start(sargs);
                                        }

                                        {
                                            string realuser = mdousername();
                                            int ix = realuser.IndexOfAny(new char[] { '@', '(' });
                                            if (-1 != ix)
                                            {
                                                realuser = realuser.Substring(0, ix);
                                            }
                                            JobsEdit.RealUserName = realuser;
                                        }

                                        if (DebugSwitch)
                                        {
                                            if (string.IsNullOrEmpty(ActualFile))
                                            {
                                                Console.Error.WriteLine("Cannot debug, jobs file does not exist: {0}", PrettyFile);
                                                return;
                                            }
                                            hashadd["DebugSwitch"] = "y";
                                            if (DebugStepSwitch)
                                            {
                                                hashadd["DebugStepSwitch"] = "y";
                                            }
                                        }

                                        hashadd["ExecArgs"] = SubArray(args, iarg + 1);

                                        if (null != xpaths)
                                        {
                                            hashadd["SourceCodeXPathSets"] = xpaths;
                                        }

                                        JobsEdit.RunJobsEditor(ActualFile, PrettyFile, hashadd);
                                    }
                                    return;
                                }

                            case "execview":
                                if (args.Length < 2)
                                {
                                    Console.Error.WriteLine("Invalid arguments for " + args[0]);
                                    return;
                                }
                                else
                                {
                                    string guid = args[1];
                                    string hostNetpath = Surrogate.NetworkPathForHost(Surrogate.MasterHost);
                                    string src = hostNetpath + @"\history." + guid + ".txt";
                                    string log = hostNetpath + @"\exechistorylog.txt";

                                    if (System.IO.File.Exists(log))
                                    {
                                        string logs = System.IO.File.ReadAllText(log);
                                        int gi = logs.IndexOf(guid);

                                        if (gi > -1)
                                        {
                                            int d1 = logs.IndexOf('*', gi);
                                            int d2 = logs.IndexOf(Environment.NewLine, d1 + 1);
                                            string command = logs.Substring(d1 + 1, d2 - d1 - 1);

                                            if (System.IO.File.Exists(src))
                                            {
                                                Environment.CurrentDirectory = AELight_Dir;
                                                _FixSciLexDLL();
                                                JobsEdit.RunJobsEditor(src, command, true);
                                            }
                                            else
                                            {
                                                Console.Error.WriteLine("No source code is found.");
                                            }
                                        }
                                        else
                                        {
                                            Console.Error.WriteLine("GUID is not found in the log file.");
                                        }
                                    }
                                    else
                                    {
                                        Console.Error.WriteLine("Log file is not found.");
                                    }
                                }
                                return;

                            case "importdir":
                            case "importdirst":
                                {
                                    if (args.Length <= 1)
                                    {
                                        Console.Error.WriteLine("Error: directory name expected");
                                        return;
                                    }
                                    else
                                    {
                                        importdir_recursive(args[1]);
                                    }
                                }
                                return;

                            case "importdirmt":
                                {
                                    if (args.Length <= 1)
                                    {
                                        Console.Error.WriteLine("Error: directory name expected");
                                        return;
                                    }
                                    else
                                    {
                                        importdir_recursive_mt(args[1]);
                                    }
                                }
                                return;

                            case "dfs":
                                if (args.Length > 1 && args[1].IndexOf("format", StringComparison.OrdinalIgnoreCase) != -1)
                                {
                                    goto format_cmd;
                                }
                                break;

                            case "clustercheck":
                                Admin.CheckClusters(SubArray(args, 1));
                                return;

                            case "recoverdfsxml":
                                Admin.Recovery.RecoverDfsXml(SubArray(args, 1));
                                return;

                            case "compspeed":
                                Admin.CompareSpeed(SubArray(args, 1));
                                return;

                            case "kick":
                                {
                                    if (args.Length < 2)
                                    {
                                        Console.Error.WriteLine("kick error: kick <username> expected.");
                                        return;
                                    }
                                    dfs dc = Surrogate.ReadMasterDfsConfig();
                                    Admin.KickUser(args[0], args[1], dc.Slaves.SlaveList);
                                    return;
                                }

                            case "kickall":
                                {
                                    if (args.Length < 3)
                                    {
                                        Console.Error.WriteLine("kickall error: kickall <username> <hosts> expected.");
                                        return;
                                    }
                                    Admin.KickUser(args[0], args[1], args[2]);
                                    return;
                                }

                            case "kickallusers":
                                {
                                    if (args.Length < 2)
                                    {
                                        Console.Error.WriteLine("kickallusers error: kickallusers <hosts> expected.");
                                        return;
                                    }
                                    string thisuser = _mdousername.Split('@')[0];
                                    Admin.KickAllUsers(args[0], new string[] { thisuser, "dataminingdspace" }, args[1]);
                                    return;
                                }

                            case "ps":
                                // Only handling ps here if -d is used, otherwise it's a normal command.
                                if (args.Length > 1 && "-d" == args[1])
                                {
                                    string driverdir = Surrogate.NetworkPathForHost(Surrogate.MasterHost);
                                    string execqfn = driverdir + @"\execq.dat";
                                    for (int rotor = 0; ; rotor++)
                                    {
                                        try
                                        {
                                            string[] qlines = System.IO.File.ReadAllLines(execqfn);
                                            for (int iq = 0; iq < qlines.Length; iq++)
                                            {
                                                string ln = qlines[iq];
                                                int ippp = ln.IndexOf("+++");
                                                if (-1 != ippp)
                                                {
                                                    string[] settings = ln.Substring(0, ippp).Split(' ');
                                                    string psspid = "0";
                                                    if (settings.Length > 1)
                                                    {
                                                        psspid = settings[1];
                                                    }
                                                    ln = ln.Substring(ippp + 4);
                                                    Console.WriteLine("  {0} {1}", psspid, ln.Replace("drule", "SYSTEM"));
                                                }
                                            }
                                            break;
                                        }
                                        catch (System.IO.IOException ioe)
                                        {
                                            if (rotor > 10)
                                            {
                                                Console.Error.WriteLine(ioe.Message);
                                                break;
                                            }
                                            System.Threading.Thread.Sleep(200);
                                            continue;
                                        }
                                    }
                                    return; // Handled!
                                }
                                break; // Not handled, normal command.

                            case "killallst":
                            case "killall":
                            case "killallmt":
#if DEBUG
                                Console.WriteLine(@"User=\\" + System.Environment.UserDomainName + @"\" + System.Environment.UserName);
#endif
                                bool isForce = false;
                                bool isMemCacheRelease = false;
                                string subact = "";
                                for (int ai = 1; ai < args.Length; ai++)
                                {
                                    if (args[ai].ToLower() == "-f")
                                    {
                                        isForce = true;
                                    }
                                    else if (0 == string.Compare(args[ai], "MemCacheRollback", true)
                                        || 0 == string.Compare(args[ai], "MemCacheRelease", true)
                                        )
                                    {
                                        isMemCacheRelease = true;
                                    }
                                    else
                                    {
                                        subact = args[ai];
                                    }
                                }

                                if (!isForce)
                                {
                                    Console.Error.WriteLine("WARNING: about to terminate all jobs on cluster.");
                                    Console.Error.WriteLine("To continue, use:  {0} {1} -f", "Qizmt", sargs);
                                    return;
                                }
                                else
                                {
                                    MakeInvincible();
                                    if (subact == "")
                                    {
                                        subact = "-f";
                                    }
                                    switch (subact)
                                    {
                                        case "xproxy":
                                            {
                                                string pact = act;
                                                if (isMemCacheRelease)
                                                {
                                                    pact = pact + " MemCacheRelease";
                                                }
                                                RunProxy("DSpace.exe " + pact + " -f");
                                            }
                                            return;

                                        case "proxy":
                                            {
                                                string pact = act;
                                                if (isMemCacheRelease)
                                                {
                                                    pact = pact + " MemCacheRelease";
                                                }
                                                RunStreamStdIO("localhost", "DSpace.exe " + pact + " -f", true);
                                            }
                                            return;

                                        case "logon2":
                                        case "logon3":
                                        case "logon4":
                                        case "logon5":
                                        case "logon6":
                                        case "logon7":
                                        case "logon8":
                                        case "logon9":
                                            break; // Keep going...

                                        case "-f":
                                            break;

                                        case "MemCacheRollback":
                                        case "MemCacheRelease":
                                            break;

                                        default:
                                            Console.Error.WriteLine("Unknown killall arguments");
                                            return;
                                    }

                                    {
                                        bool gotmaster = false;
                                        System.Threading.Thread masterthread = new System.Threading.Thread(
                                            new System.Threading.ThreadStart(delegate()
                                            {
                                                try
                                                {
                                                    // Connect to surrogate (and why not cache path).
                                                    Surrogate.NetworkPathForHost(Surrogate.MasterHost);
                                                    gotmaster = true;
                                                }
                                                catch
                                                {
                                                }
                                            }));
                                        masterthread.IsBackground = true;
                                        masterthread.Start();
                                        if (!masterthread.Join(1000 * 4) || !gotmaster) // At most, wait this long.
                                        {
                                            try
                                            {
                                                masterthread.Abort();
                                            }
                                            catch
                                            {
                                            }
                                            Console.Write('.');
                                            Exec.Shell(@"sc \\" + Surrogate.MasterHost + " stop DistributedObjects", true);
                                            System.Threading.Thread.Sleep(1000 * 10);
                                            Console.Write('.');
                                            Exec.Shell(@"sc \\" + Surrogate.MasterHost + " start DistributedObjects");
                                            System.Threading.Thread.Sleep(1000 * 10);
                                            Console.WriteLine('.');
                                        }
                                    }

                                    bool singlethreaded = act == "killallst";

                                    dfs dc;
                                    try
                                    {
                                        dc = dfs.ReadDfsConfig_unlocked(Surrogate.NetworkPathForHost(Surrogate.MasterHost) + @"\" + dfs.DFSXMLNAME);
                                    }
                                    catch (Exception e)
                                    {
                                        LogOutputToFile("killallmt accessing surrogate: " + e.ToString());
                                        Console.Error.WriteLine("Ensure the Windows services are running; {0}", e.Message);
                                        return;
                                    }

                                    List<string> hosts = new List<string>();
                                    hosts.AddRange(dc.Slaves.SlaveList.Split(';'));
                                    {
                                        // Ensure the master is at the beginning and shuts down first! (easier than admin-cmd-lock)
                                        string xmaster = IPAddressUtil.GetNameNoCache(Surrogate.MasterHost);
                                        for (int hi = 0; hi < hosts.Count; hi++)
                                        {
                                            if (0 == string.Compare(xmaster, IPAddressUtil.GetNameNoCache(hosts[hi]), StringComparison.OrdinalIgnoreCase))
                                            {
                                                hosts.RemoveAt(hi);
                                                break; // !
                                            }
                                        }
                                        hosts.Insert(0, Surrogate.MasterHost);
                                    }

                                    int threadcount = singlethreaded ? 1 : hosts.Count;
                                    if (threadcount > 15)
                                    {
                                        threadcount = 15;
                                    }

                                    //Console.WriteLine();
                                    Console.WriteLine("Stopping services");

                                    int nkilled = 0;
                                    //for (int hi = 0; hi < hosts.Count; hi++)
                                    MySpace.DataMining.Threading.ThreadTools<string>.Parallel(
                                        new Action<string>(delegate(string host)
                                        {
                                            //string host = hosts[hi];

                                            string netpath = null;
                                            try
                                            {
                                                netpath = Surrogate.NetworkPathForHost(host);

                                                {
                                                    string driverdir = Surrogate.NetworkPathForHost(Surrogate.MasterHost);
                                                    {
                                                        string dir = driverdir + @"\rget";
                                                        if (System.IO.Directory.Exists(dir))
                                                        {
                                                            foreach (string fn in System.IO.Directory.GetFiles(dir))
                                                            {
                                                                System.IO.File.Delete(fn);
                                                            }
                                                            System.IO.Directory.Delete(dir);
                                                        }
                                                    }
                                                    {
                                                        string dir = driverdir + @"\rput";
                                                        if (System.IO.Directory.Exists(dir))
                                                        {
                                                            foreach (string fn in System.IO.Directory.GetFiles(dir))
                                                            {
                                                                System.IO.File.Delete(fn);
                                                            }
                                                            System.IO.Directory.Delete(dir);
                                                        }
                                                    }
                                                }
                                            }
                                            catch (Exception e)
                                            {
#if CLIENT_LOG_ALL
                                    LogOutputToFile("CLIENT_LOG_ALL: NetworkPathForHost failed for " + host + ": " + e.ToString());
#endif
                                            }

                                            //Console.WriteLine("{0}: stopping service", host);
                                            string scresult = Exec.Shell(@"sc \\" + host + " stop DistributedObjects", true); // Suppress error.
                                            lock (hosts)
                                            {
                                                Console.Write("{0}: ", host);
                                                Console.WriteLine(scresult);
                                            }
                                            System.Threading.Thread.Sleep(1000 * 2);
                                            if (null == netpath)
                                            {
                                                for (int somewait = 0; ; somewait++)
                                                {
                                                    if (somewait >= 3)
                                                    {
                                                        lock (hosts)
                                                        {
                                                            Console.Write("Network path of host {0} is null", host);
                                                        }
                                                        break;
                                                    }
                                                    System.Threading.Thread.Sleep(1000 * 4);
                                                    lock (hosts)
                                                    {
                                                        Console.Write("Network path of host {0} is null", host);
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                for (int somewait = 0; 0 != System.IO.Directory.GetFiles(netpath, "*.pid").Length; somewait++)
                                                {
                                                    if (somewait >= 10)
                                                    {
                                                        lock (hosts)
                                                        {
                                                            Console.Write('?');
                                                        }
                                                        break;
                                                    }
                                                    System.Threading.Thread.Sleep(1000 * 4);
                                                    lock (hosts)
                                                    {
                                                        Console.Write('.');
                                                    }
                                                }
                                            }

                                            if (isMemCacheRelease)
                                            {
                                                System.Threading.Thread.Sleep(250);
                                                Exec.Shell(@"sc \\" + host + " stop MemCachePin", true); // Suppress error.
                                            }
                                        }
                                    ), hosts, threadcount);

                                    //System.Threading.Thread.Sleep(1000 * 2);
                                    Console.WriteLine();
                                    Console.WriteLine("Cleaning intermediate data");

                                    string backupdir = dc.GetMetaBackupLocation();

                                    Dictionary<string, bool> jobnames = null;
                                    if (null != backupdir)
                                    {
                                        jobnames = new Dictionary<string, bool>(100, StringComparer.OrdinalIgnoreCase); // host\jobfilenodename keys.
                                    }
                                    Dictionary<string, bool> goodfiles = new Dictionary<string, bool>(300, StringComparer.OrdinalIgnoreCase); // host\filenodename keys.
                                    List<System.Text.RegularExpressions.Regex> snowballregexes = new List<System.Text.RegularExpressions.Regex>();
                                    List<System.Text.RegularExpressions.Regex> snowballzfoilcacheregexes = new List<System.Text.RegularExpressions.Regex>();
                                    List<string> mappedsamplenames = new List<string>();
                                    foreach (dfs.DfsFile df in dc.Files)
                                    {
                                        if (0 == string.Compare(df.Type, DfsFileTypes.DELTA, StringComparison.OrdinalIgnoreCase))
                                        {
                                            string snowballname = df.Name;
                                            {
                                                string srex = Surrogate.WildcardRegexString(GetSnowballFilesWildcard(snowballname));
                                                System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(srex, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                                                snowballregexes.Add(rex);
                                            }
                                            {
                                                string srex = Surrogate.WildcardRegexString(GetSnowballFoilSampleFilesWildcard(snowballname));
                                                System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(srex, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                                                snowballzfoilcacheregexes.Add(rex);
                                            }
                                            string fnms = "zsballsample_" + snowballname + ".zsb";
                                            mappedsamplenames.Add(fnms);
                                        }
                                        else
                                        {
                                            if (null != backupdir)
                                            {
                                                if (0 == string.Compare(DfsFileTypes.JOB, df.Type, StringComparison.OrdinalIgnoreCase))
                                                {
                                                    foreach (dfs.DfsFile.FileNode fn in df.Nodes)
                                                    {
                                                        jobnames[fn.Name] = true;
                                                    }
                                                }
                                            }
                                            foreach (dfs.DfsFile.FileNode fn in df.Nodes)
                                            {
                                                foreach (string fnhost in fn.Host.Split(';'))
                                                {
                                                    goodfiles[IPAddressUtil.GetName(fnhost) + @"\" + fn.Name] = true;
                                                }
                                            }
                                        }
                                    }

                                    // Get leaked metabackups:
                                    {
                                        if (null != backupdir)
                                        {
                                            //foreach (System.IO.FileInfo fi in (new System.IO.DirectoryInfo(backupdir)).GetFiles("zd.*-????-????-????-*.zd"))
                                            MySpace.DataMining.Threading.ThreadTools<System.IO.FileInfo>.Parallel(
                                                new Action<System.IO.FileInfo>(
                                                delegate(System.IO.FileInfo fi)
                                                {
                                                    try
                                                    {
                                                        if (!jobnames.ContainsKey(fi.Name))
                                                        {
                                                            fi.Delete();
                                                            lock (hosts)
                                                            {
                                                                Console.Write('.'); // ?
                                                            }
                                                        }
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        LogOutputToFile("killall 'delete leaked metabackup zd file' exception: " + e.ToString());
                                                    }
                                                }), (new System.IO.DirectoryInfo(backupdir)).GetFiles("zd.*-????-????-????-*.zd"), threadcount);
                                        }
                                    }

#if DEBUG
                                    //System.Threading.Thread.Sleep(1000 * 8);
                                    int ixjxj = 33 + 33;
#endif

                                    MySpace.DataMining.Threading.ThreadTools<string>.Parallel(
                                        new Action<string>(delegate(string host)
                                        //for (int hi = 0; hi < hosts.Count; hi++)
                                        {

                                            //string host = hosts[hi];
                                            string netpath = null;

                                            try
                                            {
                                                netpath = Surrogate.NetworkPathForHost(host);
                                            }
                                            catch (Exception e)
                                            {
#if CLIENT_LOG_ALL
                                    LogOutputToFile("CLIENT_LOG_ALL: NetworkPathForHost failed for " + host + ": " + e.ToString());
#endif
                                                lock (hosts)
                                                {
                                                    Console.WriteLine("Skipping host, killall may have been aboarted early last run.");
                                                }
                                            }

                                            if (netpath != null)
                                            {
                                                //Console.WriteLine("{0}: cleaning intermediate data", host);
#if CLIENT_LOG_ALL
                                    Console.WriteLine("    CLIENT_LOG_ALL: cleaning leaked zd files...");
                                    int nlzdf = 0;
#endif
                                                foreach (System.IO.FileInfo fi in (new System.IO.DirectoryInfo(netpath)).GetFiles("zd.*-????-????-????-*.zd"))
                                                {
                                                    try
                                                    {
                                                        if (!goodfiles.ContainsKey(IPAddressUtil.GetName(host) + @"\" + fi.Name))
                                                        {
                                                            fi.Delete();
                                                            lock (hosts)
                                                            {
                                                                Console.Write('.'); // ?
                                                            }
                                                        }
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        LogOutputToFile("killall 'delete leaked zd file' exception: " + e.ToString());
                                                    }
                                                }
                                                foreach (System.IO.FileInfo fi in (new System.IO.DirectoryInfo(netpath)).GetFiles("zd.*-????-????-????-*.zd.zsa"))
                                                {
                                                    try
                                                    {
                                                        if (!goodfiles.ContainsKey(IPAddressUtil.GetName(host) + @"\" + fi.Name.Substring(0, fi.Name.Length - 4)))
                                                        {
                                                            fi.Delete();
                                                            lock (hosts)
                                                            {
                                                                Console.Write('.'); // ?
                                                            }
                                                        }
                                                    }
                                                    catch (Exception e)
                                                    {
                                                        LogOutputToFile("killall 'delete leaked zsa file' exception: " + e.ToString());
                                                    }
                                                }
#if CLIENT_LOG_ALL
                                    Console.WriteLine("    CLIENT_LOG_ALL: cleaned " + nlzdf.ToString() + " zd files");
#endif
                                                {
                                                    // Clean leaked snowballs...
                                                    {
                                                        int snowballregexesCount = snowballregexes.Count;
                                                        foreach (System.IO.FileInfo fi in (new System.IO.DirectoryInfo(netpath)).GetFiles("zsball_*.zsb"))
                                                        {
                                                            bool goodsnowball = false;
                                                            for (int i = 0; i < snowballregexesCount; i++)
                                                            {
                                                                if (snowballregexes[i].IsMatch(fi.Name))
                                                                {
                                                                    goodsnowball = true;
                                                                    break;
                                                                }
                                                            }
                                                            if (!goodsnowball)
                                                            {
                                                                try
                                                                {
                                                                    fi.Delete();
                                                                    Console.Write('.'); // ?
                                                                }
                                                                catch (Exception e)
                                                                {
                                                                    LogOutputToFile("killall 'delete leaked deltaCache file' exception: " + e.ToString());
                                                                    Console.Error.WriteLine("Warning: unable to delete leaked file '{0}'; cache file may be corrupt: {1}", fi.Name, e.Message);
                                                                }
                                                            }
                                                        }
                                                        int mappedsamplenamesCount = mappedsamplenames.Count;
                                                        foreach (System.IO.FileInfo fi in (new System.IO.DirectoryInfo(netpath)).GetFiles("zsballsample_*.zsb"))
                                                        {
                                                            bool goodmappedsamples = false;
                                                            for (int i = 0; i < mappedsamplenamesCount; i++)
                                                            {
                                                                if (0 == string.Compare(mappedsamplenames[i], fi.Name))
                                                                {
                                                                    goodmappedsamples = true;
                                                                    break;
                                                                }
                                                            }
                                                            if (!goodmappedsamples)
                                                            {
                                                                try
                                                                {
                                                                    fi.Delete();
                                                                    Console.Write('.'); // ?
                                                                }
                                                                catch (Exception e)
                                                                {
                                                                    LogOutputToFile("killall 'delete leaked deltaCache file' exception: " + e.ToString());
                                                                    Console.Error.WriteLine("Warning: unable to delete leaked file '{0}'; cache file may be corrupt: {1}", fi.Name, e.Message);
                                                                }
                                                            }
                                                        }
                                                    }
                                                    {
                                                        // zfoil cache!
                                                        int snowballzfoilcacheregexesCount = snowballzfoilcacheregexes.Count;
                                                        foreach (System.IO.FileInfo fi in (new System.IO.DirectoryInfo(netpath)).GetFiles("zfoil_*.zf"))
                                                        {
                                                            bool goodsnowball = false;
                                                            for (int i = 0; i < snowballzfoilcacheregexesCount; i++)
                                                            {
                                                                if (snowballzfoilcacheregexes[i].IsMatch(fi.Name))
                                                                {
                                                                    goodsnowball = true;
                                                                    break;
                                                                }
                                                            }
                                                            if (!goodsnowball)
                                                            {
                                                                try
                                                                {
                                                                    fi.Delete();
                                                                    Console.Write('.'); // ?
                                                                }
                                                                catch (Exception e)
                                                                {
                                                                    LogOutputToFile("killall 'delete leaked deltaCache file' exception: " + e.ToString());
                                                                    Console.Error.WriteLine("Warning: unable to delete leaked file '{0}'; cache file may be corrupt: {1}", fi.Name, e.Message);
                                                                }
                                                            }
                                                        }
                                                    }

                                                }
                                                {
#if DEBUG
                                                    //System.Threading.Thread.Sleep(1000 * 8);
#endif
                                                    DeleteAllMatchingFiles(netpath, "ylib_*_*.*", true); // ylib_*.ylib and ylib_*.pdb
                                                    //DeleteAllMatchingFiles(netpath, "*.xlib", true);
                                                    DeleteOldMatchingFiles(new TimeSpan(10 /* days */ , 0, 0),
                                                        netpath, "*.xlib", true);
                                                    DeleteAllMatchingFiles(netpath, "*.zb", true);
                                                    DeleteAllMatchingFiles(netpath, "zmap_*.zm", true);
                                                    DeleteAllMatchingFiles(netpath, "temp_*-????-????-????-*.pdb", true);
                                                    DeleteAllMatchingFiles(netpath, "temp_*-????-????-????-*.dll", true);
                                                    //DeleteAllMatchingFiles(netpath, "zfoil_*.zf", true); // NO! now part of snowball cleanup
                                                    DeleteAllMatchingFiles(netpath, "dbg_*~*_????????-????-????-????-????????????.*", true);
                                                    DeleteOldMatchingFiles(new TimeSpan(10 /* days */ , 0, 0),
                                                        netpath, "*_????????-????-????-????-????????????*_log.txt", true);
                                                    try
                                                    {
                                                        // Clean ALL of temp dir!
                                                        DeleteAllMatchingFiles(netpath + @"\temp", "*", true);
                                                    }
                                                    catch
                                                    {
                                                    }
                                                    DeleteAllMatchingFiles(netpath, "slaveconfig.j*.xml");
                                                    DeleteOldMatchingFiles(new TimeSpan(10 /* days */ , 0, 0),
                                                        netpath, "stdout.jid*.jso", true);
                                                }
                                                //Console.WriteLine();
                                            }
                                        }
                                    ), hosts, threadcount);

                                    try
                                    {
                                        foreach (string jidfn in System.IO.Directory.GetFiles(
                                            Surrogate.NetworkPathForHost(Surrogate.MasterHost),
                                            "*.jid"))
                                        {
                                            try
                                            {
                                                System.IO.File.Delete(jidfn);
                                            }
                                            catch
                                            {
                                            }
                                        }
                                    }
                                    catch
                                    {
                                    }

                                    Console.WriteLine();
                                    Console.WriteLine();
                                    Console.WriteLine("Starting services");

                                    MySpace.DataMining.Threading.ThreadTools<string>.Parallel(
                                        new Action<string>(delegate(string host)
                                        //for (int hi = 0; hi < hosts.Count; hi++)
                                        {
                                            //string host = hosts[hi];
                                            //string netpath = NetworkPathForHost(host);
                                            //Console.WriteLine("{0}: starting service", host);
                                            string scresult = Exec.Shell(@"sc \\" + host + " start DistributedObjects", false); // Throws on error.
                                            lock (hosts)
                                            {
                                                Console.Write("{0}: ", host);
                                                ConsoleColor oldc = Console.ForegroundColor;
                                                if (-1 == scresult.IndexOf("STATE") || -1 == scresult.IndexOf("START"))
                                                {
                                                    Console.ForegroundColor = ConsoleColor.Red;
                                                }
                                                Console.WriteLine(scresult);
                                                Console.ForegroundColor = oldc;
                                            }

                                            if (isMemCacheRelease)
                                            {
                                                System.Threading.Thread.Sleep(250);
                                                Exec.Shell(@"sc \\" + host + " start MemCachePin", true); // Suppress error.
                                            }

                                            //Console.WriteLine("{0}: done", host);

                                            //Console.WriteLine("--------");
                                            //System.Threading.Thread.Sleep(1000); // Sleep a sec, give the user a chance to see it.

                                            nkilled++;
                                        }
                                    ), hosts, threadcount);

                                    try
                                    {
                                        System.IO.File.Delete(Surrogate.NetworkPathForHost(Surrogate.MasterHost) + @"\execq.dat"); // Clear jobs list, since I killed them anyway!
                                    }
                                    catch
                                    {
                                    }

                                    Console.WriteLine("Final cleanup");
                                    {
                                        try
                                        {
                                            MasterRunStreamStdIO("-@log " + sargs);
                                        }
                                        catch
                                        {
                                        }

                                        /*try
                                        {
                                            Console.WriteLine(Exec.Shell("DSpace scrapeemptynames"));
                                        }
                                        catch
                                        {
                                        }*/

                                        try
                                        {
                                            if (singlethreaded)
                                            {
                                                Exec.Shell("dspace delst *.$*.$*");
                                            }
                                            else
                                            {
                                                Exec.Shell("dspace delmt *.$*.$*");
                                            }
                                        }
                                        catch
                                        {
                                        }

                                        try
                                        {
                                            if (singlethreaded)
                                            {
                                                Exec.Shell("dspace delst *" + dfs.TEMP_FILE_MARKER + "*");
                                            }
                                            else
                                            {
                                                Exec.Shell("dspace delmt *" + dfs.TEMP_FILE_MARKER + "*");
                                            }
                                        }
                                        catch
                                        {
                                        }
                                    }

                                    Console.WriteLine("Done; killed and restarted {0} nodes", nkilled);
                                }
                                return;

                            case "metapath":
                                Console.WriteLine(Surrogate.NetworkPathForHost(Surrogate.MasterHost) + @"\" + dfs.DFSXMLNAME);
                                return;

                            case "metahost":
                                Console.WriteLine(Surrogate.MasterHost);
                                return;

#if DEBUG
                            case "#d":
                                Console.WriteLine(Exec.Shell("sc stop DistributedObjects"));
                                Console.WriteLine(Exec.Shell("sc stop MemCachePin"));
                                return;

                            case "#u":
                                Console.WriteLine(Exec.Shell("sc start DistributedObjects"));
                                Console.WriteLine(Exec.Shell("sc start MemCachePin"));
                                return;

                            case "#install":
                                {
                                    string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                                    Console.WriteLine(Exec.Shell("installutil \"" + dir + "\\MySpace.DataMining.DistributedObjects.exe\"", false));
                                }
                                return;

                            case "#uninstall":
                                {
                                    Exec.Shell("sc stop DistributedObjects", true); // suppresserrors=true
                                    Exec.Shell("sc stop MemCachePin", true); // suppresserrors=true
                                    System.Threading.Thread.Sleep(1000 * 5);
                                    string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
                                    Console.WriteLine(Exec.Shell("installutil /u \"" + dir + "\\MySpace.DataMining.DistributedObjects.exe\"", false));
                                }
                                return;
#endif

                            case "stopallmemcachepin":
                                {
                                    string[] hosts;
                                    if (args.Length > 1)
                                    {
                                        string shosts = args[1];
                                        if (shosts.StartsWith("@"))
                                        {
                                            hosts = Surrogate.GetHostsFromFile(shosts.Substring(1));
                                        }
                                        else
                                        {
                                            hosts = shosts.Split(';', ',');
                                        }
                                    }
                                    else
                                    {
                                        dfs dc = dfs.ReadDfsConfig_unlocked(Surrogate.NetworkPathForHost(Surrogate.MasterHost) + @"\" + dfs.DFSXMLNAME);
                                        hosts = dc.Slaves.SlaveList.Split(';');
                                        // Always include self host if current cluster.
                                        if (null == IPAddressUtil.FindCurrentHost(hosts))
                                        {
                                            List<string> xhosts = new List<string>(1 + hosts.Length);
                                            xhosts.Add(System.Net.Dns.GetHostName());
                                            xhosts.AddRange(hosts);
                                            hosts = xhosts.ToArray();
                                        }
                                    }
                                    int threadcount = hosts.Length;
                                    if (threadcount > 15)
                                    {
                                        threadcount = 15;
                                    }

                                    MySpace.DataMining.Threading.ThreadTools<string>.Parallel(
                                        new Action<string>(
                                        delegate(string host)
                                        {
                                            try
                                            {
                                                Console.WriteLine("Stopping MemCachePin service on {0}...", host);
                                                Console.WriteLine(Exec.Shell("sc \\\\" + host + " stop MemCachePin").Trim());
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine("Problem stopping MemCachePin service on {0}: {1}", host, e.Message);
                                            }
                                        }
                                        ), hosts, threadcount);
                                    Console.WriteLine("Done");
                                }
                                break;

                            case "startallmemcachepin":
                                {
                                    string[] hosts;
                                    if (args.Length > 1)
                                    {
                                        string shosts = args[1];
                                        if (shosts.StartsWith("@"))
                                        {
                                            hosts = Surrogate.GetHostsFromFile(shosts.Substring(1));
                                        }
                                        else
                                        {
                                            hosts = shosts.Split(';', ',');
                                        }
                                    }
                                    else
                                    {
                                        dfs dc = dfs.ReadDfsConfig_unlocked(Surrogate.NetworkPathForHost(Surrogate.MasterHost) + @"\" + dfs.DFSXMLNAME);
                                        hosts = dc.Slaves.SlaveList.Split(';');
                                        // Always include self host if current cluster.
                                        if (null == IPAddressUtil.FindCurrentHost(hosts))
                                        {
                                            List<string> xhosts = new List<string>(1 + hosts.Length);
                                            xhosts.Add(System.Net.Dns.GetHostName());
                                            xhosts.AddRange(hosts);
                                            hosts = xhosts.ToArray();
                                        }
                                    }
                                    int threadcount = hosts.Length;
                                    if (threadcount > 15)
                                    {
                                        threadcount = 15;
                                    }

                                    MySpace.DataMining.Threading.ThreadTools<string>.Parallel(
                                        new Action<string>(
                                        delegate(string host)
                                        {
                                            try
                                            {
                                                Console.WriteLine("Starting MemCachePin service on {0}...", host);
                                                Console.WriteLine(Exec.Shell("sc \\\\" + host + " start MemCachePin").Trim());
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine("Problem starting MemCachePin service on {0}: {1}", host, e.Message);
                                            }
                                        }
                                        ), hosts, threadcount);
                                    Console.WriteLine("Done");
                                }
                                break;

                            case "stopall":
                            case "servicestopall":
                                {
                                    string[] hosts;
                                    if (args.Length > 1)
                                    {
                                        string shosts = args[1];
                                        if (shosts.StartsWith("@"))
                                        {
                                            hosts = Surrogate.GetHostsFromFile(shosts.Substring(1));
                                        }
                                        else
                                        {
                                            hosts = shosts.Split(';', ',');
                                        }
                                    }
                                    else
                                    {
                                        dfs dc = dfs.ReadDfsConfig_unlocked(Surrogate.NetworkPathForHost(Surrogate.MasterHost) + @"\" + dfs.DFSXMLNAME);
                                        hosts = dc.Slaves.SlaveList.Split(';');
                                        // Always include self host if current cluster.
                                        if (null == IPAddressUtil.FindCurrentHost(hosts))
                                        {
                                            List<string> xhosts = new List<string>(1 + hosts.Length);
                                            xhosts.Add(System.Net.Dns.GetHostName());
                                            xhosts.AddRange(hosts);
                                            hosts = xhosts.ToArray();
                                        }
                                    }
                                    int threadcount = hosts.Length;
                                    if (threadcount > 15)
                                    {
                                        threadcount = 15;
                                    }

                                    MySpace.DataMining.Threading.ThreadTools<string>.Parallel(
                                        new Action<string>(
                                        delegate(string host)
                                        {
                                            try
                                            {
                                                Console.WriteLine("Stopping service on {0}...", host);
                                                Console.WriteLine(Exec.Shell("sc \\\\" + host + " stop DistributedObjects").Trim());
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine("Problem stopping service on {0}: {1}", host, e.Message);
                                            }
                                        }
                                        ), hosts, threadcount);
                                    Console.WriteLine("Done");
                                }
                                return;

                            case "startall":
                            case "servicestartall":
                                {
                                    string[] hosts;
                                    if (args.Length > 1)
                                    {
                                        string shosts = args[1];
                                        if (shosts.StartsWith("@"))
                                        {
                                            hosts = Surrogate.GetHostsFromFile(shosts.Substring(1));
                                        }
                                        else
                                        {
                                            hosts = shosts.Split(';', ',');
                                        }
                                    }
                                    else
                                    {
                                        dfs dc = dfs.ReadDfsConfig_unlocked(Surrogate.NetworkPathForHost(Surrogate.MasterHost) + @"\" + dfs.DFSXMLNAME);
                                        hosts = dc.Slaves.SlaveList.Split(';');
                                        // Always include self host if current cluster.
                                        if (null == IPAddressUtil.FindCurrentHost(hosts))
                                        {
                                            List<string> xhosts = new List<string>(1 + hosts.Length);
                                            xhosts.Add(System.Net.Dns.GetHostName());
                                            xhosts.AddRange(hosts);
                                            hosts = xhosts.ToArray();
                                        }
                                    }
                                    int threadcount = hosts.Length;
                                    if (threadcount > 15)
                                    {
                                        threadcount = 15;
                                    }

                                    MySpace.DataMining.Threading.ThreadTools<string>.Parallel(
                                        new Action<string>(
                                        delegate(string host)
                                        {
                                            try
                                            {
                                                Console.WriteLine("Starting service on {0}...", host);
                                                Console.WriteLine(Exec.Shell("sc \\\\" + host + " start DistributedObjects").Trim());
                                            }
                                            catch (Exception e)
                                            {
                                                Console.WriteLine("Problem starting service on {0}: {1}", host, e.Message);
                                            }
                                        }
                                        ), hosts, threadcount);
                                    Console.WriteLine("Done");
                                }
                                return;

                            case "stopsurrogate":
                                {
                                    string surrogate;
                                    if (args.Length > 1)
                                    {
                                        Console.Error.WriteLine("Parameter not supported to stopsurrogate");
                                        return;
                                    }
                                    else
                                    {
                                        surrogate = Surrogate.MasterHost;
                                    }
                                    try
                                    {
                                        Console.WriteLine("Stopping surrogate on {0}...", surrogate);
                                        Console.WriteLine(Exec.Shell("sc \\\\" + surrogate + " stop DistributedObjects").Trim());
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("Problem stopping surrogate on {0}: {1}", surrogate, e.Message);
                                    }

                                    Console.WriteLine("Done");
                                }
                                return;

                            case "startsurrogate":
                                {
                                    string surrogate;
                                    if (args.Length > 1)
                                    {
                                        Console.Error.WriteLine("Parameter not supported to startsurrogate");
                                        return;
                                    }
                                    else
                                    {
                                        surrogate = Surrogate.MasterHost;
                                    }
                                    try
                                    {
                                        Console.WriteLine("Starting surrogate on {0}...", surrogate);
                                        Console.WriteLine(Exec.Shell("sc \\\\" + surrogate + " start DistributedObjects").Trim());
                                    }
                                    catch (Exception e)
                                    {
                                        Console.WriteLine("Problem starting surrogate on {0}: {1}", surrogate, e.Message);
                                    }

                                    Console.WriteLine("Done");
                                }
                                return;

                            case "servicestatussurrogate":
                                {
                                    string surrogate;
                                    if (args.Length > 1)
                                    {
                                        string shost = args[1];
                                        if (-1 != shost.IndexOf(';'))
                                        {
                                            Console.Error.WriteLine("servicestatussurrogate does not support list of hosts");
                                            //SetFailure();
                                            return;
                                        }
                                        if (shost.StartsWith("@"))
                                        {
                                            Console.Error.WriteLine("servicestatussurrogate does not support @hosts.txt");
                                            //SetFailure();
                                            return;
                                        }
                                        else
                                        {
                                            surrogate = Surrogate.LocateMasterHost(Surrogate.NetworkPathForHost(shost));
                                        }
                                    }
                                    else
                                    {
                                        surrogate = Surrogate.MasterHost;
                                    }

                                    string s = Surrogate.GetServiceStatusText(surrogate);
                                    Console.WriteLine(s);
                                }
                                return;

                            case "servicestatus":
                                {
                                    string surrogate;
                                    if (args.Length > 1)
                                    {
                                        string shost = args[1];
                                        if (-1 != shost.IndexOf(';'))
                                        {
                                            Console.Error.WriteLine("servicestatus does not support list of hosts");
                                            //SetFailure();
                                            return;
                                        }
                                        if (shost.StartsWith("@"))
                                        {
                                            Console.Error.WriteLine("servicestatus does not support @hosts.txt");
                                            //SetFailure();
                                            return;
                                        }
                                        else
                                        {
                                            surrogate = shost;
                                        }
                                    }
                                    else
                                    {
                                        surrogate = System.Net.Dns.GetHostName();
                                    }

                                    string s = Surrogate.GetServiceStatusText(surrogate);
                                    Console.WriteLine(s);
                                }
                                return;

                            case "servicestatusall":
                                {
                                    string[] hosts;
                                    if (args.Length > 1)
                                    {
                                        string shosts = args[1];
                                        if (shosts.StartsWith("@"))
                                        {
                                            hosts = Surrogate.GetHostsFromFile(shosts.Substring(1));
                                        }
                                        else
                                        {
                                            hosts = shosts.Split(';', ',');
                                        }
                                    }
                                    else
                                    {
                                        dfs dc = dfs.ReadDfsConfig_unlocked(Surrogate.NetworkPathForHost(Surrogate.MasterHost) + @"\" + dfs.DFSXMLNAME);
                                        hosts = dc.Slaves.SlaveList.Split(';');
                                        // Always include self host if current cluster.
                                        if (null == IPAddressUtil.FindCurrentHost(hosts))
                                        {
                                            List<string> xhosts = new List<string>(1 + hosts.Length);
                                            xhosts.Add(System.Net.Dns.GetHostName());
                                            xhosts.AddRange(hosts);
                                            hosts = xhosts.ToArray();
                                        }
                                    }
                                    int threadcount = hosts.Length;
                                    if (threadcount > 15)
                                    {
                                        threadcount = 15;
                                    }

                                    MySpace.DataMining.Threading.ThreadTools<string>.Parallel(
                                        new Action<string>(
                                        delegate(string host)
                                        {
                                            Console.WriteLine(Surrogate.GetServiceStatusText(host));
                                        }
                                        ), hosts, threadcount);

                                }
                                return;

                            case "restoresurrogate":
                            case "replacesurrogate":
                            case "\u0040format":
                            case "format":
                            format_cmd:
                                // Commands forwarded to aelight...
                                {
                                    try
                                    {
                                        Environment.SetEnvironmentVariable("DSPACE_EXE", "0");
                                    }
                                    catch
                                    {
                                    }
                                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(AELight_Dir + @"\AELight.exe", sargs);
                                    psi.UseShellExecute = false;
                                    try
                                    {
                                        psi.EnvironmentVariables["MDODir"] = System.Diagnostics.Process.GetCurrentProcess().Id.ToString();
                                    }
                                    catch
                                    {
                                    }
                                    System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
                                    proc.WaitForExit();
                                    Environment.Exit(proc.ExitCode);
                                    return;
                                }
                            //break;

                        }
                    }
                }

#if NOMASTER

#if DEBUG_cmiller
            {
                string computer_name = System.Environment.GetEnvironmentVariable("COMPUTERNAME");
                if (computer_name == "MAPDCMILLER")
                {
                    System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(AELight_Dir + @"\AELight.exe", sargs);
                    psi.UseShellExecute = false;
                    System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
                    proc.WaitForExit();
                    Environment.Exit(proc.ExitCode); // Not friendly to retrylogmd5
                    return;
                }
            }
#endif

                ex = MasterRunStreamStdIO(sargs);
#if CLIENT_LOG_ALL
                LogOutputToFile("CLIENT_LOG_ALL: returning from generic dspace command, StreamStdIO returned " + ex.ToString());
#endif

#else
            try
            {
                Environment.SetEnvironmentVariable("DSPACE_EXE", "0");
            }
            catch
            {
            }

            System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(AELight_Dir + @"\AELight.exe", sargs);
            psi.UseShellExecute = false;
            System.Diagnostics.Process.Start(psi).WaitForExit();
#endif

#if CLIENT_LOG_ALL
            LogOutputToFile("CLIENT_LOG_ALL: clean return from Main");
#endif

            }
            finally
            {
#if DEBUG
                //System.Threading.Thread.Sleep(1000 * 8);
#endif
                if (retrylogmd5)
                {
                    Log("\r\n[EndExec time=\"" + DateTime.Now + "\"]\r\n");
                    lock (retrylogbuf)
                    {
                        retrylogstop = true;
                    }
                    for (; ; )
                    {
                        if (retrylogthread.Join(1000 * 60))
                        {
                            break;
                        }
                        Console.WriteLine("Waiting for log file synchronization...");
                    }
                }

#if DEBUG
                if (_jobdebug)
                {
                    System.Threading.Mutex _jobdebug_m = new System.Threading.Mutex(false, "distobjlog");
                    try
                    {
                        _jobdebug_m.WaitOne();
                    }
                    catch (System.Threading.AbandonedMutexException)
                    {
                    }
                    try
                    {
                        if (System.IO.File.Exists("jobdebug.txt"))
                        {
                            DateTime _jobdebug_endtime = DateTime.Now;
                            using (System.IO.StreamWriter _jobdebu_sw = new System.IO.StreamWriter("jobdebug.txt", true))
                            {
                                _jobdebu_sw.WriteLine();
                                _jobdebu_sw.WriteLine("--------------------------------------------------------------------------------");
                                _jobdebu_sw.WriteLine();
                                _jobdebu_sw.WriteLine(" - Command:   {0}", _jobdebug_cmdline);
                                _jobdebu_sw.WriteLine(" - Started:   {0}", _jobdebug_starttime);
                                _jobdebu_sw.WriteLine(" - Finished:  {0}", _jobdebug_endtime);
                                _jobdebu_sw.WriteLine(" - Duration:  {0}", _jobdebug_endtime - _jobdebug_starttime);
                                _jobdebu_sw.WriteLine(" - Exit Code: {0}", _jobdebug_exitcode);
                                _jobdebu_sw.WriteLine();
                                foreach (string _jobdebug_ln in _jobdebug_output)
                                {
                                    _jobdebu_sw.Write(_jobdebug_ln);
                                }
                                _jobdebu_sw.WriteLine();
                                _jobdebu_sw.WriteLine("--------------------------------------------------------------------------------");
                                _jobdebu_sw.WriteLine();
                            }
                        }
                    }
                    catch
                    {
                    }
                    finally
                    {
                        _jobdebug_m.ReleaseMutex();
                    }
                }
#endif

            }

            Environment.Exit(ex);

        }
Esempio n. 46
0
 public List<string> DoSuggest(string word)
 {
     var parameter = new SuggestionParameter(word, _hunspell);
     var suggestThread = new System.Threading.Thread(DoWork);
     suggestThread.Start(parameter);
     suggestThread.Join(3000); // wait max 3 seconds
     suggestThread.Abort();
     if (!parameter.Success)
         LoadHunspell(_currentDictionary);
     return parameter.Suggestions;
 }
Esempio n. 47
0
        private void btnAgregar_Click(object sender, RoutedEventArgs e)
        {
            int iTotal = lstArchivos.Items.Count;
            int iSelec = lstArchivos.SelectedIndex + 1;
            int iEsImpar = 0;

            Archivos view = new Archivos();
            view.Owner = this;
            view.bMain = true;
            view.WindowStartupLocation = System.Windows.WindowStartupLocation.CenterOwner;
            view.ShowDialog();

            if (!bArchivos)
            {
                ITCMessageBox.Show(this,"No agregaste Archivos","Error!");
                return;
            }
            int iTadd = lArchivos.Count;
            OdbcTransaction myTrans = null;

            this.IsEnabled = false;
            System.Threading.Thread t = new System.Threading.Thread(Sending);
            t.SetApartmentState(System.Threading.ApartmentState.STA);
            t.Start(getBase());

            try
            {
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor;
                System.Data.Odbc.OdbcConnection myConn = new System.Data.Odbc.OdbcConnection();
                string sVer = (string)cmbVersion.SelectedValue;
                string sAge = (string)cmbAgencia.SelectedValue;
                string sDis = (string)cmbDispo.SelectedValue;
                string sArchivo = string.Empty;
                myConn.ConnectionString = ((Menu)this.Owner).sConexion;
                myConn.Open();
                string myNonQuery;
                OdbcCommand myCommand;
                myTrans = myConn.BeginTransaction();
                for (int i = iTotal; i >= iSelec; i--)
                {
                    myNonQuery = "UPDATE HHc_ArchivosVersion SET ORDEN = ? WHERE CODIGO_AGENCIA = ? AND VERSION = ? AND TIPO_DISPOSITIVO = ? AND ORDEN = ?";
                    myCommand = new OdbcCommand(myNonQuery, myConn);
                    myCommand.Parameters.Add("ORDEN", OdbcType.Int).Value = i + iTadd;
                    myCommand.Parameters.Add("CODIGO_AGENCIA", OdbcType.Int).Value = Int32.Parse(sAge);
                    myCommand.Parameters.Add("VERSION", OdbcType.VarChar).Value = sVer;
                    myCommand.Parameters.Add("TIPO_DISPOSITIVO", OdbcType.VarChar).Value = sDis;
                    myCommand.Parameters.Add("ORDEN", OdbcType.Int).Value = i;
                    myCommand.Transaction = myTrans;
                    myCommand.ExecuteNonQuery();
                }
                int orden = iSelec;
                foreach (Archivo aFile in lArchivos)
                {
                    byte[] bFile = null;

                    System.IO.FileStream fLoad = null;
                    string sFname = System.IO.Path.GetFileName(aFile.sName);
                    if ((sFname != "") && (System.IO.Path.GetExtension(sFname) != ""))
                    {
                        fLoad = System.IO.File.Open(aFile.sName, FileMode.Open, FileAccess.Read);
                        bFile = new byte[fLoad.Length];
                        fLoad.Read(bFile, 0, (int)fLoad.Length);
                        fLoad.Close();

                        sArchivo = BitConverter.ToString(bFile);
                        sArchivo = sArchivo.Replace("-", "");
                        sArchivo = "0x" + sArchivo;

                        if ((bFile.Length % 2) == 1)
                        {
                            sArchivo += "00";
                            iEsImpar = 1;
                        }
                    }
                    else
                    {
                        sArchivo = "NULL";
                    }

                    myNonQuery = "INSERT INTO HHc_ArchivosVersion VALUES (?, ?, ?, ?, ?, ?, ?, &, ?)";
                    myNonQuery = myNonQuery.Replace("&", sArchivo);
                    myCommand = new OdbcCommand(myNonQuery, myConn);
                    myCommand.Parameters.Add("CODIGO_AGENCIA", OdbcType.Int).Value = Int32.Parse(sAge);
                    myCommand.Parameters.Add("VERSION", OdbcType.VarChar).Value = sVer;
                    myCommand.Parameters.Add("TIPO_DISPOSITIVO", OdbcType.VarChar).Value = (string)cmbDispo.SelectedValue;
                    myCommand.Parameters.Add("ORDEN", OdbcType.Int).Value = orden;
                    myCommand.Parameters.Add("NOMBRE", OdbcType.VarChar).Value = aFile.sShort;
                    myCommand.Parameters.Add("PATH_DESTINO", OdbcType.VarChar).Value = aFile.sDestino;
                    myCommand.Parameters.Add("ACCION", OdbcType.Int).Value = aFile.option;
                    //myCommand.Parameters.Add("CONTENIDO", OdbcType.Binary).Value = bFile;
                    myCommand.Parameters.Add("ESIMPAR", OdbcType.Int).Value = iEsImpar;
                    myCommand.Transaction = myTrans;
                    myCommand.ExecuteNonQuery();
                    lstArchivos.Items.Insert(orden - 1, aFile);
                    orden++;
                }
                myTrans.Commit();
                myConn.Close();
                t.Abort();
                ITCMessageBox.Show(this, "Archivos modificados", "Mensaje!");
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
            }
            catch (Exception ex)
            {
                myTrans.Rollback();
                t.Abort();
                ITCMessageBox.Show(this, "Error al intentar modificar los archivos", "Error!");
                System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default;
            }
            this.IsEnabled = true;
        }
 private static void ObtainDbDnLoad()
 {
     string URI = "http://www.taxaideaarp.org/NLKAccess/mrhrlink/stateHrMrlnk.php";
     string param = "state=";
     ChooseSplitState ss = new ChooseSplitState();
     ss.ShowDialog();    //ss.splitState = css code
     param += ss.splitState;
     System.Threading.Thread pBar = new System.Threading.Thread(() => new Progress().Show());
     pBar.Start();
     using (WebClient webclient = new WebClient())
     {
         webclient.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
         string HtmlResult = webclient.UploadString(URI, param);
         File.WriteAllText(Path.Combine(path, fileNameInvDBdnload), HtmlResult);
     }
     pBar.Abort();
 }
Esempio n. 49
0
        public void ContentList_Concurrent_AddStringField()
        {
            string listDef0 = @"<?xml version='1.0' encoding='utf-8'?>
                <ContentListDefinition xmlns='http://schemas.sensenet.com/SenseNet/ContentRepository/ContentListDefinition'>
	                <Fields>
		                <ContentListField name='#StringField1' type='ShortText' />
	                </Fields>
                </ContentListDefinition>
                ";

            string path = RepositoryPath.Combine(this.TestRoot.Path, "Cars");
            if (Node.Exists(path))
                Node.ForceDelete(path);

            var list = new ContentList(this.TestRoot);
            list.Name = "Cars";
            list.ContentListDefinition = listDef0;
            list.AllowedChildTypes = new ContentType[] { ContentType.GetByName("Car") };

            list.Save();
            var listId = list.Id;

            Node car = new GenericContent(list, "Car");
            car.Name = "Trabant Tramp";
            car["#String_0"] = "ABC 34-78";
            car.Save();

            var t1 = new System.Threading.Thread(ContentList_Concurrent_AddStringField_Thread);
            var t2 = new System.Threading.Thread(ContentList_Concurrent_AddStringField_Thread);
            t1.Start();
            t2.Start();

            var startingTime = DateTime.Now;
            while (counter < 2)
            {
                System.Threading.Thread.Sleep(1000);
                if ((DateTime.Now - startingTime).TotalSeconds > 10)
                    break;
            }
            if (t1.ThreadState == System.Threading.ThreadState.Running)
                t1.Abort();
            if (t2.IsAlive)
                t2.Abort();

            Assert.IsTrue(counter == 2);
        }
        private void InitializeMessageQueue()
        {
            const int MAX_WAIT_TIME_SECONDS = 60;

            var worker = new System.Threading.Thread(InitializeMessageQueueWork);
            worker.Start();

            var dtWaitStart = DateTime.UtcNow;

            // Wait a maximum of 60 seconds
            if (!worker.Join(MAX_WAIT_TIME_SECONDS * 1000))
            {
                worker.Abort();
                m_MsgQueueInitSuccess = false;
                LogWarning("Unable to initialize the message queue (timeout after " + MAX_WAIT_TIME_SECONDS + " seconds)");
                return;
            }

            var elaspedTime = DateTime.UtcNow.Subtract(dtWaitStart).TotalSeconds;

            if (elaspedTime > 25)
            {
                ReportStatus("Connection to the message queue was slow, taking " + (int)elaspedTime + " seconds");
            }
        }
Esempio n. 51
0
        private static bool InitializeOutputSystem(AbstractOutput DesiredOutputSystem)
        {
            if (DesiredOutputSystem == null)
                throw new ArgumentNullException ("DesiredOutputSystem", "DesiredOutputSystem must be specified to initialize the system");

            bool success = false;

            SkipInput = true;
            System.Threading.Thread skip_input_buffer = new System.Threading.Thread (FlushKeyboard);
            skip_input_buffer.IsBackground = true;
            skip_input_buffer.Start ();

            ActiveOutputSystem = DesiredOutputSystem;
            success = ActiveOutputSystem.InitializeSystem ();

            string outputType = ActiveOutputSystem.GetType ().Name.Trim ();
            if (outputType == "") {
                outputType = "Unknown";
            }

            if (success) {
                Console.WriteLine ("- Connected to '{0}' via '{1}'", outputType, ActiveOutputSystem.Identifier);

                // Don't allow a shorter animation time than the output system processing can manage
                Light_Animation_Latency = Math.Max (ActiveOutputSystem.ProcessingLatency + 1, Light_Animation_Target_Latency);

                // Update number of lights, (re-)initalize the light queues
                LightSystem.SetLightCount (ActiveOutputSystem.LightCount);
                CreateLightQueues (LightSystem.LIGHT_COUNT);
            } else {
                Console.WriteLine ("- Could not connect to '{0}'", outputType);
            }

            SkipInput = false;
            if (skip_input_buffer.IsAlive)
                skip_input_buffer.Abort ();

            return success;
        }
Esempio n. 52
0
        public void DoExecute()
        {
            if (stbMain.Text.Length == 0)
                return;

            if (!panelBottom.Visible)
            {
                stbMain.Dock = DockStyle.Top;
                sptMain.Visible = true;
                panelBottom.Visible = true;
            }

            rtxtResults.Clear();
            rtxtResults.BringToFront();

            for (int iControl = panelGrids.Controls.Count; --iControl >= 0; )
                panelGrids.Controls.RemoveAt(iControl);

            m_oDataSet = null;
            m_fExecuteError = false;
            m_sLastError = "";
            sbpStatus.Text = "Executing query batch...";
            sbpTime.Text = GetTimeText(0);
            sbpRows.Text = "0 rows";

            try
            {
                if (m_oConn.State != ConnectionState.Open)
                {
                    m_oConn.Open();
                    m_oConn.ChangeDatabase(sbpDatabase.Text);
                }

                m_fCancelExecute = false;

                long cTickStart = DateTime.Now.Ticks;

                System.Threading.Thread oThread = new System.Threading.Thread(new System.Threading.ThreadStart(ExecuteQuery));
                oThread.Start();

                int cRows = 0;

                string sLastTime = "";
                while (oThread.IsAlive)
                {
                    string sTime = GetTimeText(DateTime.Now.Ticks - cTickStart);
                    if (sTime != sLastTime)
                    {
                        Globals.MainForm.UpdateExecuteState(this);
                        sbpTime.Text = sTime;

                        cRows = 0;
                        if (m_oDataSet != null)
                        {
                            foreach (DataTable oTable in m_oDataSet.Tables)
                                cRows += oTable.Rows.Count;
                            if (cRows == 1)
                                sbpRows.Text = "1 row";
                            else
                                sbpRows.Text = cRows.ToString("#,##0") + " rows";
                        }

                        sLastTime = sTime;
                    }

                    if (m_fCancelExecute)
                    {
                        try
                        {
                            oThread.Abort();
                        }
                        catch (Exception oEx)
                        {
                            string s = oEx.ToString();
                            s = "";
                        }
                        m_fIsExecuting = false;
                        Globals.MainForm.UpdateExecuteState(this);
                    }
                    else
                    {
                        Application.DoEvents();
                        System.Threading.Thread.Sleep(200);
                    }
                }

                int cTables = m_oDataSet.Tables.Count;
                int dypGrid = (cTables == 0) ? 0 : panelGrids.Height / cTables;
                if (dypGrid < kdypMinResults)
                    dypGrid = kdypMinResults;
                panelGrids.AutoScrollMinSize = new Size(0, dypGrid * cTables);

                //for (int iTable = cTables; --iTable >= 0; )
                for (int iTable = 0; iTable < cTables; iTable++)
                {
                    DataTable oTable = m_oDataSet.Tables[iTable];

                    NumberedDataGrid oGrid = new NumberedDataGrid();
                    oGrid.AllowSorting = false;
                    oGrid.Size = new System.Drawing.Size(panelGrids.Width, dypGrid);
                    oGrid.BackgroundColor = System.Drawing.SystemColors.Window;
                    oGrid.CaptionVisible = false;
                    oGrid.HeaderForeColor = System.Drawing.SystemColors.ControlText;
                    oGrid.ReadOnly = true;
                    oGrid.RowHeadersVisible = false;
                    //oGrid.Resize += new EventHandler(Grid_Resize);
                    panelGrids.Resize += new EventHandler(Grid_Resize);

                    panelGrids.Controls.Add(oGrid);
                    oGrid.Location = new Point(0, iTable * (dypGrid + kdypSpacing));

                    oTable.DefaultView.AllowNew = false;
                    oTable.DefaultView.AllowEdit = false;
                    oTable.DefaultView.AllowDelete = false;

                    DataGridTableStyle oTableStyle = new DataGridTableStyle();
                    oTableStyle.RowHeadersVisible = true;
                    oTableStyle.ReadOnly = true;
                    oTableStyle.MappingName = oTable.TableName;
                    oTableStyle.AllowSorting = false;

                    foreach (DataColumn oColumn in oTable.Columns)
                    {
                        DataGridColumnStyle oColStyle = GetColStyle(oColumn);
                        oTableStyle.GridColumnStyles.Add(oColStyle);
                    }

                    oGrid.TableStyles.Add(oTableStyle);
                    oGrid.DataSource = oTable;
                }

                if (cTables == 0)
                {
                    if (m_sbMessages.Length == 0)
                    {
                        SqlCommand oCommand = m_oConn.CreateCommand();
                        oCommand.CommandText = "select @@rowcount";
                        int cRecords = (int)oCommand.ExecuteScalar();
                        if (cRecords == 1)
                            m_sbMessages.AppendLine("(1 row affected)");
                        else
                            m_sbMessages.AppendLine("(" + cRecords.ToString("#,##0") + " rows affected)");
                    }
                    rtxtResults.Text = m_sbMessages.ToString();
                    rtxtResults.BringToFront();
                }
                else
                {
                    panelGrids.BringToFront();
                }

                sbpTime.Text = GetTimeText(DateTime.Now.Ticks - cTickStart);

                cRows = 0;
                foreach (DataTable oTable in m_oDataSet.Tables)
                    cRows += oTable.Rows.Count;
                if (cRows == 1)
                    sbpRows.Text = "1 row";
                else
                    sbpRows.Text = cRows.ToString("#,##0") + " rows";

                // Since the database might have changed, update it.
                if (m_oConn.State == ConnectionState.Open)
                    sbpDatabase.Text = m_oConn.Database;

                if (m_fCancelExecute)
                    sbpStatus.Text = "Query batch was cancelled";
                else
                    sbpStatus.Text = "Query batch completed";
            }
            catch (Exception oEx)
            {
                m_sLastError = oEx.Message;
            }

            if (m_fExecuteError && !m_fCancelExecute)
            {
                sbpStatus.Text = "Query batch completed with errors";
                rtxtResults.Clear();
                rtxtResults.SelectionColor = System.Drawing.Color.Red;
                rtxtResults.SelectedText = m_sLastError;
                rtxtResults.BringToFront();
            }

            m_fIsExecuting = false;
        }
Esempio n. 53
0
 private object getPropValue(PropertyInfo prop, object thisObjIN)
 {
     try
     {
         object ret = null;
         System.Threading.Thread call = new System.Threading.Thread
         (
        () =>
        {
            try { ret = prop.GetValue(thisObjIN, null); }
            catch { return; }
        }
          );
         call.Start();
         System.Threading.Thread.Sleep(10);
         call.Abort();
         return ret;
     }
     catch { return "cannot eval"; }
 }
Esempio n. 54
0
 private void cmdCancel_Click(object sender, EventArgs e)
 {
     if (MessageBox.Show("Bạn có muốn hủy việc download file hay không?", "RISlink", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
     {
         try
         {
             if (t==null && t.ThreadState != System.Threading.ThreadState.Running) return;
             t.Abort();
             t = null;
             lblCapacity.Visible = false;
             txtDir.Enabled = true;
             txtURL.Enabled = true;
             cmdDir.Enabled = true;
             cmdLoad.Enabled = true;
             lblStatus.Visible = false;
             picLoading.Visible = false;
             cmdCancel.Visible = false;
             cmdOpen.Visible = false;
             lblResult.Visible = false;
             cmdLoad.Focus();
         }
         catch
         {
             lblCapacity.Visible = false;
             txtDir.Enabled = true;
             txtURL.Enabled = true;
             cmdDir.Enabled = true;
             cmdLoad.Enabled = true;
             lblStatus.Visible = false;
             picLoading.Visible = false;
             cmdCancel.Visible = false;
             cmdOpen.Visible = false;
             lblResult.Visible = false;
             cmdLoad.Focus();
             
             t.Abort();
             t = null;
         }
     }
 }
Esempio n. 55
0
        static void ReplicationChecks(string[] args)
        {
            if (args.Length <= 1 || !System.IO.File.Exists(args[1]))
            {
                throw new Exception("Expected path to DFS.xml");
            }
            string dfsxmlpath = args[1];
            string dfsxmlpathbackup = dfsxmlpath + "$" + Guid.NewGuid().ToString();

            string masterdir;
            {
                System.IO.FileInfo fi = new System.IO.FileInfo(dfsxmlpath);
                masterdir = fi.DirectoryName; // Directory's full path.
            }
            Surrogate.SetNewMetaLocation(masterdir);

            dfs olddfs = dfs.ReadDfsConfig_unlocked(dfsxmlpath);

            string masterhost = System.Net.Dns.GetHostName();
            string[] allmachines;
            {
                string[] sl = olddfs.Slaves.SlaveList.Split(';');
                List<string> aml = new List<string>(sl.Length + 1);
                aml.Add(masterhost);
                foreach (string slave in sl)
                {
                    if (0 != string.Compare(IPAddressUtil.GetName(slave), IPAddressUtil.GetName(masterhost), StringComparison.OrdinalIgnoreCase))
                    {
                        aml.Add(slave);
                    }
                }
                allmachines = aml.ToArray();
            }

            Console.WriteLine("Backing up DFS.xml to: {0} ...", dfsxmlpathbackup);
            try
            {
                System.IO.File.Delete(dfsxmlpathbackup);
            }
            catch
            {
            }
            System.IO.File.Move(dfsxmlpath, dfsxmlpathbackup);
            try
            {
                {
                    Console.WriteLine("Formatting DFS for test...");
                    Exec.Shell("Qizmt @format Machines=" + string.Join(",", allmachines));
                }

                {
                    // Test logic:

                    {
                        long XBYTES = (long)4194304 * (long)allmachines.Length;

                        Console.WriteLine("Generating data...");
                        Console.Write("    ");
                        Exec.Shell("Qizmt gen data{476D6FE8-D645-41cc-83A1-3AB5E2DE23E7} " + (XBYTES / 4).ToString());
                        Console.Write("25%");
                        Exec.Shell("Qizmt gen data{61136275-16EC-4ff9-84CE-ACC967550181} " + (XBYTES / 4).ToString());
                        Console.Write("..50%");
                        Exec.Shell("Qizmt gen data{C76F6C06-EFC8-4808-B214-DB4D167171EB} " + (XBYTES / 2).ToString());
                        Console.Write("..100%");
                        Console.WriteLine();
                    }

                    Console.WriteLine("Ensure the cluster is perfectly healthy...");
                    EnsurePerfectQizmtHealtha();

                    Console.WriteLine("Raising replication factor to 2...");
                    Exec.Shell("Qizmt replicationupdate 2");

                    {
                        Console.WriteLine("Raising replication factor too high (ensure fail)...");
                        bool ok = false;
                        System.Threading.Thread thd = new System.Threading.Thread(
                            new System.Threading.ThreadStart(
                            delegate
                            {
                                try
                                {
                                    Exec.Shell("Qizmt replicationupdate 999999999");
                                }
                                catch (Exception e)
                                {
                                    ok = true;
                                    Console.WriteLine("Got exception as expected: {0}", e.Message);
                                }
                            }));
                        thd.Start();
                        if (!thd.Join(1000 * 10))
                        {
                            thd.Abort();
                        }
                        if (!ok)
                        {
                            throw new Exception("Test failed: expected exception");
                        }
                    }

                }

                Console.WriteLine("[PASSED] - " + string.Join(" ", args));

            }
            finally
            {
                Console.WriteLine("Restoring DFS.xml backup...");
                // Note: these are safe; the try/finally only wraps the new dfs.
                try
                {
                    Exec.Shell("Qizmt del *");
                }
                catch
                {
                }
                try
                {
                    // Delete temp dfs.xml, it's being replaced with the good one.
                    System.IO.File.Delete(dfsxmlpath);
                }
                catch
                {
                }
                System.IO.File.Move(dfsxmlpathbackup, dfsxmlpath);
            }

        }
Esempio n. 56
0
        private void cmdCancelUpload_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Bạn có muốn hủy việc Upload file hay không?", "RISlink", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                try
                {
                    if (tUpLoad == null && tUpLoad.ThreadState != System.Threading.ThreadState.Running) return;
                    tUpLoad.Abort();
                    tUpLoad = null;
                    lblUploadResult.Visible = true;
                    txtFileUpload.Enabled = true;
                    txtUploadURL.Enabled = true;
                    cmdFile.Enabled = true;
                    lblUploadCapacity.Visible = false;
                    cmdUpload.Enabled = true;
                    lblUploadStatus.Visible = false;
                    picUpLoad.Visible = false;
                    cmdCancelUpload.Visible = false;
                    lblPercent.Visible = false;
                    cmdUpload.Focus();
                }
                catch
                {
                    lblPercent.Visible = false;
                    lblUploadResult.Visible = true;
                    txtFileUpload.Enabled = true;
                    txtUploadURL.Enabled = true;
                    cmdFile.Enabled = true;
                    lblUploadCapacity.Visible = false;
                    cmdUpload.Enabled = true;
                    lblUploadStatus.Visible = false;
                    picUpLoad.Visible = false;
                    cmdCancelUpload.Visible = false;
                    cmdUpload.Focus();

                    tUpLoad.Abort();
                    tUpLoad = null;
                }
            }
        }
Esempio n. 57
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            Sound.SoundManager.Init();
            Cache.CacheManager.Init();

            System.Threading.Thread thread = new System.Threading.Thread(() =>
            {
                using (CacheProgress progressFrm = new CacheProgress())
                {
                    progressFrm.ShowDialog();
                }
            });
            thread.Start();

            try
            {
                // If dir not set, try to load from registry
                if (Settings.Default.GameDirectory.IsNullOrWhiteSpace())
                {
                    string installLocation = null;
                    string displayName = null;
                    string path;
                    string gameVerPath;
                    installLocation = Microsoft.Win32.Registry.GetValue(RegKeyx64, "InstallLocation", null) as string;
                    if (installLocation != null)
                    {
                        displayName = Microsoft.Win32.Registry.GetValue(RegKeyx64, "DisplayName", null) as string;
                        path = Path.Combine(installLocation, displayName);
                        gameVerPath = Path.Combine(path, "game.ver");
                        if (File.Exists(gameVerPath))
                        {
                            Settings.Default.GameDirectory = path;
                            Settings.Default.Save();
                        }
                    }
                    else
                    {
                        installLocation = Microsoft.Win32.Registry.GetValue(RegKeyx32, "InstallLocation", null) as string;
                        if (installLocation != null)
                        {
                            displayName = Microsoft.Win32.Registry.GetValue(RegKeyx64, "DisplayName", null) as string;
                            path = Path.Combine(installLocation, displayName);
                            gameVerPath = Path.Combine(path, "game.ver");
                            if (File.Exists(gameVerPath))
                            {
                                Settings.Default.GameDirectory = path;
                                Settings.Default.Save();
                            }
                        }
                    }
                }

                if (Settings.Default.GameDirectory.IsNullOrWhiteSpace())
                {
                    if (!OpenPreferenceWindow())
                    {
                        return;
                    }
                }
                else
                {
                    LoadCharaData();
                    LoadScriptData();
                }

                if (Cache.CacheManager.CacheIsStale)
                {
                    Cache.CacheManager.ReloadCache();
                }
            }
            finally
            {
                thread.Abort();
            }
        }
Esempio n. 58
0
        private static void WireUpTheOutputOfTheReplProcessToTheTextBox(TextBox replTextBox, Process replProcess, Entity<ReplState> replEntity)
        {
            var standardOutputStream = new StreamBuffer();
            var standardErrorStream = new StreamBuffer();
            var processOutputReader = new ProcessOutputReader(new TextBoxWriter(replTextBox, replEntity), standardOutputStream, standardErrorStream);
            var outputReaderThread = new Thread(processOutputReader.StartMarshallingTextFromReplToTextBox);
            var outputBufferStreamThread = new Thread(() => standardOutputStream.ReadStream(replProcess.StandardOutput.BaseStream));
            var errorBufferStreamThread = new Thread(() => standardOutputStream.ReadStream(replProcess.StandardError.BaseStream));

            replTextBox.Loaded +=
                (o, e) =>
                {
                    if (outputReaderThread.IsAlive) return;
                    replProcess.Start();
                    replProcess.StandardInput.AutoFlush = true;
                    outputBufferStreamThread.Start();
                    errorBufferStreamThread.Start();
                    outputReaderThread.Start();
                };

            replProcess.Exited +=
                (o, e) =>
                {
                    outputBufferStreamThread.Abort();
                    errorBufferStreamThread.Abort();
                    outputReaderThread.Abort();
                };
        }
Esempio n. 59
0
        private string CallModi(int i)
        {
            Bitmap bmp;
            try
            {
                var tmp = GetSubtitleBitmap(i);
                if (tmp == null)
                    return string.Empty;
                bmp = tmp.Clone() as Bitmap;
                tmp.Dispose();
            }
            catch
            {
                return string.Empty;
            }
            var mp = new ModiParameter { Bitmap = bmp, Text = "", Language = GetModiLanguage() };

            // We call in a seperate thread... or app will crash sometimes :(
            var modiThread = new System.Threading.Thread(DoWork);
            modiThread.Start(mp);
            modiThread.Join(3000); // wait max 3 seconds
            modiThread.Abort();

            if (!string.IsNullOrEmpty(mp.Text) && mp.Text.Length > 3 && mp.Text.EndsWith(";0]"))
                mp.Text = mp.Text.Substring(0, mp.Text.Length - 3);

            // Try to avoid blank lines by resizing image
            if (string.IsNullOrEmpty(mp.Text))
            {
                bmp = ResizeBitmap(bmp, (int)(bmp.Width * 1.2), (int)(bmp.Height * 1.2));
                mp = new ModiParameter { Bitmap = bmp, Text = "", Language = GetModiLanguage() };

                // We call in a seperate thread... or app will crash sometimes :(
                modiThread = new System.Threading.Thread(DoWork);
                modiThread.Start(mp);
                modiThread.Join(3000); // wait max 3 seconds
                modiThread.Abort();
            }
            int k = 0;
            while (string.IsNullOrEmpty(mp.Text) && k < 5)
                if (string.IsNullOrEmpty(mp.Text))
                {
                    bmp = ResizeBitmap(bmp, (int)(bmp.Width * 1.3), (int)(bmp.Height * 1.4)); // a bit scaling
                    mp = new ModiParameter { Bitmap = bmp, Text = "", Language = GetModiLanguage() };

                    // We call in a seperate thread... or app will crash sometimes :(
                    modiThread = new System.Threading.Thread(DoWork);
                    modiThread.Start(mp);
                    modiThread.Join(3000); // wait max 3 seconds
                    modiThread.Abort();
                    k++;
                }
            if (bmp != null)
                bmp.Dispose();
            if (mp.Text != null)
                mp.Text = mp.Text.Replace("•", "o");
            return mp.Text;
        }
Esempio n. 60
0
        public static void RevertChanges(Config config)
        {
            var thread = new System.Threading.Thread(() => // this has to be a foreground thread
            {
                // revert the hiding of the mouse when typing
                if (config.HideMouseWhenTyping != originalHideMouseWhenTyping)
                {
                    var hideMouseWhenTyping = originalHideMouseWhenTyping;
                    NativeMethods.SystemParametersInfo(NativeMethods.SPI.SPI_SETMOUSEVANISH, 0,
                        ref hideMouseWhenTyping, NativeMethods.SPIF.SPIF_UPDATEINIFILE);

                    NativeMethods.SendNotifyMessage(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE,
                        (UIntPtr) (uint) NativeMethods.SPI.SPI_SETMOUSEVANISH, IntPtr.Zero);
                }

                // revert the "focus follows mouse"
                if (config.FocusFollowsMouse != originalFocusFollowsMouse)
                {
                    var focusFollowsMouse = originalFocusFollowsMouse;
                    NativeMethods.SystemParametersInfo(NativeMethods.SPI.SPI_SETACTIVEWINDOWTRACKING, 0,
                        ref focusFollowsMouse, NativeMethods.SPIF.SPIF_UPDATEINIFILE);

                    NativeMethods.SendNotifyMessage(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE,
                        (UIntPtr) (uint) NativeMethods.SPI.SPI_SETACTIVEWINDOWTRACKING, IntPtr.Zero);
                }

                // revert the "set window on top on focus follows mouse"
                if (config.FocusFollowsMouseSetOnTop != originalFocusFollowsMouseSetOnTop)
                {
                    var focusFollowsMouseSetOnTop = originalFocusFollowsMouseSetOnTop;
                    NativeMethods.SystemParametersInfo(NativeMethods.SPI.SPI_SETACTIVEWNDTRKZORDER, 0,
                        ref focusFollowsMouseSetOnTop, NativeMethods.SPIF.SPIF_UPDATEINIFILE);

                    NativeMethods.SendNotifyMessage(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE,
                        (UIntPtr) (uint) NativeMethods.SPI.SPI_SETACTIVEWNDTRKZORDER, IntPtr.Zero);
                }

                // revert the minimize/maximize/restore animations
                if ((originalAnimationInfo.iMinAnimate == 1 && !config.ShowMinimizeMaximizeRestoreAnimations) ||
                    (originalAnimationInfo.iMinAnimate == 0 && config.ShowMinimizeMaximizeRestoreAnimations))
                {
                    var animationInfo = originalAnimationInfo;
                    NativeMethods.SystemParametersInfo(NativeMethods.SPI.SPI_SETANIMATION, animationInfo.cbSize,
                        ref animationInfo, NativeMethods.SPIF.SPIF_UPDATEINIFILE);

                    NativeMethods.SendNotifyMessage(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE,
                        (UIntPtr) (uint) NativeMethods.SPI.SPI_SETANIMATION, IntPtr.Zero);
                }

                // revert the size of non-client area of windows
                if ((config.WindowBorderWidth >= 0 && originalNonClientMetrics.iBorderWidth != config.WindowBorderWidth) ||
                    (SystemAndProcessInformation.isAtLeastVista && config.WindowPaddedBorderWidth >= 0 && originalNonClientMetrics.iPaddedBorderWidth != config.WindowPaddedBorderWidth))
                {
                    var metrics = originalNonClientMetrics;
                    NativeMethods.SystemParametersInfo(NativeMethods.SPI.SPI_SETNONCLIENTMETRICS, metrics.cbSize,
                        ref metrics, NativeMethods.SPIF.SPIF_UPDATEINIFILE);

                    NativeMethods.SendNotifyMessage(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE,
                        (UIntPtr) (uint) NativeMethods.SPI.SPI_SETNONCLIENTMETRICS, IntPtr.Zero);
                }
            });
            thread.Start();

            new System.Threading.Timer(_ =>
            {
                // SystemParametersInfo sometimes hangs because of SPI_SETNONCLIENTMETRICS,
                // even though SPIF_SENDCHANGE is not added to the flags
                if (thread.IsAlive)
                {
                    thread.Abort();
                    Environment.Exit(0);
                }
            }, null, 5000, 0);
        }