Warning CS7022 - The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point - c#-9.0

so I have an issue where I have this warning in my Error List:
Severity Code Description Project File Line Suppression State
Warning CS7022 The entry point of the program is global code; ignoring 'Program.Main(string[])' entry point. Project DirectoryToProject 23 Active
This is essentially where its throwing
namespace MyProgram
{
class Program
{
static async Task Main(string[] args) => await new Program.MainAsync();
}
static async Task MainAsync()
{.. do stuff.. }
}
That is the line of code that is causing the error. I've tried playing around with the Main class, I did have it with the return type void and had my GetAwaiter and GetResult method called on the MainAsync method.
I've tried researching the error but I've had no luck, so hopefully, this thread will help a few others...
I am currently running on C# 9.0
Visual Studio 2019 Build Version: 16.8.30717.126
EDIT: Forgot to show that the MainAsync was in the file... (Sorry) Im trying to limit the amount of methods I show as 95% of them aren't useful the to question... But the issue is that although my application compiles, when executing my program it quits instantly as if it doesn't know where to start...
EDIT 2:
Thanks to Hans Passant -
If anyone experiences something like this try what he mentioned:
"This is a rather awful C# v9 feature. Project > Properties > Build tab, Advanced button > Language version = 7.3 You should now get a decent error message from the code you didn't know you had to post".
Essentially upon changing back to C# 8.0 I saw it was a different file hidden away causing the issue.

Starting with net5.0, I've found that this error can be caused by having stray semicolons above the namespace keyword. Whether this is a bug or intended behavior is beyond me, however make sure you don't have any standalone semicolons as such:
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
; // This will cause CS7022
namespace Tomoe.Commands.Public
Be sure to check all your files and not just Program.cs
EDIT: Apparently this is intended behavior, see https://github.com/dotnet/roslyn/issues/53472.
TL;DR, semicolons above namespaces are interpreted as top level statements. Because nothing is being called in said statement, the program exits. This is the same as doing
static void Main() {
;
}
in your Program.cs. While I do feel some change should be made, the design decision behind this is quite logical and entirely understandable.
EDIT 2: According to jcouv on Github, this is now becoming an error instead of a warning. Hopefully, this "bug" shall harass us no more!

This can happen if a file (any file) in the project has global code, that's to say statements outside of a class.

As mentioned by others, this is caused by a new C# 9 feature that is called "Top-level statements". This Feature enables you to write statements in the global context and the compiler will create it's own Main() based on that.
In my case I had a semicolon after my using statements in any of my files. As far as I know Visual Studio or the compiler don't give you any option to find this "entry-point" without changing any settings as descripted by others in this thread.
My solution was to just create another "Top-level statement entry point" in my project. Due to the fact that there is only one allowed the compiler complains about that.
I just added a semicolon directly after the using statements in my Program.cs. Because this file is one of the first that are processed by the compiler any other file that contains a "Top-level statement" will cause an error.

I've also seen this compiler error in the following scenario. You've written your code with top-level statements. Later, you decide to absorb that logic into a Main() method. (Maybe you find you now need to return an async Task, or you need to modify it to meet a company coding standard, for example.) Even though the following code block will compile (in VS2022 at least), it generates the error in question with a green squiggly beneath Main:
static void Main()
{
Console.WriteLine("Inside the Main() method");
//Do some other work here
}
Where's the issue? The method declaration is correct, and it will run, but even when this is the only code in the Program.cs file, and even when no other entry point is specified in the project/solution settings, we do not get the expected output:
Even the Microsoft documentation isn't much help in this case, because it pretty much repeats in more detail what the error is saying.
What's missing is the Program class definition. Without it, the compiler is still looking for a top-level statement - which it finds, namely static void. Then the next thing it finds is the Main() method declaration, but it finds this after the (unintended) top-level statement static void. Hence, the error sorta makes sense now.
The fix is to wrap the above code in a Program class:
class Program
{
static void Main()
{
Console.WriteLine("Inside the Main() method");
}
}
And now we get the expected output:

Related

Unity Can't Find C# Script

I can't seem to compile on Unity because all of my scripts have errors. The error messages keep on repeating, "The associated script cannot be loaded. Please fix any compile errors and assign a valid script." I have checked all of my scripts on Visual Studio 2017 and have not found any errors.
The image below shows the error showing on the inspector view of the unity engine:
If there are really no compiler errors as you say the reason might be incorrect file names or class types.
Make sure that the file names and the class names match!
If your class is called
public class Player_Collision1 : MonoBehaviour
{
...
}
the script/file must exactly be called
Player_Collision1.cs
and the other way round.
Attention: The Unity project view (Assets) strips of the file endings so there it should only display as
Player_Collision1
Another reason for a script to be not valid is e.g. if your class doesn't inherit from MonoBehaviour at all.
Unity would usually prevent you from adding those "invalid" scripts to an object but it might happen that you renamed them or changed their type afterwards. In this case you will see the error you currently have.
Check you log and see if any compiler error has happened.If no have a look at your class name and file name are same.
I see that you are (relatively) new here. welcome to Stack Overflow! ^^
what unity is trying to say is that it can't compile your scripts because there is one or more another script(s) that have errors in them.
in the Console, you will find your errors and by double left clicking on one of then, you will be taken to the script and the location of its error.
by selecting (left click) an error you will be able to read more a more detailed description of the error.

