What is the right way to invoke a button's click event? - c#

Here: http://msdn.microsoft.com/en-us/library/hkkb40tf(v=VS.90).aspx, it says that, to call a button's click event from another button, you can/should do it this way:
button1.PerformClick();
However, in my situation (VS 2003. NET 1.1), this doesn't compile (admittedly, the link above specifies VS 2008, but it does not have a link to the pertinent info for prior versions, as msdn often does).
This compiles:
private void btnPrint_Click(object sender, System.EventArgs args)
{
if (this.recordChanged)
{
//btnSave.Click();
btnSave_Click(sender, args);
}
. . .
...but I don't know if it's THE way to do it.

Put the business logic that you want to execute in a separate method (e.g. DoSave()), and then your event handlers can both just call that internal method rather than calling each other directly.
"Faking" events by calling the event handler methods directly is ugly and can lead to bugs (any programmer modifying the event handler in future may be unaware that it could be called under different conditions than expected/documented, which could cause the print option to behave strangely or even crash when it tries to do a save operation)
Also there is a good chance that you may want to cause a save operation from somewhere else in future - so it's always a very good idea to keep the business logic separate from the use interface that activates it.

I would do btnSave.Click(sender, args);. Here's the page on MSDN: http://msdn.microsoft.com/en-us/library/aa645739(v=VS.71).aspx

Related

C# (object sender, RoutedEventArgs e) Properties

Visual Studio keeps saying (object sender, RoutedEventArgs e) properties are not used and to remove them. But if I do, it errors out the MainPage.g.cs reference. What should I do?
//MainPage.Xaml.cs
private void TextBoxSingleArray_GotFocus(object sender, RoutedEventArgs e)
{
var textBoxSingleArray_GotFocus = e.OriginalSource as TextBox;
textBoxSingleArray_GotFocus.SelectAll();
}
//MainPage.g.cs
//If I remove object sender, this will display error
((global::Windows.UI.Xaml.Controls.TextBox)this.TextBoxSingleArray).GotFocus += this.TextBoxSingleArray_GotFocus;
There are two ways to solve this.
1) Remove the name of the parameters using "discards" .
REf. https://learn.microsoft.com/en-us/dotnet/csharp/discards .
The error you see is due to you are not using those parameters inside the method.
2) Disable the warning:
Ref https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives/preprocessor-pragma-warning
Ref http://www.blackwasp.co.uk/SuppressWarnings.aspx
You just cannot simply remove the parameters since TextBoxSingleArray_GotFocus is a referenced event that requires to receive those two parameters. Even if you don't use them.
Hope it helps.
Juan Simon
I've seen messages like that (not in that particular case, though) from ReSharper (do you have that installed?), but Visual Studio itself may also do something similar.
Often, messages like that can help you keep your code cleaner... or sometimes catch bugs because it highlights when something you thought was being used is actually being missed. But in some cases, such as when creating a library with a public API but that isn't fully used within the same solution and leaves some "public" members unused, a suggestion such as "can be made private" isn't really true--it just has no way of knowing that.
This sounds like a similar case. You have arguments which are required for an event handler, but until it is used as an event handler somewhere within your code it wouldn't know that and might warn you that they aren't being used. Or, properties on the RoutedEventArgs aren't being referenced within the handler (or elsewhere in the code that it can see), so it gives you that warning and suggestion. But really, they are required--just perhaps not within your solution--and you can't really remove properties from a defined event args type that comes from WinForms, anyway.
But, you generally want to take note of messages like and consider whether the suggestion applies or if you have missed using something you should--or maybe you're just still in the middle of coding it and it might go away once you're done. If it's really a warning (shows up in the Errors box after a build) you may want to suppress it around the unavoidable cases where you know you don't want to access the other properties to "fix" it, but as #HereticMonkey commented, it's probably just a suggestion and not an actual warning. The main reason to suppress it is so that other, real, warnings aren't missed and can be attended to (or similarly suppressed if not important). Either way, as long as it's not preventing it from building successfully, you don't have to follow the suggestion--because it's not always right.
I believe you can get VS to be quite about this by naming your parameters _ and __.
Alternatively, you could add a SuppressMessage annotation to your method.

Injection custom class in Form windows C#?

