Injection custom class in Form windows C#? - 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.

Related

Manually fire SpeechRecognizedEvent

I need to fire the SpeechRecognizedEvent manually for unit testing so I can't use the EmulateSpeech Method from a SpeechRecognitionEngine
Edit:
I have already encapsulated the SpeechRecognition into a separate Class with its own interface to mock it.
I need to call the Event because I have an AutoResetEvent, which I Set() during the event. The Unit test needs this to proceed.
The general idea with unit tests is not to use real things as they either:
Slow (e.g. database)
Dangerous to poke to often (e.g. Google Search API)
Not available (e.g. web service or hardware)
For such scenarios you suppose to use mocks/stubs. In other words things that behave identically, but in reality under your full control.
In your case SpeechRecognitionEngine, even if it might be available, would be too cumbersome for unit tests. Who/what would speak things to it? And even if you trigger an event, why to instantiate an instance of real SpeechRecognitionEngine?
Looking at MSDN for SpeechRecognitionEngine definition indicates that it doesn't implement an interface, which means it would be difficult to mock/stub.
For this case, you need to wrap, in other words, encapsulate SpeechRecognitionEngine into your own class which implements your interface. Then, all you need to do is to have two implementations of your interface, one with real SpeechRecognitionEngine for a real speech recognition, and another class for unit tests, which would just mimic your own callback, instead of using SpeechRecognized event.
You just swap one instance for another, and your code won't see a difference, as they are implementing single interface.
If you just want to simulate an event, you just call an event handler, as this is a method. Or another method, if you can't create some EventArgs. But the problem is that you'll have to expose inner methods from outside of your class (e.g. mark it public or internal), and this does looks nasty.
private void recognizer_SpeechRecognized(object sender, SpeechRecognizedEventArgs e)
{
this.ProcessSpeechRecognition(e.Result);
}
public void ProcessSpeechRecognition(RecognitionResult result)
{
// your logic here
}
Then in test you just call something similar to the below:
ProcessSpeechRecognition(new RecognitionResult { Text = "test" });
Despite posting an answer before that describes best practices for TDD; here is an answer specific to SpeechRecognitionEngine.
Microsoft has already thought about emulation of speech recognition. Here is MSDN article for SpeechRecognitionEngine.EmulateRecognize Method:
https://learn.microsoft.com/en-us/dotnet/api/system.speech.recognition.speechrecognitionengine.emulaterecognize

Manual editing of *.designer.cs file

I'm aware, that the .designer.cs file contains data generated by the visual form designer in Visual Studio. However, I have some additional methods though, which I want to put into the .designer.cs file as well, because these are responsible for lower-level form handling (for example, pieces of my visual state manager).
The InitializeComponent method inside the .designer.cs file has a comment stating, that it is automatically generated and should not be modified by user. Does this restriction apply only to that method or shouldn't the .designer.cs file be edited by user at all? I've noticed, that among others, it contains the Dispose() method, which the user might want to modify - what suggests the first option. I want to be sure, though.
You should never modify .designer.cs. Period. Your changes will be overwritten without mercy.
Update: To be a bit more helpful, C# since v3 (VS 2008) has included partial methods, which many designers will now use to let you implement custom behavior.
I think the other answers are simplifying too much.
First of all, I totally agree that it's almost always a bad idea to edit a .designer file, but there are a few cases where I've done so, feel it was good and proper, and didn't get burned.
Say I create a label and accidentally double click. Designer creates a method in my main .cs file which I then delete:
private void label1_Click(object sender, EventArgs e)
{
}
Well, now the code won't build unless I also delete the following from my .designer file:
this.label1.Click += new System.EventHandler(this.label1_Click);
Less frequently, the order in which things are added to a form or panel (or menu!) matters, and it can be easier to change this order in the code than in the Designer GUI. In my experience VS 2010 always picks up on this, updates its GUI's info, and redraws its preview. Just remember to focus on the Add() methods--the order variables are declared in generally doesn't matter.
Ditto if you set a property that causes a line to be added to the .designer file, deleting the line gets picked up quickly and Designer refreshes. Maybe it's wiser/safer to use the GUI to change the property, but I think deleting the line is cleaner.
Code that is not inside this region, #region Windows Form Designer generated code, will only get generated once. It is safe to move, and as others have recommended elsewhere (https://stackoverflow.com/a/6527072/1593924), moving the Dispose(bool) method out actually can make a lot of sense, if you're modifying it or adding a Dispose() method that should ideally sit next to Dispose(bool).
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
DISCLAIMERS:
That said, I've only tried VS 2010 Ultimate; your mileage may vary on 1-3 above, but 4 should be safe as long as the .designer is a partial class with Dispose(bool) outside that #region. I also make sure the latest good version of a .designer file is committed into the source repository before messing with it.
By admitting to having gone along with the Dispose(bool disposing) pattern, I'm not meaning to promote that approach. There seem to be good reasons to simply use Dispose() in most cases, and only do more for unmanaged resources, each of which is encapsulated one-to-one in a dedicated Disposable object.
this instruction applies to the complete designer.cs file.
As all the code written in it is automatically generated.
You should not do any modifications in this file as it can be recreated anytime... this will remove your methods...
If you want to keep the code separate from the form code file, then I suggest to create another file which contains a partial class where you can put all such methods...
Hope it helps...
Leaving designer.cs in peace not only prevents your changes from being overwritten, but also helps other developers by saying that nothing unexpected should come out of it. That being said, there is at least one exception I can think of and that is the one mentioned by author of the post: extension of Dispose() method. To my knowledge this code - once generated - will not be overwritten.
However, in my opinion much better solution is to override the Dispose method and than call the base.Dispose(), so that we leave designer.cs clean.
Partial designer form class it's used by Visual Studio for placing all code need for build the control.
The method InitializeComponent() can't be overwrite: it's used by designer editor for render a preview of your form!
Try in a new project: resize your form, add a label and a button and rename the InitializeComponent() method + re-compile.
Your form back to default size!
If you need to call code by form loading, just override OnLoad() virtual method, if you need to call code by form showing, simple override OnShown() virtual method.
Remember to call the base.Method() at begin of it override.
Hope this little my experience can help!

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

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

