public void SimulateNewMail(String from, String to, String subject) { //Объект для хранения инфорамации, которую необходимо передать NewMailEventArgs e = new NewMailEventArgs(from, to, subject); //Уведомление о событии OnNewMail(e); }
private void FaxMsg(Object sender, NewMailEventArgs e) { // 'sender' нам нужен, если хотим с ним еще пообщаться. // 'e' доп инфо для нас // Типа отправка факса Console.WriteLine("Faxing mail message: "); Console.WriteLine(" From=_{0}, To={1}, Subject={2}", e.From, e.To, e.Subject); }
// This is the method that the MailManager will call // when a new e-mail message arrives private void SendMsgToPager(Object sender, NewMailEventArgs e) { // 'sender' identifies the MailManager in case we want to communicate back to it. // 'e' identifies the additional event information that the MailManager wants to give us. // Normally, the code here would send the e-mail message to a pager. // This test implementation displays the info on the console Console.WriteLine("Sending mail message to pager:"); Console.WriteLine(" From={0}, To={1}, Subject={2}", e.From, e.To, e.Subject); }
// Этап 4. Определение метода, преобразующего входную // информацию в желаемое событие public void SimulateNewMail(String from, String to, String subject) { // Создать объект для хранения информации, которую // нужно передать получателям уведомления NewMailEventArgs e = new NewMailEventArgs(from, to, subject); // Вызвать виртуальный метод, уведомляющий объект о событии // Если ни один из производных типов не переопределяет этот метод, // объект уведомит всех зарегистрированных получателей уведомления OnNewMail(e); }
// Step #4: Define a method that translates the // input into the desired event public void SimulateNewMail(String from, String to, String subject) { // Construct an object to hold the information we wish // to pass to the receivers of our notification NewMailEventArgs e = new NewMailEventArgs(from, to, subject); // Call our virtual method notifying our object that the event // occurred. If no type overrides this method, our object will // notify all the objects that registered interest in the event OnNewMail(e); }
public event EventHandler <NewMailEventArgs> NewMail; //Событие //Метод, ответственный за уведомление protected virtual void OnNewMail(NewMailEventArgs e) { //Сохранить поле делегата во временное поле для обеспечения безопасности потоков EventHandler <NewMailEventArgs> temp = NewMail; //Если есть объекты, уведомить их if (temp != null) { temp(this, e); } }
// MailManager вызывает этот метод для уведомления // объекта Fax о прибытии нового почтового сообщения private void FaxMsg(Object sender, NewMailEventArgs e) { // 'sender' используется для взаимодействия с объектом MailManager, // если потребуется передать ему какую-то информацию // 'e' определяет дополнительную информацию о событии, // которую пожелает предоставить MailManager // Обычно расположенный здесь код отправляет сообщение по факсу // Тестовая реализация выводит информацию на консоль Console.WriteLine("Faxing mail message:"); Console.WriteLine(" From={0}, To={1}, Subject={2}", e.From, e.To, e.Subject); }
// Этап 3. Определение метода, ответственного за уведомление // зарегистрированных объектов о событии // Если этот класс изолированный, нужно сделать метод закрытым // или невиртуальным protected virtual void OnNewMail(NewMailEventArgs e) { // Сохранить ссылку на делегата во временной переменной // для обеспечения безопасности потоков EventHandler <NewMailEventArgs> temp = Volatile.Read(ref NewMail); // Если есть объекты, зарегистрированные для получения // уведомления о событии, уведомляем их if (temp != null) { temp(this, e); } }
// Méthode appelée sur nouveau mail private void newActionOutlook(object sender, NewMailEventArgs e) { if (invokeControl.InvokeRequired) { invokeControl.Invoke(new NewMailEventHandler(newActionOutlook), new object[] { sender, e }); } else // Demande d'ajout de mail à une action { TLaction action = new TLaction(); action.Texte = e.Mail.Titre; action.addPJ(e.Mail); new ManipAction(action).Show(); } }
// This is the method the MailManager will call // when a new e-mail message arrives private void FaxMsg(Object sender, NewMailEventArgs e) { // 'sender' identifies the MailManager object in case // we want to communicate back to it. // 'e' identifies the additional event information // the MailManager wants to give us. // Normally, the code here would fax the e-mail message. // This test implementation displays the info in the console Console.WriteLine("Faxing mail message:"); Console.WriteLine(" From={0}, To={1}, Subject={2}", e.From, e.To, e.Subject); }
// Тот самый метод, который возбуждает событие. Можно сделать private virtual, если бы наш MailManager был sealed protected virtual void OnNewMail(NewMailEventArgs e) { #if CompilerImplementedEventMethods EventHandler <NewMailEventArgs> temp = Volatile.Read(ref NewMail); #else EventHandler <NewMailEventArgs> temp = Volatile.Read(ref m_NewMail); #endif // Если кто-то подписался на эвент - уведомим их if (temp != null) { temp(this, e); } }
// Gestion de l'arrivée des mails private void addMail(object sender, NewMailEventArgs e) { if (linksView.InvokeRequired) // Gestion des appels depuis un autre thread { linksView.Invoke(new NewMailEventHandler(addMail), new object[] { sender, e }); } else { this.addMailRequested = false; this.addPJToForm(e.Mail); // Ajout de mail à l'action this.AddMailLabel.Visible = false; // Disparition du label de statut this.addLinkBut.Visible = true; this.addMailBut.Visible = true; OutlookIF.Instance.NewMail -= new NewMailEventHandler(addMail); // Inscription à l'event NewMail } }
private void FaxMsg(Object sender, NewMailEventArgs e) { try { MailMenager mm = (MailMenager)sender; Console.WriteLine("факс получил сообщение: "); Console.WriteLine("From: {0}, To: {1}, Subject: {2}", e.From, e.To, e.Subject); mm.SimulateNewMail("a", "b", "c"); } catch (StackOverflowException ex) { MailMenager mm = (MailMenager)sender; Unregister(mm); Console.WriteLine("Отписались"); } }
// Step #3: Define a method responsible for raising the event // to notify registered objects that the event has occurred // If this class is sealed, make this method private and nonvirtual protected virtual void OnNewMail(NewMailEventArgs e) { // Copy a reference to the delegate field now into a temporary field for thread safety //e.Raise(this, ref m_NewMail); #if CompilerImplementedEventMethods EventHandler <NewMailEventArgs> temp = Volatile.Read(ref NewMail); #else EventHandler <NewMailEventArgs> temp = Volatile.Read(ref m_NewMail); #endif // If any methods registered interest with our event, notify them if (temp != null) { temp(this, e); } }
public void SimulateNewMail(string from, string to, string subject) { NewMailEventArgs e = new NewMailEventArgs(from, to, subject); OnNewMail(e); }
protected virtual void OnNewMail(NewMailEventArgs e) { e.Raise(this, ref NewMail); }
private void CheckUnhandledMail() { _config.Tracer?.TraceVerbose($"Checking for new UIDs", $"{this}"); var uids = _imapClient.GetUis(); var unhandledUids = uids.Where(uid => uid.Id > LastHandledUid).OrderBy(uid => uid.Id).ToList(); int maxMailPerBatch = int.MaxValue; while (unhandledUids.Count > 0) { maxMailPerBatch = Math.Min(maxMailPerBatch, unhandledUids.Count); var unhandledUidsBatch = unhandledUids.GetRange(0, maxMailPerBatch); _config.Tracer?.TraceVerbose($"Getting message summaries for a new batch of {maxMailPerBatch} mails", $"{this}"); IList <IMessageSummary> messages; try { messages = _imapClient.GetFullMessagesSummaries(unhandledUidsBatch); } catch (Exception e) { _config.Tracer?.TraceError($"An error has occured while getting full messages summaries - {e}", $"{this}"); if (maxMailPerBatch > 1) { // try again but fetch only 1 message at a time maxMailPerBatch = 1; continue; } messages = new List <IMessageSummary>(); } NewMessageBatchStarting?.Invoke(this, new BatchEventArgs(new MailSimpleSmtpActuator(_smtpClient), _config.Tracer)); foreach (var message in messages) { _config.Tracer?.TraceVerbose($"New mail with subject -> {message.Envelope.Subject}", $"{this}"); var newMessageEvent = new NewMailEventArgs(message, new MailActuator(_imapClient, _smtpClient), _config.Tracer); try { //MulticastDelegate m = (MulticastDelegate)myEvent; ////Then you can get the delegate list... //Delegate [] dlist = m.GetInvocationList(); ////and then iterate through to find and invoke the ones you want... //foreach(Delegate d in dlist) //{ // if(aListOfObjects.Contains(d.Target)) // { // object [] p = { /*put your parameters here*/ }; // d.DynamicInvoke(p); // } // else // MessageBox.Show("Not Invoking the Event for " + d.Target.ToString() + ":" + d.Target.GetHashCode().ToString()); //} NewMessage?.Invoke(this, newMessageEvent); } catch (Exception e) { _config.Tracer?.TraceError($"An error has occured in the {nameof(NewMessage)} event handler - {e}", $"{this}"); } try { if (newMessageEvent.ToDelete) { _config.Tracer?.TraceVerbose($"Deleting message -> {message.Envelope.Subject}", $"{this}"); _imapClient.DeleteMessage(new List <UniqueId> { message.UniqueId }); } else if (!string.IsNullOrEmpty(newMessageEvent.MoveToSubfolder)) { _config.Tracer?.TraceVerbose($"Moving message to {newMessageEvent.MoveToSubfolder} for subject -> {message.Envelope.Subject}", $"{this}"); _imapClient.MoveMessagesToInboxSubFolder(new List <UniqueId> { message.UniqueId }, newMessageEvent.MoveToSubfolder); } } catch (Exception e) { _config.Tracer?.TraceError($"An error has occured after the {nameof(NewMessage)} event handler - {e}", $"{this}"); } LastHandledUid = message.UniqueId.Id; } NewMessageBatchEnding?.Invoke(this, new BatchEventArgs(new MailSimpleSmtpActuator(_smtpClient), _config.Tracer)); unhandledUids.RemoveRange(0, maxMailPerBatch); } }
private void SendMsgToPager(Object sender, NewMailEventArgs e) { Console.WriteLine("Sending mail message to pager:"); Console.WriteLine(" From={0}, To={1}, Subject={2}", e.From, e.To, e.Subject); }
private void FaxMsg(Object sender, NewMailEventArgs e) { Console.WriteLine("Faxing main messager:"); Console.WriteLine("From={0}, To={1}, Subject={2}", e.From, e.To, e.Subject); }
public void SimulateNewMail(String from, String to, String subject) { NewMailEventArgs e = new NewMailEventArgs(from, to, subject); OnNewMail(e); }
protected virtual void OnNewMail(NewMailEventArgs e) { EventHandler<NewMailEventArgs> temp = Interlocked.CompareExchange(ref NewMail, null, null); if (temp != null) temp(this, e); }