system ("pause") in C# won't work. Alternatives? - c#

I am building a program for the purposes of displaying Smartgraph3 readings. Whenever I start debugging, the command line opens but it then immediately disappears. I know ctrl + f5 works, but I was looking for a solution where I would not have to enter the same command to keep it from disappearing.
I have used System("pause"); but it keeps coming up with a blue line under System, and in the error list says 'System' is a 'namespace' but is used like a 'variable'. Does anybody know what is wrong?
Also, I have heard System("pause") should not be used, so does anybody have an alternative that's just as effective?
Here is a copy of my code. Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using Infowerk.SmartGraph3.SmartGraph3API;
//using CSTestClient.SmartGraph;
namespace CSTestClient
{
class Program
{
static void Main(string[] args)
{
TestAPI();
}
static void TestAPI()
{
System.ServiceModel.Channels.Binding service_binding = new BasicHttpBinding();
EndpointAddress endpoint_address = new EndpointAddress("http://localhost:8000/SmartGraph3API/APIV01");
SmartGraph3APIClient client = new SmartGraph3APIClient(service_binding, endpoint_address);
List<SG3APIDeviceIdentification> device_list = client.GetDeviceList();
foreach (SG3APIDeviceIdentification device_identification in device_list)
{
Console.WriteLine("device id: {0}", device_identification.DeviceId);
System("pause");
}
}
}
}

Go ahead and simply use:
Console.ReadKey();

Set a breakpoint on the closing brace of your Main(). Or use an IDE which streams console output to a debug window which persists after the process exits (e.g., Eclipse, I assume basically anything other than VS). No reason to force everyone who actually wants to run your program the normal way to invoke it like:
:; ./myProgram.exe < /dev/null; exit $?
.\myProgram.exe < NUL
See https://stackoverflow.com/a/20487235.

Related

How can I add a static 'Main' method suitable for an entry point?

I am getting an error on my code that says "Error CS5001
Program does not contain a static 'Main' method suitable for an entry point"
I am coding in C# using Microsoft Visual Studio and .NET. This is my code.
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System;
class projectsummer
{
[CommandMethod("OpenDrawing", CommandFlags.Session)]
public static void OpenDrawing()
{
string strFileName = "C:\\DRAFT.dwg";
DocumentCollection acDocMgr = Application.DocumentManager;
if (File.Exists(strFileName))
{
acDocMgr.Open(strFileName, false);
}
else
{
acDocMgr.MdiActiveDocument.Editor.WriteMessage("File " + strFileName +
" does not exist.");
}
}
}
I am not sure how to go about this error. Thank you!
Looking at this post and your previous question, let's try and break down what's going on.
You created a new Console application in Visual Studio. You did not tick "Do not use top level statements". This gave you a Program.cs file that was essentially empty (there was no "Main" method visible).
You erased the Hello World code given to you, and went to make a static method - the code from your previous question.
Damien_The_Unbeliever commented that based on the error, you put your method inside a "top level statement" file, and to put your method inside a class.
You wrap your method (which is still inside Program.cs) in a class, and now suddenly you get a Can't Find Entry Point error.
User Ryan Pattillo posted a great explanation of the original issue - where your method was "by itself" in the Program.cs file. You should follow their advice, but you should also ensure that this class is in its own file.
You should end up with this:
Program.cs
// this is the entire contents of the file
using ConsoleApp1;
ProjectSummer.OpenDrawing();
ProjectSummer.cs
using System.IO;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.Runtime;
using System;
namespace ConsoleApp1
{
public class ProjectSummer
{
[CommandMethod("OpenDrawing", CommandFlags.Session)]
public static void OpenDrawing()
{
// ...
}
}
}
Change ConsoleApp1 to the name of your project.
The entry point of your application, which right now is the only file that has "top level statements", remains Program.cs, thus you fix the Can't Find Entry Point error.
Another adjustment you can make, which seeing you're new to C# might be useful, is to not use top level statements at all. Modify your Program.cs to this:
namespace ConsoleApp1
{
internal static class Program
{
// this is your program's entry point
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
ProjectSummer.OpenDrawing();
}
}
}
Change ConsoleApp1 to the name of your project.
You cannot use the AutoCAD .NET API out of process. To be able to use the AutoCAD .NET libraries, you have to build a "class library" project (DLL) and NETLOAD this DLL from a running AutoCAD process. See this topic about in-process vs out-of-process and you can start from this other one to see how to create an AutoCAD .NET project.

