My windows service runs properly if I debug or run as console application, but if I install, it shows in services but doesn't runs at all. Please Help
This is main function
static void main(){
if (Environment.UserInteractive)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Service1";
// Determine whether the directory exists.
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
//di.Delete();
}
StreamWriter sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Service1\\program.txt", true);
sw.WriteLine(DateTime.Now.ToString() + " : Here if\n");
// sw.WriteLine("userprofile " + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + " : ");
// sw.WriteLine("application data " + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + " : ");
sw.Flush();
sw.Close();
Console.WriteLine("here1");
Service1 service1 = new Service1();
string[] args = { "Kun", "Singh" };
service1.TestStartupAndStop(args);
}
else
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Service1";
// Determine whether the directory exists.
if (!Directory.Exists(path))
{
DirectoryInfo di = Directory.CreateDirectory(path);
//di.Delete();
}
StreamWriter sw = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Service1\\program.txt", true);
sw.WriteLine(DateTime.Now.ToString() + " : Here else\n");
// sw.WriteLine("userprofile " + Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + " : ");
// sw.WriteLine("application data " + Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + " : ");
sw.Flush();
sw.Close();
Console.WriteLine("here2");
// Put the body of your old Main method here.
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new Service1()
};
ServiceBase.Run(ServicesToRun);
// RunAsync().Wait();
Service1 myServ = new Service1();
myServ.write("hello bb");
Console.Read();
}
Might because of Environment.UserInteractive is returning false. You are running a service which means there is no user interface. See Environment.UserInteractive Property
The UserInteractive property reports false for a Windows process or a
service like IIS that runs without a user interface. If this property
is false, do not display modal dialogs or message boxes because there
is no graphical user interface for the user to interact with.
I suggest try changing the condition to if (!Environment.UserInteractive)
I just made a new setup WIX and now its working, though there is second problem... I have some references in my windows service project, How can I include them in setup as I when install and run, i have log file which says xxx.dll is missing
I have following references -> jose-jwt.dll , entity framework..
So how do I setup along with reference files
Related
I have scheduled an EXE and in that I wrote a code to save all logs in a file. When I run that project locally, the logs are generated but when the exe is scheduled in task scheduler the log file is not generated. I checked my debug folder path but the file is not generated there. I checked this path as well : C:\\Windows\System32\ScheduleProcessing_Errors. But it is not generated there either.
This is how I am writing the logs:
public static void WriteErrorLog(string MsgBody, string innerexp, string Caller, string MethodName)
{
try
{
string Path;
string Todaydate = System.DateTime.Now.ToString("dd-MMM-yyyy");
Path = Application.StartupPath + "\\ScheduleProcessing_Errors";
if (Directory.Exists(Path) == false)
{
Directory.CreateDirectory(Path);
}
Path += "\\NewLogToFindMyErr" + Todaydate + ".txt";
StreamWriter SW = new StreamWriter(Path, true);
SW.WriteLine(DateTime.Now);
SW.WriteLine(Caller + "\t" + MethodName + "\t" + MsgBody + "\t" + innerexp);
SW.WriteLine(Environment.NewLine);
SW.WriteLine("-------------------------------------------");
SW.Write(Environment.NewLine);
SW.Close();
}
catch (Exception ex)
{
throw new Exception(ex.message);
}
}
While you setup the task scheduler, chose Run Whether the user logged in or not, and opt=> Do not store password. It will give access to computer local resources
Most would probably ignore this but I really need help. I am currently developing a Windows Service that uses FileSystemWatcher to monitor the changes on the web.config files on remote web servers.
What it generally does is upon initialization of the service, it gets the websites on IIS from a list of web servers defined in app.config, then puts a FileSystemWatcher on the the websites' web.config file and another file named web.config.orig.
When either the web.config or the web.config.orig file changes, it triggers the FileSystemWatcher then checks the LastModifiedDate of both files. If is not equal, it should generate an event log that says the the file's modified dates are not in sync.
The service successfully installs then I was able to test it one time, but it triggers the FileSystemWatcher a lot then generates a lot of this sort of error in the System Logs:
DCOM was unable to communicate with the computer Server1 using any of the configured protocols; requested by PID 4c08 (C:\Users\user1\Desktop\DynamicFSW\DynamicFSW\bin\Debug\DynamicFSW.exe).
You can download the source code here: https://www.dropbox.com/s/1pkh543g5n578fy/DynamicFSW.rar?dl=0
private void file_OnChanged(object sender, FileSystemEventArgs e)
{
FileSystemWatcher fsw = (FileSystemWatcher)sender;
try
{
fsw.EnableRaisingEvents = false;
string directory = Path.GetDirectoryName(e.FullPath);
string webconfig = directory + "\\web.config";
string webconfigorig = directory + "\\web.config.orig";
DateTime dt1 = File.GetLastWriteTime(webconfig);
DateTime dt2 = File.GetLastWriteTime(webconfigorig);
DynamicFSWEventLog.WriteEntry("" + e.FullPath);
string server = "";
for (int i = 2; i < directory.Length; i++)
{
if (directory[i] != '\\')
{
server += directory[i];
}
else
{
break;
}
}
DynamicFSWEventLog.WriteEntry("" + server);
if (!System.DateTime.Equals(dt1, dt2))
{
ServerManager IIS = Microsoft.Web.Administration.ServerManager.OpenRemote(server);
foreach (Site site in IIS.Sites)
{
if (Path.GetDirectoryName(e.FullPath).Equals("\\\\" + server + "\\" + site.Applications["/"].VirtualDirectories[0].PhysicalPath.Replace(':', '$')))
{
string message = "Server: " + server + "\n" +
"Website: " + site.Name + "\n" +
"Web.config.LastWriteTime: " + dt1 + "\n" +
"Web.config.orig.LastWriteTime: " + dt2 + "\n\n" +
"Web.config and Web.config.orig file's last write time not in sync!";
DynamicFSWEventLog.WriteEntry("" + message);
}
}
}
}
finally
{
fsw.EnableRaisingEvents = true;
}
}
I would really appreciate anyone's help on this.
Thanks!
My requirement is to execute a bash script "PostProcessShellScript.sh" in PostProcessBuild. Unity build runs fine, but build fails in Unity Cloud Build.
Below is my code :
public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject) {
.....
string scriptPath = Application.dataPath + "/Plugins/Android/Editor/PostProcessShellScript.sh";
//Runs fine on Local Unity build
//RunInShell("C:\\Program Files\\bash.exe","/" + scriptPath + " " + " " + "/" + apkPath + "/"+ "/" + apkName, false);
RunInShell("open","/" + scriptPath + " " + " " + "/" + apkPath + "/"+ "/" + apkName, false);
}
public static void RunInShell(string file, string args, bool waitForExit = true) {
System.Diagnostics.Process ppScriptProcess = new System.Diagnostics.Process();
ppScriptProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
ppScriptProcess.StartInfo.FileName = file;
ppScriptProcess.StartInfo.Arguments = args;
ppScriptProcess.StartInfo.UseShellExecute = false;
ppScriptProcess.StartInfo.CreateNoWindow = false;
ppScriptProcess.StartInfo.RedirectStandardOutput = true;
ppScriptProcess.StartInfo.RedirectStandardError = true;
ppScriptProcess.Start ()
}
Error details on UCB :
! Unity player export failed!
! build of 'default_-android' failed. compile failed
Publishing build 22 of surbhijain87/roll-a-ball-game for target
'default_-android'...
publishing finished successfully.
done.
Build step 'Execute shell' marked build as failure
postbuildstatus finished successfully. Finished: FAILURE
too implicit.
I am using the shell scripting to resolve the issues.
UCB running on mono and shell scripting looks like the way to go.
Your resolution: convert the code to a shell script and attach on the UCB config from the UI
I am writing a program to function as a testing plugin with a third party program. I have talked with the developer on the other end (don't get me started) and he is using VB 6 to create a batch file and then calls the batch file using a shell command. His batch file is calling my plugin which I have written to output data to a file based on the parameters that I receive via his batch file.
My problem is that when his program calls the batch file via a shell command (again, he is using VB 6), my program executes and the console writelines that I put in place in front of and after the filestream stuff all execute, but the files are not created and therefore his program does not read the file I create (CP07.txt in this case). If I manually run the batch file from Windows explorer everything works as expected. I do have a process monitor capture if that is beneficial. The program is running as the local admin on a Win7 machine (although it is not elevated), UAC is disabled, there is no anti-virus software installed, and it is not writing to a root or system folder.
I appreciate any pointers. Since the ProcMon capture is long (1400+ lines), I have not posted it.
Regards,
S
Here is a sample batchfile from the other program...
Full path to my exe
Full path to the output file
Parameter for my use
Username
Password
C:\SpecifiedDir\myprogram.exe C:\Specified\Directory\CP07.txt parameter username password
I am overwriting the output file parameter as you can see because it did not work initially the other way (I think maybe something to do with the slashes being escaped or something) and I wanted to start with a simple and working program and then clean it up from there.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace Plugin
{
class Program
{
static void Main(string[] args)
{
Console.Write("Press any key to begin: ");
Console.Write("Starting...", Console.ReadLine());
//Console.WriteLine("Done");
Console.WriteLine("Number of command line parameters = {0}",args.Length);
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
}
Console.WriteLine("");
TextWriter defaultOutputMethod = Console.Out;
TextWriter defaultErrorOutputMethod = Console.Error;
FileStream fStream;
StreamWriter strWriter;
FileStream fErrorStream;
StreamWriter strErrorWriter;
try
{
fStream = new FileStream("./Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write);
strWriter = new StreamWriter(fStream);
}
catch (Exception e)
{
Console.WriteLine("Cannot open Redirect.txt for writing");
Console.WriteLine(e.Message);
return;
}
try
{
fErrorStream = new FileStream("./RedirectError.txt", FileMode.OpenOrCreate, FileAccess.Write);
strErrorWriter = new StreamWriter(fErrorStream);
}
catch (Exception e)
{
Console.WriteLine("Cannot open RedirectError.txt for writing");
Console.WriteLine(e.Message);
return;
}
Console.SetOut(strWriter);
Console.SetError(strErrorWriter);
Console.WriteLine("Number of command line parameters = {0}", args.Length);
for (int i = 0; i < args.Length; i++)
{
Console.WriteLine("Arg[{0}] = [{1}]", i, args[i]);
}
// Store parameters into variables for reference
string pSuccess = "OK";
string pFail = "FAIL";
string pOutputFile = args[0];
string pLookupType = args[1];
string pUserName = args[2];
string pPassword = args[3];
Console.SetOut(defaultOutputMethod);
// Console.SetError(defaultErrorOutputMethod);
strWriter.Close();
fStream.Close();
// Setup Commnet filestream and stream writer, and assign output to stream if file successfully created
FileStream fCommnetStream;
StreamWriter strCommnetWriter;
string sCommnetOutputFile = #"./CP07.txt";
try
{
fCommnetStream = new FileStream(sCommnetOutputFile, FileMode.OpenOrCreate, FileAccess.Write);
strCommnetWriter = new StreamWriter(fCommnetStream);
}
catch (Exception e)
{
Console.WriteLine("Cannot open " + sCommnetOutputFile + " for writing");
Console.WriteLine(e.Message);
return;
}
Console.SetOut(strCommnetWriter);
// Test Variables to determine output: Success or Failure
string sSuccessPass = "1111";
string sFailPass = "0000";
if (pPassword == sSuccessPass)
{
Console.WriteLine(pSuccess);
}
else if (pPassword == sFailPass)
{
Console.WriteLine(pFail);
}
else
{
Console.WriteLine("OTHER");
}
Console.WriteLine("Output File: <" + pOutputFile + ">");
Console.WriteLine("Lookup Type: <" + pLookupType + ">");
Console.WriteLine("User Name: <" + pUserName + ">");
Console.WriteLine("User Pass: <" + pPassword + ">");
Console.SetOut(defaultOutputMethod);
Console.SetError(defaultErrorOutputMethod);
strCommnetWriter.Close();
fCommnetStream.Close();
strErrorWriter.Close();
fErrorStream.Close();
Console.Write("Press any key to finish: ");
Console.Write("Ending...", Console.ReadLine());
//Console.WriteLine("Done");
}
}
}
I guess the problem is that you are writing into the "current directory", which can be anything when your program is started by a batch file, which itself has been started by another application. It is not impossible that your files are written into the directory where the batch file resides :)
In debug mode, while running the C# WinForms App, I successfully select multiple files through the OpenFileDialog, which is then displayed in the logging window, these files are copied to a temp directory and I believe I get the error when trying to convert the excel files to csv. I get the following runtime debug error:
Error: You may not have permission to read the file or it may be corrupt.
Reported Error: Length Can not be less than zero.
Parameter Name: Length.
How do I fix this error?
Here's my code on MainForm.cs
// Consolidate Button Click Commands that executes if there are no user input errors
void ExecuteConsolidate()
{
string consolidatedFolder = targetFolderBrowserDialog.SelectedPath;
string tempfolder = targetFolderBrowserDialog.SelectedPath + "\\tempDirectory";
string sFile = "";
//create a temporary directory to store selected excel and csv files
if (!Directory.Exists(tempfolder))
{
Directory.CreateDirectory(tempfolder);
}
try
{
for (int i = 0; i < listBoxSourceFiles.Items.Count; i++)
{
sFile = listBoxSourceFiles.Items[i].ToString();
// Copy each selected xlsx files into the specified Temporary Folder
System.IO.File.Copy(textBoxSourceDir.Text + "\\" + sFile, tempfolder + #"\" + System.IO.Path.GetFileName(sFile), true);
Log("File " + sFile + " has been copied to " + tempfolder + #"\" + System.IO.Path.GetFileName(sFile));
} // ends foreach
Process convertFilesProcess = new Process();
// remove xlsx extension from filename so that we can add the .csv extension
string csvFileName = sourceFileOpenFileDialog.FileName.Substring(0, sourceFileOpenFileDialog.FileName.Length - 3);
// command prompt execution for converting xlsx files to csv
convertFilesProcess.StartInfo.WorkingDirectory = "I:\\CommissisionReconciliation\\App\\ConvertExcel\\";
convertFilesProcess.StartInfo.FileName = "ConvertExcelTo.exe";
convertFilesProcess.StartInfo.Arguments = " ^ " + targetFolderBrowserDialog.SelectedPath + "^" + csvFileName + ".csv";
convertFilesProcess.StartInfo.UseShellExecute = true;
convertFilesProcess.StartInfo.CreateNoWindow = true;
convertFilesProcess.StartInfo.RedirectStandardOutput = true;
convertFilesProcess.StartInfo.RedirectStandardError = true;
convertFilesProcess.Start();
//Process that creates all the xlsx files in temp folder to csv files.
Process consolidateFilesProcess = new Process();
// command prompt execution for CSV File Consolidation
consolidateFilesProcess.StartInfo.WorkingDirectory = targetFolderBrowserDialog.SelectedPath;
consolidateFilesProcess.StartInfo.Arguments = "Copy *.csv ^" + csvFileName + ".csv";
consolidateFilesProcess.StartInfo.UseShellExecute = false;
consolidateFilesProcess.StartInfo.CreateNoWindow = true;
consolidateFilesProcess.StartInfo.RedirectStandardOutput = true;
consolidateFilesProcess.StartInfo.RedirectStandardError = true;
consolidateFilesProcess.Start();
Log("All Files at " + tempfolder + " has been converted to a csv file");
Thread.Sleep(2000);
StreamReader sOut = consolidateFilesProcess.StandardOutput;
sOut.Close();
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. The user lacks appropriate permissions to read files, discover paths, etc. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n");
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
MessageBox.Show("You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
try
{
if (Directory.Exists(tempfolder))
{
Directory.Delete(tempfolder, true);
}
}
catch (SecurityException ex)
{
// The user lacks appropriate permissions to read files, discover paths, etc.
MessageBox.Show("Security error. The user lacks appropriate permissions to read files, discover paths, etc. Please contact your administrator for details.\n\n" +
"Error message: " + ex.Message + "\n\n");
}
catch (Exception ex)
{
// Could not load the image - probably related to Windows file system permissions.
MessageBox.Show("You may not have permission to read the file, or " +
"it may be corrupt.\n\nReported error: " + ex.Message);
}
finally
{
// reset events
m_EventStopThread.Reset();
m_EventThreadStopped.Reset();
// create worker thread instance;
m_WorkerThread = new Thread(new ThreadStart(this.WorkerThreadFunction));
m_WorkerThread.Start();
}
} // ends void ExecuteConsolidate()
Thanks for looking! :)
All helpful answers will receive up-votes! :)
If you need more information like the workerThread method or the app.config code, let me know!
It is most likely this line that is causing your problem:
string csvFileName = sourceFileOpenFileDialog.FileName.Substring(0, sourceFileOpenFileDialog.FileName.Length - 3);
Why not use Path.GetFileNameWithoutExtension to get the filename without extension?
I suppose it dies here:
string csvFileName = sourceFileOpenFileDialog.FileName.Substring(0,
sourceFileOpenFileDialog.FileName.Length - 3);
Write it like this and see if it helps:
string selectedFile = sourceFileOpenFileDialog.FileName;
string csvFileName = Path.Combine(Path.GetDirectoryName(selectedFile),
Path.GetFileNameWithoutExtension(selectedFile));
This is the translation of your line.
But I think, you really wanted to just have the filename without path:
string csvFileName =
Path.GetFileNameWithoutExtension(sourceFileOpenFileDialog.FileName);
And to break on All Errors:
Go to "Debug" -> Exceptions (or CTRL+ALT+E)
Tick "Thrown" on Common Language Runtime Exceptions
Once done with you fix, dont forget to reset it (Reset All button)