Im working with the custom compiler from MSDN website. When I try to compile/run some test code (drag and drop to .exe), the console window opens then closes instead of staying open until I choose to close it. How do I keep it open?
Source: http://msdn.microsoft.com/en-us/magazine/cc136756.aspx#S8
Program.cs
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
} //if
add a Console.ReadLine();
at the last inside the try block
try this
if (args.Length != 1)
{
// Display title, reset cursor to normal, add space
Console.WriteLine("Alt ver 1.0 (Alpha)");
Console.WriteLine();
Console.ReadLine();
try
{
Scanner scanner = null;
using (TextReader input = File.OpenText(args[0]))
{
scanner = new Scanner(input);
}
Parser parser = new Parser(scanner.Tokens);
CodeGen codeGen = new CodeGen(parser.Result, Path.GetFileNameWithoutExtension(args[0]) + ".exe");
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.ReadLine();
}
finally
{
Console.Readkey();
}
} //if
else
{
Console.WriteLine("no args");
Console.ReadKey();
}
EDIT:--- passing argument problem
i have made this program and it works perfectly as far as getting filename as arguments
please have a look
class Program
{
static void Main(string[] args)
{
if (args.Length > 0)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
Console.ReadKey();
}
else
{
Console.WriteLine("NO ARGS");
var fileName = Console.ReadLine();
Main(new string[] { fileName });
}
}
}
Related
I am trying to use Microsoft Cognitive Face API for the first time. Documentation gives quite a simple method to detect face from memory stream. I am trying to detect faces from images located inside a folder. Right now there is only one image inside the folder. The issue is whenever the control reaches the following line:
var faces = await faceServiceClient.DetectAsync(memStream, true, true);
it terminates without any exception or error. Here is the complete code I have written.
using Microsoft.ProjectOxford.Face;
using Microsoft.ProjectOxford.Common;
using Microsoft.ProjectOxford.Face.Contract;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
namespace FaceDetection.FaceDetect
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Face Detect";
Start();
}
static async Task Stop()
{
await Close();
}
private static Task Close()
{
return Task.Run(() =>
{
Environment.Exit(0);
});
}
static async Task ReStart(string _reason = "")
{
Console.WriteLine(_reason + "To restart the process press 'R'. To exit press 'X'");
var _response = Console.ReadLine();
if (_response == "r" || _response == "R")
await Start();
else
await Stop();
}
static async Task Start()
{
Console.Clear();
Console.WriteLine("Enter Folder Path");
string imageFolderPath = Console.ReadLine();
if (!Directory.Exists(imageFolderPath))
{
await ReStart("Folder does not exist! ");
}
else
{
await SaveFiles(imageFolderPath);
}
}
static async Task SaveFiles(string imageFolderPath)
{
try
{
DirectoryInfo dInfo = new DirectoryInfo(imageFolderPath);
string[] extensions = new[] { ".jpg", ".jpeg" };
FileInfo[] files = dInfo.GetFiles()
.Where(f => extensions.Contains(f.Extension.ToLower()))
.ToArray();
if (files.Length == 0)
await ReStart("No files found in the specified folder! ");
else
{
string subscriptionKey = "ADSFASDFASDFASDFASDFASDFASDF";
if (!String.IsNullOrEmpty(ConfigurationManager.AppSettings["subscriptionKey"]))
subscriptionKey = ConfigurationManager.AppSettings["subscriptionKey"].ToString();
//var stringFaceAttributeType = new List<FaceAttributeType> { FaceAttributeType.Smile, FaceAttributeType.Glasses, FaceAttributeType.Gender, FaceAttributeType.Age };
//IEnumerable<FaceAttributeType> returnFaceAttributes = stringFaceAttributeType;
IFaceServiceClient faceServiceClient = new FaceServiceClient(subscriptionKey);
foreach (FileInfo file in files)
{
try
{
using (FileStream fileStream = File.OpenRead(imageFolderPath + "\\" + file.Name))
{
MemoryStream memStream = new MemoryStream();
memStream.SetLength(fileStream.Length);
fileStream.Read(memStream.GetBuffer(), 0, (int)fileStream.Length);
//Used following commented code to make sure MemoryStream is not corrupted.
//FileStream _file = new FileStream(imageFolderPath + "\\test.jpg", FileMode.Create, FileAccess.Write);
//memStream.WriteTo(_file);
//_file.Close();
//memStream.Close();
try
{
//This line never returns a result. The execution terminates without any exception/error.
var faces = await faceServiceClient.DetectAsync(memStream, true, true);
if (faces != null)
{
foreach (var face in faces)
{
var rect = face.FaceRectangle;
var landmarks = face.FaceLandmarks;
}
}
else
Console.WriteLine("No face found in image: " + file.FullName);
}
catch (Exception ex)
{
Console.WriteLine("Error");
}
}
}
catch (Exception ex)
{
Console.WriteLine("There was an error!");
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("There was an error!");
}
await ReStart();
}
}
}
Can someone point out what am I missing. Why is this code not working?
When you read the file in to the MemoryStream, your read pointer is advanced to the end. So memStream passed in to DetectAsync() appears empty. The fact is you need not copy your file to memory. You could simply pass in the FileStream after opening.
using (FileStream fileStream = File.OpenRead(imageFolderPath + "\\" + file.Name))
{
try
{
var faces = await faceServiceClient.DetectAsync(fileStream, true, true);
if (faces != null)
{
foreach (var face in faces)
{
var rect = face.FaceRectangle;
var landmarks = face.FaceLandmarks;
}
}
else
{
Console.WriteLine("No face found in image: " + file.FullName);
}
catch (Exception ex)
{
Console.WriteLine("Error");
}
}
Alternatively, you can rewind the memory stream by setting memStream.Position = 0 before calling DetectAsync.
I keep getting a StaleElementReferenceException error when I try to find all links and navigate through them in my console application, I have the following code and tried all day to fix it yesterday but with no result:
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Starting the browser...");
IWebDriver driver = new FirefoxDriver();
driver.Navigate().GoToUrl("http://www.site.ro");
System.Threading.Thread.Sleep(2000);
Console.WriteLine("Gathering the Links...");
List<IWebElement> links = new List<IWebElement>();
try
{
foreach (IWebElement item in driver.FindElements(By.TagName("a")))
{
try
{
if (item.Displayed == true)
{
item.Click();
Console.WriteLine("Item is displayed \a\n" + "Navigating to link...");
} else
{
continue;
}
Random r1 = new Random();
Random r2 = new Random();
Random r3 = new Random();
var last = r3.Next(1, 10) * 700;
var mseconds = r2.Next(1, 10) * 500;
var time = mseconds + r1.Next(1, 10) * 300;
Console.WriteLine("Waiting for " + (time + last) + " miliseconds before next link");
System.Threading.Thread.Sleep(time + last);
driver.Navigate().Back();
System.Threading.Thread.Sleep(2000);
}
catch (Exception e2)
{
Console.WriteLine(e2);
Console.ReadLine();
}
}
}
catch (Exception e1)
{
Console.WriteLine(e1);
Console.ReadLine();
}
Console.WriteLine("Test finished.");
driver.Quit();
}
catch (Exception e)
{
Console.WriteLine(e);
Console.ReadLine();
}
}
}
}
driver.FindElements(By.TagName("a")) is finding for you all the links on the page.
Then you are going to the another page using the first link : item.Click();
Finally you are going back driver.Navigate().Back();
But that's not the initial page (by selenium's opinion). And all the links stored at the first step are gone because your initial page is gone. That's why you can't click the second of them.
You need to refind all the links after each driver.Navigate().Back();
Or better store all the hrefs to a list like linksList.Add(Item.getAttribute("href")); and use stored hrefs.
Hello Friends I'm back with another question! This time it's actually pretty basic. I'm learning how to use text files at the moment and I'm trying to use user input to complete a streamreader argument. The problem I have is that when the program does find that a text file exists, it does not print its contents to the console. Could someone help me with this? The output does not show anything and it continues to infinity not printing. I.E. its just scrolling down.
here's what I have so far.
static void Main(string[] args)
{
Console.WriteLine("Hello! This application lets you write application entries!");
Console.WriteLine("Please Enter The text File: ");
string input = Console.ReadLine();
try
{
StreamReader reader = new StreamReader("C:\\Users\\Nate\\Desktop\\TextFiles\\" + input);
using (reader)
{
string line = reader.ReadLine();
while (reader != null)
{
Console.WriteLine(line);
line = reader.ReadLine();
}
}
}
catch (FileNotFoundException)
{
Console.WriteLine("That file does not exist!");
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Directory does not exist!");
}
catch (IOException)
{
Console.WriteLine("Oops! Something Wrong happened!");
}
Console.ReadKey();
}
Change the following:
while (reader != null)
To:
while (!reader.EndOfStream )
In that way you are reading from the file until its end.
ReadLine need to be inside the loop:
while (!reader.EndOfStream )
{
string line = reader.ReadLine();
// ....
}
For readibility purpose, you can change this:
StreamReader reader = new StreamReader("C:\\Users\\Nate\\Desktop\\TextFiles\\" + input);
using (reader)
{
//...
}
To:
using (StreamReader reader = new StreamReader(#"C:\Users\Nate\Desktop\TextFiles\" + input))
{
// ...
}
Your try block should be as follows;
try
{
StreamReader reader = new StreamReader(#"C:\Users\Nate\Desktop\TextFiles\" + input);
using (reader)
{
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
Console.WriteLine(line);
}
}
}
I'm writing a flesch index calculator and I want to be able to start my program with a console command and the .exe itself. I want to read in .txt files in the console with the command fleschIndexCalc.exe -f "path of the file" and then be able to select the calculation formula either for an english text with the parameter -e or a german text with -g.
When I start it with the console command: I type in the parameters by myself.
When I start it with the .exe: The program asks for the language and I just have to write g ore and press enter.
Now my question: how can I tell my program while starting it with the console that I already chose the language so it doesn't ask me for it again like I started it with the .exe?
Here's what I got:
(If you need more code from my FleschScore.cs ask for it :) )
namespace Flesch_Reading_Ease
{
public class Program
{
public static void Main(string[] args)
{
string fileName = string.Empty;
string[] parameters = new string[] { "-f", "-g", "-e" };
Console.WriteLine("Flesch Reading Ease");
Console.WriteLine("");
if (args.Length == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error!");
Console.ResetColor();
Console.WriteLine("no file found!");
Console.WriteLine("");
Console.Write("press any key...");
Console.ReadKey();
return;
}
foreach (string arg in args)
{
//------- WHAT TO WRITE HERE? -------
}
fileName = args[0];
FleschScore fs = new FleschScore(fileName);
fs.Run();
}
}
}
My method to choose the language looks like this:
private void SelectLanguage()
{
do
{
Console.WriteLine("choose language:");
Console.WriteLine("- german(g)");
Console.WriteLine("- english(e)");
string lang = Console.ReadLine();
switch (lang.ToUpper())
{
case "D":
_selectedLanguage = Language.German;
break;
case "E":
_selectedLanguage = Language.English;
break;
default:
_selectedLanguage = Language.Undefined;
Console.WriteLine("wrong input. Enter viable letter.");
Console.WriteLine("");
break;
}
} while (_selectedLanguage == Language.Undefined);
}
You basically loop through all the arguments and keep track of what's already entered. Then after that you check if you have all the info you need and pass everything as parameters to whatever method/class needs it.
bool isGerman = false;
bool isEnglish = false;
bool nextEntryIsFileName = false;
string filename = null;
foreach (string arg in args)
{
switch (arg)
{
case "-e":
isEnglish = true;
nextEntryIsFileName = false;
break;
case "-g":
isGerman = true;
nextEntryIsFileName = false;
break;
case "-f":
nextEntryIsFileName = true;
break;
default:
if (nextEntryIsFileName)
{
filename = arg;
nextEntryIsFileName = false;
}
break;
}
}
if (!(isEnglish ^ isGerman))
{
// Select language
}
if (String.IsNullOrEmpty(filename))
{
// Ask for filename
}
var language = ...
FleschScore fs = new FleschScore(language, fileName);
fs.Run();
Here's my C# console program that uses Powerpoint to convert ppt files to folders of pngs. This is supposed to be an automated process that runs on its own server.
I expect that as soon as a thread creates an image from a file, it should immediately remove the images and the source file.
The actual behavior is that, if five threads are running, it'll wait for five folders of images to be created before any thread can move any files. I'm able to see the images being created, and compare that with the Console readout, so I can see that a thread isn't trying to move the file.
Only after all the other threads have made their images, will any thread try to move the files. I suspect this is wrong.
This is an Amazon EC2 Medium instance, and it appears to max out the CPU, so five threads might be too much for this.
I also find that I can hardly use Windows Explorer while this program is running.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.IO;
using Microsoft.Office.Core;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using System.Diagnostics;
using System.Timers;
namespace converter
{
class Program
{
public static int threadLimit=0;
public static int currThreads = 0;
static void Main(string[] args)
{
var inDir = args[0];
var outDir = args[1]+"\\";
var procDir = args[2]+"\\";
Int32.TryParse(args[3],out threadLimit);
Thread[] converterThreads = new Thread[threadLimit];
while (true)
{
System.Threading.Thread.Sleep(1000);
var filePaths = Directory.GetFiles(inDir, "*.*", SearchOption.AllDirectories).Where(s => s.EndsWith(".pptx") && !s.Contains("~$") || s.EndsWith(".ppt") && !s.Contains("~$"));
var arrPaths = filePaths.ToArray();
for(var i=0; i< arrPaths.Length; i++)
{
if (currThreads < threadLimit && currThreads < arrPaths.Length)
{
Console.WriteLine("currThreads= " + currThreads + " paths found= " + arrPaths.Length);
try
{
var fileNameWithoutExtension = arrPaths[currThreads].Replace(inDir, "").Replace(".pptx", "").Replace(".ppt", "").Replace("\\", "");
var filenameWithExtension = arrPaths[currThreads].Substring(arrPaths[currThreads].LastIndexOf("\\") + 1);
var dir = arrPaths[currThreads].Replace(".pptx", "").Replace(".ppt", "");
Conversion con = new Conversion(arrPaths[currThreads], dir, outDir, procDir, filenameWithExtension, fileNameWithoutExtension);
converterThreads[i] = new Thread(new ThreadStart(con.convertPpt));
converterThreads[i].Start();
Console.WriteLine(converterThreads[i].ManagedThreadId + " is converting " + fileNameWithoutExtension);
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to convert {0} ", arrPaths[i]) + e);
}
}
}
for (var i = 0; i < converterThreads.Length; i++)
{
if (converterThreads[i] != null)
{
if (!converterThreads[i].IsAlive)
{
converterThreads[i].Abort();
converterThreads[i].Join(1);
Console.WriteLine("thread " + converterThreads[i].ManagedThreadId + " finished, "+currThreads+" remaining");
converterThreads[i] = null;
}
}
}
if (currThreads == 0)
{
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
}
}
class Logger{
static void toLog(String msg)
{
//TODO: log file
}
}
class Conversion{
static int numberOfThreads=0;
String input;
String output;
String outDir;
String process;
String nameWith;
String nameWithout;
int elapsedTime;
System.Timers.Timer time;
public Conversion(String input, String output, String outDir, String processDir, String nameWith, String nameWithout)
{
this.input = input;
this.output = output;
this.outDir = outDir;
process = processDir;
this.nameWith = nameWith;
this.nameWithout = nameWithout;
numberOfThreads++;
Console.WriteLine("number of threads running: " + numberOfThreads);
Program.currThreads = numberOfThreads;
time = new System.Timers.Timer(1000);
time.Start();
time.Elapsed += new ElapsedEventHandler(OnTimedEvent);
elapsedTime = 0;
}
private void OnTimedEvent(object source, ElapsedEventArgs e)
{
elapsedTime++;
}
public void convertPpt()
{
var app = new PowerPoint.Application();
var pres = app.Presentations;
try
{
var file = pres.Open(input, MsoTriState.msoFalse, MsoTriState.msoFalse, MsoTriState.msoFalse);
file.SaveAs(output, Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPNG, MsoTriState.msoTrue);
file.Close();
app.Quit();
Console.WriteLine("file converted " + input);
}
catch (Exception e)
{
Console.WriteLine("convertPpt failed");
}
moveFile();
moveDir();
}
public void moveFile()
{
Console.WriteLine("moving" + input);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving {0} to {1}", input, process + nameWith));
if (File.Exists(process + nameWith))
{
File.Replace(input, process + nameWith, null);
}
else
{
File.Move(input, process + nameWith);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the file {0} ", input) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
}
public void moveDir()
{
Console.WriteLine("moving dir " + output);
try
{
System.Threading.Thread.Sleep(500);
Console.WriteLine(string.Format("moving dir {0} to {1} ", output, outDir + nameWithout));
if (Directory.Exists(outDir + nameWithout))
{
Directory.Delete(outDir + nameWithout, true);
}
if (Directory.Exists(output))
{
Directory.Move(output, outDir + nameWithout);
}
}
catch (Exception e)
{
Console.WriteLine(string.Format("Unable to move the directory {0} ", output) + e);
try
{
foreach (Process proc in Process.GetProcessesByName("POWERPNT"))
{
proc.Kill();
}
}
catch (Exception e3)
{
}
}
finally
{
numberOfThreads--;
Program.currThreads = numberOfThreads;
Console.WriteLine("took " + elapsedTime + "seconds");
}
}
}
}
Every 1000ms you get a list of files in inDir and potentially start a thread to process each file. You have very complex logic surrounding whether or not to start a new thread, and how to manage the lifetime of the thread.
The logic is too complex for me to spot the error without debugging the code. However, I would propose an alternative.
Have a single thread watch for new files and place the file path into a BlockingCollection of files for processing. That thread does nothing else.
Have N additional threads that retrieve file paths from the BlockingCollection and process them.
This is known as a Producer / Consumer pattern and is ideal for what you are doing.
The example code at the bottom of the linked MSDN page shows an implementation example.
On a side note, you are catching and swallowing Exception e3. Don't catch something you will not handle, it hides problems.