C# - Best way for handling multiple methods and its completion [closed] - c#

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I have an application that have several methods which checks for various errors on a computer. Right now i am calling the methods on load event of the form, but i kinda want to display what the program is doing by updating a label text for everything it does, like a progressbar. It should go from method to method in order.
And later i also want to check if everything has runned successfully. Should i look into Threading Tasks for this? Like starting a task for each method, stopping the task if it fails?

I would suggest to create the following classes:
WorkstationCheckBase - should be the base class for all checks.
WorkstationCheckRunner - gets a list of all checks and summarize
the result of each WorkstationCheckBase.
With that, you will encapsulate the checking from your UI and separete these concepts.
Now for you second question to show up on the UI some information (my assumation is that you use WinForm). For that you need a background task and update the UI frequently. You could use the Backgroundworker class for that.

Short answer: No, don't use threading-
Long answer: It depends!
When you get yourself into threading you start to face loads of other concurrency related problems, if all you want is to show a label of what is happening I would not suggest to use threads.
Since I have no code to look at I can only give you suggestions for how to solve your problem (without threading). The simplest way would be:
public void CheckErrors()
{
string errorText = string.Empty;
if (ErrorOneHasOccured(out errorText))
{
ErrorLabel += errorText;
}
errorText = string.Empty;
if (ErrorTwoHasOccured(out errorText))
{
ErrorLabel += errorText;
}
}
private bool ErrorOneHasOccured(out string errorText)
{
bool errorHasOccured = false;
errorText = string.Empty;
// DO error checking somehting
if (errorHasOccured)
{
errorText = "An error description";
return true;
}
return false;
}
Where :
ErrorLabel is the string property for the error text you want to display.
ErrorOneHasOccured is an example method for error checking, using the "Try" pattern.
I think this is the simplest way you can do it, but you can obviously engineer it further depending on what and why you need it.

Related

