|
private async void FindAllBTN_Click(object sender, EventArgs e)
{
progressBar.Minimum = 0;
if (!isRunning)
{
OutputTB.Hide();
OutputRTB.Show();
FlipNextAllCKB.Checked = true;
OutputRTB.Text = OutputTB.Text;
FindAllBTN.Text = "Cancel";
FindAllBTN.ForeColor = Color.Red;
Progress<int> prog = new Progress<int>(SetProgress);
m_cancelTokenSource = new CancellationTokenSource();
try
{
await FindAllMatches(searchTB.Text, prog, m_cancelTokenSource.Token);
}
catch (OperationCanceledException)
{
}
finally
{
FindAllBTN.Text = "Find All";
FindAllBTN.ForeColor = Color.Black;
isRunning = false;
m_cancelTokenSource = null;
progressBar.Value = 0;
replaceLTB.Focus();
}
}
else
{
m_cancelTokenSource.Cancel();
}
return;
}
public Task FindAllMatches(string searchString, IProgress<int> prog, CancellationToken ct)
{
return Task.Run(() =>
{
try
{
bool yesno = false;
string source = "";
Regex re;
if (searchString == "")
{
OutputTB.AppendText("\r\nNeed RegEx Expression Input\r\n");
return;
}
try
{
re = new Regex(searchString);
}
catch (ArgumentException e)
{
OutputTB.AppendText("\r\nEx Err " + e.ToString() + "\r\n");
return;
}
source = OutputTB.Text;
if (source == "")
{
OutputTB.AppendText("Need Source Text Input");
return;
}
OutputRTB.SelectionStart = 0;
OutputRTB.SelectionLength = OutputRTB.Text.Length;
OutputRTB.SelectionBackColor = Color.White;
MatchCollection matches = Regex.Matches(OutputRTB.Text, searchString);
progressBar.Maximum = matches.Count;
for(int i = 0; i < matches.Count; i++)
{
prog.Report(i);
if (ct.IsCancellationRequested)
{
OutputRTB.AppendText($"\r\nCanceled at Loop {i}");
OutputRTB.AppendText("\r\n");
throw new OperationCanceledException(ct);
}
OutputRTB.SelectionStart = matches[i].Index;
OutputRTB.SelectionLength = matches[i].Length;
if (yesno)
{
OutputRTB.SelectionBackColor = Color.GreenYellow;
yesno = false;
}
else
{
OutputRTB.SelectionBackColor = Color.Turquoise;
yesno = true;
}
}
}
catch (Exception ex)
{
if(ex.ToString().Contains("OperationCanceledException"))
{
}
else
{
}
}
finally
{
}
}, ct);
}
The async await was taken from this sit
Handling long operations with cancel and progress in C# with async – Cowthulu[^]
************************************************************************
ee the end of this message for details on invoking
just-in-time (JIT) debugging instead of this dialog box.
************** Exception Text **************
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Windows.Forms.RichTextBox.EditStreamProc(IntPtr dwCookie, IntPtr buf, Int32 cb, Int32& transferred)
at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at System.Windows.Forms.NativeWindow.DefWndProc(Message& m)
at System.Windows.Forms.Control.DefWndProc(Message& m)
at System.Windows.Forms.Control.WndProc(Message& m)
at System.Windows.Forms.TextBoxBase.WndProc(Message& m)
at System.Windows.Forms.RichTextBox.WndProc(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
I Appreciate Your Willingness to Help me
Ok Thank you I got it.
modified 20-Jan-22 15:40pm.
|
|
|
|
|
I can't test that code, but at first glance, you cannot touch the OutputTB nor the progressBar from the Task. All method and property access on controls must be done from the startup (UI) thread.
|
|
|
|
|
private async void FindAllBTN_Click(object sender, EventArgs e)
{
progressBar.Minimum = 0;
if (!isRunning)
{
isRunning = true; <<============ I missed this line, Now it works smouthly
OutputTB.Hide();
OutputRTB.Show();
FlipNextAllCKB.Checked = true;
OutputRTB.Text = OutputTB.Text;
FindAllBTN.Text = "Cancel";
FindAllBTN.ForeColor = Color.Red;
Progress<int> prog = new Progress<int>(SetProgress);
m_cancelTokenSource = new CancellationTokenSource();
try
{
await FindAllMatches(searchTB.Text, prog, m_cancelTokenSource.Token);
}
catch (OperationCanceledException)
{
}
finally
{
FindAllBTN.Text = "Find All";
FindAllBTN.ForeColor = Color.Black;
isRunning = false;
m_cancelTokenSource = null;
progressBar.Value = 0;
replaceLTB.Focus();
}
}
else
{
m_cancelTokenSource.Cancel();
}
return;
}
see above
I'am very thank you for your eforts to help
|
|
|
|
|
I have an existing code base, which we catch exceptions etc.
Does anyone know if there is a way to list all the exceptions that either the code catches or raises so that I can do a review? reason for the review is the result of a pen test, which they flagged that the responses had too much details inside the exception.
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
modified 17-Jan-22 8:37am.
|
|
|
|
|
I'd probably use Notepad++ to do a File Content search for "Catch" and "Throw" on my project folder
|
|
|
|
|
Thanks, was wondering there was a clever way to do this but sadly not.
Thanks for you time
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
VS can do a "Find in files" across a whole project or solution, and that can be a regex. So "\scatch\s" and "\sthrow\s" would find and list them all in the "Find" pane (which can be copied to the clipboard) or double clicked to go to each in turn)
"I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
"Common sense is so rare these days, it should be classified as a super power" - Random T-shirt
AntiTwitter: @DalekDave is now a follower!
|
|
|
|
|
Thanks, was wondering there was a clever way to do this but sadly not.
Thanks for you time
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
In my experience the most interesting exceptions are the ones we do not throw or catch ourselves, but we get for free by calling some CLR class. Example: Image.FromFile() can throw an OutOfMemoryException when the file's format isn't recognized! Now how do you make sure your code base handles that properly???
Luc Pattyn [My Articles]
The Windows 11 "taskbar" is disgusting. It should be at the left of the screen, with real icons, with text, progress, etc. They downgraded my developer PC to a bloody iPhone.
|
|
|
|
|
Thanks Luc,
the reason I was asking is that we have a task from the security team who pen tested a platform we released. to review all the messages that are returned by the platform to mobile devices.
this main api in this platform is large and requires a lot of reading and was wondering if I could in a automated fashion return on the exceptions rather than used human eye.
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
Log them in FirstChanceException. Have a white / black dictionary / list as you work through them.
Quote: This event is only a notification. Handling this event does not handle the exception or affect subsequent exception handling in any way. After the event has been raised and event handlers have been invoked, the common language runtime (CLR) begins to search for a handler for the exception. FirstChanceException provides the application domain with a first chance to examine any managed exception.
AppDomain.FirstChanceException Event (System) | Microsoft Docs
"Before entering on an understanding, I have meditated for a long time, and have foreseen what might happen. It is not genius which reveals to me suddenly, secretly, what I have to say or to do in a circumstance unexpected by other people; it is reflection, it is meditation." - Napoleon I
|
|
|
|
|
Thanks Gerry I'll have a look into that
Every day, thousands of innocent plants are killed by vegetarians.
Help end the violence EAT BACON
|
|
|
|
|
Look at the points where you expose data from the backend (typically a REST service or similar). If an exception is raised, you generally speaking just return "500 Internal Server error" without any further details - and (very important) log those details on the server.
In case you use exception to trigger responses like like "404 NOT FOUND" you need to make sure they do not show stack traces or internal details as well.
This is typically done in a central place in the response handler of the API so it will automatically kick in for any exception raised - you need to write this code and test it so you trust it no matter which exception is raised from the lower levels of the code. Then you do not need to hunt your entire code base for possible exceptions - which is an impossible task anyway as some system exceptions can be raised from anywhere.
Java tried to get the code to declare all exceptions so you could track it down (checked exceptions) but it was not a great success.
UPDATE: And make sure you only catch exceptions in 2 cases:
1) When you can FIX the issue - i.e. no error will be returned to the client, and hence no information will be leaked. Example: You want to read some data from a disk cache. If the read throws an exception catch it and recalculate the data.
2) When you can throw an exception with more details. Example: You try to read the data but the exception just says "Access denied". You know what you where trying to read and which user you where running as, so catch it and throw a new exception adding these datails - keeping the original exception as inner exception.
|
|
|
|
|
Isn't there an option to hide that?
Bastard Programmer from Hell
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Probably, but hard to say without any details. I am surprised it is not the default behavior of whatever framework he is using, so maybe the default was just changed to make it easier to debug. In ASP.NET you do for example get the "to read the error details, change this setting" message - and someone not understanding the impact might just have followed these instructions. In that case the only thing he needs to do is revert that setting. But I am not going to google the solution to every imaginable framework out there, just because the poster forgot to mention what they are using.
|
|
|
|
|
lmoelleb wrote: I am surprised it is not the default behavior of whatever framework he is using, so maybe the default was just changed to make it easier to debug. It is hidden by default because of hackers.
Details should be hidden if it is not on localhost.
Bastard Programmer from Hell
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Of course. That is kind of what I have been saying the entire time
|
|
|
|
|
I'm currently on coffee two.
Not entirely alive yet.
Bastard Programmer from Hell
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
If you go and do a "replace all"..
..then have your exceptions inherit from a custom class inheriting from Exception . For logging, use FirstChanceException as suggested by Gerry; it will show a lot more than the exceptions you throw yourself.
Bastard Programmer from Hell
"If you just follow the bacon Eddy, wherever it leads you, then you won't have to think about politics." -- Some Bell.
|
|
|
|
|
Simon_Whale wrote: list all the exceptions that either the code catches or raises so that I can do a review
That process would need to find that those in all of the libraries that you use also.
Simon_Whale wrote: reason for the review is the result of a pen test,
Probably because you have an API and you are returning the exception stack trace as part of the API error handling. The solution to that is the following
1. Catch all exceptions so "catch(Exception e)" in your API layer.
2. Log the exception. You should of course already be doing this.
3. Return an error result from the API. Do not return the exception. Probably 500. But over time you can differentiate this in the error handling code.
I would suggest that you also create an id and log that as well and return that as part of the error message. That way you can track an error reported from a caller back to the specific log entry. You can use a GUID but it is going to be more user friendly, especially if a UI is involved, if you create a simple id. It can rotate over time because the context of the error (when reported) is enough to localize in the logs.
|
|
|
|
|
C# >= 4
Curious to know if you've had to deal with the issues described here.
1) assume you have a generic method of Type T
2) in that method a Func<IEnumerable<T>, IEnumerable<T>> is called on an IEnumerable of T
3) the result of calling the func is in a variable 'temp ... when you examine 'temp in the Command Window at run-time after hitting a break-point:
> ? temp
{System.Linq.Enumerable.WhereListIterator<int>}
Current: 0
Results View: Expanding the Results View will enumerate the IEnumerable
> ? temp == null
false
> ? temp == default
false
> ? temp is null
false
> ? temp.Any()
false
> ? temp.Count()
0 4) in the case where the Func call results in no content (no items)
4a) you want to evaluate whether 'temp has any "items" ... i.e., has a Count of #0 (as shown above)
4b) but, you do not want to trigger iteration/enumeration of 'temp by calling Count()
I have read that .Any() will not cause iteration in this very interesting SO thread: [^].
And, on the same thread: [^]: is mention of a new C#6 Linq function 'TryGetNonEnumeratedCount
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|
There is no way to do it in general, not even in theory.
TryGetNonEnumeratedCount is neat, but only actually outputs the count when it is called on a collection that knows its count. For general enumerables such as WhereListIterator , it returns false. So OK, it doesn't evaluate the enumerable, but it also doesn't help.
Any on a WhereListIterator has to evaluate until it finds an element or runs out of input. There's nothing else it could do. BTW Any includes TryGetNonEnumeratedCount -like tricks, examining the type of the object it is called on, and if it is an ICollection then it just checks whether its count is zero (there are additional details but they don't help here either), but those tricks cannot apply to a filtered enumerable.
If there was any method that could in general predict whether a filtered enumerable is going to have anything in it (without iterating through it), that would have strange implications. It would act as a powerful oracle (of the theoretical computer science variety) that can extract information from a black box function without ever actually evaluating the function. Spooky.
|
|
|
|
|
thanks, Harold, as I'd expect from you, a very thoughtful reply.
I've found very little documentation on 'TryGetNonEnumeratedCount so far. My impression in the SO thread cited is that this new Linq method is somehow more efficient.
Given .Any short-circuits when it encounters a first instance: I find myself wondering if under-the-hood .Any is in any way more "efficient" in a function that returns an IEnumerable ... compared to invoking Count().
In this context: in a loop where a series of functions are called in sequence, and the goal is to exit the loop when any function returns an empty IEnumerable ... .Any can be used while testing for null or == default are useless.
cheers, Bill
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|
TryGetNonEnumeratedCount is always efficient, but that's because in the case that the enumerable doesn't already know its count, instead of falling back to counting elements one-by-one (as Count does), it just gives up. It is Count but without the default/slow path, only the special cases. I wouldn't really call it "more efficient", it's more like a niche thing that you can use when you would like to have a count but you don't really need it (such as to create a collection with an initial size, which isn't worth counting one-by-one for, but if getting the count is basically free then you may as well use it).
Any can certainly be more efficient than Count , thanks to the early-out. In some cases Count is actually more efficient, but let's put that aside, that's not really relevant to the case you're dealing with.
So far I have no specific reason to think that there is any better solution than Any . Maybe if there is some special property of the Mystery Function that's being called, or of the overall algorithm, there may be some other technique.
|
|
|
|
|
Thanks, again !
A few gaps in (my understanding of) the puzzle:
1) "TryGetNonEnumeratedCount ... in the case that the enumerable doesn't already know its count, instead of falling back to counting elements one-by-one (as Count does), it just gives up"
If an IEnumerable "knew" its count ... is that a contradiction in terms ? Clearly, some collections "know" their count, because it is a Property not a method.. But, a generic IEnumerable created at run-time ?
2) "In some cases Count is actually more efficient"
fascinating; I try to imagine a case of a generic IEnumerable where Count() would be more efficient ... but, draw a blank
3) if you had a function that returned a generic IEnumerable, and in that Function you used Count(): would there be any structural differences between that returned result and a returned result IEnumerable you had never used Count on.
4) comparing a a generic IEnumerable you used Count() on with one you used Any() on: would there be any structural differences ?
«The mind is not a vessel to be filled but a fire to be kindled» Plutarch
|
|
|
|
|