Using XmlDocument.Save() Effectively

I'm working with a .XML document in C# to which I'm selecting nodes from, adding nodes to, and deleting nodes many, many times over a span of my code.
All of the XML editing of this document is contained within a class, which other classes call to.
Since the Data Access class has no way of telling if the classes using it are done with editing the document, it has no logic as to if/when to save.
I could save after every modification of the document, but I'm concerned with performance issues.
Alternatively I could just assume/hope that it will be saved by the other classes that use it (I created a one-line public method to save the document, so another class can request a save).
The second option concerns me as I feel like I should have it globally enforced in some manner to avoid it being called upon and modifications not being committed. To this point there will never be a case where a rollback is needed; any change is a change that should be committed.
Does .Net (Or coding design) have a way to balance performance and safety in such a situation?
If you always want to save the changes (just don't know when) then you could add the save command to the class destructor. This way you know the changes will always be saved.
If you need additional help or want an example please leave a comment, otherwise select an answer as correct.
Update: It has been brought to my attention that the class destructor may fire after other objects (like a FileStream) have already been disposed.
I recommended that you test for this condition in your destructor and also that you implement and use the IDisposable interface. You can then subscribe to the either the Application.Exit event or Application.ApplicationExit event and call dispose there.
Be sure to keep the code in the destructor (but make sure you have it in a try block) in case the program crashes or there is some other, unexpected exit.
Basically your question says i all: You need to save, but you don't know when, as the knowledge about the savepoints is otside your class.
My recommendation is to wrap your calls - assuming you have something like public void MyClass.SomeEditing(int foo), create a wrapper like public void MyClass.SomeEditing(int foo, bool ShouldSave) with shouldsave defaultingto true.
This way, a consumer of your class can decide, wether he wants an immediate save or not, chosing false if he knows, an immediately following other edit will cause the save. Existing code, which calls the "old" API is protected by the default of "save imediately"

Problems with, or best practices for, passing data back through eventargs?

I've got a non-GUI class that generates events as to what it is doing (which are in turn used by a Form to display to the user the progress).
One of the events is a AboutToDoSomethingDestructiveEvent. Now we want to have the Form display a dialog to the user when AboutToDoSomethingDestructiveEvent is raised, asking them if they would like SomethingDestructive to happen. If they select no, then we would set a value on the customer EventArgs and the original form would read that value and then skip doing SomethingDestructive.
Is this a proper use of Events and EventArgs? Are there problems with this approach? Are there any best practices for doing this sort of thing?
The approach is so good there's even a class in the .NET Framework for this: CancelEventArgs
The way you are thinking is the proper way to do it. The Console.CancelKeyPress event is essentially the same thing.
Console.CancelKeyPress
This is a proper approach, as long as you have your own EventArgs, which are inheriting from System.EventArgs. It is very common, the best example I can think of is in PostSharp with the FlowBehavior.

Categories