C# Service doesn´t open script - c#

(Sorry for bad english i´m german)
I´m writing a service for a bigger project, the task for it is to check a folder for files and then call a Powershell-Script and give it the name of the file. This part is a bit unclean because i use a Powershellinstance to open a Powershell-Script. The Service itself is working, i tested it with different code to execute and the code to call the Script works when executed by a normal program, but when i let the service call the Script it seems like he just skips that part. The executionpolicy of the Script isn´t the problem. I post the part of the code that is supposed to open the Script. Any ideas?
static void Do()
{
Thread.Sleep(5000);
DirectoryInfo dir = new DirectoryInfo(#"C:\RecosDienstTest"); // Anpassen (json)
try
{
foreach (var datei in dir.EnumerateFiles())
{
using (PowerShell PowerShellInstance = PowerShell.Create())
{
PowerShellInstance.AddScript("C:\\Users\\ZO066\\Desktop\\test.ps1 " + datei.FullName); // Anpassen (PS-Script)
PowerShellInstance.Invoke();
if (PowerShellInstance.Streams.Error.Count > 0) { break; }
}
File.Move(datei.FullName, #"C:\RecosDienstTest2\" + datei.Name); // Anpassen
}
} catch {}
Do();
}

Boys, I finally got it! And I feel so stupid now... In the act of fixing this I changed the code so often, used different methods to open the script, I even destroyed my Visual Studio and had to reinstall it. At some point i decided to open txt-files instead of PS-Scripts but had exactly the same problem: Nothing happend and no Errors what-so-ever. The reason is that when a Service opens something, it just runs in the background no matter what it is(I had a few hundred Notepadinstances opened). The strange thing about this, and the reason why I didn´t thought of it: That happens to the whole chain. The service opened a script that opened a txt-file, but because the script was started by the service the txt-file is also opened in the background. I dont know why that is but I´m glad that I atleast found out why the fck nothing happened.

Related

How do I render debug.log messages before crashing unity

When unity crashes debug.log s from the previous event don't render. Which happens to be the very event that crashed unity (probably via a loop)
So far, I've found Application.Quit(), but obviously, I can only use that if I know precisely when unity would crash (for example for finding out which of some (non nested) loops crashes)
(I also found a lot of info that didn't actually do anything, like opening the console window before starting the game. not listing all of that though)
I guess this example code should describe the problem well enough:
while (condition) {
DoSomething(); //contains a loop too
Debug.Log (value);
Application.Quit ();
}
obviously, only the first iteration happens.
But the inner loop usually won't crash for the first few times. So I'd like to log some values every time the inner loop terminates.
You can add a listener to log message's event (Application.logMessageReceived) in unity and store it in a file or send it via the network to prevent losing them.
void Awake()
{
DontDestroyOnLoad(this);
Application.logMessageReceived += HandleLog;
}
void OnApplicationQuit()
{
Application.logMessageReceived -= HandleLog;
}
void HandleLog(string logString, string stackTrace, LogType type)
{
File.AppendAllText ("D:/Log.txt" /*Path to your log folder*/, logString + stackTrace);
}
You can use Adb logs in cmd.
If you're using Unity with android, you must have already installed adb through Android SDK. Given that, yeah, it should be simple and obvious. And Ben is right. You didn't seem to google enough or take any effort here... But I just hate simple unanswered questions.
There are just a couple things to assure:
Make sure USB debugging is enabled on the Android device (check under Settings -> Development). - Run adb through the command prompt (with command line argument logcat) that comes with the Android SDK while running the game on the Android, still connected via USB to the computer.
adb logcat -s Unity ActivityManager PackageManager dalvikvm DEBUG
Finally, if the Android Debug Bridge can't help you, I'm not sure what could. There was this one time, actually, it couldn't help me... But I was ignoring a unity warning, so I did the debugging checklist in the wrong order.
Source of the answer
You could surround the block in question with a try catch. If it throws an error, you can log it in the catch block.
try
{
while (condition) {
DoSomething(); //contains a loop too
Debug.Log (value);
}
}
catch
{
Debug.Log(value);
}

uglify crashing after running child_process.execFile

EDIT 2
I "solved" the problem, but I don't want to post it as an answer b/c it doesn't explain what actually happened. In the code for the .NET resourceReader.exe I use
Console.OutputEncoding = System.Text.Encoding.UTF8;
to output the internationalized resources to stdout in unicode. If I reset the encoding at the end of my program with
Console.OutputEncoding = System.Text.Encoding.Default;
then I don't get any errors in Node. If I don't reset it, I get the error described in the original question. It seems that .NET is somehow messing up some of the output encoding settings on the cmd.exe and causing the subsequent node run to fail!
EDIT
I narrowed down the error to being caused by resourceReader.exe. It's a.NET program which reads some resource streams out of the .NET assembly and prints them to the stdout using Console.WriteLine. I added Console.OutputEncoding = System.Text.Encoding.UTF8 to resourceReader.exe because some of the resources are in non ASCII letters and that's whats causing the crash in grunt!
If I take that line out, the task doesn't crash, but the resources show up in non printable ASCII characters! Also, the crash only happens if I actually print non-ASCII to sdtout. If I don't print them, it doesn't error.
ORIGINAL
I added a step to my Gruntfile which uses child_process.execFile to run an read some data from an external program and uses it in the build. Now whenever I run my build, it runs fine the first time, but crashes the second time!
Here's the output from the crash (this is during the uglify task):
File build/Scripts/NDB.contacts.min.js created: 16.85 kBevents.js:85
throw er; // Unhandled 'error' event
^
Error: This socket is closed.
at WriteStream.Socket._writeGeneric (net.js:656:19)
at WriteStream.Socket._write (net.js:709:8)
at doWrite (_stream_writable.js:301:12)
at writeOrBuffer (_stream_writable.js:288:5)
at WriteStream.Writable.write (_stream_writable.js:217:11)
at WriteStream.Socket.write (net.js:634:40)
at Log._write (C:\...\node_modules\grunt\node_modules\grunt-legacy-log\index.js:161:26)
at Log.wrapper [as _write] (C:\...\node_modules\grunt\node_modules\grunt-legacy-log\node_modules\lodash\index.js:3095:19)
at Log._writeln (C:\...\node_modules\grunt\node_modules\grunt-legacy-log\index.js:166:8)
at Log.wrapper [as _writeln] (C:\...\node_modules\grunt\node_modules\grunt-legacy-log\node_modules\lodash\index.js:3095:19)
at Log.writeln (C:\...\node_modules\grunt\node_modules\grunt-legacy-log\index.js:177:8)
at Log.wrapper (C:\...\node_modules\grunt\node_modules\grunt-legacy-log\node_modules\lodash\index.js:3095:19)
at writeln (C:\...\node_modules\grunt\lib\grunt\fail.js:30:13)
at Object.fail.fatal (C:\...\node_modules\grunt\lib\grunt\fail.js:46:3)
at process.uncaughtHandler (C:\...\node_modules\grunt\lib\grunt.js:121:10)
at process.emit (events.js:129:20)
at process._fatalException (node.js:236:26)
at Task.runTaskFn (C:\...\node_modules\grunt\lib\util\task.js:250:7)
at Task.<anonymous> (C:\...\node_modules\grunt\lib\util\task.js:293:12)
at C:\...\node_modules\grunt\lib\util\task.js:220:11
at process._tickCallback (node.js:355:11)
Here's the code for the task which uses child_process.
function readAllCultures() {
var readDeferred = q.defer();
childProc.execFile("../tools/resourceReader.exe", function (err, stdout, stderr) {
if (err) throw new Error(err);
var cultures = JSON.parse(stdout);
readDeferred.resolve(cultures);
});
return readDeferred.promise;
}
Here's some things I discovered debugging that might be helpful
If I redirect the output of grunt (using either > filename or | process) it runs fine
When I redirect output, I never see the message from uglify that it created the main output only that it created the source map.
If I close and reopen my command prompt (cmd.exe) it works fine
I added a listener to the exit and close events of the child process using rdr.on("close", function() { console.log("close"); }); and the same for exit. Both events fire as expected in the first run.
Using Process Explorer, I can see node.exe open under the command prompt and close again when my command finishes running. There are no processes visibly "left open" under the command prompt.
The fact that the stack trace is ultimately showing a socket.write error is interesting. Nothing in the code you've provided suggests you are trying to write to a socket.
If we follow the stack down, we can see that it's actually grunt that is trying to write to a socket, as it's attempting to log an uncaught exception.
So, first your grunt task throws a currently unknown error, and then grunt itself errors because it can't tell you about it.
I would first try and log the error that occurs in your child process. Currently if there is an error present, you simply throw it without finding out what it is. It's likely that this is what grunt is trying and failing to log.
Replace
if (err) throw new Error(err);
With
if (err) console.error(err);
This will hopefully avoid the socket.write problem and give you specific information about what error is happening on the child process. What do you see?
Second, I would try using child_process.exec instead of child_process.execFile. This will spawn a shell and run resourceReader.exe inside of it (instead of running it directly). This might help avoid any problems you are encountering with the command still running/failing in the background, which could be the cause of the socket.write error.

CPU is 100% at multithreading

First I've read all the posts here regarding this issue and I manged to progress a bit. However it seems I do need your help :)
I have a program with several threads, sometimes (not always) the CPU usage of the program is increasing up to 100% and never reduced until I shut down the program.
As I read in other similar posts, I ran the app using the visual studio (2012 - Ultimate).
I paused the app, and open the threads window.
There I pauses the threads until I've found the 4 threads which stuck the app.
The all refer to the same line of code (a call for constructor).
I checked the constructor inside and outside and couldn't find any loop which could cause it.
To be more careful I've added break point to almost every line of code and resume the app. None of them have been triggered.
This is the line of code:
public static void GenerateDefacementSensors(ICrawlerManager cm)
{
m_SensorsMap = new Dictionary<DefacementSensorType, DefacementSensor>();
// Create instance of all sensors
// For any new defacement sensor, don't forget to add an appropriate line here
// m_SensorsMap.add(DefacementSensorType.[Type], new [Type]Sensor())
try
{
if (m_SensorsMap.Count <= 0)
{
m_SensorsMap.Add(DefacementSensorType.BackgroundSensor, new BackgroundSensor());
m_SensorsMap.Add(DefacementSensorType.TaglinesSensor, new TaglinesSensor(cm.Database));
m_SensorsMap.Add(DefacementSensorType.SingleImageSensor, new SingleImageSensor());
}
}
catch (Exception)
{
Console.WriteLine("There was a problem initializing defacement sensors");
}
}
The second "m_SensorsMap.Add" is marked with green arrow, as I understand it, it means it's still waiting to the first line to finish.
By the way, the m_SensorsMap.Count value is 3.
How can I find the problem?
Is it a loop?
Or maybe a deadlock (not make sense because it shouldn't be 100% cpu, right?)
It's pointless to upload a code because this is a huge project.
I need more general help like how to debug?
Is it could something else than a loop?
Because it's a bug that returns every while and than I'm not closing the app until I found the problem :)
Thanks in advance!!
Edit:
The constructors:
public TaglinesSensor(IDatabase db)
{
m_DB = db;
}
I couldn't found the problem so I've changed the design on order not to call those constructors anymore.
Thanks for the guys who tried to help.
Shaul

Disable or remove all Console#WriteLine calls?

In my application I have a lot of Console#WriteLine or Console#Write calls. This are so many, that the application is really slower than necessary.
So I'm looking for an easy way to remove or at least disable all Console#WriteLine and Console#Write calls.
What's the easiest way to achieve that?
Here's a even quicker quick fix I implemented.
...
static int Main(String[] args)
{
...
#if !DEBUG
Console.SetOut(TextWriter.Null);
Console.SetError(TextWriter.Null);
#endif
...
}
HTH
Maybe Find&Replace function in any code editor?
For example find all
Console.WriteLine
and replace with
//Console.WriteLine
To switch off Console.WriteLine() output in runtime temporarily use
// backup the previous output handler connected to Console
TextWriter backupOut = Console.Out;
// activate a null handle
Console.SetOut(TextWriter.Null);
// this console output will be invisible
Console.WriteLine("Hidden output on Console.");
// restore the previous handle
Console.SetOut(backupOut);
// this console output will be visible
Console.WriteLine("Showing output on Console.");
Similarly, you can disable program Debug.WriteLine() output in runtime, also while compiling in Debug mode, by using a dummy TextWriterTraceListener, like so
using System.Diagnostics;
using System.IO;
//...
public class MyDummyListener: TextWriterTraceListener
{ }
// ......
[STAThread]
static void Main()
{
// Back up the old one
DefaultTraceListener[] debuglisteners = {(DefaultTraceListener) Debug.Listeners[0]};
// Plug in dummy listener
TextWriterTraceListener[] dummylisteners = {new MyDummyListener()};
Debug.Listeners.Clear();
Debug.Listeners.AddRange(dummylisteners);
// this is an invisible debug message
Debug.WriteLine("This one is invisible");
// ..
// to activate output again, plug in the previous listener
Debug.Listeners.Clear();
Debug.Listeners.AddRange(debuglisteners);
Debug.WriteLine("This one is visible again");
// ....
}
Note: I tested above code in .NET Framework 4.7.2 in Debug mode, using the Winforms platform.
If they are non-essential (logging) then you should have used System.Diagnostics.Debug.Print() to start with.
Luckily WriteLine() is compatible with Debug.Print() so that's an easy S&R. And fix some usings maybe.
Replacing Console.Write() might be a little trickier.
To be complete: The Debug.Print() statements can be turned on/off with a checkbox in project|Properties.
Use a simple, non regex, Find/Replace dialog, and replace every Console.WriteLine( by Debug.WriteLine(.
You can then keep the possibility to track what was previously outputted directly to the console window, still optimizing performance in release mode.
In Visual Studio, use the Tools|Macros|Record temporary macro option to record a macro that does a Find of "Console.Write", and deletes the line. That is:
Ctrl+F to find "Console.Write"
then Ctrl+L to delete the line.
Save the macro and then run it against every file in the project that has the offending lines.
Should take about two minutes.
I would suggest, however, that you back up your source first. Just in case.

Why do I get an InteropServices.COMException when attempting to launch QTP from C#?

This question is a follow-up to the one at Can I use a language other than VBScript to programmatically execute QTP Tests?. I have a C# (.Net 2.0) program which creates an instance of QuickTest.Application and launches QuickTest Professional (version 10.0). All my development testing worked well.
This morning, I attempted to execute the program from a test machine without the development environment (SharpDevelop 2.2.1). I received an error attempting to execute the program when I double-clicked the Windows icon. The console window flashed too quickly to see what it was, so I dropped down to a command prompt and executed the program from there. Everything worked fine. On the second attempted program launch, and all subsequent ones, I receive a System.Runtime.InteropServices.COMException which seems to be caused by the COM object throwing an RPC_E_SERVERFAULT. The function in question is
virtual public QuickTest.Application LaunchQuickTestPro()
{
QuickTest.Application qtpApp = new QuickTest.Application();
qtpApp.Launch();
qtpApp.Visible = false;
return qtpApp;
}
and the qtpApp.Launch(); line is throwing the exception.
I'm at a complete loss as to what could be wrong. It works fine on the dev machine and worked fine once on the test machine. Rebooting between attempts seems to do no good. I'm fairly new to C#, .NET, and COM, so was hoping someone more experienced here might have seen this before. I'm probably missing something simple.
UPDATE: I have discovered this morning, after a reboot, that the Debug build works fine on the test machine (no development environment), but the Release build does not. I am going to try rebuilding and redeploying. Anyone have a suggestion for build options to examine for the Release build?
UPDATE2: It appears that both releases (Debug and Release) work correctly after a fresh reboot. If I try and launch either a second time, I get the error. I've added part of my Main() method and my ExitQTP() method below.
I'm wondering if part of the problem is my misunderstanding how ref should be used. However, the code does work every time when run in the IDE (SharpDevelop 2.2.1).
It does appear that something is not being properly cleaned up after the first run, but I don't know what. Looking at the task monitor, the QTP* processes go away as I expect them to. I think there may be a third process that is causing the problem, but haven't been able to isolate what that is,
//Program starts here
[STAThread]
public static void Main(string[] args)
{
string configFileName =
ConfigurationManager.AppSettings.Get("TestPathsConfigFile");
TextReader configFile = new StreamReader(configFileName);
QTPLauncher launcher = new QTPLauncher();
string testName = null;
try
{
Debug.WriteLine("Creating QuickTest.Application object...");
QuickTest.Application qtpApp = launcher.LaunchQuickTestPro();
Debug.WriteLine("Successfully created QuickTest.Application object...");
while((testName = configFile.ReadLine()) != null)
{
if((testName != string.Empty) &&
(!(testName.TrimStart()).StartsWith(COMMENT_START)))
{
Debug.WriteLine(testName);
launcher.ExecuteQTPTest(testName, ref qtpApp);
}
}
configFile.Close();
... //code unrelated to problem removed.
configFile = null;
launcher.ExitQTP(ref qtpApp);
}
catch(System.Runtime.InteropServices.COMException ce)
{
Console.Error.WriteLine(ce.StackTrace);
}
}
//Exits QTP
virtual public void ExitQTP(ref QuickTest.Application qtpApp)
{
qtpApp.Quit();
qtpApp = null;
}
I suspect the issue is that you are not properly closing (quitting) your QT app instance (if you check your task manager you may see it running) so the subsequent runs fail to initialize properly.
There is a decent blog post where Grant Holliday automates QT for running under Team Build. Many of the same principles would apply.
http://ozgrant.com/2008/02/28/running-hp-quicktest-professional-ui-tests-with-team-build/
If that's not the issue you'll need to provide more details about what you do with the QT application object.
Use the following:
Object oQTPapp;
oQTPapp = Server.CreateObject("QuickTest.Application");
Application qtpApp = (Application) oQTPapp;
Hopefully it will resolve your problem.

Categories

Resources