public void Stop() { this._isCancelRequested = true; if (this._filesReaderTask != null) { if (this._filesReaderTask.IsRunning) { this._filesReaderTask.Stop(); } } this._cts.Cancel(); this._taskThread?.Join(); this.IsRunning = false; }
public static void Preview(Engine engine, NukeBuild build) { var _messageEvent = new AutoResetEvent(false); var _changedFiles = new ConcurrentQueue <string>(); var _exit = new InterlockedBool(false); // Start the preview server DirectoryPath previewPath = (NukeBuild.RootDirectory / "output").ToString(); engine.Execute(); var previewServer = PreviewServer.Start(previewPath, 5080, true, null, true, new Dictionary <string, string>()); Trace.Information("Watching paths(s) {0}", string.Join(", ", engine.FileSystem.InputPaths)); var inputFolderWatcher = new ActionFileSystemWatcher( engine.FileSystem.GetOutputDirectory().Path, engine.FileSystem.GetInputDirectories().Select(x => x.Path), true, "*.*", path => { _changedFiles.Enqueue(path); _messageEvent.Set(); }); // Start the message pump if an async process is running ExitCode exitCode = ExitCode.Normal; // Only wait for a key if console input has not been redirected, otherwise it's on the caller to exit if (!Console.IsInputRedirected) { // Start the key listening thread Thread thread = new Thread(() => { Trace.Information("Hit Ctrl-C to exit"); Console.TreatControlCAsInput = true; while (true) { // Would have prefered to use Console.CancelKeyPress, but that bubbles up to calling batch files // The (ConsoleKey)3 check is to support a bug in VS Code: https://github.com/Microsoft/vscode/issues/9347 ConsoleKeyInfo consoleKey = Console.ReadKey(true); if (consoleKey.Key == (ConsoleKey)3 || (consoleKey.Key == ConsoleKey.C && (consoleKey.Modifiers & ConsoleModifiers.Control) != 0)) { _exit.Set(); _messageEvent.Set(); break; } } }) { IsBackground = true }; thread.Start(); } // Wait for activity while (true) { _messageEvent.WaitOne(); // Blocks the current thread until a signal if (_exit) { break; } // Execute if files have changed HashSet <string> changedFiles = new HashSet <string>(); string changedFile; while (_changedFiles.TryDequeue(out changedFile)) { if (changedFiles.Add(changedFile)) { Trace.Verbose("{0} has changed", changedFile); } } if (changedFiles.Count > 0) { Trace.Information("{0} files have changed, re-executing", changedFiles.Count); engine.Execute(); previewServer?.TriggerReloadAsync().GetAwaiter().GetResult(); } // Check one more time for exit if (_exit) { break; } Trace.Information("Hit Ctrl-C to exit"); _messageEvent.Reset(); } // Shutdown Trace.Information("Shutting down"); inputFolderWatcher?.Dispose(); previewServer?.Dispose(); }
public void OnMessageReceived(WaveServerComponent dest, Enum msgID, WaveMessage data) { if (msgID is UserManagerMessageID) { if (data != null) { switch ((UserManagerMessageID)msgID) { case UserManagerMessageID.Challenge: { bool createAccount = false; // check if there is login already (otherwise set defaults) if (!Core.Application.HasLogin) { createAccount = true; Core.Application.UpdateCredentials(GenerateNewUsername(), StringHelper.GetBytes(DefaultPassword)); } // get CSL version WaveCSLVersion serverCSL = (WaveCSLVersion)(data[UserManagerFieldID.CSLVersion].AsShort() ?? (short)WaveCSLVersion.Unknown); switch (serverCSL) { case WaveCSLVersion.Version5: case WaveCSLVersion.Version4: Core.CSLVersion = serverCSL; break; default: Core.CSLVersion = WaveCSLVersion.Version3; break; } // get maximum protocol version WaveProtocolVersion serverProto = (WaveProtocolVersion)(data[UserManagerFieldID.MaxWeMessageVersion].AsByte() ?? (byte)WaveProtocolVersion.Unknown); switch (serverProto) { case WaveProtocolVersion.Version4: Core.ProtocolVersion = WaveProtocolVersion.Version4; break; default: Core.ProtocolVersion = WaveProtocolVersion.Version3; break; } // get challenge BinaryField challenge = (BinaryField)data[UserManagerFieldID.Challenge]; // assemble login message WaveMessage msgOut = new WaveMessage(); msgOut.AddInt16(UserManagerFieldID.CSLVersion, (short)Core.CSLVersion); msgOut.AddBoolean(UserManagerFieldID.EncryptSession, Core.UseEncryption); msgOut.AddInt16(UserManagerFieldID.PriorityMask, NetworkAgent.PrioritiesActiveMask); msgOut.AddBinary(UserManagerFieldID.UserCredentials, ProcessChallenge(challenge.Data, Core.Application, createAccount)); msgOut.AddBoolean(UserManagerFieldID.CreateAccount, createAccount); // cache hash byte[] cacheHash = Core.Cache.CacheHash; msgOut.AddBinary(CacheAgentFieldID.CacheHashCompressed, (cacheHash.Length > 0) ? CompressionHelper.GZipBuffer(cacheHash) : cacheHash); // cache ID (if any) if (Core.Cache.CacheID.HasValue) { msgOut.AddBinary(MessageOutFieldID.CacheItemID, Core.Cache.CacheID.Value.ToByteArray()); } // compiling device settings FieldList deviceSettingsList = FieldList.CreateField(UserManagerFieldID.DeviceSettings); deviceSettingsList.AddString(UserManagerFieldID.DeviceBuildID, Core.BuildID); deviceSettingsList.AddBoolean(NaviAgentFieldID.DeviceSupportsTouch, true); deviceSettingsList.AddInt16(NaviAgentFieldID.DeviceScreenResolutionWidth, 480); deviceSettingsList.AddInt16(NaviAgentFieldID.DeviceScreenResolutionHeight, 800); DeviceGroup[] devs = Core.System.SupportedDeviceGroups; foreach (DeviceGroup dev in devs) { deviceSettingsList.AddInt16(NaviAgentFieldID.DeviceProfileGroup, (short)dev); } deviceSettingsList.AddString(UserManagerFieldID.LanguageID, CultureInfo.CurrentCulture.Name); deviceSettingsList.AddString(UserManagerFieldID.Timezone, Core.Settings.TimeZone); deviceSettingsList.AddBoolean(UserManagerFieldID.AlphaSupport, true); deviceSettingsList.AddBoolean(UserManagerFieldID.CompressionSupport, true); msgOut.AddFieldList(deviceSettingsList); // compiling application request list FieldList appRequestList = FieldList.CreateField(UserManagerFieldID.ApplicationRequest); appRequestList.AddString(NaviAgentFieldID.ApplicationURN, Core.Application.URI); appRequestList.AddInt16(NaviAgentFieldID.ApplicationRequestAction, (short)AppRequestAction.GetAppEntryPage); msgOut.AddFieldList(appRequestList); msgOut.Send(WaveServerComponent.UserManager, UserManagerMessageID.Login); Core.UI.SignalViewNavigationStart(Core.UI.RootViewID); break; } case UserManagerMessageID.EncryptionKeys: { // setting encryption (if allowed by build configuration) if (Core.UseEncryption && (sessionHandshakeFish != null)) { BinaryField sessionKeyField = (BinaryField)data[UserManagerFieldID.SessionKey]; byte[] sessionKey = (byte[])sessionKeyField.Data; sessionHandshakeFish.Decrypt(sessionKey, sessionKey.Length); BinaryField globalServerKeyField = (BinaryField)data[UserManagerFieldID.GlobalServerKey]; byte[] globalServerKey = (byte[])globalServerKeyField.Data; sessionHandshakeFish.Decrypt(globalServerKey, globalServerKey.Length); Core.NotifyEncryptionKeysChanged(this, sessionKey, globalServerKey); } else { Core.NotifyEncryptionKeysChanged(this, null, null); } // setting login data StringField userName = (StringField)data[UserManagerFieldID.CreatedAccountUserName]; if (userName != null) { BinaryField userPass = (BinaryField)data[UserManagerFieldID.CreatedAccountPasswordHash]; if ((userPass != null) && (sessionHandshakeFish != null)) { byte[] passBuffer = (byte[])userPass.Data.Clone(); sessionHandshakeFish.Decrypt(passBuffer, passBuffer.Length); Core.Application.UpdateCredentials(userName.Data, passBuffer); // no longer needed sessionHandshakeFish = null; } } break; } case UserManagerMessageID.LoginResponse: { if (!authenticated) { Int16Field loginStatus = (Int16Field)data[UserManagerFieldID.LoginStatus]; switch ((UserLoginStatus)loginStatus.Data) { case UserLoginStatus.Success: { // signal authentication success Core.NotifyAuthentication(this, data[UserManagerFieldID.SessionInfo].AsByteArray()); // preparing login data message FieldList appContext = (FieldList)data[UserManagerFieldID.ApplicationContext]; if (appContext != null) { int appID = appContext[MessageOutFieldID.ApplicationID].AsInteger() ?? 0; string unqualifiedAppURI = appContext[UserManagerFieldID.ApplicationUnqualifiedURI].AsText(); string fullyQualifiedAppURI = appContext[UserManagerFieldID.ApplicationFullyQualifiedURI].AsText(); Core.NotifySuccessfulLogin(this, appID, unqualifiedAppURI, fullyQualifiedAppURI); } authenticated = true; authenticatedEver = true; break; } case UserLoginStatus.FailedInvalidCredentials: Core.NotifyTerminateSession(this, SessionTerminationReasonCode.InvalidCredentials); break; case UserLoginStatus.FailedNoUser: Core.NotifyTerminateSession(this, SessionTerminationReasonCode.NoSuchUser); break; } } break; } } } } }
public void Stop() { this._isCancelRequested = true; this._readThread?.Join(); this.IsRunning = false; }
public void Start(string inputText, string seperators, string pattern, SearchParameters searchParameters, Action <IEnumerable <string>, double> callback) { if (this.IsRunning) { this.Stop(); } this.IsRunning = true; this._cts = new CancellationTokenSource(); _taskThread = new Thread(() => { try { Console.WriteLine("started normal search thread"); callback(null, PROGRESS_MAX / 100); IEnumerable <string> seperated = Split(inputText, seperators, searchParameters.SplitSettings); if (this._isCancelRequested) { callback(null, PROGRESS_MAX); } else { callback(null, PROGRESS_MAX / 10); } IEnumerable <string> trimmed = Trim(seperated, searchParameters.TrimSetting); if (this._isCancelRequested) { callback(null, PROGRESS_MAX); } else { callback(null, PROGRESS_MAX / 9); } IEnumerable <string> output; switch (searchParameters.SearchType) { case SearchType.StartsWith: output = StartsWith(trimmed, pattern, searchParameters.StringComparison, this._cts.Token); break; case SearchType.Contains: output = Contains(trimmed, pattern, searchParameters.StringComparison, this._cts.Token); break; case SearchType.Regex: output = SearchRegex(trimmed, pattern, searchParameters.RegexOptions, this._cts.Token); break; #if (DEBUG) case SearchType.Test: output = StartsWithTest(trimmed, pattern, searchParameters.StringComparison, this._cts.Token); break; #endif default: throw new NotImplementedException("Start() " + searchParameters.SearchType); } Console.WriteLine("Finished searching"); callback(output, PROGRESS_MAX); } catch (Exception ex) { MessageBox.Show("Exception: \n" + ex.Message + "\n" + ex.StackTrace, "Unexpected exception", MessageBoxButtons.OK, MessageBoxIcon.Error); callback(null, PROGRESS_MAX); } }) { Name = "Extractor Tasks Thread", IsBackground = true }; _taskThread.Start(); }