I have a question, is there a way to somehow save the code you write in some sort of file and call it in to my app? I have started to learn visual C# for a couple of weeks now and I've noticed as I am doing more complex applications the amount of code to write for a single operation is getting out of hand. For example i need to write things like
richtextbox1.text ="";
for multiple richtextboxes. I don't mind writing a lot of code but I wish I could somehow save it and call it by the file's name so I can be organized and be able to keep track of things. Is there such a way to do this?
example:
private void button_click(object sender, eventargs e)
{
do "from the file"
}
and that's all i need to write. all help is appreciated.
Would not calling a method be much easier?
Example:
private void restTextboxes()
{
richtextbox1.text = "";
richtextbox2.text = "";
}
private void button1_click(object sender, eventargs e)
{
resetTextboxes();
}
private void button2_click(object sender, eventargs e)
{
resetTextboxes();
}
Normally you put your code in other classes. You mention you have too much code in one file. The code in your file should only have something to do with the task. i.e MyApp form should only handle the very basics. Load/save and setting up the rest of the app.
Your code that has nothing to do with user interface you put in a so-called business object so you might reuse them someday.
The different sections in your ui, you put in smaller panels so these small panels will each have a file which will be nice and small. Repeat untill everything is in nice and small files.
That was just the 10k overview. In short a better question would be: how do I put different sections of my ui in userpanels. And how do I design classes with low coupling and high cohesion.
If you are using Visual Studio, you could have a look at using code snippets. These can be a bit annoying to define (though there are plugins/addons that can help, eg Snippet Designer), but very useful when writing code that has common elements. If using Visual Studio 2005/2008, see this article which links to some examples. If using Visual Studio 2010, have a look here. Other IDE's probably also support snippets in some form.
A code snippet is a small piece of code that can be modified when you insert it into your file via the IDE. You can do things like click once to add timing code around a block of code, or easily create getters and setters (though most IDEs seem to offer this anyway).
If the code you want to add does exactly what existing code does, I would recommend refactoring, as per Daniel's answer. However if some small part is different, code snippets can be very useful.
Related
Windows 10.0.18362,
Visual Studio 16.4.5,
.NET 4.8.03752
Hi there
I wanted to setup a keyboard short cut to do something. So I set up the following code:
private void MainWindow_KeyDown(object sender, KeyEventArgs e)
{
if (Keyboard.IsKeyDown(Key.D))
{
// do something
}
}
Basically it works. The only (very nasty) thing that happens is that as soon as I implement "Keyboard.IsKey...(...)" into the code, run it, then pressing any key makes the window scales down (to
about 80%) totally out of nowhere.
I can replace the condition with "true" and it just runs as expected without any random out of nowhere scaling.
Did any one out there experience something similar? This behaviour does absolutely not make any sense, so searching for solutions obviously leads in dead ends only.
Thanks for any help or recommendation.
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.
In my program, I need Memory Scanner. I've used this one: http://www.codeproject.com/Articles/716227/Csharp-How-to-Scan-a-Process-Memory
I've created a new C# file named MemoryScanner.cs and copied the code there.
How to run it from here:
private void startButton_Click(object sender, EventArgs e)
{
//here I would like to invoke the MemoryScanner
}
Thanks in advance for every help. :)
Apparently (from looking at the code of the link your provided), the entry point of the program is the static method Main in class Program in namespace MemoryScanner. Call this method to start the code.
Some points should be noted:
The implementation is left as an exercise. (If you really don't know how to call a static method in C#, please start with a good, basic C# tutorial.)
Currently, the code analyzes a process called notepad, outputs the result to dump.txt and waits for Console entry before returning. If you want to use that as part of your program, you will need to change these things. (Hint: Remove the Console parts and pass the values, which are currently hard-coded, as method parameters.)
In a nutshell: If you want to use the code, you won't get around reading and (at least partly) understanding it.
You need to add a using statement at the top of your page.
using MemoryScanner;
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I'm using Visual c# 2010 express edition
I have nearly 1500 effective lines of code, and been using regions regularly, but it's getting out of control, how can i better organize or directly show a method, without having to click in the design form?
Edit: i've read about this http://msdn.microsoft.com/en-us/library/jj739835.aspx (Map dependencies) but it's for visual studio 2013, never heard of anything like it
It's part personal preference, but one can use CTRL+M, CTRL+L to collapse/expand everything to keep things a bit more compact.
Or, through the selector (top-right side of the editor window) you can go straight to a method.
Or (again), the good old Go to definition (F12)
I usually use comments if there's a lot of code in a single file and just ctrl-f to whatever I'm looking for or when applicable I break things up into class files
Try not to keep too much in a single file. Regions are great, but it's even better to avoid the need for them. There is a lot of dogma around "maximum number of lines in a file/class", but all you need to know is, if the file starts getting annoying to read, you need to try and split it up :)
ALways try to describe and name your classes by their functionality. For example, you may have a ScientificCalculator class. As you start to add functions, you start to notice groups of related functionality. Once they go beyond say, 2-3 functions, move them out into new classes!
So your ScientificCalculator class may now refer to smaller classes like BasicOperations, TrigonometricOperations, LogarithmicOperations, etc... you get the picture.
There are many advantages to this, including, but not limited to, easily finding your way around your code. Oh, you want to modify the Sine() function? You know exactly where to look - the TrigonometricOperations class! And that's a much more enjoyable experience in the long run.
Do you have 1500 lines of code in your entire project? Or 1500 lines in a single class? Or (much, much worse) in a single method?
1500 lines for a given project isn't so bad, provided that you've logically broken out your dependencies. 1500 for one class is probably way more than you want to manage.
When writing your classes, try to keep in mind what the class is responsible for. Is it doing to much? Are all the methods related to a single responsiblity? Does it mix things like logic and database interaction? Does it mix presentation logic with business logic?
And if it's 1500 lines of code for a single method, well...
Also, keep in mind that everything in this response should be prefaced with "In general" - there are no strictly prescriptive statements anyone can make about your code without actually seeing it, and there are always special cases.
Finally, if refactoring into separate classes seems like a large effort now, keep in mind that it will only become more and more difficult as your project grows in size and complexity.
Here's a tip that is a bit more controversial than others...
I'll assume the code is not directly under your control, say a legacy set of libraries or web site you inherited instead of designed... If this is not the case then there are much better options as already suggested by others (DRY, Encapsulate, Refactor, etc, etc, etc). However one stop-gap measure that has worked for me in the past is to make use of partial classes.
-----SuperBigClass.cs-----
class SuperBigClass {
public void MethodA(){
}
public void MethodB(){
}
public void MethodC(){
}
...
public void MethodZZTop(){
}
}
....can be separated into a couple smaller files....
-----SuperBigClass - Methods A through Z .cs -----
public partial SuperBigClass {
public void MethodA(){
}
...
public void MethodZ(){
}
}
-----SuperBigClass - MethodZZTop.cs -----
public partial SuperBigClass {
public void MethodZZTop(){
}
}
As long as the term partial is applied to the class definition of all class files and all class definitions are in the same namespace this will work just fine. Here's a link for more info: Partial Classes and Methods (C# Programming Guide)
Again... The best approach is to DRY up code, encapsulate, refactor, etc, etc, etc... but sometimes when you hop into a legacy app and you need to restructure the files themselves without making any functional changes, this shortcut (admittedly an unintended use of the partial class syntax) can be helpful for cutting large files up and helping to make sense of things.
This question is related to C#, but may be applicable to other languages as well. I have a reservation against using code such as the following:
using System.Windows.Forms;
class MyForm : Form
{
private Timer myTimer;
private Button myButton;
public MyForm()
{
// Initialize the components, etc.
myTimer.Tick += new EventHandler( myTimer_Tick );
myButton.Click += new EventHandler( myButton_Click );
myTimer.Start();
}
private void myTimer_Tick( object sender, EventArgs eventArgs )
{
myTimer.Stop();
// also, I see a lot of usage of
// Timer.Enabled = true/false instead of -^
myButton_Click( this, ea /* or event EventArgs.Empty, or null */ );
return;
}
private void myButton_Click( object sender, EventArgs eventArgs )
{
// do a lot of stuff, with lots of logic that doesn't even use the
// state of the eventArgs
return;
}
}
Am I alone, in that the above style is a pet peeve of mine? Are there others who enjoy the clarity of separating event handling from the workload of functions, or even separating out complex routines into separate functions?
Is there even an accepted style? I feel like any expressiveness and flexibility that event handling in C# has can be lost with styles like this. I feel like if you have a method that means "a button has been clicked", then it should only be called when a button is clicked.
To those who write like this, I would say: if you insist on having an EventHandler method to handle your timer tick, and your button click, then call it something other than button_Click -- perhaps "handleUserEvent( object sender, EventArgs eventArgs )".
Really, though, the question is, are there any style guidelines that are widely used which either support or discourage usage such as the above?
This is definitely not a "personal preference". There is a clear, well-understood approach of how to write code that is well-structured, maintainable, reusable, and understandable. Each method in your code should encapsulate a single piece of reusable functionality. The structure of your code should be:
void ButtonClickEventHandler(...)
{
UserData userData = //determine user data from event data
DoUserThing(userData);
}
void DoUserThing(UserData userData)
{
//do stuff
}
void SomeOtherMethod()
{
UserData userData = //get userdata from some other source
DoUserThing(userData);
}
(This is a very loose example. In a proper application everything should be separated into different classes by concern.)
I agree with Rex M's answer, but I'd take it one step further. If you are using the MVC pattern (or something similar), the view would delegate the button click to the controller. The controllers methods can of course be called from elsewhere in your class - say, from your timer callback.
So, back to your original code:
using System.Windows.Forms;
class MyForm : Form
{
private Timer myTimer;
private Button myButton;
private MyController myController;
public MyForm()
{
// ...
// Initialize the components, etc.
// ...
myTimer.Tick += new EventHandler( myTimer_Tick );
myButton.Click += new EventHandler( myButton_Click );
myTimer.Start();
}
private void myTimer_Tick( object sender, EventArgs eventArgs )
{
myTimer.Stop();
myController.SomeMethod()
}
private void myButton_Click( object sender, EventArgs eventArgs )
{
// All the stuff done here will likely be moved
// into MyController.SomeMethod()
myController.SomeMethod();
}
}
One advantage of using MVC is the decoupling of the controller from the view. The controller can now be used across multiple view types easily and exiting GUIs are easier to maintain as they contain very little application logic.
EDIT: Added in response to comments from the OP
The fundamental design principals of software engineering talk about coupling and cohesion. Importantly we strive to minimise coupling between components while maximising cohesion as this leads to a more modular and maintainable system. Patterns like MVC and principals like the Open/Closed Principal build on these fundamentals, providing more tangible patterns of implemenation for the developer to follow.
So, anyone who writes code as seen in the original post has not understood the fundamentals of software design and needs to develop their skills considerably. The OP should be commended for identifying this "code smell" and trying to understand why it's not quite right.
Some relevant references:
http://en.wikipedia.org/wiki/Coupling_(computer_science)
http://en.wikipedia.org/wiki/Cohesion_(computer_science)
http://en.wikipedia.org/wiki/Loose_coupling
http://en.wikipedia.org/wiki/Model–view–controller
http://en.wikipedia.org/wiki/Design_patterns
http://en.wikipedia.org/wiki/Open/closed_principle
http://en.wikipedia.org/wiki/Design_Patterns_(book)
myButton.PerformClick() is probably slightly nicer, if you don't need to pass eventargs. Sometimes you just want to simulate a click.
But yes, I would agree that it's nicer to move the real code into another function. I prefer my event handlers to be very simple - just connect the UI to the logic, which is elsewhere.
Then you can rearrange and redesign your UI without worrying so much about where the logic is.
This code increase the chance of problems if another coder works on the myButton_Click method.
What if I came in to adjust the implementation of the myButton.Click handler? I might assume that the sender object is a Button, and try to cast:
Button b = (Button)sender;
I have no knowledge without reading the rest of the class implementation that I'm not always receiving a Button as the sender.
So my point is: -1 for maintainability, because of breaking the assumptions of what objects will be passed as myButton_Click parameters.
The short answer is that why would you simulate a button click by calling the handler directly? If you want to wire both methods up to the same event, you would just wire it up. Event handlers are multicast delegates, which means you can add more than one of them. Wiring up an event more than once is totally acceptable.
myTimer.Tick += myTimer_Tick;
myTimer.Tick += myButton_Click;
myButton.Click += myButton_Click;
Whether or not this is a WTF is an engineering call that we can't make from a short code snippet. However, based on your comments, it smells like a WTF. Forms or any UI should never handle business logic. They need to be business-logic-aware to some degree (as in validation) but they don't encapsulate / enforce the logic themselves.
Going further, following some simple practices as basic refactorings and using a layered (n-tier) approach to software will take you a long way, and you will realise along the way that the code you presented smells bad.
Eventually you'll come across some high-level patterns like MVC (model-view-controller) and MVP (model-view-presenter) which go a step beyond the simple layering. If you follow them you get a good separation of concerns.
I agree with the accepted answer, but jumping right into 'Use MVC', here's some code that doesn't illustrate MVC, without explaining why is a little cargo-cult for me.
The special things about events in C# (and the .Net framework in general is the delegate, which is the C/C++ equivalent of a function pointer. the method attached to the event itself is not special in any way and should be callable from anywhere.
Update:
perhaps I should have been more verbose, but I thought my use of "should" instead of "can" or "may" would be enough. It is my assertion that event handlers should be called when the functionality they implement is needed, instead of having them become wrappers to methods that "do the work" the less method calls you have in the stack the better you will be, specially with the performance implications of .Net's exception handling.
I know it's a long time since this was asked but I'm going to differ and say no. As long as (1) it works and (2) it's clear what it does. I've heard all the standard arguments about design principles and such but think sometimes people go overboard and forget about the basics of design in not making things overly complicated. I see this in people forcing OOB where procedural design is really more suited as well.
One response is to move the code elsewhere and instead call that function but the problem with arbitrarily moving code is it creates unnecessary duplication making it more complex and less readable which is the opposite of good design. Following the approach of having one function do one thing people end up having to call a bunch of functions from multiple places only really succeeding in creating more opportunities for errors and additional overhead.
I believe this is what's responsible for all of the bloat we're seeing in buggy programs. I'm rather from the school of reusing and grouping as much as what makes sense and if that includes calling a function directly instead of indirectly where it makes sense and does the same thing then that can actually improve readability and decrease complexity.