cannot debug GWT native code within gwtmockito

I have a GwtMockitoTestCase and the debugger seems not to enter inside any vanilla GWT class like Widget, ResizeLayoutPanel, etc.
However, when running the same code inside DevMode, the debugger steps correctly through that code.
Does this have to do with GWT running inside a JRE? If not, could it be that my classpath is wrong somehow? Or maybe the gwt-user jar doesn't have debugging information?
I've also tried to extend a GWT class:
ResizeLayoutPanel w = new ResizeLayoutPanel() {
#Override
public void setWidget(Widget pW) {
super.setWidget(pW); (1)
}
};
And breakpoint on line (1) is working but pressing F5, it doesn't go inside ResizeLayoutPanel's setWidget method.
Thank you!
After digging in the GwtMockito code, it seems there are a certain set of classes that are stubbed and some methods' body is removed. Therefore it's not possible to debug those methods.
The question that remains is that somehow GWTMockito breaks the code coverage tool(EclEmma) which shows less code covered than it's supposed to. I've posted a separate question on this topic on SO: false code coverage reported using GwtMockito
Some technical background:
GwtMockitoClassLoader stubs some classes from GWT completely, please check GwtMockitoTestRunner#getClassesToStub() which includes Widget and ResizeLayoutPanel classes.
The stubbing process removes the body completely for the methods returning primitive values or void, see GwtMockitoClassLoader#onLoad. If the return is a java bean, it will return a mocked version for it.

What causes GWT to output: <SomethingNotNull>.nullMethod()?

I have my own emulation of java.util.Timer (and quite a lot of other stuff missing in GWT). I have even a JUnit test proving it works in the browser.
I've just tried to convert some third-party library to GWT, which needed a Timer, and in some part of it, I call:
SystemUtils.getTimer().scheduleAtFixedRate(timerTask, value, value);
But the GWT compiler turns getTimer().scheduleAtFixedRate() to:
getTimer().nullMethod()
SystemUtils.getTimer() is a static method. I have googled for nullMethod(), but most hits are about:
null.nullMethod();
That doesn't apply to me. What could be going wrong, and what can I do to fix it?
[EDIT] Actually, the java.util.Timer emulation itself works, but it seems that (atm?) SystemUtils.getTimer() returns "undefined". Could that be the reason? Since getTimer() returns an instance created dynamically, how could the GWT compiler possibly make any assumption about the return value of getTimer(), and the presence/usage of the methods of the Timer type?
When I have seen this kind of errors it was caused by unreachable code: GWT had determined that some code was not reachable, turning off compilation for some stuff, but then it still somehow tried to link the unreachable code, showing this kind of errors.
For completeness sake
If this error shows up (which often happens after deploying to App Engine) then compile without obfuscation, turn off super dev mode, restart jetty and refresh the browser. Open the generated javascript and find where the problem occurs by searching for 'nullMethod'. You'll see that the compiler may have removed whole chunks of code that it believes is 'unreachable'.
The code surrounding 'null.nullMethod' is probably very different than what you expected. The simplest way around this is to add a null /undefined check and initializing whatever variable that is generated as 'null'. This forces the compiler to reconsider because now the variable can never be null and the code that follows it must be reachable.
For example, if null.nullMethod is found and 'null' is actually supposed to be var a = ... then add if(a == null) { a = ""; } before it (in Java of course).
For anybody who struggles with this null.nullMethod issue:
It may be possible that your GWT compiler isn't able to find the properties of your JSON bean object if your object variable is declared with its interface type:
MyTypeIF item = ...;
...
item.getStart();
...
In my scenario, GWT compiled that into:
MyTypeIF item = ...;
...
null.nullMethod();
...
Instead, I had to declare and cast it to its real implementation class:
JSMyType item = (JSMyType)...;
...

Java / Eclipse - macro to specify current method name?