I built the standard windows form application. Just one form with button "Check data".
After click that I send request to Http server and get back data.
I have to execure at once when form was built.
For this I have created separated custom class: CustomRequest.
How to inject this class inside:
public Form1()
{
InitializeComponent();
// Create instance of my custom class here
}
Is it good practic to inject direectly? Does it break SOLID priciples? Or I need to create also abstract class and use custom class through it?
`
It really depends on your use case. Ask yourself these questions:
Does my code perform operations on the UI?
Does my code require information from the form or about the form?
Does my code perform a time consuming operation?
If the answer to any of these is yes, then I think the best solution is to override the OnLoad method and execute the code you want there. This is debatable regarding the time consuming code case. However, if your code performs any operation on the UI, you should definitely take this approach.
protected override void OnLoad(EventArgs e)
{
// Your code here
}
NOTE: You can also subscribe to the Load event, which will yield a similar result, but is only recommended for very specific cases.
If your code isn't related to the UI itself, then using the constructor is the simplest solution, and will likely work just fine. However, there are a few caveats to this approach. First off, you have to remember that the constructor runs when the form is instantiated, regardless of whether or not its ever displayed. Additionally, make sure that you place that code after the call to InitializeComponent(), to prevent any delays in opening the form.
I'm giving you the succinct version. For a more detailed explanation, I recommend you give this and this answer by Hans Passant a quick read. He has some great information about the difference between Load and OnLoad, as well as when to use one of those two and when to use the constructor.

How to decide between a method or event?

I read a question ages ago "How do C# Events work behind the scenes?" and Jon answered that all events are similar to methods...
In a purely hypothetical situation, I was wondering if someone could explain or point me to a resource that says when to use an event over a method?
Basically, If I want to have a big red/green status picture which is linked to a Bool field, and I wanted to change it based on the value of the bool, should I:
a) Have a method called Changepicture which is linked to the field and changes the state of the bool and the picture.
b) Have a get/set part to the field and stick an event in the set part.
c) Have a get/set part to the field and stick a method in the set part.
d) Other?
To gain more information about events see this post.
You have options.
If your object already implements INotifyPropertyChanged and your red/green picture is a control which supports databinding, then you can simply fire the NotifyPropertyCHanged event on the bool's set method, and add a databinding on that property to your control.
If not implementing INotifyPropertyChanged, I would still recommend doing something similar. I.e. creating your own event handler, and having the reg/green picture subscribe to the event. Just straight up calling a method from the set of your property creates a tight coupling, which is generally a bad thing to do.
The answer is: It depends.
If your boolean value is in the codebehind class of your visual component (e.g. WinForm) you can call a method ChangePicture without doing strange things. But if your boolean value is architectural more far away from the visual component an event is the right way to handle the scenario because you can not easily call a method on the visual component because the class that contains the boolean value perhaps doesn´t even know your visual component exists. :)
The best way to figure out what you should do is to look at classes in the .NET framework and see how they are designed.
Methods are "doers" or "actions", while you can see events as notification mechanisms. That is if others could be interested is being notified when something happens in an object then you can surface an event and have one or more subscribers to these events.
Since events in .NET are multi-cast, meaning multiple objects can subscribe and therefore be notified of an event happening, that may be other reason to raise an event in your objects. Events also follow the observer pattern in that the subject (your class) is really unaware of the subscribers (loosely coupled). While in order to call a method, the secondary object needs to have a reference to an instance of your class.
Note that, a method in your class eventually raises and event. So let's say you have a method in your class called ChangePicture. Then in the method's implementation, you could eventually raise an event PictureChanged. if someone is interested in being notified of this event, they can subscribe to this event. This someone is typically not the one that made the method call to change the picture.
Events are delegates. Delegates are objects. Event's are actually MulticastDelegates (a base class in the .NET framework). These objects eventually call a method, which is the method that gets called as part of the event notification. So they are slightly "heavier" then just a method call, but that should almost never determine your design.

User-initiated action implementation

In Flash 10 there are methods that require that they are triggered from user-initiated actions like button click, keyboard up/down keys, etc.
Is it possible to implement this behaviour in .NET? For example, if we have this subroutine:
void SomeMethod() {
// Here some stuff
}
how to check inside it whether the method was called from a mouse click event handler?
Also we can think of this methods like the protected functions in World of Warcraft, if anyone knows what I mean.
EDIT: Looks like this behaviour is implemented in Silverlight — we can popup file dialogs (open, save) ONLY by mouse click or other user-initiated action, otherwise a SecurityException will be thrown. I want to achieve this bevaviour but in my case it’s not a file dialog but our own methods.
Why not just provide it as a parameter?
void SomeMethod(bool userInitiated) {
// Here some stuff
}
Given that you're already calling it, sometimes from an event handler and sometimes not, you already have that information.
EDIT: Another approach is to have a thread-static field which you set on entry to an event-handler and then reset on exit (in a finally block). Any code which wants to test whether they're "responding to a user action" can then test that field.
If that's not good enough, then I suspect the answer is simply "no".
EDIT: You can get at the call stack (see the StackTrace class) but that's relatively slow and can miss out stack frames due to inlining. There's also Code Access Security which may just about help you - but I doubt it.
It seems that you are writing some sort of plugin API. You want to provide a method that does something the user might not want, e.g. changes the clipboard contents, and you want to ensure that your plugins can call that method only in response to a user action.
The only way I can think of to do this is that the API needs to be continually aware of whether it is currently processing a user-initiated action or not. Presumably there will be some code in your program that calls the plugin-provided code, e.g.
if (plugin.HasHandlerForMouseClick)
plugin.HandleMouseClick();
At this point you will need to remember that this is a user-initiated action. Once the method returns, that’s the end of the user-initiated action:
if (plugin.HasHandlerForMouseClick)
{
_userInitiated = true;
try
{
plugin.HandleMouseClick();
}
finally
{
_userInitiated = false;
}
}
Then, in your “unsafe” method, e.g. the one to set the clipboard, you will have to check this flag:
public void SetClipboard(object newValue)
{
if (!_userInitiated)
return; // or throw AccessDeniedException?
// set clipboard here
}
As hinted by Jon, the field should be declared thread-static. This means that there is a separate copy of the field for each thread:
[ThreadStatic]
private static bool _userInitiated = false;

Order of Precedence with methods?

Say I have 2 methods. One is an method triggered by the selected index changing in the listbox. The second method helps by clearing all textboxes, setting listbox index to -1, and setting the focus.
Question:
Method two executes, during the code it changes the selected index of the listbox to -1, thereby setting off the event trigger for the 1st method. Does Method 2 HALT it's own execution and transfer the process to the event, and then return back to its work after Method 1 is finished... OR does method 2 finish its entire codeblock then transfer to Method 1 since the selected index changes?
The first case.
Let's leave threads out of it for a moment, particularly because they're not involved in your scenario.
You're talking about properties and methods, but underneath it all, it's all just functions. When one function invokes another, control in your program transfers to the called function. When that function finishes running, control returns to the point where it was called. Your program automatically remembers where it needs to go back to, no matter how deeply functions call more functions.*
When your second function sets the index, what really happens is that the compiler translates the property-set operation into a function call. (Properties are ultimately just "syntactic sugar" for functions.) That function calls a bunch of other functions that aren't important to the scenario, except that one of them is the one that invokes the "index changed" event handler. It sees that you have a method associated with that event, and it calls your first method.
Your first method runs, and when it finishes, it returns to the "invoke the index-changed event handler" function. Eventually, that and all the other unimportant functions finish running (perhaps after making more function calls in sequence), and the "set the index property" function returns control to your second method.
You can prove to yourself that your first suggestion is how it works. Display a message box in your first method, and display another message box after the point in your second method where you set the index property. (Use different messages!) You should see the first message appear, and after you dismiss the message box, you should see the second message appear, thus showing that the second method did not continue executing while the first one was running.
* There is a limit, but it's rarely hit unless there's a bug in your program. When you have too many nested function calls, what happens is a stack overflow.
There's a third alternative you can explore: they can also run at the same time! If I understand your question correctly, method 2 would be triggered by the index change event. In a C# Windows Forms application, this other event would occur in a separate thread of execution.
Concepts to explore: threading.
I hope this gives you a starting point in your explorations of knowledge.
Assuming no multi-thread situation, the event will fire before he end of execution of the method. If you want to see this, code what you have suggested in a .NET language and examine the Il produced. You can do this with ILDASM, or Reflector, or even create your own relfletion application. You do have to understand the syntax of IL enough to see the branch, but it is not that difficult, as long as you understand programming concepts.
Rob has labeled this "syntactical sugar", which I will agree with somewhat. It is really a compiler trick, but I guess it falls under the label "syntactical sugar" as it is commonly used.
I assume the language in question is c# and you thus have a language that supports multiple threads. If you don't want to worry about threads (which would be a bad idea if you consider user experience) you can run your GUI in one thread and have the same behavior, unless the components create their own thread (which would be a bit weird though). If you want to achieve an asynchronous (parallel) execution of the event you need to have the the event triggering in its own thread.
To answer your question: if you aren't using multiple threads, the method triggered by the event will be queued. This is exactly what happens when you see GUI responding slowly in some programs.
Hope it cleared things out and welcome from another newcomer :)
I myself am a beginner, maybe I can help. Method2 would fire, then when the selection changes, Method1 would do his stuff, then Method2 would continue.
If you don't want Method1 to fire at that time, you might want to do is something like:
(REALLY pseudo code)
Method2(object sender, System.EventArgs e)
{
//Unsubscribe Method1 from ListboxEvent
Listbox.OnSelectionChange -= Method1;
... Stuff Method2 actually does ...
Manualy call Method1 if you want it to fire
//Subscribe Method1 from ListboxEvent
Listbox.OnSelectionChange += Method1;
}
It's probably not optimal (and maybe some Best Practices...) but for a lack of a better explanation, at least you have a bit of information to help you search. Hope it helps!

Categories