I have created a separate class to handle mail sending. To make it hassle free from future changes I have used dependency injection to design it. Now, when I try to use SendMessageAsync() method, I want to check SendMailCompleted event to see status of message sent failed/succeeded. I am confused how I'm supposed to implement the event in the class that is implementing it. Without mentioning this event in the interface I won't be able to catch it in the injection class. Can any one suggest how to solve this? My interface looks like as follows  public interface IMailing {     string Host { get; set; }     int Port { get; set; }     Task SendMailAsync(string toAddress, string subject, string body);      event SendCompletedEventHandler OnEmailSendComplete; }   The class that is implementing the interface is as follows -  public class Mailing : IMailing {     private SmtpClient client = new SmtpClient();     MailMessage mm = null;      public string Host{ get;  set; }     public int Port { get; set; }  // do i need this? without event being in the interface I would have had this //two following lines to manually raise the event      public event SendCompletedEventHandler OnEmailSendComplete;      public delegate void SendCompletedEventHandler(object source, AsyncCompletedEventArgs e);    // following lines were generated from the vs2017 IDE // how do I use it when actual Send mail completed event fires?     event System.Net.Mail.SendCompletedEventHandler IMailing.OnEmailSendComplete     {         add         {             throw new NotImplementedException();         }          remove         {             throw new NotImplementedException();         }     }      public async Task SendMailAsync(string toAddress, string subject, string body)     {                     mm = new MailMessage(User, toAddress, subject, body);         client.SendCompleted += Client_SendCompleted;         await client.SendMailAsync(mm).ConfigureAwait(false);     }      private void Client_SendCompleted(object sender, AsyncCompletedEventArgs e)     {         OnEmailSendComplete?.Invoke(sender, e);     } }   Now, the injection class uses constructor injection, which looks like follows -  public class MailingInjection {     IMailing mailing = null;      private MailingInjection()     { }     public MailingInjection(IMailing imail)     {         mailing = imail;     }                    public async Task SenMailAsync(string to, string subject, string body)     {         mailing.OnEmailSendComplete += EmailSendCompleted;         await mailing.SendMailAsync(to, subject,body).ConfigureAwait(false);        }      private void EmailSendCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)     {         mailing.OnEmailSendComplete -= EmailSendCompleted;     } }   I tried to put as less code as possible to explain my confusion so this code will not work in real scenarios but has the structure I believe. Please let me know if I have over exaggerated it. I appreciate any help.
120463
I have a problem: imagine I have a plugin-based system.  I need some kind of interface with which I could catch events from every plugin, which implements for example IReporting interface.  (IReporting) object.OnSomeEvent += &lt;.....&gt;   But I can't find a way to do that.
56379
I'm writing a wrapper class for a command line executable.  This exe accepts input from stdin until I hit Ctrl+C in the command prompt shell, in which case it prints output to stdout based on the input.  I want to simulate that Ctrl+C press in C# code, sending the kill command to a .NET Process object.  I've tried calling Process.Kill(), but that doesn't seem to give me anything in the process's StandardOutput StreamReader.  Might there be anything I'm not doing right?  Here's the code I'm trying to use:  ProcessStartInfo info = new ProcessStartInfo(exe, args); info.RedirectStandardError = true; info.RedirectStandardInput = true; info.RedirectStandardOutput = true; info.UseShellExecute = false; Process p = Process.Start(info);  p.StandardInput.AutoFlush = true; p.StandardInput.WriteLine(scriptcode);  p.Kill();  string error = p.StandardError.ReadToEnd(); if (!String.IsNullOrEmpty(error))  {     throw new Exception(error); } string output = p.StandardOutput.ReadToEnd();   The output is always empty, even though I get data back from stdout when I run the exe manually.  Edit: This is C# 2.0 by the way.
36484
I'm trying to implement a KeyListener for my JFrame. On the constructor, I'm using this code:  System.out.println("test"); addKeyListener(new KeyListener() {     public void keyPressed(KeyEvent e) { System.out.println( "tester"); }      public void keyReleased(KeyEvent e) { System.out.println("2test2"); }      public void keyTyped(KeyEvent e) { System.out.println("3test3"); } });   When I run it, the test message comes up in my console. However, when I press a key, I don't get any of the other messages, as if the KeyListener was not even there.  I was thinking that it could be because the focus is not on the JFrame and so they KeyListener doesn't receive any events.  But, I'm pretty sure it is.  Is there something that I am missing?
101111
We've had a community deployment and my brain is fried and I just whipped up a quick class that is throwing the below error. What have I done wrong here?     Error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, MSI_UserTrigger:   execution of AfterInsert caused by: System.StringException: Invalid   id: () : [] () : []: ()   What I am trying to accomplish is:   When a new user is created and is active, if they are linked to a ContactId and part of a specific profile (by name), add their ContactId to a Set&lt;ID> Then loop through contacts where the Id is in the set, and update the Community_User__c field to TRUE      Trigger:   trigger MSI_UserTrigger on User (after insert) {       if(Trigger.isAfter){          if(Trigger.isInsert){              MSIUserTriggerHandler.executeAfterInsert(Trigger.new);          }      } }      Class:   public with sharing class MSIUserTriggerHandler {     private static final String COMMUNITY_PROFILE = 'Community Knowledge User';     private MSIUserTriggerHandler() {}      public static void executeAfterInsert(List&lt;User&gt; newList){         setCreatedCommunityUsers(newList);     }      private static void setCreatedCommunityUsers(List&lt;User&gt; newList){         List&lt;User&gt; usersWithContacts = new List&lt;User&gt;();         List&lt;Contact&gt; contactsToUpdate = new List&lt;Contact&gt;();         Set&lt;ID&gt; contactIds = new Set&lt;ID&gt;();          for(User u: newList){             if(u.ContactId == null &amp;&amp; u.ContactId == ''){                 continue;             }             if((u.ContactId != null &amp;&amp; u.ContactId != '') &amp;&amp; u.Profile.Name == COMMUNITY_PROFILE &amp;&amp; u.isActive == true){                 contactIds.add(u.ContactId);             }         }          for(Contact c : [Select Id,Name,Community_User_Created__c from Contact where Id in :contactIds]){             if(!c.Community_User_Created__c){                 c.Community_User_Created__c = true;                 contactsToUpdate.add(c);             }         }         update contactsToUpdate;     } }   Am I not adding the ID correctly to the Set&lt;ID>, or am I querying wrong in my for(Contacts) loop?
69308
I like instantiating my WCF service clients within a using block as it's pretty much the standard way to use resources that implement IDisposable: using (var client = new SomeWCFServiceClient())  {     //Do something with the client  }  But, as noted in , wrapping a WCF client in a using block could mask any errors that result in the client being left in a faulted state (like a timeout or communication problem). Long story short, when Dispose() is called, the client's Close() method fires, but throws an error because it's in a faulted state. The original exception is then masked by the second exception. Not good. The suggested workaround in the MSDN article is to completely avoid using a using block, and to instead instantiate your clients and use them something like this: try {     ...     client.Close(); } catch (CommunicationException e) {     ...     client.Abort(); } catch (TimeoutException e) {     ...     client.Abort(); } catch (Exception e) {     ...     client.Abort();     throw; }  Compared to the using block, I think that's ugly. And a lot of code to write each time you need a client. Luckily, I found a few other workarounds, such as this one on the (now defunct) IServiceOriented blog. You start with: public delegate void UseServiceDelegate&lt;T&gt;(T proxy);   public static class Service&lt;T&gt;  {      public static ChannelFactory&lt;T&gt; _channelFactory = new ChannelFactory&lt;T&gt;(&quot;&quot;);           public static void Use(UseServiceDelegate&lt;T&gt; codeBlock)      {          IClientChannel proxy = (IClientChannel)_channelFactory.CreateChannel();          bool success = false;          try          {              codeBlock((T)proxy);              proxy.Close();              success = true;          }          finally          {              if (!success)              {                  proxy.Abort();              }          }       }  }   Which then allows: Service&lt;IOrderService&gt;.Use(orderService =&gt;  {      orderService.PlaceOrder(request);  });   That's not bad, but I don't think it's as expressive and easily understandable as the using block. The workaround I'm currently trying to use I first read about on . Basically, you override the client's Dispose() method wherever you use it. Something like: public partial class SomeWCFServiceClient : IDisposable {     void IDisposable.Dispose()      {         if (this.State == CommunicationState.Faulted)          {             this.Abort();         }          else          {             this.Close();         }     } }  This appears to be able to allow the using block again without the danger of masking a faulted state exception. So, are there any other gotchas I have to look out for using these workarounds? Has anybody come up with anything better?
6154
In the example below, is the connection going to close and disposed when an exception is thrown if it is within a using statement?  using (var conn = new SqlConnection("...")) {     conn.Open();     // stuff happens here and exception is thrown... }   I know this code below will make sure that it does, but I'm curious how using statement does it.  var conn; try {     conn = new SqlConnection("...");     conn.Open();     // stuff happens here and exception is thrown... } // catch it or let it bubble up finally {     conn.Dispose(); }   Related:
48735
I recently implemented a class like:  class TestClass : IDisposable {     RegistryKey m_key;     public TestClass()     {         m_key = Registry.CurrentUser.OpenSubKey("Software", false);     }      public void Dispose()     {         // m_key.Dispose();         IDisposable disp = m_key;         disp.Dispose();     } }   If I uncomment the direct call to Dispose, I get error CS0117 ("'Microsoft.Win32.RegistryKey' does not contain a definition for 'Dispose'").  Some Googling led me to , where I learned what was going on, so I now understand the mechanics of it.  The  documentation suggests that the author would prefer that I call Close() instead of Dispose(), but doesn't explain why.  What is the purpose of this pattern (which I think I've seen it in the IO classes as well)?  In light of the fact that this was an intentional decision by the class author, how bad is the code above (the call to Dispose through the IDisposable interface)?  It can't be too bad - after all, it's what would happen in a using statement, right?  [edits: 1) changed title from "non-public" to "explicit" 2) removed the explicit implementation from my code, accidentally left in from experimentation]
39808
I am using a service component through ASP.NET MVC. I would like to send the email in a asynchronous way to let the user do other stuff without having to wait for the sending.  When I send a message without attachments it works fine. When I send a message with at least one in-memory attachment it fails.  So, I would like to know if it is possible to use an async method with in-memory attachments.  Here is the sending method       public static void Send() {          MailMessage message = new MailMessage("from@foo.com", "too@foo.com");         using (MemoryStream stream = new MemoryStream(new byte[64000])) {             Attachment attachment = new Attachment(stream, "my attachment");             message.Attachments.Add(attachment);             message.Body = "This is an async test.";              SmtpClient smtp = new SmtpClient("localhost");             smtp.Credentials = new NetworkCredential("foo", "bar");             smtp.SendAsync(message, null);         }     }   Here is my current error   System.Net.Mail.SmtpException: Failure sending mail.  ---> System.NotSupportedException: Stream does not support reading.    at System.Net.Mime.MimeBasePart.EndSend(IAsyncResult asyncResult)    at System.Net.Mail.Message.EndSend(IAsyncResult asyncResult)    at System.Net.Mail.SmtpClient.SendMessageCallback(IAsyncResult result)    --- End of inner exception stack trace ---     Solution      public static void Send()     {              MailMessage message = new MailMessage("from@foo.com", "to@foo.com");             MemoryStream stream = new MemoryStream(new byte[64000]);             Attachment attachment = new Attachment(stream, "my attachment");             message.Attachments.Add(attachment);             message.Body = "This is an async test.";             SmtpClient smtp = new SmtpClient("localhost");             //smtp.Credentials = new NetworkCredential("login", "password");              smtp.SendCompleted += delegate(object sender, System.ComponentModel.AsyncCompletedEventArgs e)             {                     if (e.Error != null)                     {                             System.Diagnostics.Trace.TraceError(e.Error.ToString());                      }                     MailMessage userMessage = e.UserState as MailMessage;                     if (userMessage != null)                     {                             userMessage.Dispose();                     }             };              smtp.SendAsync(message, message);     }
53887
I have seen a few mentions of this idiom (including ):  // Deliberately empty subscriber public event EventHandler AskQuestion = delegate {};   The upside is clear - it avoids the need to check for null before raising the event.  However, I am keen to understand if there are any downsides.  For example, is it something that is in widespread use and is transparent enough that it won't cause a maintenance headache?  Is there any appreciable performance hit of the empty event subscriber call?
55180
So I have a method that takes as a parameter an Id of a object and uses it to make an external callout.  Unfortunately I can't seem to figure out any way to test it.  @isTest static void sometimes_salesforces_sucks() {    My_Object__c foo = new My_Object__c(Name='test');    insert foo;    MyClient client = new MyClient();    MyMockResponseGenerator mockResponse = new MyMockResponseGenerator();    Test.setMock(HttpCalloutMock.class,mockResponse);     Test.startTest();    client.bar(foo.Id);    Test.stopTest(); }    says that using start/stop test should work, but it doesn't work for me
105631
Please consider the below scenario:   I have an Application__c object. I have a trigger on that (for simplicity, coded directly in trigger) which does one thing if the record name is Error then throws exception.     trigger ApplicationTrigger on Application__c (before insert, after update){          if(trigger.new[0].Name == 'Error'){             Application__c application;             System.debug(application.Name);         } }    Now I am running below code:     Now notice the catch statement is not executing, means system was not able to catch the exception. It came as the Fatal Error.   This is kind of a big issue where if there is null pointer or any other exception in trigger and exception handling code will not be able to do anything. Not even logging since it never reaches to catch block.   Let me know if you guys ever faced such situation and if yes what you did to make sure that it is properly caught.
101661
Just read a couple MSO posts about editing guidelines, after seeing  getting rejected.  I had stumbled upon an old question that somehow made it onto the front page, and saw a great answer there. The question was about "understanding events and event handlers in C#", and the answer was great but there was further information in the comments.  So I started editing the post; I found that "if we create a delegate void MyDelegate(object sender, EventArgs e)" was clearer if the backtick encompassed the delegate word, so I moved it.  A commenter was asking "How is the event fired?", and the answerer replied with a comment instead of editing his answer, so I added a code snippet to give an example of how the event would be fired.  Then I noticed the code block actually included two parts that really belonged in two separate classes (the one where the event is created, and the one where the event is registered/handled), so I split the definition and the consumption of the event into two code blocks. That made it much clearer what belonged where, even though there weren't any classes involved (didn't add any).  And then I added the part why I actually wanted to edit the post in the first place: I added the shorthand notation for registering events: myObj.SomethingHappened += HandleSomethingHappened;. I left the full notation in place.  And lastly I added a line of code to show how a handler could be unregistered with -=.  As the first reviewer approved the edit, I thought to myself "hmm this last paragraph I added to introduce the -= really just restates the previous one from the original author" - shortly after that, my edit was rejected by 3 reviewers in a row.  The reason was "This edit is incorrect or an attempt to reply to or comment on the existing post." -- really? Is this how constructive edits are being welcomed? Have I introduced bad code that's just plain wrong? I mean, I use the shorthand notation all the time, I know it's correct. The -= part was just added for the sake of completeness, and the backtick would have been too minor of an edit. Reordering the code snippets and splitting them in two distinct blocks really improves the post I find, but someone who just glanced at the diff could think I removed the event handler snippet, when I merely cut it &amp; pasted it below the event registration code.  So I'm guessing the redundant paragraph killed it? Should I submit another edit, minus that paragraph? Actually I don't even care, it's a question from 2009 with almost 60K views and the answer is great enough as it is to have received 155 upvotes (plus mine), and if people don't know they don't need to new up the delegate to register the event then they can just buy ReSharper and have the tool teach them it's redundant. And if they want to unregister a handler then they can certainly find how to do that somewhere else. And maybe I should be doing something else to kill my spare time than browsing SO and upvoting good questions and answers, downvoting and flagging bad ones, and improve the few posts I can contribute to with the few things I do know. I mean, I intended to genuinely improve an excellent post, it's a bit (quite) irritating to read it's an "incorrect" edit.  I take the [Reject] edits that change an answer's explanation or code, with a supposedly "better" alternative. Even if the proposed solution is better, it should be added as a comment, or a separate answer. guideline as what caused my edit to be rejected. Point is, I was adding information to the answer, not changing or replacing anything.  So, was this edit legit? If I understand  correctly, my edit should have been rejected for changing too much of the post, not for being incorrect or an attempt to comment on the answer. And if Servy's MSO answer is still right, it means I should have posted my content as a brand new answer... to a question that's like 4 years old? , but I find it would have been better to just edit the post, given that "Edits are expected to be substantial and to leave the post better than you found it."  Sorry for the long post.
36889
Is it possible to have an anonymous type implement an interface?  I've got a piece of code that I would like to work, but don't know how to do this.  I've had a couple of answers that either say no, or create a class that implements the interface construct new instances of that. This isn't really ideal, but I'm wondering if there is a mechanism to create a thin dynamic class on top of an interface which would make this simple.  public interface DummyInterface {     string A { get; }     string B { get; } }  public class DummySource {     public string A { get; set; }     public string C { get; set; }     public string D { get; set; } }  public class Test {     public void WillThisWork()     {         var source = new DummySource[0];         var values = from value in source                      select new                      {                          A = value.A,                          B = value.C + "_" + value.D                      };          DoSomethingWithDummyInterface(values);      }      public void DoSomethingWithDummyInterface(IEnumerable&lt;DummyInterface&gt; values)     {         foreach (var value in values)         {             Console.WriteLine("A = '{0}', B = '{1}'", value.A, value.B);         }     } }   I've found an article  that describes one approach. Is this the best way of doing this?
3569
Is it possible to unsubscribe an anonymous method from an event?  If I subscribe to an event like this:  void MyMethod() {     Console.WriteLine("I did it!"); }  MyEvent += MyMethod;   I can un-subscribe like this:  MyEvent -= MyMethod;   But if I subscribe using an anonymous method:  MyEvent += delegate(){Console.WriteLine("I did it!");};   is it possible to unsubscribe this anonymous method?  If so, how?
46765
Take the below code:  private void anEvent(object sender, EventArgs e) {     //some code }     What is the difference between the following ?  [object].[event] += anEvent;  //and  [object].[event] += new EventHandler(anEvent);   [UPDATE]  Apparently, there is no difference between the two...the former is just syntactic sugar of the latter.
95737
I am using platform event and subscribing them in a lightning component. When i use my component as standalone lightning app or use it on lightning record page, the components subscribe well to the event.  // Client-side function that invokes the subscribe method on the empApi component. subscribe: function (component, event, helper) {     // Get the empApi component.     console.log('calling to subscribe');     debugger;     var empApi = component.find('empApi');     // Get the channel from the attribute.     var channel = component.get('v.channel');     // Subscription option to get only new events.     var replayId = -1;     // Callback function to be passed in the subscribe call.     // After an event is received, this callback prints the event     // payload to the console. A helper method displays the message     // in the console app.     var subscribeCallback = function (message) {         console.log('Event Received : ' + JSON.stringify(message));         helper.onReceiveNotification(component, message);     };     // Subscribe to the channel and save the returned subscription object.     empApi.subscribe(channel, replayId, subscribeCallback).then($A.getCallback(function (newSubscription) {         console.log('Subscribed to channel ' + channel);         component.set('v.subscription', newSubscription);     }));      /*.catch(         function(error) {             console.error('cant subscribe to event ', JSON.stringify(error));         }     );*/ },   In the subscribe method - there is a console log - Subscribed to channel.   empApi.subscribe(channel, replayId, subscribeCallback).then($A.getCallback(function (newSubscription) {     console.log('Subscribed to channel ' + channel);     component.set('v.subscription', newSubscription); }));   It works fine for above mentioned scenarios and gets called well from Init.  If i put the component on the community page, the component stops subscribing and 'Subscribed to channel' does not show.
100018
My code is as follows:  List&lt;Messaging.SingleEmailMessage&gt; emails = new List&lt;Messaging.SingleEmailMessage&gt;(); Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage (); email.setTemplateId(templateId); email.setSaveAsActivity(false); email.setToAddresses('raytest1@domain.com'); email.setTargetObjectId(leadId); //having email raytest2@domain.com email.setWhatId(customObject.Id); emails.add(email); List&lt;Messaging.SendEmailResult&gt; results = Messaging.sendEmail(emails);   I want the email to be sent to raytest1@domain.com (the email sent in the setToAddresses method), but not raytest2@domain.com (the email of the targetObject, which is Lead.Email).  Is this doable?