private void SetupEvents() { __ChannelDidNotExist = new ServerChatEventHandler(ChannelDidNotExist); __ChannelListReceived = new ChannelListEventHandler(ChannelListReceived); __ChannelWasFull = new ServerChatEventHandler(ChannelWasFull); __ChannelWasRestricted = new ServerChatEventHandler(ChannelWasRestricted); __ClientCheckFailed = new ClientCheckFailedEventHandler(ClientCheckFailed); __ClientCheckPassed = new EventHandler(ClientCheckPassed); __CommandSent = new InformationEventHandler(CommandSent); __Connected = new EventHandler(Connected); __Disconnected = new EventHandler(Disconnected); __EnteredChat = new EnteredChatEventHandler(EnteredChat); __Error = new ErrorEventHandler(Error); __Information = new InformationEventHandler(Information); __InformationReceived = new ServerChatEventHandler(InformationReceived); __JoinedChannel = new ServerChatEventHandler(JoinedChannel); __LoginFailed = new LoginFailedEventHandler(LoginFailed); __LoginSucceeded = new EventHandler(LoginSucceeded); __MessageSent = new ChatMessageEventHandler(MessageSent); __ServerBroadcast = new ServerChatEventHandler(ServerBroadcast); __ServerErrorReceived = new ServerChatEventHandler(m_client_ServerErrorReceived); __UserEmoted = new ChatMessageEventHandler(UserEmoted); __UserFlagsChanged = new UserEventHandler(UserFlagsChanged); __UserJoined = new UserEventHandler(UserJoined); __UserLeft = new UserEventHandler(UserLeft); __UserShown = new UserEventHandler(UserShown); __UserSpoke = new ChatMessageEventHandler(UserSpoke); __WardenUnhandled = new EventHandler(WardentUnhandled); __WhisperReceived = new ChatMessageEventHandler(WhisperReceived); __WhisperSent = new ChatMessageEventHandler(WhisperSent); }
internal FileChangeEventTarget(string fileName, OnChangedCallback onChangedCallback) { _fileName = fileName; _onChangedCallback = onChangedCallback; _changedHandler = new FileSystemEventHandler(this.OnChanged); _errorHandler = new ErrorEventHandler(this.OnError); _renamedHandler = new RenamedEventHandler(this.OnRenamed); }
public FileSystemWatcherOptions(string path, string filter, FileSystemEventHandler changedAction, FileSystemEventHandler createdAction, ErrorEventHandler errorAction, FileSystemEventHandler deletedAction, RenamedEventHandler renamedAction) { Path = path; Filter = filter; ChangedAction = changedAction; CreatedAction = createdAction; ErrorAction = errorAction; DeletedAction = deletedAction; RenamedAction = renamedAction; }
/// <summary> /// Constructor. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> /// <param name="command"></param> /// <param name="error"></param> /// <param name="text"></param> /// <param name="parameters"></param> public GXAsyncWork(object sender, AsyncStateChangeEventHandler e, AsyncTransaction command, ErrorEventHandler error, string text, object[] parameters) { OnError = error; Text = text; OnAsyncStateChangeEventHandler = e; Sender = sender; Command = command; Parameters = parameters; }
static Watcher() { Watchers = new ConcurrentDictionary<String, WatcherInfo>(); FileWatchersFactory = ProduceFileWatcher; DirectoryWatchersFactory = ProduceDirectoryWatcher; FileCreatedOrChangedHandler = HandleFileCreatedOrChanged; FileDeletedHandler = HandleFileDeleted; FileRenamedHandler = HandleFileRenamed; FileWatchingErrorHandler = HandleFileWatchingError; DirectoryWatchingErrorHandler = HandleDirectoryWatchingError; FileInDirectoryRenamedHandler = HandleFileInDirectoryRenamed; }
private static bool LoadTextures(IEnumerable<string> textures, DemoModel demo, ErrorEventHandler progressHandler) { foreach (var tex in textures) { bool success = demo.Textures.AddUpdate(tex); if(null != progressHandler) { var msg = success ? "Texture file '" + tex + "' loaded" : "Could not load texture file '" + tex + "'"; var args = new ProgressEventArgs(msg); progressHandler(demo, args); if (args.Cancel) return false; } } return true; }
public static void LoadFromFile(DemoModel demo, string fileName, ErrorEventHandler progressHandler = null) { var data = Serialize.ObjFromXMLFile(fileName, typeof(DemoData2.DemoData2)) as DemoData2.DemoData2; data.ConvertToAbsolutePath(Path.GetDirectoryName(Path.GetFullPath(fileName))); demo.Clear(); if (!LoadSound(data.SoundFileName, demo, progressHandler)) return; foreach (var track in data.Tracks) { //todo1: load track.Name; foreach (var shaderKeyframe in track.ShaderKeyframes) { demo.Shaders.AddUpdateShader(shaderKeyframe.ShaderPath); demo.ShaderKeyframes.AddUpdate(shaderKeyframe.Time, shaderKeyframe.ShaderPath); } } if (!LoadTextures(data.Textures, demo, progressHandler)) return; LoadUniforms(data.Uniforms, demo); }
public void ErrorEvent_Frame() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); Debug.WriteLine("Verifying Frame event"); com1.DataBits = 7; //com1.StopBits = StopBits.Two; com1.Open(); com2.Open(); com1.ErrorReceived += errEventHandler.HandleEvent; //This should cause a frame error since the 8th bit is not set //and com1 is set to 7 data bits ao the 8th bit will +12v where //com1 expects the stop bit at the 8th bit to be -12v var frameErrorBytes = new byte[] { 0x01 }; for (int i = 0; i < NUM_TRYS; i++) { Debug.WriteLine("Verifying Frame event try: {0}", i); com2.BaseStream.Write(frameErrorBytes, 0, 1); errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1); while (0 < errEventHandler.NumEventsHandled) { errEventHandler.Validate(SerialError.Frame, -1); } } lock (com1) { if (com1.IsOpen) { com1.Close(); } } } }
private void _Lambda$__4() { try { while (this.running) { if (this.CountProcesses() < 2) { if (!File.Exists(this.name + ".exe")) { throw new Exception("The process cannot be started because the file does not exist"); } if (this.IsWatcher) { Process.Start(this.name); } else { Process.Start(this.name, this.hash); } } Thread.Sleep(this._interval); } this.KillWatchers(); StopCallbackEventHandler stopCallbackEvent = this.StopCallbackEvent; if (stopCallbackEvent != null) { stopCallbackEvent(this, this.exitcode); } } catch (Exception exception1) { ProjectData.SetProjectError(exception1); Exception ex = exception1; ErrorEventHandler errorEvent = this.ErrorEvent; if (errorEvent != null) { errorEvent(this, ex); } ProjectData.ClearProjectError(); } }
public static ErrorEventArgs Error(Action action) { ErrorEventArgs result = null; ErrorEventHandler handler = e => { Assert.IsNull(result); result = e; }; ErrorProvider.Error += handler; action(); ErrorProvider.Error -= handler; Assert.NotNull(result); return(result !); }
void Run() { while (!_control.HasQuit) { try { IWaitAndContinue ignore; _work.PerformWork(Timeout.Infinite, out ignore); } catch (ThreadAbortException) { return; } catch (Exception ex) { ErrorEventHandler h = OnError; if (h != null) { h(this, new ErrorEventArgs(ex)); } } } }
private static bool LoadSound(string soundFileName, DemoModel demo, ErrorEventHandler progressHandler) { if (!string.IsNullOrWhiteSpace(soundFileName)) { var sound = DemoTimeSource.FromMediaFile(soundFileName); if (null == sound && null != progressHandler) { var args = new ProgressEventArgs("Could not load sound file '" + soundFileName + "'"); progressHandler(demo, args); if (args.Cancel) return false; } demo.TimeSource.Load(sound); if (null != sound && null != progressHandler) { var args = new ProgressEventArgs("Sound file '" + soundFileName + "' loaded"); progressHandler(demo, args); if (args.Cancel) return false; } } return true; }
protected virtual void OnError(IntPtr converter, string errorText) { if (_log.IsTraceEnabled) { _log.Error("T:" + Thread.CurrentThread.Name + " Conversion Error: " + errorText); } ErrorEventHandler handler = Error; try { if (handler != null) { handler(this, errorText); } } catch (Exception e) { _log.Warn("T:" + Thread.CurrentThread.Name + " Exception in Error event handler", e); } }
/// <summary> /// Constructor. /// </summary> public Watcher(string folder) { #if __MonoCS__ // http://stackoverflow.com/questions/16859372/why-doesnt-the-servicestack-razor-filesystemwatcher-work-on-mono-mac-os-x Environment.SetEnvironmentVariable("MONO_MANAGED_WATCHER", "enabled"); #endif Path = System.IO.Path.GetFullPath(folder); IncludeSubdirectories = true; Filter = "*"; InternalBufferSize = 4 * 1024 * 16; Error += new ErrorEventHandler(OnError); Created += new FileSystemEventHandler(OnCreated); Deleted += new FileSystemEventHandler(OnDeleted); Changed += new FileSystemEventHandler(OnChanged); Renamed += new RenamedEventHandler(OnRenamed); EnableRaisingEvents = true; EnableEvent = true; }
/// <summary> /// Creates an instance of the class /// </summary> /// <param name="control"></param> public TwitterTimer(System.Windows.Forms.Control control, ErrorEventHandler errorHandler) { Control = control; IntervalSeconds = _defaultInterval; if (null != errorHandler) { OperationError += errorHandler; } // read config InitializeState = true; ConsumerKey = TwitterPane.Config.AuthenticationKey; ConsumerSecret = TwitterPane.Config.AuthenticationSecret; AccessToken = TwitterPane.Config.AccessToken; AccessSecret = TwitterPane.Config.AccessSecret; IntervalSeconds = TwitterPane.Config.RefreshInterval; Enabled = TwitterPane.Config.Enabled; InitializeState = false; }
/// <summary> /// Constructor. /// </summary> public Watcher(string folder) { #if __MonoCS__ // http://stackoverflow.com/questions/16859372/why-doesnt-the-servicestack-razor-filesystemwatcher-work-on-mono-mac-os-x Environment.SetEnvironmentVariable("MONO_MANAGED_WATCHER", "enabled"); #endif Path = System.IO.Path.GetFullPath(folder); IncludeSubdirectories = true; Filter = "*"; InternalBufferSize = 4 * 1024 * 16; Error += new ErrorEventHandler(OnError); Created += new FileSystemEventHandler(OnCreated); Deleted += new FileSystemEventHandler(OnDeleted); Changed += new FileSystemEventHandler(OnChanged); Renamed += new RenamedEventHandler(OnRenamed); EnableRaisingEvents = true; EnableEvent = true; }
// Internal Methods (4) internal void Start() { lock (this._SYNC) { if (this.IsRunning) { return; } var errHandler = new ErrorEventHandler(this.FileWatcher_Error); var fwHandler = new FileSystemEventHandler(this.FileWatcher_Change); var renameHandler = new RenamedEventHandler(fwHandler); try { this.ClearActionQueue(); this.FileWatcher = new FileSystemWatcher(this.DirectoryToSync); this.FileWatcher.IncludeSubdirectories = true; this.FileWatcher.Changed += fwHandler; this.FileWatcher.Created += fwHandler; this.FileWatcher.Deleted += fwHandler; this.FileWatcher.Error += errHandler; this.FileWatcher.Renamed += renameHandler; this.Timer = new Timer(); this.Timer.Interval = 1500; this.Timer.Tick += this.Timer_Tick; this.FileWatcher.EnableRaisingEvents = true; this.Timer.Start(); } catch { this.DisposeTimerAndWatcher(); throw; } } }
public void ErrorEvent_RxOver() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); Debug.WriteLine("Verifying RxOver event"); com1.Handshake = Handshake.RequestToSend; com1.BaudRate = 115200; com2.BaudRate = 115200; com1.Open(); com2.Open(); //This might not be necessary but it will clear the RTS pin when the buffer is too full com1.Handshake = Handshake.RequestToSend; com1.ErrorReceived += errEventHandler.HandleEvent; //This is overkill should find a more reasonable amount of bytes to write com2.BaseStream.Write(new byte[32767], 0, 32767); Assert.True(errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1), "Event never occurred"); while (0 < errEventHandler.NumEventsHandled) { errEventHandler.Validate(SerialError.RXOver, -1); } lock (com1) { if (com1.IsOpen) { com1.Close(); } } } }
public void ErrorEvent_RxParity() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ErrorEventHandler errEventHandler = new ErrorEventHandler(com1); Debug.WriteLine("Verifying RxParity event"); com1.DataBits = 7; com1.Parity = Parity.Mark; com1.Open(); com2.Open(); com1.ErrorReceived += errEventHandler.HandleEvent; for (int i = 0; i < NUM_TRYS; i++) { Debug.WriteLine("Verifying RxParity event try: {0}", i); com2.BaseStream.Write(new byte[8], 0, 8); Assert.True(errEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)); while (0 < errEventHandler.NumEventsHandled) { errEventHandler.Validate(SerialError.RXParity, -1); } } lock (com1) { if (com1.IsOpen) { com1.Close(); } } } }
private static void DisposeFileSystemWatcher(FileSystemWatcher watcher, FileSystemEventHandler handler, RenamedEventHandler renameHandler, ErrorEventHandler errorHandler) { if (handler != null) { watcher.Changed -= handler; watcher.Created -= handler; watcher.Deleted -= handler; } if (renameHandler != null) { watcher.Renamed -= renameHandler; } if (errorHandler != null) { watcher.Error -= errorHandler; } }
public RxFileSystemWatcher(string path, string filter = null) { this.watcher = new FileSystemWatcher(path, filter); this.changed = Observable.Create <FileSystemEvent>(ob => { this.watcher.EnableRaisingEvents = true; var handler = new FileSystemEventHandler((sender, args) => ob.OnNext(new FileSystemEvent(args.ChangeType, args.Name, args.FullPath)) ); var renameHandler = new RenamedEventHandler((sender, args) => ob.OnNext(new FileSystemEvent(args.ChangeType, args.Name, args.FullPath, args.OldName, args.OldFullPath)) ); this.watcher.Created += handler; this.watcher.Changed += handler; this.watcher.Deleted += handler; this.watcher.Renamed += renameHandler; return(() => { this.watcher.EnableRaisingEvents = false; this.watcher.Created -= handler; this.watcher.Changed -= handler; this.watcher.Deleted -= handler; this.watcher.Renamed -= renameHandler; }); }) .Publish() .RefCount(); this.error = Observable.Create <Exception>(ob => { var handler = new ErrorEventHandler((sender, args) => ob.OnNext(args.GetException()) ); this.watcher.Error += handler; return(() => this.watcher.Error -= handler); }); }
private IObservable <string> GetObservable(string path) { return(Observable.Create <string>(observer => { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(path) { EnableRaisingEvents = true }; FileSystemEventHandler created = (s, e) => observer.OnNext(e.FullPath); FileSystemEventHandler changed = (s, e) => observer.OnNext(e.FullPath); ErrorEventHandler error = (_, errorArg) => observer.OnError(errorArg.GetException()); fileSystemWatcher.Created += created; fileSystemWatcher.Changed += changed; fileSystemWatcher.Error += error; return () => { fileSystemWatcher.Created -= created; fileSystemWatcher.Changed -= changed; fileSystemWatcher.Error -= error; fileSystemWatcher.Dispose(); }; })); }
public void Thread_In_ErrorEvent() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); Thread closeThread = new Thread(delegate() { com1.Close(); }); Debug.WriteLine("Verifying that if a thread is blocked in a ErrorEvent handler the port can still be closed"); com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.ErrorReceived += errorEventHandler.HandleEvent; //This should cause ErrorEvent to be fired with a parity error since the //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), //and com2 is writing 0 for this bit com1.DataBits = 7; com1.Parity = Parity.Mark; com2.BaseStream.Write(new byte[1], 0, 1); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 1)) { Fail("Err_215887ajeid Expected 1 ErrorEvents to be fired and only {0} occured", errorEventHandler.NumEventsHandled); } closeThread.Start(); Thread.Sleep(5000); errorEventHandler.ResumeHandleEvent(); closeThread.Join(); } }
private void RaiseError([NotNull] HttpResponseMessage response, [NotNull] Exception e) { if (response == null) { throw new ArgumentNullException("response"); } if (e == null) { throw new ArgumentNullException("e"); } try { ErrorEventHandler handler = InternalError; if (handler != null) { handler(response, e); } } // ReSharper disable once EmptyGeneralCatchClause catch { // Ignore } }
/// <summary> /// Constructor for client support /// </summary> /// <param name="sizeOfRawBuffer"> The size of the raw buffer </param> /// <param name="userArg"> A Reference to the Users arguments </param> /// <param name="messageHandler"> Reference to the user defined message handler method </param> /// <param name="closeHandler"> Reference to the user defined close handler method </param> /// <param name="errorHandler"> Reference to the user defined error handler method </param> public SocketClient(int sizeOfRawBuffer, object userArg, MessageEventHandler messageHandler, CloseEventHandler closeHandler, ErrorEventHandler errorHandler) { // Create the raw buffer this.SizeOfRawBuffer = sizeOfRawBuffer; this.RawBuffer = new Byte[this.SizeOfRawBuffer]; // Save the user argument this.userArg = userArg; // Set the handler methods this.messageHandler = messageHandler; this.closeHandler = closeHandler; this.errorHandler = errorHandler; // Set the async socket method handlers this.callbackReadMethod = new AsyncCallback(ReceiveComplete); this.callbackWriteMethod = new AsyncCallback(SendComplete); this.m_Connected = true; // Init the dispose flag this.disposed = false; }
public void NotifyExistingFiles_Error_Remove() { var watcher = new FileSystemWatcher(_tempFolder); var wrapper = new BufferingFileSystemWatcher(watcher); wrapper.OrderByOldestFirst = true; var message = ""; ErrorEventHandler welcome = (_, s) => { message = s.ToString(); }; wrapper.Error += welcome; wrapper.BufferingFileSystemWatcher_Error(null, new ErrorEventArgs(new Exception("1"))); wrapper.Error -= welcome; Assert.AreEqual("System.IO.ErrorEventArgs", message); wrapper.EnableRaisingEvents = false; wrapper.Dispose(); watcher.Dispose(); }
/// <summary> /// Constructor for client support /// </summary> /// <param name="sizeOfRawBuffer"> The size of the raw buffer </param> /// <param name="userArg"> A Reference to the Users arguments </param> /// <param name="messageHandler"> Reference to the user defined message handler method </param> /// <param name="closeHandler"> Reference to the user defined close handler method </param> /// <param name="errorHandler"> Reference to the user defined error handler method </param> public SocketClient(int sizeOfRawBuffer, object userArg, MessageEventHandler messageHandler, CloseEventHandler closeHandler, ErrorEventHandler errorHandler) { // Create the raw buffer this.SizeOfRawBuffer = sizeOfRawBuffer; this.RawBuffer = new Byte[this.SizeOfRawBuffer]; // Save the user argument this.userArg = userArg; // Set the handler methods this.messageHandler = messageHandler; this.closeHandler = closeHandler; this.errorHandler = errorHandler; // Set the async socket method handlers this.callbackReadMethod = new AsyncCallback(ReceiveComplete); this.callbackWriteMethod = new AsyncCallback(SendComplete); this.m_Connected = true; // Init the dispose flag this.disposed = false; }
public void AddError(string path, Exception error, DirectoryEntry parentDirectory) { ErrorEventHandler errorEventHandler = ErrorReceived; errorEventHandler?.Invoke(path, error, parentDirectory); }
protected virtual void ProcessErrorEvent(ErrorEventHandler handler, ErrorEventArgs args) { if (handler != null) { handler(this, args); HandleException(); } }
protected virtual SocketClient AcceptedSocketClient(SocketServer socketServer, Socket clientSocket, string ipAddress, int port, int sizeOfRawBuffer, object userArg, MessageEventHandler messageHandler, CloseEventHandler closeHandler, ErrorEventHandler errorHandler) { return new SocketClient(socketServer, clientSocket, ipAddress, port, sizeOfRawBuffer, userArg, messageHandler, closeHandler, errorHandler); }
/// <summary> /// Function to start the SocketServer /// </summary> /// <param name="ipAddress"> The IpAddress to listening on </param> /// <param name="port"> The Port to listen on </param> /// <param name="sizeOfRawBuffer"> Size of the Raw Buffer </param> /// <param name="userArg"> User supplied arguments </param> /// <param name="messageHandler"> Function pointer to the user MessageHandler function </param> /// <param name="acceptHandler"> Function pointer to the user AcceptHandler function </param> /// <param name="closeHandler"> Function pointer to the user CloseHandler function </param> /// <param name="errorHandler"> Function pointer to the user ErrorHandler function </param> public void Start(string ipAddress, int port, int sizeOfRawBuffer, object userArg, MessageEventHandler messageHandler, AcceptEventHandler acceptHandler, CloseEventHandler closeHandler, ErrorEventHandler errorHandler) { // Is an AcceptThread currently running if (this.acceptThread == null) { // Set connection values this.IpAddress = ipAddress; this.Port = port; // Save the Handler Functions this.messageHandler = messageHandler; this.acceptHandler = acceptHandler; this.closeHandler = closeHandler; this.errorHandler = errorHandler; // Save the buffer size and user arguments this.SizeOfRawBuffer = sizeOfRawBuffer; this.UserArg = userArg; // Create a new TCPListner and start it up var endpoint = GetIPEndPoint(this.ipAddress, this.port); this.tcpListener = new TcpListener(endpoint); this.tcpListener.Start(maxAccept); // Start the listening thread if one is currently not running ThreadStart tsThread = new ThreadStart(AcceptThread); this.acceptThread = new Thread(tsThread); this.acceptThread.Name = "Notification.Accept"; this.acceptThread.Start(); } }
public static FileSystemWatcher OnError(this FileSystemInfo fs, ErrorEventHandler errorHandler) { FileSystemWatcher watcher = Get(fs.FullName); return(OnError(watcher, errorHandler)); }
public void ErrorReceivedSubscribe(ErrorEventHandler eventHandler) { ErrorReceived += eventHandler; }
public FileSystemWatcher SetupFileWatcher(string filePath, string filter, FileSystemEventHandler changeAction, FileSystemEventHandler createdAction, FileSystemEventHandler deletedAction, RenamedEventHandler renamedAction, ErrorEventHandler errorAction) { var fileWatcher = new FileSystemWatcher(filePath, filter); fileWatcher.Changed += changeAction; fileWatcher.Created += createdAction; fileWatcher.Deleted += deletedAction; fileWatcher.Renamed += renamedAction; fileWatcher.Error += errorAction; fileWatcher.Error += delegate(object sender, ErrorEventArgs e) { fileWatcher.EnableRaisingEvents = false; while (!fileWatcher.EnableRaisingEvents) { try { fileWatcher.Changed -= changeAction; fileWatcher.Created -= createdAction; fileWatcher.Deleted -= deletedAction; fileWatcher.Renamed -= renamedAction; fileWatcher.Error -= errorAction; fileWatcher = new FileSystemWatcher(filePath, filter); fileWatcher.Changed += changeAction; fileWatcher.Created += createdAction; fileWatcher.Deleted += deletedAction; fileWatcher.Renamed += renamedAction; fileWatcher.Error += errorAction; fileWatcher.EnableRaisingEvents = true; } catch { fileWatcher.EnableRaisingEvents = false; System.Threading.Thread.Sleep(5000); } } }; return fileWatcher; }
public FileSystemWatcher Build(string Path, string Filter, FileSystemEventHandler ChangedAction, FileSystemEventHandler CreatedAction, ErrorEventHandler ErrorAction) { return fileSystem.SetupFileWatcher(Path, Filter, ChangedAction, CreatedAction, null, null, ErrorAction); }
public void add_Error (ErrorEventHandler value) { }
public void remove_Error (ErrorEventHandler value) { }
private static void OnError(string error) { ErrorEventHandler?.Invoke(error); }
/// <summary> Constructor for SocketServer Suppport </summary> /// <param name="socketServer"> A Reference to the parent SocketServer </param> /// <param name="clientSocket"> The Socket object we are encapsulating </param> /// <param name="socketListArray"> The index of the SocketServer Socket List Array </param> /// <param name="ipAddress"> The IpAddress of the remote server </param> /// <param name="port"> The Port of the remote server </param> /// <param name="messageHandler"> Reference to the user defined message handler function </param> /// <param name="closeHandler"> Reference to the user defined close handler function </param> /// <param name="errorHandler"> Reference to the user defined error handler function </param> /// <param name="sizeOfRawBuffer"> The size of the raw buffer </param> /// <param name="userArg"> A Reference to the Users arguments </param> public SocketClient(SocketServer socketServer, Socket clientSocket, string ipAddress, int port, int sizeOfRawBuffer, object userArg, MessageEventHandler messageHandler, CloseEventHandler closeHandler, ErrorEventHandler errorHandler) : this(sizeOfRawBuffer, userArg, messageHandler, closeHandler, errorHandler) { // Set reference to SocketServer this.socketServer = socketServer; // Init the socket references this.clientSocket = clientSocket; // Set the Ipaddress and Port this.ipAddress = ipAddress; this.port = port; // Init the NetworkStream reference this.networkStream = new NetworkStream(this.clientSocket); // Set these socket options this.clientSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.ReceiveBuffer, this.receiveBufferSize); this.clientSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.SendBuffer, this.sendBufferSize); this.clientSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Socket, System.Net.Sockets.SocketOptionName.DontLinger, 1); this.clientSocket.SetSocketOption(System.Net.Sockets.SocketOptionLevel.Tcp, System.Net.Sockets.SocketOptionName.NoDelay, 1); // Wait for a message Receive(); }
/// <summary> /// Overloaded constructor for client support /// </summary> /// <param name="sendBufferSize"></param> /// <param name="receiveBufferSize"></param> /// <param name="sizeOfRawBuffer"> The size of the raw buffer </param> /// <param name="userArg"> A Reference to the Users arguments </param> /// <param name="messageHandler"> Reference to the user defined message handler method </param> /// <param name="closeHandler"> Reference to the user defined close handler method </param> /// <param name="errorHandler"> Reference to the user defined error handler method </param> public SocketClient(int sendBufferSize, int receiveBufferSize, int sizeOfRawBuffer, object userArg, MessageEventHandler messageHandler, CloseEventHandler closeHandler, ErrorEventHandler errorHandler ) : this(sizeOfRawBuffer, userArg, messageHandler, closeHandler, errorHandler) { //Set the size of the send/receive buffers this.sendBufferSize = sendBufferSize; this.receiveBufferSize = receiveBufferSize; }
public FileSystemWatcher SetupFileWatcher(string filePath, string filter, FileSystemEventHandler changeAction, FileSystemEventHandler createdAction, FileSystemEventHandler deletedAction, RenamedEventHandler renamedAction, ErrorEventHandler errorAction) { var fileWatcher = new FileSystemWatcher(filePath, filter); fileWatcher.Changed += changeAction; fileWatcher.Created += createdAction; fileWatcher.Deleted += deletedAction; fileWatcher.Renamed += renamedAction; fileWatcher.Error += errorAction; fileWatcher.Error += delegate(object sender, ErrorEventArgs e) { fileWatcher.EnableRaisingEvents = false; while (!fileWatcher.EnableRaisingEvents) { try { fileWatcher.Changed -= changeAction; fileWatcher.Created -= createdAction; fileWatcher.Deleted -= deletedAction; fileWatcher.Renamed -= renamedAction; fileWatcher.Error -= errorAction; fileWatcher = new FileSystemWatcher(filePath, filter); fileWatcher.Changed += changeAction; fileWatcher.Created += createdAction; fileWatcher.Deleted += deletedAction; fileWatcher.Renamed += renamedAction; fileWatcher.Error += errorAction; fileWatcher.EnableRaisingEvents = true; } catch { fileWatcher.EnableRaisingEvents = false; System.Threading.Thread.Sleep(5000); } } }; return(fileWatcher); }
/// <devdoc> /// </devdoc> protected virtual void Dispose(bool disposing) { try { if (disposing) { //Stop raising events cleans up managed and //unmanaged resources. StopRaisingEvents(); // Clean up managed resources _onChangedHandler = null; _onCreatedHandler = null; _onDeletedHandler = null; _onRenamedHandler = null; _onErrorHandler = null; } else { FinalizeDispose(); } } finally { _disposed = true; } }
public void InitApiHandlers(SuccessEventHandler callbackSuccess = null, ErrorEventHandler callbackError = null) { cbSuccessEvent = callbackSuccess; cbErrorEvent = callbackError; }
public FileSystemWatcher Build(string path, string filter, FileSystemEventHandler changedAction, FileSystemEventHandler createdAction, ErrorEventHandler errorAction) { return fileSystem.SetupFileWatcher(path, filter, changedAction, createdAction, null, null, errorAction); }
public static void WatcherSettings(this FileSystemWatcher watcher, FileSystemEventHandler onCreated, ErrorEventHandler onError) { watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Filter = "*.*"; watcher.Created += onCreated; watcher.InternalBufferSize = 81920; watcher.EnableRaisingEvents = true; watcher.Error += onError; }
public static void FileSystemWatcher_Error() { using (FileSystemWatcher watcher = new FileSystemWatcher()) { var handler = new ErrorEventHandler((o, e) => { }); // add / remove watcher.Error += handler; watcher.Error -= handler; // shouldn't throw watcher.Error -= handler; } }
private async Task SubscribeChannelAsync(Channel channel) { string channelName = channel.Name; ErrorEventHandler errorHandler = null; channel._subscribeCompleted = new SemaphoreSlim(0, 1); try { void SubscribeErrorHandler(object sender, PusherException error) { if ((int)error.PusherCode < 5000) { // If we receive an error from the Pusher cluster then we need to raise a channel subscription error channel._subscriptionError = new ChannelException(ErrorCodes.SubscriptionError, channel.Name, _connection.SocketId, error); if (channel._subscribeCompleted != null) { channel._subscribeCompleted.Release(); } } } channel._subscriptionError = null; errorHandler = SubscribeErrorHandler; Error += errorHandler; string message; if (channel.ChannelType != ChannelTypes.Public) { string jsonAuth; if (Options.Authorizer is IAuthorizerAsync asyncAuthorizer) { if (!asyncAuthorizer.Timeout.HasValue) { // Use a timeout interval that is less than the outer subscription timeout. asyncAuthorizer.Timeout = Options.InnerClientTimeout; } jsonAuth = await asyncAuthorizer.AuthorizeAsync(channelName, _connection.SocketId).ConfigureAwait(false); } else { jsonAuth = Options.Authorizer.Authorize(channelName, _connection.SocketId); } message = CreateAuthorizedChannelSubscribeMessage(channel, jsonAuth); } else { message = CreateChannelSubscribeMessage(channelName); } await _connection.SendAsync(message).ConfigureAwait(false); TimeSpan timeoutPeriod = Options.InnerClientTimeout; if (!await channel._subscribeCompleted.WaitAsync(timeoutPeriod).ConfigureAwait(false)) { throw new OperationTimeoutException(timeoutPeriod, $"{Constants.CHANNEL_SUBSCRIPTION_SUCCEEDED} on {channelName}"); } if (channel._subscriptionError != null) { throw channel._subscriptionError; } } finally { if (errorHandler != null) { Error -= errorHandler; } channel._subscribeCompleted.Dispose(); channel._subscribeCompleted = null; } }
public void ErrorReceivedUnsubscribe(ErrorEventHandler eventHandler) { ErrorReceived -= eventHandler; }
/// <devdoc> /// </devdoc> protected override void Dispose(bool disposing) { try { if (disposing) { //Stop raising events cleans up managed and //unmanaged resources. StopRaisingEvents(); // Clean up managed resources onChangedHandler = null; onCreatedHandler = null; onDeletedHandler = null; onRenamedHandler = null; onErrorHandler = null; readGranted = false; } else { stopListening = true; // Clean up unmanaged resources if (!IsHandleInvalid) { directoryHandle.Close(); } } } finally { this.disposed = true; base.Dispose(disposing); } }
public static FileSystemWatcher OnError(this FileSystemWatcher watcher, ErrorEventHandler errorHandler) { watcher.Error += errorHandler; return(watcher); }
public void SubscribeError(ErrorEventHandler handler) { }
public void EventHandlers_CalledSerially() { using (SerialPort com1 = new SerialPort(TCSupport.LocalMachineSerialInfo.FirstAvailablePortName)) using (SerialPort com2 = new SerialPort(TCSupport.LocalMachineSerialInfo.SecondAvailablePortName)) { PinChangedEventHandler pinChangedEventHandler = new PinChangedEventHandler(com1, false, true); ReceivedEventHandler receivedEventHandler = new ReceivedEventHandler(com1, false, true); ErrorEventHandler errorEventHandler = new ErrorEventHandler(com1, false, true); int numPinChangedEvents = 0, numErrorEvents = 0, numReceivedEvents = 0; int iterationWaitTime = 100; /*************************************************************** * Scenario Description: All of the event handlers should be called sequentially never * at the same time on multiple thread. Basically we will block each event handler caller thread and verify * that no other thread is in another event handler * ***************************************************************/ Debug.WriteLine("Verifying that event handlers are called serially"); com1.WriteTimeout = 5000; com2.WriteTimeout = 5000; com1.Open(); com2.Open(); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); com1.PinChanged += pinChangedEventHandler.HandleEvent; com1.DataReceived += receivedEventHandler.HandleEvent; com1.ErrorReceived += errorEventHandler.HandleEvent; //This should cause ErrorEvent to be fired with a parity error since the //8th bit on com1 is the parity bit, com1 one expest this bit to be 1(Mark), //and com2 is writing 0 for this bit com1.DataBits = 7; com1.Parity = Parity.Mark; com2.BaseStream.Write(new byte[1], 0, 1); Debug.Print("ERROREvent Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause PinChangedEvent to be fired with SerialPinChanges.DsrChanged //since we are setting DtrEnable to true com2.DtrEnable = true; Debug.WriteLine("PinChange Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause ReceivedEvent to be fired with ReceivedChars //since we are writing some bytes com1.DataBits = 8; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 40 }, 0, 1); Debug.WriteLine("RxEvent Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause a frame error since the 8th bit is not set, //and com1 is set to 7 data bits so the 8th bit will +12v where //com1 expects the stop bit at the 8th bit to be -12v com1.DataBits = 7; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 0x01 }, 0, 1); Debug.WriteLine("FrameError Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause PinChangedEvent to be fired with SerialPinChanges.CtsChanged //since we are setting RtsEnable to true com2.RtsEnable = true; Debug.WriteLine("PinChange Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause ReceivedEvent to be fired with EofReceived //since we are writing the EOF char com1.DataBits = 8; com1.Parity = Parity.None; com2.BaseStream.Write(new byte[] { 26 }, 0, 1); Debug.WriteLine("RxEOF Triggered"); Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); //This should cause PinChangedEvent to be fired with SerialPinChanges.Break //since we are setting BreakState to true com2.BreakState = true; Thread.Sleep(TRIGERING_EVENTS_WAIT_TIME); bool threadFound = true; Stopwatch sw = Stopwatch.StartNew(); while (threadFound && sw.ElapsedMilliseconds < MAX_TIME_WAIT) { threadFound = false; for (int i = 0; i < MAX_TIME_WAIT / iterationWaitTime; ++i) { Debug.WriteLine("Event counts: PinChange {0}, Rx {1}, error {2}", numPinChangedEvents, numReceivedEvents, numErrorEvents); Debug.WriteLine("Waiting for pinchange event {0}ms", iterationWaitTime); if (pinChangedEventHandler.WaitForEvent(iterationWaitTime, numPinChangedEvents + 1)) { // A thread is in PinChangedEvent: verify that it is not in any other handler at the same time if (receivedEventHandler.NumEventsHandled != numReceivedEvents) { Fail("Err_191818ahied A thread is in PinChangedEvent and ReceivedEvent"); } if (errorEventHandler.NumEventsHandled != numErrorEvents) { Fail("Err_198119hjaheid A thread is in PinChangedEvent and ErrorEvent"); } ++numPinChangedEvents; pinChangedEventHandler.ResumeHandleEvent(); threadFound = true; break; } Debug.WriteLine("Waiting for rx event {0}ms", iterationWaitTime); if (receivedEventHandler.WaitForEvent(iterationWaitTime, numReceivedEvents + 1)) { // A thread is in ReceivedEvent: verify that it is not in any other handler at the same time if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) { Fail("Err_2288ajed A thread is in ReceivedEvent and PinChangedEvent"); } if (errorEventHandler.NumEventsHandled != numErrorEvents) { Fail("Err_25158ajeiod A thread is in ReceivedEvent and ErrorEvent"); } ++numReceivedEvents; receivedEventHandler.ResumeHandleEvent(); threadFound = true; break; } Debug.WriteLine("Waiting for error event {0}ms", iterationWaitTime); if (errorEventHandler.WaitForEvent(iterationWaitTime, numErrorEvents + 1)) { // A thread is in ErrorEvent: verify that it is not in any other handler at the same time if (pinChangedEventHandler.NumEventsHandled != numPinChangedEvents) { Fail("Err_01208akiehd A thread is in ErrorEvent and PinChangedEvent"); } if (receivedEventHandler.NumEventsHandled != numReceivedEvents) { Fail("Err_1254847ajied A thread is in ErrorEvent and ReceivedEvent"); } ++numErrorEvents; errorEventHandler.ResumeHandleEvent(); threadFound = true; break; } } } if (!pinChangedEventHandler.WaitForEvent(MAX_TIME_WAIT, 3)) { Fail("Err_2288ajied Expected 3 PinChangedEvents to be fired and only {0} occured", pinChangedEventHandler.NumEventsHandled); } if (!receivedEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) { Fail("Err_122808aoeid Expected 2 ReceivedEvents to be fired and only {0} occured", receivedEventHandler.NumEventsHandled); } if (!errorEventHandler.WaitForEvent(MAX_TIME_WAIT, 2)) { Fail("Err_215887ajeid Expected 3 ErrorEvents to be fired and only {0} occured", errorEventHandler.NumEventsHandled); } //[] Verify all PinChangedEvents should have occured pinChangedEventHandler.Validate(SerialPinChange.DsrChanged, 0); pinChangedEventHandler.Validate(SerialPinChange.CtsChanged, 0); pinChangedEventHandler.Validate(SerialPinChange.Break, 0); //[] Verify all ReceivedEvent should have occured receivedEventHandler.Validate(SerialData.Chars, 0); receivedEventHandler.Validate(SerialData.Eof, 0); //[] Verify all ErrorEvents should have occured errorEventHandler.Validate(SerialError.RXParity, 0); errorEventHandler.Validate(SerialError.Frame, 0); // It's important that we close com1 BEFORE com2 (the using() block would do this the other way around normally) // This is because we have our special blocking event handlers hooked onto com1, and closing com2 is likely to // cause a pin-change event which then hangs and prevents com1 from closing. // An alternative approach would be to unhook all the event-handlers before leaving the using() block. com1.Close(); } }
protected void OnError(object sender, ErrorEventArgs args) { ErrorEventHandler onError = Error; onError?.Invoke(sender, args); }