Could not find 'Program' specified for Main method [duplicate] - c#

This question already has answers here:
Could not find 'WindowsFormsApplication1.Program' specified for Main method after renaming name space
(3 answers)
Closed 2 years ago.
I have this problem where i have 2 files inside a project. One called Program.cs and another called Book.cs
I tried running the Program.cs but it comes up with the error: "Could not find 'Program' specified for Main method".
Here's the code for Program.cs
using System;
namespace Classes_Objects
{
class Program
{
public static void Main(string[] args)
{
Book book1 = new Book();
book1.title = "Harry Potter";
book1.author = "JK Rowling";
book1.pages = 400;
Console.WriteLine(book1.pages);
Console.ReadLine();
}
}
}
Here's the code for Book.cs
using System.Text;
using System.Threading.Tasks;
namespace Classes_Objects
{
class Book
{
public string title;
public string author;
public int pages;
}
}

Please download .net core SDk after that open VS code, open the folder where you want to execute .cs programs and install C# plugin
after that please try these commands which worked for me
open terminal in VS code and type dotnet new console
it will create Program.cs file , .csproj, obj folder
Create your file Book.cs and implement both of your book code and program code in that folder which should have same namespace name
then run this command dotnet run .\Program.cs
The Output will be :
400
Remember in your code there is Console.ReadLine(); after printing the value.

Related

How do I set up an environment to solve LeetCode problems in Visual Studio? C#

When making the file, I am thinking of selecting a console application. But which target framework do I choose? Is this incorrect? Also, I am having trouble figuring out how to make a method in the class Program that is able to be called in the Main method. Can someone give me some advice?
one thing you can do is using interface to keep your code clean; for example :
you create an interface like this:
public interface IQuestionSolving
{
public void Solution();
}
you create some question class :
public class Question1 : IQuestionSolving
{
public void Solution()
{
}
}
and you use it like this :
static void Main(string[] args)
{
IQuestionSolving solve = new Question1();
solve.Solution();
Console.ReadKey();
}
now each time you solve a question you need to change
IQuestionSolving solve = new Question1();
to
IQuestionSolving solve = new Question2(); // 2 3 4 .. etc
you can extract your project as template so you dont have to do this each time .
or you can just use one solution and many classes .
This will get you started with Visual Studio:
Create a new console project - use the latest version of C#, which is probably what VS will "suggest" to you. Currently that's .NET 6 or .NET 7
A modern (net 6 or later) console app lets you start writing code immediately. You could create a method and then call the method right in this little Program.cs file that you start out with. However, I would probably do the following instead:
a) Create a new class for your "problem"
b) In that class create a method that solves the problem.
c) In your Program.cs add a using statement to use the namespace that your new class uses
d) In your program.cs instantiate that class and call its method/test its method
Here is an example:
Program.cs
using LeetCodeProject;
var solver = new Problem001_CalculateSquareRoot();
var solution = solver.calculate_square_root(8);
Console.WriteLine(solution);
Console.WriteLine("Press any key...");
Console.ReadKey();
Problem001_CalculateSquareRoot.cs (solves one leetcode problem)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LeetCodeProject
{
public class Problem001_CalculateSquareRoot
{
public double calculate_square_root(int number)
{
double root = 1;
int i = 0;
while (true)
{
i = i + 1;
root = (number / root + root) / 2;
if (i == number + 1)
{
break;
}
}
return root;
}
}
}
Now you can just add new classes for each problem, and as you work on them just edit Program.cs to create the class you are currently working with and calls its solution methods.
I can (and would - and actually have, in similar cases) implement an interface for this, but the goal here is not to get into OO design principles, but just to get you started so you can get to work on the leetcode problems...once you have a few done you can start thinking about better organization of the code.

Title: C# File.Exist returning false when file can be read from/written to