Invoking PS script from C# code (Visual studio 2017)

I am trying to invoke my PS script from C# code.
**PS code. -- Try.ps1**
Write-Host "HelloHost"
Write-Debug "HelloDebug"
Write-Output "HelloOutput"
echo "tofile" > $PSScriptRoot/a.txt
**C# code**
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.ObjectModel;
using System.Management.Automation.Runspaces;
namespace TryitOut
{
class Program
{
static void Main(string[] args)
{
using (PowerShell pshell = PowerShell.Create())
{
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
pshell.AddScript(path + "\\Try.ps1");
IAsyncResult result = pshell.BeginInvoke();
while (result.IsCompleted == false)
{
Console.WriteLine("Waiting for PS script to finish...");
Thread.Sleep(1000);
}
Console.WriteLine("Finished!");
Console.ReadKey();
}
}
}
}
When I run "Try.ps1" independently it runs ok and creates a.txt ans shows console output as expected.
But, it not getting invoked/executed via this C# code.
Question 1. can you please help, what I am doing wrong?
Q 2. How can I see PS console output when invoking Try.ps1 via C# code
Thank you for your time :).
Dealing with output from the PowerShell object is done in two ways. One is the direct return values of the Invoke call, and the other is via various streams. In both cases, you are responsible for dealing with the data; the console does not automatically output them as when you run a script in the standard PowerShell window. For example, to get the results from Write-Object, you can add the following to your C# code after your while loop:
foreach(PSObject pso in pshell.EndInvoke(result))
{
Console.WriteLine(pso);
}
This works fine for the simple strings in your example, but for complex objects with multiple properties, you need to pull the individual properties by name. For example:
string propValue = pso.Members["PropertyName"].Value.ToString();
Have a look at a previous answer of mine to see one way to convert complex objects to your own type: Dealing with CimObjects with PowerShell Inside C#
Handle the debug, information, verbose, etc like this:
foreach(DebugRecord dbr in pshell.Streams.Debug)
{
Console.WriteLine(dbr);
}
You will need to add this to the start of your script as well:
$DebugPreference = 'continue'

Cannot launch Repl() (Xamarin)

I'm writing UITests on Xamarin. I'm trying to launch the Repl window, but it doesn't launch.
My code:
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;
using Xamarin.UITest;
using Xamarin.UITest.Android;
using Xamarin.UITest.Queries;
namespace MurakamiKiev.UITests
{
[TestFixture]
public class Tests
{
AndroidApp app;
[SetUp]
public void BeforeEachTest ()
{
app = ConfigureApp.Android.StartApp();
}
[Test]
public void ClickingButtonTwiceShouldChangeItsLabel ()
{
app.Repl();
}
}
}
What's wrong with my code? Thanks for the help.
I had the same issue, the problem was that app.Repl(); was already running in the background, from the previous session.(When you are debugging if you terminate debugger it wont close automatically)
The error I got was:
System.Exception: 'Error while performing Repl()
Inner exception
IOException: The process cannot access the file 'C:\Users\daniel\AppData\Local\Temp\uitest\repl\ICSharpCode.NRefactory.CSharp.dll because it is being used by another process.
So you just need to close app.Repl(); command prompt that is running in the background
Nothing is wrong with that code. I have seen this happen before but now can't recall the exact resolution. Might have been using NUnit version >= 3. Can you see if you still get the same issue using NUnit version 2.6.3?

C# Console Application Does NOT read from the command line, as it should

