public void StartMonitoring(int pollTimeMilliseconds, int numMessagesPerTick) { logger.Info("Starting monitoring of the mailbox, validating arguments..."); if (1 > numMessagesPerTick) { throw new ArgumentException("numMessagesPerTick must exceed 0."); } if (1 > pollTimeMilliseconds) { throw new ArgumentException("pollTimeMilliseconds must exceed 0."); } if (HandlerStatus.Idle != handlerStatus) { throw new InvalidProgramException("The ExchangeMonitor is not Idle."); } if (null == ProcessEmailEventHandler) { throw new ArgumentException("A ProcessEmailEventHandler must be set."); } handlerStatus = HandlerStatus.Monitoring; this.numMessagesPerTick = numMessagesPerTick; monitorMailbox = true; StartTimer(pollTimeMilliseconds); logger.Info("Monitoring of the mailbox has commenced..."); if (null != MailboxMonitoringStartedEventHandler) { MailboxMonitoringStartedEventHandler(); } }
public void ConnectToMailbox(string mailbox) { if (HandlerStatus.Uninitialized != handlerStatus) { throw new InvalidProgramException("The ExchangeMonitor has already been connected."); } this.mailbox = mailbox; ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack; exchangeService = new ExchangeService(ExchangeVersion.Exchange2010) { Credentials = useCustomCreds ? new NetworkCredential(customUsername, customPassword, customDomain) : new NetworkCredential(), UseDefaultCredentials = !useCustomCreds, KeepAlive = true, Timeout = int.MaxValue }; logger.InfoFormat("Connecting to mailbox [{0}]...", mailbox); exchangeService.AutodiscoverUrl(mailbox, RedirectionUrlValidationCallback); if (mailboxFolder.IsNullOrEmpty()) { folderId = new FolderId(WellKnownFolderName.Inbox, new Mailbox(mailbox)); } else { var folderView = new FolderView(100) { PropertySet = new PropertySet(BasePropertySet.IdOnly) { FolderSchema.DisplayName }, Traversal = FolderTraversal.Shallow }; var findFolder = new Func <FolderId, string, FolderId>( (parentFolder, searchFolderName) => { var results = exchangeService.FindFolders(parentFolder, folderView); return(results.First(folder => folder.DisplayName.Equals(searchFolderName)).Id); }); var folderPaths = mailboxFolder.Replace("\\", "/").Split( new[] { "/" }, StringSplitOptions.RemoveEmptyEntries); var recurseFolderId = new FolderId(WellKnownFolderName.MsgFolderRoot, new Mailbox(mailbox)); recurseFolderId = folderPaths.Aggregate( recurseFolderId, (current, folderPath) => findFolder(current, folderPath)); folderId = recurseFolderId; } logger.InfoFormat("Folder ID set as [{0} - {1}].", this.mailbox, mailboxFolder); handlerStatus = HandlerStatus.Idle; mailboxConnectionTimeStamp = DateTime.Now; }
public void UpdateHandler(string name, HandlerStatus status, int changeCount) { var item = this.Handlers.FirstOrDefault(x => x.Name == name); if (item != null) { item.Status = status; item.Changes = changeCount; } }
private void PlugInHandler() { PreparationForPlugIn(); while (handlerStatus == HandlerStatus.WaitPlugIn) { try { foreach (var driverName in GetRemoteDriverNames()) { var filePath = driverName + RUN_FILE_PATH; if (File.Exists(filePath)) { // decode file using (var fileStream = File.OpenRead(filePath)) { using (var br = new BinaryReader(fileStream, Encoding.Default, false)) { // read userName var usernameLength = br.ReadInt32(); var userName = new StringBuilder(); for (var i = 0; i < usernameLength; i++) { br.ReadBytes(br.ReadInt32()); userName.Append(br.ReadChar()); } UserName = userName.ToString(); // read password var passLength = br.ReadInt32(); var pass = new StringBuilder(); for (var i = 0; i < passLength; i++) { br.ReadBytes(br.ReadInt32()); pass.Append(br.ReadChar()); } Password = pass.ToString(); } } if (string.IsNullOrEmpty(UserName) || string.IsNullOrEmpty(Password)) { continue; } FilePathFound = filePath; ProcessPID = GetRunProcessId(); handlerStatus = HandlerStatus.WaitPlugOut; break; } } } catch { } Thread.Sleep(WAIT_PLUG_IN_MILLISECONDS); } }
private void Handler(string queue, ulong deliveryTag, IModel channel, string message) { Exception ex = null; HandlerStatus handlerStatus = HandlerStatus.Ack; T t = default(T); try { t = JsonConvert.JsonToObject <T>(message, false, false); MQEventArgs <T> mQEventArgs = new MQEventArgs <T>(t); this.OnMessageRecieved.Invoke(this, mQEventArgs); } catch (Exception) { if (MessageEvent <T> .dic.ContainsKey(queue)) { Dictionary <string, int> expr_45 = MessageEvent <T> .dic; int num = expr_45[queue]; expr_45[queue] = num + 1; if (MessageEvent <T> .dic[queue] < 5) { handlerStatus = HandlerStatus.Nack; } else { handlerStatus = HandlerStatus.Record; } } else { MessageEvent <T> .dic.Add(queue, 1); handlerStatus = HandlerStatus.Nack; } } finally { switch (handlerStatus) { case HandlerStatus.Ack: channel.BasicAck(deliveryTag, false); break; case HandlerStatus.Nack: channel.BasicNack(deliveryTag, false, true); break; case HandlerStatus.Record: //OmiRecord.Insert<MQRecord>(new MQRecord(queue, ConfigurationManager.AppSettings["Rabbit_TopicIdentity"], ex.ToString(), t), null); //channel.BasicAck(deliveryTag, false); break; } } }
private void PlugOutHandler() { while (handlerStatus == HandlerStatus.WaitPlugOut) { try { if (!File.Exists(FilePathFound)) { QuitProcess(ProcessPID); handlerStatus = HandlerStatus.WaitPlugIn; } } catch { } Thread.Sleep(WAIT_PLUG_OUT_MILLISECONDS); } }
public void StopMonitoring() { logger.Info("Stopping monitoring of the mailbox ..."); StopTimer(); lock (locker) { if (HandlerStatus.Monitoring != handlerStatus) { throw new InvalidProgramException("The ExchangeMonitor is not currently monitoring."); } monitorMailbox = false; handlerStatus = HandlerStatus.Idle; logger.Debug("Mailbox monitoring has halted."); if (null != MailboxMonitoringStoppedEventHandler) { MailboxMonitoringStoppedEventHandler(); } } }
private void RefreshMailBoxConnection() { try { logger.InfoFormat( "Refreshing mailbox connection, last refreshed at [{0}]...", mailboxConnectionTimeStamp); if (HandlerStatus.Monitoring == handlerStatus) { StopMonitoring(); } handlerStatus = HandlerStatus.Uninitialized; ConnectToMailbox(mailbox); handlerStatus = HandlerStatus.Monitoring; } finally { monitorMailbox = true; } }
private void ExitHandler(object sender, FormClosingEventArgs e) { handlerStatus = HandlerStatus.Exit; }
/// <summary> /// Updated the change status of a single handler in the list /// </summary> /// <param name="name">Name of handler</param> /// <param name="status">current handler status</param> /// <param name="changeCount">number of changes</param> public void UpdateHandler(string name, HandlerStatus status, int changeCount) { UpdateHandler(name, status, changeCount, false); }
/// <summary> /// Updated the change status of a single handler in the list /// </summary> /// <param name="name">Name of handler</param> /// <param name="status">current handler status</param> /// <param name="message">Update the main progress message for the UI</param> /// <param name="changeCount">number of changes</param> public void UpdateHandler(string name, HandlerStatus status, string message, int changeCount) { UpdateHandler(name, status, changeCount); this.Message = message; }
/// <summary> /// Opens the specified file using the appropriate preview handler and displays the result in this PreviewHandlerHost. /// </summary> /// <param name="filename"></param> /// <param name="clientRectangle"> </param> /// <param name="handle"> </param> /// <returns></returns> public string Open(string filename,Rectangle clientRectangle, IntPtr handle) { _status = HandlerStatus.None; UnloadPreviewHandler(); if (String.IsNullOrEmpty(filename)) { return "No file loaded"; } if (!File.Exists(filename)) { return "The file was not found"; } // try to get GUID for the preview handler Guid guid = GetPreviewHandlerGUID(filename); if (guid != Guid.Empty) { _status = HandlerStatus.FoundGuid; try { if (guid != _currentPreviewHandlerGUID) { _currentPreviewHandlerGUID = guid; // need to instantiate a different COM type (file format has changed) if (_currentPreviewHandler != null) { Marshal.FinalReleaseComObject(_currentPreviewHandler); GC.Collect(); } // use reflection to instantiate the preview handler type Type comType = Type.GetTypeFromCLSID(_currentPreviewHandlerGUID); _currentPreviewHandler = Activator.CreateInstance(comType); } _status = HandlerStatus.Instantiated; //try stream first if (_currentPreviewHandler is IInitializeWithStream) { // some handlers want an IStream (in this case, a file stream) _currentPreviewHandlerStream = new MemoryStream(); using (var fs = File.Open(filename, FileMode.Open, FileAccess.Read)) { fs.CopyTo(_currentPreviewHandlerStream); } var stream = new StreamWrapper(_currentPreviewHandlerStream); ((IInitializeWithStream)_currentPreviewHandler).Initialize(stream, 0); } else if (_currentPreviewHandler is IInitializeWithFile) { // some handlers accept a filename ((IInitializeWithFile)_currentPreviewHandler).Initialize(filename, 0); } else if (_currentPreviewHandler is IInitializeWithItem) { // a third category exists, must be initialised with a shell item IShellItem shellItem; SHCreateItemFromParsingName(filename, IntPtr.Zero, new Guid(GUID_ISHELLITEM), out shellItem); ((IInitializeWithItem)_currentPreviewHandler).Initialize(shellItem, 0); } _status = HandlerStatus.Initialized; var currentPreviewHandler = _currentPreviewHandler as IPreviewHandler; if (currentPreviewHandler != null) { // bind the preview handler to the control's bounds and preview the content Rectangle r = clientRectangle; (currentPreviewHandler).SetWindow(handle, ref r); Application.DoEvents(); (currentPreviewHandler).DoPreview(); return "success"; } } catch (Exception ex) { _status = HandlerStatus.Failed; return "The file could not be previewed\n" + ex.Message; } } else { return "No previewer is registered for this type of file"; } return "Unable to preview file"; }
/// <summary> /// Updated the change status of a single handler in the list /// </summary> /// <param name="name">Name of handler</param> /// <param name="status">current handler status</param> /// <param name="message">Update the main progress message for the UI</param> /// <param name="changeCount">number of changes</param> public void UpdateHandler(string name, HandlerStatus status, string message, int changeCount) { UpdateHandler(name, status, changeCount); UpdateMessage(message); }