I'm using eclipse and want to have a "macro" that the preprocessor will replace with the name of the current method before compiling it.
I have an error reporting function, that is called as: reportthis(String errormessage) - different functions throughout the application have try/catch blocks, that call reportthis(...) from the catch block upon errors.
I'd like to be able to specify something like reportthis(MACRO_CURRENT_METHOD_NAME + ":" + e.ToString()); - where MACRO_CURRENT_METHOD_NAME will be preprocessed by eclipse before compilation and result in the name of the method where the catch {} block calls reportthis().
So if the catch{} block happens in main(), the macro should return the string "main" (or "main()", etc.).
Is this possible? how do i go about achieving my goal?
Thank you!
Edit
I wish to get this done by preprocessors in Eclipse - are those impossible? isn't it possible to perhaps write a plugin for eclipse to replace all occurrences of "MACRO_CURRENT_METHOD_NAME" with the current function name?
I've not found an automated way of doing this, so have manually added a string literal that indicates the name of the caller at each invocation of the logging code.
Nokia's S40 platform is also based on Java-ME, and I know some Nokia S40 developers have made good use of Jarrut, which is available on Sourceforge, to produce stack traces by modifying the program to track the stack. You could leverage this functionality to get the calling function name in your logging code, but you may need to modify Jarrut a bit to make that work.
Java does not support Macros.
But what you can do to determine the current method is something like
final StackTraceElement aTop = Thread.currentThread ().getStackTrace ()[1];
System.out.println (aTop.getMethodName ());
By using the element at index [1] you get the calling method, because the element at [0] is Thread.getStackTrace().
If you wrap this code in an additional method, you must adopt the array index e.g. to 2, depending on the number of wrapping methods you are using.
There is no preprocessor in java, and no macro language either.
While there are situations where either could be useful, if I understand your problem its entirely pointless, since the stack trace of the exception will already contain class and method of the place where the excetion occured.
Instead of passing a String to your "reportthis()", make a signature that just takes the exception and prints it (or just write e.printStackTrace()).

Silverlight 4, MEF, Export/Import errors, Mefx doesn't want to work

Out of frustration and more than 3 days googling up this issue... i have no choice but to bother you guys with my question.
i am creating a Silverlight application. I am using MEF. When i try to run my application i get the following error.
The invocation of the constructor on
type
'IFG.Silverlight.Client.Views.MenuView'
that matches the specified binding
constraints threw an exception. [Line:
25 Position: 47]
and its Inner exception is as follow...
The composition remains unchanged. The
changes were rejected because of the
following error(s): The composition
produced a single composition error.
The root cause is provided below.
Review the CompositionException.Errors
property for more detailed
information.
1) No valid exports were found that
match the constraint
'((exportDefinition.ContractName ==
"MenuViewModel") AndAlso
(exportDefinition.Metadata.ContainsKey("ExportTypeIdentity")
AndAlso
"IFG.Silverlight.Client.ViewModel.MenuViewModel".Equals(exportDefinition.Metadata.get_Item("ExportTypeIdentity"))))',
invalid exports may have been
rejected.
Resulting in: Cannot set import
'IFG.Silverlight.Client.Views.MenuView.ViewModel
(ContractName="MenuViewModel")' on
part
'IFG.Silverlight.Client.Views.MenuView'.
Element:
IFG.Silverlight.Client.Views.MenuView.ViewModel
(ContractName="MenuViewModel") -->
IFG.Silverlight.Client.Views.MenuView
Ok. my code is very simple since it's a test application.
i have an Interface IRetailModel
namespace IFG.Silverlight.Client.Common
{
public interface IRetailModel
{ ............
then i have a class that implements this interface
namespace IFG.Silverlight.Client.Model
{
[Export(typeof(IRetailModel))]
public class RetailModel : IRetailModel
{ .................
Then I have my ViewModel for the View
namespace IFG.Silverlight.Client.ViewModel
{
[PartCreationPolicy(CreationPolicy.NonShared)]
[Export(ViewModelTypes.MenuViewModel)]
public class MenuViewModel : IFGViewModelBase
{
IRetailModel _model;
[ImportingConstructor]
public MenuViewModel(IRetailModel model)
{
Well, i found that there is a magical tool called MefX that it's supposed to debug deep to the bone your code and tells you what's going on... I havent been able to get this to work.
I followed directions from this article http://blogs.msdn.com/b/nblumhardt/archive/2009/09/24/debug-composition-from-within-visual-studio.aspx
When i try to run it says
Error: Unable to load one or more of
the requested types. Retrieve the
LoaderExceptions property for more
information.
Then went back to Google and i found this Visual MefX (which is the same but with a GUI) and i can load the .xap but basically it gives me the same info that i get from Visual Studio. I can't find the darn [BECAUSE]...
I am really, HONESTLY AND DEEPLY, frustrated with this situation. Can anyone explain to me where am i failing to get MefX to do its job? I know the risk of dealing with these Overnight Frameworks (lack of documentation, buggy, etc etc) that MEF seems to be, but Prism is not a option to me (i feel like buying a M16 to kill a fly when i can use my finger).
Thank you
For future reference, an updated version of Visual Mefx is attached to this blog post: How to Debug and Diagnose MEF Failures. It is also part of MEFContrib, although I'm not sure if the MEFContrib version has all the changes from the version in the blog post.