Visual Studio said my variables are useless in a private method [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have simple scenario where I started to repeat same code multiple times, so I decided to move it in a private method, depending on a if/else it's being edited and my variables that are listed below might overwrite it's value which is perfectly fine:
ProductResponse identificationResults = new ProductResponse(); // I understand this assignment gets overridden in private method below but that is goal
long? productIdentificationRecordId = null; // I understand this assignment gets overridden in private method below but that is goal
I'm invoking my method on a few places in a code that's reason why I created private method to avoid code repetition in same file:
await SetProductStatusAndPerformDbActions(productCompany, userId );
private async Task SetProductStatusAndPerformDbActions(Company productCompany, long userId, ProductType productType, ProductStatus status, long? productIdentificationRecordId, ProductResponse identificationResults, CancellationToken cancellationToken)
{
status = GetCompanyProductStatus(productCompany.Id, identificationResults);
productIdentificationRecordId = await PerformDbAction(status, productType, userId, cancellationToken); // underlined this code
identificationResults = await IdentifyCompanyProduct(productCompany, cancellationToken); // underlined this code
}
Visual Studio says 'Remove this useless assignment to a local variable
productIdentificationRecordId'
Visual Studio says 'Remove this useless assignment to a local variable
identificationResults'
I understand this assignments gets overridden in private method below but that is point of private method because I want to use for example productIdentificationRecordId and its new value right after I call this private method because goal of private method is to modify it and that is it..
I'm not using vars which might cause this warning so I don't know what to do here.
How this could be written to avoid this scenarios ?
Edit:
Added screenshot from the private method, variables are grayed as they are not used:
Because these parameters are not being passed by reference, setting them to any value will only change the value of the parameter variables local to your helper method: it will not impact the values that were passed in to those parameters.
Since you don't use the new values you're assigning to those parameters inside the method, Visual Studio is smart enough to recognize that setting values to them has no effect. It's warning you about that, which is good because in this case you might think your code is doing something that it's not really doing.

Property or get method with cached result [closed]

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 4 years ago.
Improve this question
I have a method that takes around 200ms to run and would therefor like to cache the result. This result will be used frequently, but it never changes.
I'm not entirely sure what the best solution would be for this, should I put this to a property or a get method?
As an example:
1
private string _result;
public string Result => _result ?? (_result = GetSlowResult());
2
private string _result;
public string GetResult() => _result ?? (_result = GetSlowResult());
Personally, from a property I typically expect it to be available "now" rather than "later" but with a Get method I expect the result to always retrieve a fresh GetSlowResult rather than using a cached value. I could change the method name to GetCachedResult but I'm not sold on that either as then it would seem you need to have called a GetResult method first.
Are there any guidelines to this? What do you prefer?
I would recommend you to use the Lazy<T> class. It causes you to pass a factory that talks about how to create that object, and after that, it is created only the first time you ask for it, and then uses the same reference(cached value).
Here's how it would look:
Lazy<T> Result = new Lazy<T>(GetSlowResult); //T is your type
Then, to use the result, just get her property Value:
T myResult = Result.Value;
You can see more about this in the official dotnet docs.
I would do this with read-only property and a method that fills the property.
If you know that result will be needed, you can load it at the begining - during startup of a service, activation ov view etc.
I mostly use ReactiveUI in WPF apps, so it would look like that:
// ViewModel constructor
GetResult = ReactiveCommand.CreateFromTask(async () => _model.GetResultAsync()); // notice that method is async
// there is also overload with CancelationToken
_result = GetResult.Retry(3).ToProperty(this, x => x.Result); // we can retry few times and we get change notification
GetResult.Subscribe(result =>{
// do something as soon as the result is loaded
});
GetResult.ThrownExceptions.Subscribe( errorHandler);
// ViewModel properties
private ObservableAsProperetyHelper<ResultType> _result;
public ResultType Result => _result.Value;
// view constructor
this.WhenActivated(d =>{ // d is CompositeDisposable for cleanup
ViewModel.GetResult.Execute().Subscribe().DisposeWith(d); // cancel command if the view is deactivated before it's finished
});
That way you can make async call in proper moment and store the result for later. You can also easily refresh the result - that becomes dirty when using lazy properties alone.
On another plus side, you can easily create loading spinner:
_isBusy = GetResult.IsExecuting.ToProperty(this, x => x.IsBusy);
I followed this pattern in a always-on windows service running custom HTTP server in the background. You can await GetResult.Execute() if you want to enforce loading at a particular moment.
In my practice, this pattern shows very little shortcomings - main one is boilerplate code, but with proper tools it can be written really fast.
If you are creating some service type app, console or whatever, MVVM pattern is still very usefull, you just don't do views.

Where should I put my try and catch in my game? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I'm building a Number Guessing Game for a lab in school, the basic rules of the game are you have 10 guesses to try to guess the number between 1 and 100. My teacher want me to put all the game logic in one class and use the btn_Click methods in the form class to call methods from the game logic class. I feel like it makes sense to put the try catch in the btn_CLick methods because then I can use MessageBox.show to put a message like "You have to enter a number" or "Then number must be between 1 and 100" and but he said he wants the me to be able to take the code and use it without the form class. Any suggestions?
I would not use a try-catch. You could use a TryParse and convert your input from a string into an integer. If it doesn't convert just show an error. If it does convert to an integer you can do an if-then to find out if it's within your wanted parameters.
This could be done via methods contained in the "Logic Class". You could have one method return a true/false that checks if the input is able to be an integer and another that can determine if it's in the range you want.
Your UI would then take those true/falses and display/not display your message box for an error message.
Try/Catches are expensive and it's not useful in this case. If/thens and input validation/sanitation would solve the problems you could have for this program.
I would suggest not using try/catch at all unless you really really need it. So for validating user input, instead of attempting to type-cast the value, which may throw an exception, inspect the input string to see if it is an integer. I'd be surprised if there wasn't already a method for doing this in the C# Library.
Your game logic should be unconcerned with the where and how you get the guesses (numbers) so there really shouldn't be any need for try/catch in the game logic. I'd imagine it would expose a method that might look like this:
public GuessResult MakeAGuess(int guess)
Notice that it takes an integer which it's going to compare with the target number. So nothing here is going to throw. The body might look something like this:
public GuessResult MakeAGuess(int guess)
{
if (guess > target)
return GuessResult.TooHigh;
if (guess < target)
return GuessResult.TooLow;
return GuessResult.Correct;
}
Where GuessResult is a public enum with TooHigh, TooLow and Correct values.
Your UI will be responsible for converting strings to numbers (if that's needed) and any try/catching would be done there. BUT, it would be better to use int.TryParse rather than int.Parse wrapped in a try/catch because it is more efficient. Even better would be to use a more appropriate control on your form to get user input. One that actually is designed for numbers.

How to move to MVVM [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I made WPF application using Devexpress and Ado.net Connectivity mode with data base.I worked in other languages and now move to C#, i am new to WPF .I wrote this code to edit single and grouped rows:
void EditRow(int focRowHand, nrcsaEntities a)
{
Name nametext = grid.GetRow(focRowHand) as Name;
try
{
if (nametext.Name1 != string.Empty)
{
update_id = nametext.PK_ID;
txtName2.Text = update_text = nametext.Name1;
if (Panel3.Visibility == System.Windows.Visibility.Visible)
{
Panel1.Visibility = System.Windows.Visibility.Visible;
Panel3.Visibility = System.Windows.Visibility.Collapsed;
}
else
{
Panel1.Visibility = System.Windows.Visibility.Collapsed;
Panel3.Visibility = System.Windows.Visibility.Visible;
}
}
}
catch (Exception err)
{
DXMessageBox.Show(err.StackTrace);
}
}
private void ToggleButton1_Copy_Click(object sender, RoutedEventArgs e)
{
if (view.FocusedRowHandle == -1)
{
DXMessageBox.Show("Please Select any Item From Grid List");
}
else
{
try
{
int FocRowHand = view.FocusedRowHandle;
nrcsaEntities a = new nrcsaEntities();
if (grid.IsGroupRowHandle(FocRowHand))
{
int childCount = grid.GetChildRowCount(FocRowHand);
for (int i = 0; i < childCount; i++)
{
int childHandle = grid.GetChildRowHandle(FocRowHand, i);
EditRow(childHandle, a);
}
}
else
{
EditRow(FocRowHand, a);
}
}
catch (Exception ee)
{
DXMessageBox.Show(ee.StackTrace);
}
}
As my client demands to generate code with high quality. It is possible that more than 1000 users will use this application and can save users data more than 5000, My Question is that : As i have less time to submit my application to my client. If i want to convert this code into MVVM, how to do this as it's little complex to convert for me. Secondly, What do you think about this code quality. I am very much confuse about this. I am looking forward to your reply.
All I can tell you is that if you convert this application to WPF and MVVM in particular, then you will need to re-write a LOT of code. One problem is that WPF is very different from other languages... most developers face an uphill struggle when first learning WPF because of these differences.
Then, if you want to use the MVVM design pattern, things become even more different... for example, it is generally frowned upon to write code in code behind files. Of course, it is possible to use the code behind files, but we tend to implement Attached Properties that 'wrap' the functionality of these UI control event handlers, such as SelectionChanged instead.
Typically, the code that you have shown us would have to be moved into a view model, but then you'd lose the ability to reference your controls and so you'd have to find other ways to re-implement the same behaviour, but in an MVVM way. You'd also need to implement a load of ICommand instances to replace a lot of your Click handlers, etc.
Now, I must admit that my comments so far may make you think that I am not recommending that you convert your project. However, I am not not recommending that you convert your project. There are great benefits to WPF and using the MVVM pattern... the graphics, animations, styles and the ability to make any control look like anything else among other things.
The last point that I'd like to make relates to your question about 'big data'. WPF is a processor hungry framework... there's no way around this. It can be slow when rendering tens of thousands of data items into pretty UI elements. However, after working on a large scale application for a couple of years now, I've found that there are ways of improving the situation.
We can make WPF use the power of installed graphics cards, or use virtualised panels that only load data for the visible items, among other things. You really need to hear this negative side of WPF before you start your conversion, because once it has been converted, it'll be too late. I would also recommend that the computers that will run the application are made powerful enough, one way or another.
I hope this 'summary' has not been too negative for you and has helped in some way. I would like to end by saying that I personally am a huge fan of both WPF and MVVM.
I suggest you to take more days from your client and go for Devexpress MVVM Scaffolding Wizard It is ready to use. You have to just make connection to database and just have to change interface of your application.

How to reduce the complexity of if statements? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I've searched google and stackvoverflow to get the answers but it all boils down to: Create methods.
I want my code to be reusable. I don't want to create other methods in the same class. This class already contains a lot of code. How can I reduce the complexity while have a readable class?
I thought about creating another class and having all the new methods there.
The code
public Issue GetIssue(int issueId, IssueOption issueOption)
{
string resource = "issues/{id}.xml?";
if (issueOption.IncludeRelation)
{
resource += "include=relations&";
}
if (issueOption.IncludeChildren)
{
resource += "include=children";
}
//To fetch multiple associations use comma (e.g ?include=relations,journals
RestRequest request = new RestRequest(resource);
request.AddParameter("id", issueId, ParameterType.UrlSegment);
Issue issue = Execute<Issue>(request);
if (issueOption.IncludeVersion)
{
issue.Fixed_version = GetVersion(issue.Project.Id);
}
if (issue.Parent != null && issueOption.IncludeParent)
{
issue.Parent = GetIssue(issue.Parent.Id, issueOption);
}
if (issueOption.IncludeUsers)
{
if (issue.Author.Id == issue.Assigned_to.Id)
{
issue.Author = GetUser(issue.Author.Id);
issue.Assigned_to = issue.Author;
}
else
{
issue.Author = GetUser(issue.Author.Id);
if (issue.Assigned_to != null)
{
issue.Assigned_to = GetUser(issue.Assigned_to.Id);
}
}
}
if (issueOption.IncludeProject)
{
issue.Project = GetProject(issue.Project.Id);
}
return issue;
}
The road to readable code is very rough out of legacy code.
First off, you should have tests that fully cover the code you are refactoring otherwise you end up traversing that rough road in a blinding blizzard -- it's possible but not fun and very dangerous.
Once you've covered your butt there, you can start the refactorings. By and large, most of the early refactorings (assuming a lot of similar methods to what you have above) will be Extract Method. From there, some class behaviors should start becoming apparent and you can extract them out then.
I thought about creating another class and having all the new methods there.
This is analogous to cleaning your room by pushing everything under the bed. The room is clean but you've only hidden the mess. Don't do without any thought otherwise you'll end up with a Utility class that's even worse than what you have now.
From an OOP-perspective, working towards a SOLID solution is generally desired. The key tenet to focus on from a legacy standpoint is Single Responsibility for your classes. If you have that, the O-L-I-D tend to just fall into place (from my experience, though I've had way more brownfield development experience than I'd really like).
This class already contains a lot of code.
...
I thought about creating another class and
having all the new methods there.
That is exactly what you should do.
As you mentioned, breaking the code into smaller methods is the way to go. How about organizing your code using static extension methods, seeing as how Issue is the main subject of the code:
// top-down:
RestRequest request = GetRequestForIssueOption(issueId, issueOption);
Issue issue = Execute<Issue>(request);
// make it fluent...
return issue.SetVersion()
.SetParent()
.SetUsers()
.SetProject();
I think static extension methods make sense to use. Personally, I think making the static extensions fluent helps bring further clarity to code, not sure if that's your cup of tea though.
public static Issue SetVersion(this Issue issue_)
{
// code here
}
public static Issue SetParent(this Issue issue_)
{
// code here
}
public static Issue SetUsers(this Issue issue_)
{
// code here
}
public static Issue SetProject(this Issue issue_)
{
// code here
}

Categories