I have spent a good while trying to get this simple code to read from the command line:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
if(args.Length > 0)
{
for (int i = 0; i < args.Length; ++i)
System.Console.WriteLine(args[i]);
}
else System.Console.WriteLine("NO COMMAND INPUT DETECTED");
System.Console.ReadLine();
}
}
}
When typing the command:
ConsoleApplication3.application "pleasework"
I get the following message in the command line:
NO COMMAND INPUT DETECTED
indicating that the command line is not working properly. Any thoughts? I am very bad with Visual Studio (this is 2012) so I imagine there is some special property I need to change or something ridiculous.
Thanks!
Using this:
using System;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(args.Length);
Console.Read();
}
}
}
I was able to go to my command prompt and run:
C:\ProjectPath\ConsoleApplication1\bin\debug\ConsoleApplivation1.exe "Test" "Test2"
With a result of:
2
Edit: It looks like you are running a ClickOnce Console Application. This complicates what you want to do, but it isn't impossible. Here are several resources that discuss this particular issue:
Processing Command Line Arguments in an Offline ClickOnce Application
Harvesting ClickOnce Command Line Arguments
How to pass arguments to an offline ClickOnce application
Your code seems to be okay.
You're probably not passing the argument properly.
Take the following steps:
Right-Click on your Project => Properties => Debug => insert "Pleasework" into the command line arguments => save and debug your code step-by-step.
And you'll see:

"does not contain a static 'main' method suitable for an entry point"

I can't figure what's my wrong with my code below.
When I try to compile I get the message:
does not contain a static 'main' method suitable for an entry point.
This is my code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace RandomNumberGenerator
{
public partial class Form1 : Form
{
private const int rangeNumberMin = 1;
private const int rangeNumberMax = 3;
private int randomNumber;
public Form1()
{
randomNumber = GenerateNumber(rangeNumberMin, rangeNumberMax);
}
private int GenerateNumber(int min,int max)
{
Random random = new Random();
return random.Next(min, max);
}
private void Display(object sender, EventArgs e)
{
switch (randomNumber)
{
case 1:
MessageBox.Show("A");
break;
case 2:
MessageBox.Show("B");
break;
case 3:
MessageBox.Show("C");
break;
}
}
}
}
Can someone please tell me where I've gone wrong.
Every C# program needs an entry point. By default, a new c# Windows Forms project includes a Program class in a Program.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace StackOverflow6
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
You are probably missing this or deleted it.
Your project must be created as an empty project. So the output type shows as Console Application. Change it to Class library, and it should work
simple change in code.
main method should be 'Main' (Capital M).
I just had this issue myself.
I created a winforms project, decided to refactor my code and the project would now not contain the UI, so I deleted the Program.cs and winforms files only to get the same error you were getting.
You either need to re add the static void main() method as Matt Houser mentioned above, or go into the project properties and change the output type in the Application tab to Class Library.
I have also experienced this wrong. I changed the dropdown situated in Project properties/Application tab (Output type:). The original selected value was "Class Library" but i changed to "Windows Application" and found same error. Now resolved.
I also faced the similar issue, and i wasted my 13 hours in finding the solution. Lastly, i got the sol...
Right click on the project --> Go to properties -->Change output type to "Class Library"
Vote me up it this helped you.
Late, but for me, it was a "Console Application" project type, but "Build Action" in the file properties was some set to "None". Changed it to "Compile" and it was fine.
Might be you deleted Program file from your project. Just add Program.cs file your problem get resolved
in the Solution Explorer: Right click on Project-->select properties-->select application tab-->select output type as Class library and save it and build it.
My case was very strange - app built fine before, but in one moment I faced with same issue.
What I had :
ConsoleApplication
public static async void Main(string[] args)
so my main is async, but return type is void, but must be Task
public static async Task Main(string[] args)
Worked brilliantly before with void, not sure what was trigger this scenario, where void is became not ok to build
¯ \ (ツ) / ¯

Categories