Windows Task Scheduler EXE log file not generating - c#

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

Related

FileSystemWatcher DCOM Errors

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!

Problems in accessing server for file in asp.net c#?

I am trying to connect to a remote server and access a specific directory in that server for searching a file but for some reason it shows that the directory doesnt exist on the server even though it actually exists. I am guessing that my file path is wrong. Can anyone please suggest me if I made a syntax error?
filepath = #"\\172.17.20.11\E$\MessageLogs\" + logType + "\\" + country + "\\" + year + "\\" + month + "\\" + day + "\\";
private void GetFiles(string filePath)
{
try
{
tblFileContent = new DataTable();
getColumns(tblFileContent);
//C:\MessageLogs\ElmaCore\KENYA\2016\March\22
//filePath = #"C:\MessageLogs\"+filePath; //Pick a folder on your machine to store the uploaded files
if (!Directory.Exists(filePath))
{
fn.MessageLine(this.Page, "Log folder does not exist.", System.Drawing.Color.Red, "lblMessageLine");
dtDate.Focus();
return;
}
string searchReference = txtReference.Text.Trim();
//string filePath = System.Configuration.ConfigurationManager.AppSettings["InFolder"].ToString();
DirectoryInfo DirInfo = new DirectoryInfo(filePath);
FileInfo[] CsvFiles = DirInfo.GetFiles("*" + searchReference + "*.log").OrderByDescending(p => p.LastWriteTime).ToArray();
if (CsvFiles.Length > 0)
{
foreach (var file in CsvFiles)
{
string FileName = file.Name;
string sourceFile = System.IO.Path.Combine(filePath, FileName);
ProcessFile(FileName, sourceFile);
}
//LoadGrid();
}
else {
fn.MessageLine(this.Page, "Sorry, No files found for the specified reference.", System.Drawing.Color.Red, "lblMessageLine");
txtReference.Focus();
return;
}
}
catch (Exception ex)
{
fn.MessageLine(this.Page, "Sorry an Error Occured. Please try again", System.Drawing.Color.Red, "lblMessageLine");
ErrLogger.LogError("filelog-" + ex.Message); //oledbconn.Close();
return;
}
}
As you say your directory exists than it might the problem with permission.
Please make sure account under which code is been running have permission to that folder.
Also note that once you deploy in IIS, change identity of apppool to a domain user who has permission.
If you want to verify if its permission problem, than just do this.
Right click into that folder and give permission to everyone and test.

Windows Service don't runs properly c#

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

Log file is not being created by class library after installing the dll

I have created a class library with some functionality and maintaining a log file to track the steps executed. If i run this class library in debug mode it is successfully creating log file.
But, I have created the cab file after creating the tlb file of that class library and installed into the system. Now i am using that library, all the functions are working properly, only logs files are not written.
I've used the code to create log file is below-
public static void LogTrace(string LogMessage)
{
try
{
string LogError = string.Empty;
String DirPath = string.Empty;
DirPath= Convert.ToString(ConfigurationSettings.AppSettings["DirPath"]);
LogError = Convert.ToString(ConfigurationSettings.AppSettings["LogError"]);
//if logging is not required
if (LogError.ToLower() == "true")
{
if (DirPath == null || DirPath == string.Empty)
DirPath = #"C:\LogAndError";
if (LogError == null || LogError == string.Empty)
LogError = "True";
//creation of date wise file name
string LogFileName = DirPath + "\\Log_ " + DateTime.Now.ToString("MM_dd_yyyy") + ".txt";
createLogAndErrorFile(DirPath);
StreamWriter streamWriter = null;
streamWriter = new StreamWriter(LogFileName, true);
streamWriter.WriteLine("Time :" + DateTime.Now.ToString() + " ");
streamWriter.WriteLine(LogMessage);
streamWriter.WriteLine(Environment.NewLine);
streamWriter.Flush();
streamWriter.Close();
}
}
catch
{
//We are not throwing any exception because all the exeption is logged using this method
//and throwing the exception could lead to recursive call of function.
}
}
public static void createLogAndErrorFile(string DirPath)
{
if (!Directory.Exists(DirPath))
Directory.CreateDirectory(DirPath);
}
}
Am i missing something ?
Verify that you have permission to acces to your file
Place your code in try catch block and capture exception
I suggest you to use using block
try
{
var path = Path.Combine(DirPath, string.Concat("\\Log_",DateTime.Now.ToString("MM_dd_yyyy"), ".txt"));
using (StreamWriter streamWriter = new StreamWriter(path))
{
streamWriter.WriteLine("Time :" + DateTime.Now.ToString() + " ");
streamWriter.WriteLine(LogMessage);
streamWriter.WriteLine(Environment.NewLine);
}
}
catch(Exception ex)
{
Console.Write(ex.Message);
throw ex;
}

C# WinForms App - Debug Error - Length can not be less than zero. Parameter Name: Length

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)

Categories