private void _wc_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { bool errorOccured = false; if (e.Error != null) { errorOccured = true; string text = "Error occured while downloading dependency " + _currentDependency.Name + ": \n" + e.Error.Message; if (!_downloadCanceled) { Logger.Log("Error while doanloading dependency: " + _currentDependency.Name, Logger.LogLevel.error); Logger.Log("Error was: " + e.Error.Message, Logger.LogLevel.error); } if (e.Error is System.Net.WebException) { if (_downloadCanceled) { text = null; } else { CancelDownload(); } } Exception ex = null; if (text != null) { ex = new Exception(text); } if (DownloadCanceled != null) { Task.Run(() => DownloadCanceled.Invoke(ex)); } cleanup(); return; } Logger.Log("Download complete: " + _currentDependency.Name); if (_downloadCanceled || errorOccured) { return; } Task.Run(() => { Logger.Log("Extracting dependency: " + _currentDependency.Name); if (ExtractionStarted != null) { Task.Run(() => ExtractionStarted(_currentDependency.Name)); } try { extractDependency(); } catch (Exception ex) { Logger.Log("Error while removing temp directory: " + ex.Message, Logger.LogLevel.error); if (ErrorOccured != null) { Task.Run(() => ErrorOccured.Invoke(ex)); } } }); }
public LocalRawCommandRunner(string command, string arguments) { _processStartInfo = new ProcessStartInfo(command, arguments); _processStartInfo.RedirectStandardError = true; _processStartInfo.RedirectStandardInput = true; _processStartInfo.RedirectStandardOutput = true; _processStartInfo.UseShellExecute = false; _processStartInfo.CreateNoWindow = true; _localProcess = System.Diagnostics.Process.Start(_processStartInfo); _localProcess.Exited += OnProcessExited; _localProcess.EnableRaisingEvents = true; _stdoutWriter = new StreamWriter(_localProcess.StandardInput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 4096, leaveOpen: false); _processReader = _localProcess.StandardOutput; _processError = _localProcess.StandardError; System.Threading.Tasks.Task.Run(() => ReadLoop(_processReader, _cancellationSource.Token, (msg) => { OutputReceived?.Invoke(this, msg); })); System.Threading.Tasks.Task.Run(() => ReadLoop(_processError, _cancellationSource.Token, (msg) => { ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(new Exception(msg))); })); }
internal void OnError(ChatType type, string sender, string error) => ErrorOccured?.Invoke(type, sender, error);
protected void OnErrorOccured() { ErrorOccured?.Invoke(this, new ConnectionMessageEventArgs()); }
protected void OnErrorOccured(Error error) { ErrorOccured?.Invoke(this, error); }
private void OnErrorOccured(string errorMessage) { ErrorOccured?.Invoke(errorMessage); }
private void Poll() { var jObject = new JObject(); jObject["chat_token"] = Token; jObject["usernames"] = JArray.FromObject(AccountData.Users.Where(x => x.Update).Select(x => x.Name).ToArray()); jObject["after"] = LastPollTime + 0.005; try { var response = Requester.PostRequest(Methods.ChatHistory, jObject); var obj = JsonConvert.DeserializeObject(response) as JObject; var chatHistory = new ChatHistory(); var chatObject = obj["chats"] as JObject; foreach (var kvp in chatObject) { foreach (JObject msgObject in kvp.Value as JArray) { var channel = string.Empty; if (msgObject["channel"] != null) { channel = msgObject["channel"].ToString(); } if (msgObject["is_join"] != null) { var presence = new Presence( msgObject["id"].ToString(), double.Parse(msgObject["t"].ToString()), kvp.Key, msgObject["from_user"].ToString(), channel, bool.Parse(msgObject["is_join"].ToString()) ); chatHistory.Push(presence); } else { var message = new Message( msgObject["id"].ToString(), double.Parse(msgObject["t"].ToString()), kvp.Key, msgObject["from_user"].ToString(), channel, msgObject["msg"].ToString() ); chatHistory.Push(message); } } } if (!chatHistory.IsEmpty) { LastPollTime = chatHistory.Last.Timestamp; } while (!chatHistory.IsEmpty) { var element = chatHistory.Pop(); if (element is Presence) { var pres = element as Presence; var channel = AccountData.FindUser(pres.To).FindChannel(pres.Channel); if (channel != null) { if (!pres.Joined) { if (channel.MemberExists(pres.From)) { channel.Members.Remove(pres.From); } } else { if (!channel.MemberExists(pres.From)) { channel.Members.Add(pres.From); } } } PresenceReceived?.Invoke(this, new PresenceEventArgs(pres)); continue; } else if (element is Message) { if (element.From != element.To) { if (!RelayedIDs.Contains(element.ID)) { RelayedIDs.Add(element.ID); MessageReceived?.Invoke(this, new MessageEventArgs(element as Message)); } } else { if (!RelayedIDs.Contains(element.ID)) { RelayedIDs.Add(element.ID); MessageSent?.Invoke(this, new MessageEventArgs(element as Message)); } } if (RelayedIDs.Count > 100) { RelayedIDs.Clear(); } } } } catch (RequestException e) { ErrorOccured?.Invoke(this, new ErrorEventArgs(e)); } }
/// <summary> /// Event procedure: Called when a error occurs on the websocket layer. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnError(object sender, ErrorEventArgs e) { LastException = new NetworkException(e.Message, e.Exception); ErrorOccured?.Invoke(e.Message, e.Exception); }
protected async Task <string> ReceiveTillEnd(CancellationToken ct) { ArraySegment <Byte> buffer = new ArraySegment <byte>(new Byte[8192]); using (var ms = new MemoryStream()) { WebSocketReceiveResult?result = null; do { try { result = await wsAmiVoice.ReceiveAsync(buffer, CancellationToken.None); ms.Write(buffer.ToArray(), 0, result.Count); if (result.CloseStatus != null) { Debug.WriteLine(result.CloseStatusDescription); } if (result.MessageType == WebSocketMessageType.Close) { Debug.WriteLine("WebSocket Close Recieved"); break; } if (ct.IsCancellationRequested) { break; } } catch (WebSocketException ex) { var errStr = String.Format("WebSocketError: {0} - {1}", ex.WebSocketErrorCode, ex.Message); ErrorOccured?.Invoke(this, errStr); Debug.WriteLine(ex.Message); Debug.WriteLine(ex.StackTrace); if (wsAmiVoice.CloseStatus != null) { Debug.WriteLine(wsAmiVoice.CloseStatusDescription); } Debug.WriteLine(ex.WebSocketErrorCode); string temp; try { temp = Encoding.UTF8.GetString(ms.ToArray()); Debug.WriteLine(temp); } catch (Exception encex) when(encex is ArgumentException || encex is ArgumentNullException) { } return(""); } } while ((result == null || result.EndOfMessage != true) && (wsAmiVoice.State == WebSocketState.Open || wsAmiVoice.State == WebSocketState.CloseSent)); var payload = ms.ToArray(); try { var encodedData = System.Text.Encoding.UTF8.GetString(payload); Debug.WriteLine(encodedData); return(encodedData); } catch (Exception ex) when(ex is ArgumentException || ex is ArgumentNullException || ex is DecoderFallbackException) { return(""); } } }
//Call this method from subclasses when an error or exception occurs. /// <summary> /// The FireErrorEvent. /// </summary> /// <param name="sender">The sender<see cref="RFIDData"/>.</param> /// <param name="errorMsg">The errorMsg<see cref="String"/>.</param> /// <param name="exceptionMessage">The exceptionMessage<see cref="String"/>.</param> /// <param name="stackTrace">The stackTrace<see cref="String"/>.</param> protected void FireErrorEvent(RFIDData sender, String errorMsg, String exceptionMessage = null, string stackTrace = null) { ErrorOccured?.Invoke(sender, new ErrorEventArgs(errorMsg, exceptionMessage, stackTrace)); }
private void OnListenerPositionError(object sender, PositionErrorEventArgs e) { StopListening(); ErrorOccured?.Invoke(this, e); }
/// <summary> /// Event procedure: Called, if an error occurs at the websocket layer. /// </summary> /// <param name="e">Message and optional Exception info</param> protected override void OnError(ErrorEventArgs e) { LastException = new NetworkException(e.Message, e.Exception); ErrorOccured?.Invoke(e.Message, e.Exception); }
void OnPositionError(PositionErrorEventArgs e) { StopListening(); ErrorOccured?.Invoke(this, e); }
/// <summary> /// Extracts the current Dependency and informs if it's the last one /// </summary> private void extractDependency() { // extract nuget packages System.IO.Compression.ZipFile.ExtractToDirectory(Path.Combine(TempDirectory, _currentDependency.Name), TempDirectory); // copy files to destination foreach (var sourceDirectory in _currentDependency.SourceDirectories) { string sourceFolder = Path.Combine(TempDirectory, sourceDirectory); if (!Directory.Exists(DestinationDirectory)) { Directory.CreateDirectory(DestinationDirectory); } // copy to correct position var files = Directory.GetFiles(sourceFolder); foreach (var file in files) { if (file.ToLower().EndsWith(".pdb") || file.ToLower().EndsWith(".xml") || file.ToLower().EndsWith(".txt")) { continue; } File.Copy(file, Path.Combine(DestinationDirectory, Path.GetFileName(file)), true); } var dirs = Directory.GetDirectories(sourceFolder); foreach (var dir in dirs) { string dirName = new DirectoryInfo(dir).Name; Common.CopyFolder(dir, Path.Combine(DestinationDirectory, dirName)); } } cleanup(); if (_currentDependency != _allDependencies.Last()) { // download next dependency int index = _allDependencies.IndexOf(_currentDependency); var curDep = _allDependencies[index + 1]; downloadDependency(curDep); } else { // finalize setup copyNecessaryDlls(); string destinationFile = Path.Combine(DestinationDirectory, Path.GetFileName(OwnPath)); if (_copyOwnExecutable) { if (Path.GetFullPath(destinationFile) != Path.GetFullPath(OwnPath)) { try { File.Copy(OwnPath, destinationFile, true); } catch (Exception ex) { if (ErrorOccured != null) { ErrorOccured.Invoke(new Exception("Could not copy main executable, error was: " + ex.Message)); } return; } } } Logger.Log("Setup finished"); if (InstallationFinished != null) { Task.Run(InstallationFinished); } } }
protected virtual void OnErrorOccured(string message) { ErrorOccured?.Invoke(this, message); }
protected async Task MessageLoop(CancellationToken ct) { ProvidingState = ProvidingStateType.Initialized; try { Func <Task <bool> > connectAction = async() => { var connectionResult = await Connect(ct); if (connectionResult.isSuccess == false) { LastErrorString = connectionResult.message; ErrorOccured?.Invoke(this, LastErrorString); return(false); } Trace?.Invoke(this, "Connection complete."); return(true); }; sendQueue.Clear(); CancellationTokenSource receiveTokenSource = new CancellationTokenSource(); CancellationToken receiveToken = receiveTokenSource.Token; Task?receiveTask = null; char[] charsToTrim = { ' ', '\x00' }; while (!ct.IsCancellationRequested) { if (ProvidingState == ProvidingStateType.Initialized || (receiveTask != null && receiveTask.Status == TaskStatus.RanToCompletion)) { Trace?.Invoke(this, "Try to connect."); if (receiveTask != null && receiveTask.Status == TaskStatus.Running) { receiveTokenSource?.Cancel(); await receiveTask; } var connectResult = await connectAction(); if (!connectResult) { break; } receiveTask?.Dispose(); receiveTokenSource = new CancellationTokenSource(); receiveToken = receiveTokenSource.Token; receiveTask = Task.Run(() => ReceiveLoop(receiveToken), receiveToken); } string receiveData; if (receiveQueue.TryDequeue(out receiveData)) { receiveData = receiveData.Trim(charsToTrim); //Debug.WriteLine(String.Format("Recieve: {0}", receiveData)); // セッションタイムアウト等による切断 // 実際は強制的に切断されていたりするのでここを通らなかったりする if (receiveData.StartsWith("p") && receiveData.Length > 3) { Debug.WriteLine("Timeout occured."); Trace?.Invoke(this, receiveData.Substring(1).Trim()); RecognizingState = RecognizingStateType.NotRecognizing; DetectingState = DetectingStateType.NotDetecting; ProvidingState = ProvidingStateType.Initialized; continue; } // エラー処理 if ((receiveData.StartsWith("e") && receiveData.Length > 3)) { LastErrorString = receiveData; ErrorOccured?.Invoke(this, receiveData.Substring(1)); ProvidingState = ProvidingStateType.Error; RecognizingState = RecognizingStateType.NotRecognizing; DetectingState = DetectingStateType.NotDetecting; break; } // 発話区間開始 if (receiveData.StartsWith("S")) { uint startMiliSec; if (uint.TryParse(receiveData.Substring(2), out startMiliSec)) { //Debug.WriteLine(String.Format("S: {0}", receiveData)); VoiceStart?.Invoke(this, startMiliSec); } DetectingState = DetectingStateType.Detecting; } // 発話区間終了 if (receiveData.StartsWith("E")) { uint endMiliSec; if (uint.TryParse(receiveData.Substring(2), out endMiliSec)) { //Debug.WriteLine(String.Format("E: {0}", receiveData)); VoiceEnd?.Invoke(this, endMiliSec); } DetectingState = DetectingStateType.NotDetecting; } // 認識処理開始 if (receiveData.StartsWith("C")) { RecognizingState = RecognizingStateType.Recognizing; RecognizeStarting?.Invoke(this, true); } // 認識処理返却 if (receiveData.StartsWith("U") || receiveData.StartsWith("A")) { try { //Debug.WriteLine(receiveData.Substring(2).Trim()); var result = JsonSerializer.Deserialize <SpeechRecognitionEventArgs>(receiveData.Substring(2), jsonSerializerOptions); if (receiveData.StartsWith("U")) { // 認識途中 Recognizing?.Invoke(this, result); } else if (receiveData.StartsWith("A")) { // 認識終了 Recognized?.Invoke(this, result); RecognizingState = RecognizingStateType.NotRecognizing; } } catch (JsonException ex) { Debug.WriteLine(ex.Message); } } } // 受信が異常終了していないか確認 if (receiveTask != null && receiveTask.Status == TaskStatus.Faulted) { Debug.WriteLine(String.Format("Loop:ReceiveWSException: {0}", receiveTask.Exception.InnerException.Message)); ErrorOccured?.Invoke(this, String.Format("ReceiveTaskException")); break; } // 音声データを送る byte[] sendData; if (wsAmiVoice.State == WebSocketState.Open && sendQueue.TryDequeue(out sendData)) { sendData = prefixC.Concat(sendData).ToArray(); if (sendData.Length == 0) { continue; } try { await wsAmiVoice.SendAsync(sendData, WebSocketMessageType.Binary, true, CancellationToken.None); } catch (Exception ex) when(ex is WebSocketException || ex is IOException) { var sendErrString = String.Format("Send:WebSocketException: {0}", ex.Message); Trace?.Invoke(this, sendErrString); } } } // 終了処理 byte[] endArray = new byte[] { (byte)CommandType.End }; await wsAmiVoice.SendAsync(endArray, WebSocketMessageType.Text, true, CancellationToken.None); string disconnectionStr = ""; while (wsAmiVoice.State == WebSocketState.Open && receiveTask != null && receiveTask.Status == TaskStatus.Running) { if (!receiveQueue.TryDequeue(out disconnectionStr)) { continue; } if (disconnectionStr.StartsWith("e") && disconnectionStr.Length == 1) { receiveTokenSource?.Cancel(); receiveTask.Wait(1000); ProvidingState = ProvidingStateType.Initialized; RecognizingState = RecognizingStateType.NotRecognizing; DetectingState = DetectingStateType.NotDetecting; RecognizeStopped?.Invoke(this, true); } else if (disconnectionStr.StartsWith("e")) { RecognizingState = RecognizingStateType.NotRecognizing; DetectingState = DetectingStateType.NotDetecting; ProvidingState = ProvidingStateType.Error; LastErrorString = disconnectionStr.Substring(2); ErrorOccured?.Invoke(this, LastErrorString); } } if (receiveTokenSource != null && !receiveTokenSource.IsCancellationRequested) { receiveTokenSource.Cancel(); if (receiveTask != null && receiveTask.Status == TaskStatus.Running) { receiveTask.Wait(3000); } } } catch (WebSocketException ex) { ErrorOccured?.Invoke(this, String.Format("Loop:WebSocketException: {0}", ex.Message)); } finally { if (wsAmiVoice.State == WebSocketState.Open) { try { await wsAmiVoice.CloseAsync(WebSocketCloseStatus.NormalClosure, "", CancellationToken.None); } catch (WebSocketException ex) { Debug.WriteLine(String.Format("Close:WebSocketException: {0} - {1}", ex.Message, wsAmiVoice.State.ToString())); } } } Trace?.Invoke(this, "Disconnected."); }
/// <summary> /// Уведомляет слушателей об ошибке на странице /// </summary> /// <param name="error">Содержит информацию об ошибке</param> public void SendError(VKError error) => ErrorOccured?.Invoke(this, error);
/// <summary> /// Invokes "ErrorOccured" to other application's modules. /// </summary> /// <param name="errorMessage">Message of a thrown error.</param> private void ErrorHandler(string errorMessage) { ErrorOccured?.Invoke(this, errorMessage); }
public void RequestMessageHistory() { if (!IsAuthenticated) { throw new InvalidOperationException("Not authenticated. Request/set token first."); } if (AccountData == null) { throw new InvalidOperationException("No account data requested. Request account data first."); } var jObject = new JObject(); jObject["chat_token"] = Token; jObject["usernames"] = JArray.FromObject(AccountData.Users.Where(x => x.Update).Select(x => x.Name).ToArray()); try { var response = Requester.PostRequest(Methods.ChatHistory, jObject); var obj = JsonConvert.DeserializeObject(response) as JObject; var chatHistory = new ChatHistory(); var chatObject = obj["chats"] as JObject; foreach (var kvp in chatObject) { foreach (JObject msgObject in kvp.Value as JArray) { var channel = string.Empty; if (msgObject["channel"] != null) { channel = msgObject["channel"].ToString(); } if (msgObject["is_join"] != null) { var presence = new Presence( msgObject["id"].ToString(), double.Parse(msgObject["t"].ToString()), kvp.Key, msgObject["from_user"].ToString(), channel, bool.Parse(msgObject["is_join"].ToString()) ); chatHistory.Push(presence); } else { var message = new Message( msgObject["id"].ToString(), double.Parse(msgObject["t"].ToString()), kvp.Key, msgObject["from_user"].ToString(), channel, msgObject["msg"].ToString() ); chatHistory.Push(message); } } } LastPollTime = chatHistory.Last.Timestamp; ChatHistoryReceived?.Invoke(this, new ChatHistoryEventArgs(chatHistory)); } catch (RequestException e) { ErrorOccured?.Invoke(this, new ErrorEventArgs(e)); } }
private void ProcessBlog(string linkBlog, DataInput Data, List <BlogInfo> InfoMoreBlogs) { BlogInfo InfoBlog = new BlogInfo(); InfoBlog.InfoSingeBlogs = new List <ArticleInfo>(); InfoBlog.hrefBlogs = linkBlog; HtmlWeb web = new HtmlWeb(); int check = 0; HtmlDocument htmlDoc = null; while (check >= 0) { try { htmlDoc = web.Load(linkBlog); check = -1; } catch { check++; if (check >= 4) { ErrorOccured?.Invoke(this, String.Format(_unableConnect, linkBlog)); return; } } } HtmlNodeCollection nodes = htmlDoc.DocumentNode.SelectNodes(_title); List <string> links = new List <string>(); if (nodes == null) { return; } int pagesCount = 0; if (Data.searchDepth == -1) { Data.searchDepth = Int32.MaxValue; } while (nodes != null && pagesCount < Data.searchDepth) { foreach (HtmlNode node in nodes) { links.Add(node.Attributes[_atrib].Value); } foreach (var element in ProcessArticleLinks(links)) { InfoBlog.InfoSingeBlogs.Add(element); } links.Clear(); nodes = null; var nextPage = htmlDoc.DocumentNode.SelectSingleNode(_next_page); if (nextPage == null || nextPage.Attributes[_atrib] == null) { break; } check = 0; while (check >= 0) { try { htmlDoc = web.Load(_start_page + nextPage.Attributes[_atrib].Value); check = -1; } catch { check++; if (check >= 4) { ErrorOccured?.Invoke(this, String.Format(_unableConnect, nextPage.Attributes[_atrib].Value)); break; } } } nodes = htmlDoc.DocumentNode.SelectNodes(_title); pagesCount++; } InfoMoreBlogs.Add(InfoBlog); StatusProcessing?.Invoke(this, String.Format("The unit successfully processed : {0}", linkBlog)); return; ////// }
public static void Error(Exception ex, [CallerMemberName] string member = "") { ErrorOccured?.Invoke(null, ex.Message + " => " + member); }
private void OnError(object sender, liblinux.ErrorOccuredEventArgs e) { ErrorOccured?.Invoke(sender, new ErrorOccuredEventArgs(e.Exception)); }
private void OnConnectionErrorOccured(object source, ConnectionMessageEventArgs e) { ErrorOccured?.Invoke(source, e); }
void OnErrorOccured(Exception obj) { ErrorOccured?.Invoke(obj); }
private void OnErrorOutput(object sender, DataReceivedEventArgs e) { ErrorOccured?.Invoke(sender, new ErrorOccuredEventArgs(new Exception(e.Data))); }
protected void OnErrorOccured(int code, string description) { ErrorOccured?.Invoke(this, code, description); }
private void WebSocket_ErrorOccured(object sender, ErrorEventArgs e) { ErrorOccured?.Invoke(this, e.Exception); }
void HandleError(string error) { // Stop the timer when an error is encoutered Enabled = false; ErrorOccured?.Invoke(error); }
async Task DoRecord() { try { var frameInterval = TimeSpan.FromSeconds(1.0 / _frameRate); var frameCount = 0; Task <IBitmapFrame> task = null; // Returns false when stopped bool AddFrame(IBitmapFrame Frame) { try { _frames.Add(Frame); ++frameCount; return(true); } catch (InvalidOperationException) { return(false); } } bool CanContinue() { try { return(_continueCapturing.WaitOne()); } catch (ObjectDisposedException) { return(false); } } while (CanContinue() && !_frames.IsAddingCompleted) { var timestamp = DateTime.Now; if (task != null) { var frame = await task; if (!AddFrame(frame)) { return; } var requiredFrames = _sw.Elapsed.TotalSeconds * _frameRate; var diff = requiredFrames - frameCount; for (var i = 0; i < diff; ++i) { if (!AddFrame(RepeatFrame.Instance)) { return; } } } task = Task.Factory.StartNew(() => _imageProvider.Capture()); var timeTillNextFrame = timestamp + frameInterval - DateTime.Now; if (timeTillNextFrame > TimeSpan.Zero) { Thread.Sleep(timeTillNextFrame); } } } catch (Exception E) { ErrorOccured?.Invoke(E); Dispose(false, true); } }
private void timer1_Tick(object sender) { try { var task = ServiceConfig.Default.GetTask(fromPath.Path, toPath.Path); if (task != null) { if (!task.IsEnabled) //first check if task become disabled { Stop(); IsRunning = false; return; } fromPath = task.From; toPath = task.To; Schduletask = task.ScheduleTask; } bool CanRunNow = false, MustStop = false; if (Schduletask == null || !Schduletask.IsEnabled) { if (IsRunning) { return; } CanRunNow = true; } else if (Schduletask != null && Schduletask.IsEnabled) { if (Schduletask.EndTime.HasValue)// if schduled enabled then check the end time { switch (Schduletask.EndTime_Type) { case EndOnType.SameStartTime: if (!LastRunOn.HasValue && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) //didn't run yet { MustStop = true; } else if (LastRunOn.HasValue && DateTime.Now.Date >= LastRunOn.Value.Date && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) { MustStop = true; } break; case EndOnType.NextDay: if (!LastRunOn.HasValue && DateTime.Now.Date >= Schduletask.EndTime.Value.Date.AddDays(1) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) //didn't run yet { MustStop = true; } else if (LastRunOn.HasValue && DateTime.Now.Date >= LastRunOn.Value.Date.AddDays(1) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) { MustStop = true; } break; case EndOnType.After_2_days: if (!LastRunOn.HasValue && DateTime.Now.Date >= Schduletask.EndTime.Value.Date.AddDays(2) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) //didn't run yet { MustStop = true; } else if (LastRunOn.HasValue && DateTime.Now.Date >= LastRunOn.Value.Date.AddDays(2) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) { MustStop = true; } break; case EndOnType.After_3_days: if (!LastRunOn.HasValue && DateTime.Now.Date >= Schduletask.EndTime.Value.Date.AddDays(3) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) //didn't run yet { MustStop = true; } else if (LastRunOn.HasValue && DateTime.Now.Date >= LastRunOn.Value.Date.AddDays(3) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) { MustStop = true; } break; case EndOnType.After_5_days: if (!LastRunOn.HasValue && DateTime.Now.Date >= Schduletask.EndTime.Value.Date.AddDays(5) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) //didn't run yet { MustStop = true; } else if (LastRunOn.HasValue && DateTime.Now.Date >= LastRunOn.Value.Date.AddDays(5) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) { MustStop = true; } break; case EndOnType.After_7_days: if (!LastRunOn.HasValue && DateTime.Now.Date >= Schduletask.EndTime.Value.Date.AddDays(7) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) //didn't run yet { MustStop = true; } else if (LastRunOn.HasValue && DateTime.Now.Date >= LastRunOn.Value.Date.AddDays(7) && Schduletask.EndTime.Value.TimeOfDay <= DateTime.Now.TimeOfDay) { MustStop = true; } break; default: break; } if (MustStop) { Stop(); return; } } switch (Schduletask.Triggertype) { case TriggerType.Daily: if (DateTime.Now >= Schduletask.StartTime) { if (!LastRunOn.HasValue) { CanRunNow = true; } else if (LastRunOn.HasValue && LastRunOn.Value.Date != DateTime.Now.Date) { CanRunNow = true; } } break; case TriggerType.Weekly: if (DateTime.Now.DayOfWeek == Schduletask.StartTime.DayOfWeek && (DateTime.Now.Hour >= Schduletask.StartTime.Hour || (DateTime.Now.Hour == Schduletask.StartTime.Hour && DateTime.Now.Minute >= Schduletask.StartTime.Minute))) { CanRunNow = true; } break; case TriggerType.Monthly: if (DateTime.Now.Day == Schduletask.StartTime.Day && (DateTime.Now.Hour >= Schduletask.StartTime.Hour || (DateTime.Now.Hour == Schduletask.StartTime.Hour && DateTime.Now.Minute >= Schduletask.StartTime.Minute))) { CanRunNow = true; } break; default: break; } } if (CanRunNow && !IsRunning) { thrd = new Thread(RunRoboCopyProcess); thrd.Start(); } } catch (Exception er) { ErrorOccured?.Invoke(this, er); } finally { // have the timer starts in 1 second, and then fire once every min timer1.Change(TIME_INTERVAL_IN_MILLISECONDS, Timeout.Infinite); } }