Development Environment: .Net Framework 4.7.2 using VS 2022 on Win 10 Pro x64
Preface: I've reviewed the two similar questions I found at SO; the first deals with permissions and the second with restrictions on using the root directory. Neither contained info that enabled me to resolve my issue.
I'm working on a C# winforms app which uses a SQLite database. I recently discovered "PRAGMA integrity_check" will create an empty DB and return “ok” if the target DB file is missing so I need to ensure the file’s not gone missing before executing the PRAGMA. My simple solution is to wrap integrity_check in an IF (File.Exist) ELSE but the Exist method is returning ”false”.
In MSDN documentation there 7 stated reasons why a false might be returned in addition to the file actually not existing (listed to avoid the need to follow a link):
path is null
path is invalid
path exceeds maximum length (260)
path is a zero-length string
path has invalid characters
storage media is failing/missing
caller has insufficient permissions to read the specified file
My operating assumption is none of those are the root cause since I can read from and write to the DB programmatically in the app.
Code building the path:
namespace BURS_Library
{
public class MISC
{
public const string DBName = "BURS.db";
}
}
using System;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
namespace BURS_Library
{
public class BURS_Path
{
public static string AppData()
{
string userAppDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
userAppDataDir = userAppDataDir.Replace("Roaming", "LocalLow");
if ( ! Directory.Exists(Path.Combine(userAppDataDir, "BURS_Data_tst")))
{
// display error MessageBox
Environment.Exit(1);
}
return Path.Combine(userAppDataDir, "BURS_Data_tst");
}
public static string DB()
{
return Path.Combine(AppData(), MISC.DBName);
}
{
}
Resultant path: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db
Code with File.Exist
using _Library;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Windows.Forms;
namespace BURS_UI
{
public static class Program
{
[STAThread]
public static void Main(string[] tsArgs)
{
if (File.Exists(BURS_Path.DB()))
{
// perform db Integrity Check
}
else
{
// display error MessageBox
Environment.Exit(2);
}
BURS_Connections.SetConnection(BURS_Path.DB());
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Discover());
}
}
}
If my operating assumption is valid why is File.Exist returning false?
Thank you for your time & expertise.
Following #BentTranberg's suggestion a test was run using the following code (in case its useful to somebody):
if (Directory.Exists(#"C:\Users"))
Save2Log(#"FOUND: C:\Users", true);
if (Directory.Exists(#"C:\Users\Art"))
Save2Log(#"FOUND: C:\Users\Art", true);
if (Directory.Exists(#"C:\Users\Art\AppData"))
Save2Log(#"FOUND: C:\Users\Art\AppData", true);
if (Directory.Exists(#"C:\Users\Art\AppData\LocalLow"))
Save2Log(#"FOUND: C:\Users\Art\AppData\LocalLow", true);
if (Directory.Exists(#"C:\Users\Art\AppData\LocalLow\BURS_Data_tst"))
Save2Log(#"FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst", true);
if (File.Exists(#"C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db"))
Save2Log(#"FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db", true);
Save2Log($"METHOD: {BURS_Path.DB()}", true);
Which produced the following result:
FOUND: C:\Users
FOUND: C:\Users\Art
FOUND: C:\Users\Art\AppData
FOUND: C:\Users\Art\AppData\LocalLow
FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst
FOUND: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db
METHOD: C:\Users\Art\AppData\LocalLow\BURS_Data_tst\BURS.db
Next I reran my original code which surprisingly now worked as expected. To validate that result I ran more test:
int existFail = 0;
for (int i = 0; i < 10000; i++)
{
if ( ! File.Exists(BURS_Path.DB())) existFail++;
}
Save2Log($"number of exist fail in 10,000 = {existFail}", true);
I did that 5 times and in 50,000 iterations there were zero incorrect returns. At this point the error has not been reproduced.
My computer was shut down over night which may have impacted the findings. I will rerun this each morning for the next 3 days and post the results as an edit.

Wixsharp how to reference custom action project

I currently have two projects in my solution, a deployment project which builds the msi and another project which contains my custom actions. I am having trouble referencing my custom actions the same two errros keep appearing:
..\WixSharp Setup\bin\Debug\WixSharpSetup.exe" "/MSBUILD:WixSharp Setup" "/WIXBIN:"" exited with code -532462766. WixSharp Setup ..\WixSharp Setup\packages\WixSharp.1.9.2\build\WixSharp.targets 6
No CA or UI entry points found in module: ..\WixSharp Setup\WixSharp Setup\WixSharpSetup.exe WixSharp Setup ..\WixSharp Setup\WixSharp Setup\EXEC
Deployment project
using System;
using System.Windows.Forms;
using Deploy.CustomAction;
using WixSharp;
using WixSharp.Forms;
namespace WixSharp_Setup
{
class Program
{
static void Main()
{
var project = new ManagedProject("MyProduct",
new Dir(#"%ProgramFiles%\My Company\My Product",
new File("Program.cs")),
new ManagedAction(SearchAPIActions.SearchAPIInstall));
project.GUID = new Guid("6fe30b47-2577-43ad-9095-1861ba25889b");
project.ManagedUI = ManagedUI.Default; //all standard UI dialogs
project.BuildMsi();
}
CustomAction project
public class SearchAPIActions
{
[CustomAction]
public static ActionResult SearchAPIInstall(Session session)
{
session.Log("Begin CustomAction1");
return ActionResult.Success;
}
In case anyone is interested i found the solution to my problem, as the Custom action was compiling to a .dll you need to give a direct reference to it when you declare a managedAction.
new ManagedAction(CustomActions.IISReset, #"Your full Path\Customs.dll"));

Read text file into Clipboard

after along time of searching via google, I decided to poste my problem here.
First: I am total C# Noob. I am using a Macro Recorder from Jitbit and I have no choice to use a different. The Problem is in the Macro Recorder, it is missing some essential things.
Like reading a text file into a variable and paste this variable via Clipboard :-(
However the good thing is, the tool support "some" type of native C# Code
If I open the C# Command I get this:
public class Program
{
public static void Main()
{
System.Windows.Forms.MessageBox.Show("test");
}
}
And the C# program has to follow also these rules:
=> This Code MUST contain a class named "Program" with a static method "Main"
I already used google and found code that should do the job but I get errors, I guess the
code doesn`t follow the above rules.
This is what I found and tried:
using System;
using System.IO;
public class Program
{
public static void Main()
{
// Read the file as one string.
System.IO.StreamReader myFile =
new System.IO.StreamReader("Counter.txt");
string counter = myFile.ReadToEnd();
myFile.Close();
// Load string into clipboard
Clipboard.SetDataObject( counter, true );
}
}
I always get the error : "Line 15: The Name Clipboard is not existing in the context"?!?
I hope that someone can explain a noob (me) what is wrong and what is the correct code.
Thanks.
add reference to System.Windows.Forms
using System;
using System.IO;
using System.Windows.Forms;
public class Program
{
[STAThread]
public static void Main()
{
Clipboard.SetDataObject(File.ReadAllText("Counter.txt"), true);
}
}
Note that to Avoid the ThreadStateException you need to applying the STAThread attribute to your Main() function

C# and Objects/Classes

I have tried to compile code from Deitel's C# 2010 for programmers. I copied it exactly out of the book, but it still can't find main, even though I declared it in one of the classes. Here is a look at the two classes:
For GradeBookTest:
// Fig. 4.2: GradeBookTest.cs
// Create a GradeBook object and call its DisplayMessage method.
public class GradeBookTest
{
// Main method begins program execution
public static void Main(string[] args)
{
// create a GradeBook object and assign it to myGradeBook
GradeBook myGradeBook = new GradeBook();
// call myGradeBook's DisplayMessage method
myGradeBook.DisplayMessage();
} // end Main
} // end class GradeBookTest
Now for the GradeBook class:
// Fig. 4.1: GradeBook.cs
// Class declaration with one method.
using System;
public class GradeBook
{
// display a welcome message to the GradeBook user
public void DisplayMessage()
{
Console.WriteLine( "Welcome to the Grade Book!" );
} // end method DisplayMessage
} // end class GradeBook
That is how I copied them. Here is how they appeared in the book:
1 // Fig. 4.2: GradeBookTest.cs
2 // Create a GradeBook object and call its DisplayMessage method.
3 public class GradeBookTest
4 {
5 // Main method begins program execution
6 public static void Main( string[] args )
7 {
8 // create a GradeBook object and assign it to myGradeBook
9 GradeBook myGradeBook = new GradeBook();
10
11 // call myGradeBook's DisplayMessage method
12 myGradeBook.DisplayMessage();
13 } // end Main
14 } // end class GradeBookTest
and
// Fig. 4.1: GradeBook.cs
// Class declaration with one method.
using System;
public class GradeBook
{
// display a welcome message to the GradeBook user
public void DisplayMessage()
{
Console.WriteLine( "Welcome to the Grade Book!" );
} // end method DisplayMessage
} // end class GradeBook
I don't see why they are not working. Right now I am using Visual Studio Pro 2010. Any Thoughts?
You probably created the wrong type of project at Visual Studio. To be able tu run a project, it must be an application. This means it could be a web application, web site, windows application, console application and so on.
The easier for you to begin is with the console application. Open Visual Studio and point to File > New > Project > Visual C# > Windows > Console Application.
When you create it, you'll notice a Program.cs file. There you can find the main point of your application.
Tip: you might want to add another line below the call of DisplayMessage, which is
Console.ReadLine();
Otherwise the prompt will close so fast that you won't be able to read it.
Good luck on your study!

Categories

Resources