How to make code supression messages always appear in english? - visual-studio

My project has quite a set of StyleCop/FxCop rules active, and when I violate one, Intellisense suggest me some repair features for whatever I break. If I want to ignore the rule, it can automatically create the suppression. However, these messages always are automatically generated in german, since my OS, language setting and even Visual Studio are in german. I want the comments in the code to be english, though.
Consider this code:
public static AngleUnit CreateUnit(string unit)
{
try
{
return CallSomeLegacyFunctionWhichMayThrowRandomExceptions(unit);
}
catch (Exception ex)
{
Logger.Log(string.Format(CultureInfo.CurrentCulture, "{0}\n\n{1}", ex.Message, ex.StackTrace));
}
return new AngleUnit("deg", 0.017453292519943295);
}
Correctly, there's a warning on the catch that I should not catch Exception. To suppress I select Possible solutions from the popup, then Suppress CA1301 and in source. I get:
}
#pragma warning disable CA1031 // Keine allgemeinen Ausnahmetypen abfangen
catch (Exception ex)
#pragma warning restore CA1031 // Keine allgemeinen Ausnahmetypen abfangen
{
If I choose in source (attribute) instead, I get:
[System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1031:Keine allgemeinen Ausnahmetypen abfangen", Justification = "<Ausstehend>")]
public static AngleUnit CreateUnit(string unit)
How do I get VS to write out the comments in english? I don't want to manually update these each time. I also don't want to switch my VS or OS to english.

We don't have a way to configure that, but that's a good idea. I've filed a bug at https://github.com/dotnet/roslyn/issues/51135.

Related

Break when exception is thrown except for when thrown in specific place in Rider

In Visual Studio there is a possibility to mute an exception when it happens in particular place, e.g. We are aware that there is some NullRefereneceException in Calculator.cs and we still want to catch those types of exceptions when thrown from all other places in code, but Calculator.cs.
How it looks like in VS:
Is such a feature available in Rider?
I wasn't able to find a solution to your question.
The only thing I found is to not break on a specific exception type - but that's unrelated to the line.
For example, let's take the following code:
public class OtherClass
{
public void ThrowNullReferenceException()
{
try
{
throw new NullReferenceException();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
}
}
With the following Exception Settings, the handled NullReferenceException gets swallowed:
Maybe you can get in contact with Rider support.
As of now the feature is not yet available, but there is a Youtrack ticket for this feature.

UmbrellaException which contains ClassCastException when using GWTBootstrap3 Extras Summernote event handling (KeyUp Event)

I try to handle a Summernote Keyup event with this:
myEditor.addSummernoteKeyUpHandler(new SummernoteKeyUpHandler() {
#Override
public void onSummernoteKeyUp(final SummernoteKeyUpEvent event) {
// TODO Auto-generated method stub
log.fine("hello");
}
});
I get a UmbrellaException which is IMHO a class cast exception.
This is the call stack
I identified the following spot where te cast failes:
#HasNoSideEffects
static native boolean canCast(Object src, JavaScriptObject dstId) /*-{
if (#com.google.gwt.lang.Cast::instanceOfString(*)(src)) {
return !!#com.google.gwt.lang.Cast::stringCastMap[dstId];
} else if (src.#java.lang.Object::castableTypeMap) {
return !!src.#java.lang.Object::castableTypeMap[dstId]; //<-- this returns false!!!
} else if (#com.google.gwt.lang.Cast::instanceOfDouble(*)(src)) {
return !!#com.google.gwt.lang.Cast::doubleCastMap[dstId];
} else if (#com.google.gwt.lang.Cast::instanceOfBoolean(*)(src)) {
return !!#com.google.gwt.lang.Cast::booleanCastMap[dstId];
}
return false;
}-*/;
dstId contains:
Any help greatly appreciated!
I tested this with a small demo which actually works. But in my large application, I get this exception and I don't see why.
Do you have any idea whats wrong here?
Best regards
Hannes
As Andrei suggested I set the style to DETAILED. I use Eclipse as a development environment. I decided to clean build the system (which I had done before). Now the problem has simply vanished !! Furthermore, I use SDBG (see: https://sdbg.github.io/) to debug my GWT application. This works pretty well (even without -style DETAILED). Now the very very strange thing remains. I can set breakpoints for my application and they all work well, except setting a breakpoint within the event handling method. I use a logger to print some text to the console, so I see that the event handler for summernote is actually called but the debugger will not stop. I checked whether the breakpoint is listed in the tab "Breakpoints" and it is and it is checked. I don't get it. Perhaps I have to rebuild all again.
But to keep long things short:
The solution to the problem is probably to really issue a clean build and then hope for the best.

Visual Basic - Check To See If Program Can Edit Registry [duplicate]

Does anybody know how I can programmatically check (using C#) whether my program will be able to read / write a particular registry key (specifically: "SOFTWARE\Microsoft\Windows\CurrentVersion\Run")?
I am asking because my program has the option to enable or disable the 'run at startup' behaviour. I want to disable this option if the current user is not allowed to make changes to the registry. Is this key always allowed to be written by the current user, or is there the possibility that it has been locked down? If the latter, how do I check this?
I have seen several conflicting ways of checking registry permissions - but basically I can't find a way to check a specific key before I try to read it. I would rather perform the check before accessing the key than trying to access it and receive an exception.
Any help is much appreciated.
Tom
The RegistryPermission class governs the security permissions around reg keys. To check if you may have write access to a permission you use it in the following manner:
RegistryPermission perm1 = new RegistryPermission(RegistryPermissionAccess.Write, #"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
You would then use the "Demand" method in a try/catch and return on failure (the raising of a security exception). On success you'd carry on and perform your update. Although this isn't quite what you want, a check on permissions before access, it is the accepted way of ensuring you have the permissions you need before you operate on the keys. In a fully structured manner this would equate to:
try
{
RegistryPermission perm1 = new RegistryPermission(RegistryPermissionAccess.Write, #"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
perm1.Demand();
}
catch (System.Security.SecurityException ex)
{
return;
}
//Do your reg updates here
EDIT: Thinking on what I mentioned in the comment, here are extension methods to the RegistryPermission class for permission checks:
using System.Security.Permissions;
using System.Security;
public static class RegistryExtensions
{
public static bool HavePermissionsOnKey(this RegistryPermission reg, RegistryPermissionAccess accessLevel, string key)
{
try
{
RegistryPermission r = new RegistryPermission(accessLevel, key);
r.Demand();
return true;
}
catch (SecurityException)
{
return false;
}
}
public static bool CanWriteKey(this RegistryPermission reg, string key)
{
try
{
RegistryPermission r = new RegistryPermission(RegistryPermissionAccess.Write, key);
r.Demand();
return true;
}
catch (SecurityException)
{
return false;
}
}
public static bool CanReadKey(this RegistryPermission reg, string key)
{
try
{
RegistryPermission r = new RegistryPermission(RegistryPermissionAccess.Read, key);
r.Demand();
return true;
}
catch (SecurityException)
{
return false;
}
}
}
One thing you should know about permissions is that they are volatile. That means you could do your security check on the registry key, attempt to add your value only if the check passes, and then still fail with an insufficient access exception because the permissions changed in between when you made the check and when you acted on the results. This is possible even if they are consecutive statements in your program.
Granted security permissions tend to be relatively stable, but the chance still exists. This means that you must have code to handle the security exception, and if you have to do that anyway there's not really any point in making the check in the first place. Instead, put your time into making your exception handler a little bit better.
That said, "boo" to any app that wants to run something at start-up. YAGNI.
I think you best bet is to just try to add your value to the key, and handle failure gracefully by informing the user they didn't have enough permissions to do that.
If you're writing some sort of administrative tool that is designed to always be run by an administrator, you should indicate that in the manifest. That way your app will elevate at startup (via UAC prompt).
Simplest option is to try and open the key with write access and see if you get it. Remember to close the key afterwards.
bool fWriteAccess;
try {
Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).Close();
fWriteAccess = True;
} catch (SecurityException) {
fWriteAccess = False;
}
I'm not sure how to it with C#, but with Win32, you would use RegGetKeySecurity(). Maybe there's a C# wrapper? Otherwise, use P/Invoke.
Just try to open the registry key with WRITE permissions.
That said, what others have said is right: There is no way to tell if an operation is going to succeed unless you try it. Maybe someon deleted the Run key. Maybe the registry will exceed allocated memory. Maybe the disk failed.

Switch Screens in BlackBerry

I have a BlackBerry App that has a Listener for the Send Button implemented in the CheckIn Screen. Data is sent through a web service. If the data is sent successfully, a confirmation message of "OK" is received. I am trying to switch screens in my BlackBerry App depending on the response received.
FieldChangeListener sendBtnListener = new FieldChangeListener() {
public void fieldChanged(Field field, int context)
{
try {
String alertMsg=sendTextCheckIn();
if(alertMsg.equals("OK"))
{
UiApplication.getUiApplication().invokeLater( new Runnable()
{
public void run ()
{
UiApplication.getUiApplication().pushScreen(new MyScreen());
}
} );
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
However, the above is throwing an App Error 104: IllegalStateException. Can anyone please guide on how to switch screens between a BlackBerry App.
EDIT: I can switch to any other screen but I CAN NOT switch to MyScreen. NOTE: MyScreen is the main (first) screen of the App. The above method sendTextCheckIn() calls another method that is placed inside MyScreen. Has this got anything to do with the error? Please advice.
The 'fieldChanged' event is already running on the UI event thread, so you shouldn't need to do the invokeLater call within it, just call pushScreen directly.
You mention that your problem with IllegalStateException only happens for MyScreen. That makes it sound like something specific with the implementation of MyScreen. Start narrowing down the problem - look at what happens in the constructor of MyScreen, and any events that might get called before the screen is visible. Some of that code is what is causing the problem.
Wrap everything that could possibly raise in exception in try/catch.
Don't do e.printStackTrace() - that won't give you much.
Instead do something like System.err.println ("KABOOM in method abc() - " + e); - seems like more effort, but trust me, that becomes INVALUABLE when debugging issues like this.
Catch Exception, unless you have a VERY good reason to catch a specific a subtype - otherwise you WILL end up with unexpected, and uncaught exceptions, which you will hunt for DAYS.

Visual Studio: How to break on handled exceptions?

I would like Visual Studio to break when a handled exception happens (i.e. I don't just want to see a "First chance" message, I want to debug the actual exception).
e.g. I want the debugger to break at the exception:
try
{
System.IO.File.Delete(someFilename);
}
catch (Exception)
{
//we really don't care at runtime if the file couldn't be deleted
}
I came across these notes for Visual Studio.NET:
1) In VS.NET go to the Debug Menu >>
"Exceptions..." >> "Common Language
Runtime Exceptions" >> "System" and
select "System.NullReferenceException"
2) In the bottom of that dialog there
is a "When the exception is thrown:"
group box, select "Break into the
debugger"
3) Run your scenario. When the
exception is thrown, the debugger will
stop and notify you with a dialog that
says something like:
"An exception of type "System.NullReferenceException" has
been thrown.
[Break] [Continue]"
Hit [Break]. This will put you on the
line of code that's causing the
problem.
But they do not apply to Visual Studio 2005 (there is no Exceptions option on the Debug menu).
Does anyone know where the find this options dialog in Visual Studio that the "When the exception is thrown" group box, with the option to "Break into the debugger"?
Update: The problem was that my Debug menu didn't have an Exceptions item. I customized the menu to manually add it.
With a solution open, go to the Debug - Windows - Exception Settings (Ctrl+Alt+E) menu option. From there you can choose to break on Thrown or User-unhandled exceptions.
EDIT: My instance is set up with the C# "profile" perhaps it isn't there for other profiles?
There is an 'exceptions' window in VS2005 ... try Ctrl+Alt+E when debugging and click on the 'Thrown' checkbox for the exception you want to stop on.
Took me a while to find the new place for expection settings, therefore a new answer.
Since Visual Studio 2015 you control which Exceptions to stop on in the Exception Settings Window (Debug->Windows->Exception Settings). The shortcut is still Ctrl-Alt-E.
The simplest way to handle custom exceptions is selecting "all exceptions not in this list".
Here is a screenshot from the english version:
Here is a screenshot from the german version:
From Visual Studio 2015 and onward, you need to go to the "Exception Settings" dialog (Ctrl+Alt+E) and check off the "Common Language Runtime Exceptions" (or a specific one you want i.e. ArgumentNullException) to make it break on handled exceptions.
Step 1
Step 2
Check Managing Exceptions with the Debugger page, it explains how to set this up.
Essentially, here are the steps (during debugging):
On the Debug menu, click Exceptions.
In the Exceptions dialog box, select Thrown for an entire category of exceptions, for example, Common Language Runtime Exceptions.
-or-
Expand the node for a category of exceptions, for example, Common Language Runtime Exceptions, and select Thrown for a specific exception within that category.
A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:
if(!GlobalTestingBool)
{
try
{
SomeErrorProneMethod();
}
catch (...)
{
// ... Error handling ...
}
}
else
{
SomeErrorProneMethod();
}
I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.
The online documentation seems a little unclear, so I just performed a little test. Choosing to break on Thrown from the Exceptions dialog box causes the program execution to break on any exception, handled or unhandled. If you want to break on handled exceptions only, it seems your only recourse is to go through your code and put breakpoints on all your handled exceptions. This seems a little excessive, so it might be better to add a debug statement whenever you handle an exception. Then when you see that output, you can set a breakpoint at that line in the code.
There are some other aspects to this that need to be unpacked. Generally, an app should not throw exceptions unless something exceptional happens.
Microsoft's documentation says:
For conditions that are likely to occur but might trigger an exception, consider handling them in a way that will avoid the exception.
and
A class can provide methods or properties that enable you to avoid making a call that would trigger an exception.
Exceptions degrade performance and disrupt the debugging experience because you should be able to break on all exceptions in any running code.
If you find that your debugging experience is poor because the debugger constantly breaks on pointless exceptions, you may need to detect handled exceptions in your tests. This technique allows you to fail tests when code throws unexpected exceptions.
Here are some helper functions for doing that
public class HandledExceptionGuard
{
public static void DoesntThrowException(Action test,
Func<object?, Exception, bool>? ignoreException = null)
{
var errors = new List<ExceptionInformation>();
EventHandler<FirstChanceExceptionEventArgs> handler = (s, e) =>
{
if (e.Exception is AssertFailedException) return;
if (ignoreException?.Invoke(s, e.Exception) ?? false) return;
errors.Add(new ExceptionInformation(s, e.Exception, AppDomain.CurrentDomain.FriendlyName));
};
AppDomain.CurrentDomain.FirstChanceException += handler;
test();
AppDomain.CurrentDomain.FirstChanceException -= handler;
if (errors.Count > 0)
{
throw new ExceptionAssertionException(errors);
}
}
public async static Task DoesntThrowExceptionAsync(Func<Task> test,
Func<object?, Exception, bool>? ignoreException = null)
{
var errors = new List<ExceptionInformation>();
EventHandler<FirstChanceExceptionEventArgs> handler = (s, e) =>
{
if (e.Exception is AssertFailedException) return;
if (ignoreException?.Invoke(s, e.Exception) ?? false) return;
errors.Add(new ExceptionInformation(s, e.Exception, AppDomain.CurrentDomain.FriendlyName));
};
AppDomain.CurrentDomain.FirstChanceException += handler;
await test();
AppDomain.CurrentDomain.FirstChanceException -= handler;
if (errors.Count > 0)
{
throw new ExceptionAssertionException(errors);
}
}
}
If you wrap any code in these methods as below, the test will fail when a handled exception occurs. You can ignore exceptions with the callback. This validates your code against unwanted handled exceptions.
[TestClass]
public class HandledExceptionTests
{
private static void SyncMethod()
{
try
{
throw new Exception();
}
catch (Exception)
{
}
}
private static async Task AsyncMethod()
{
try
{
await Task.Run(() => throw new Exception());
}
catch (Exception)
{
}
}
[TestMethod]
public void SynchronousTest()
{
HandledExceptionGuard.DoesntThrowException(() => SyncMethod());
}
[TestMethod]
public async Task AsyncTest()
{
await HandledExceptionGuard.DoesntThrowExceptionAsync(() => AsyncMethod());
}
}

Resources