FileSystemWatcher DCOM Errors - c#

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!

Related

Windows Task Scheduler EXE log file not generating

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

How to read the list of files in a directory on another drive in web app?

Here is a part of a simple web page to show a selector list of the available log files on an attached drive:
public void OnGet()
{
StringBuilder logContent = new StringBuilder();
string[] files = null;
string directory = #"Q:\logs";
string reason = "Undefined";
try
{
files = Directory.GetFiles(directory, "*.csv");
}
catch (Exception ex)
{
reason = ex.Message;
}
if (files != null && files.Length > 0)
{
logContent.Append(#"<select>");
foreach (string file in files)
{
string aFile = file.Substring(file.LastIndexOf(Path.DirectorySeparatorChar) + 1);
logContent.Append("<option value=\"" + aFile + "\">" + aFile + "</option>");
}
logContent.Append(#"</select>");
...
else
{
logContent.Append("<h3>An Exception occurred: " + reason + "</h3>");
}
Message = logContent.ToString();
}
When the page runs, I get the exception
"Cannot find a part of the path Q:\logs.
The drive is there and if I do a dir Q:\logs in the command prompt from C drive it displays the contents.
What am I missing here?
What are you using IIS?
If so, then the user that is running the application (application pool in IIS) has to be you. Otherwise, you need to map the drive for that user, since it sounds like Q is a network mapped drive.

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.

Value assigned more than once in single assignment

I made script task that's downloading and saving on disk two spreadsheets from Google Drive using file ID and prepared URL address.
This is main() from my C# code, there are no things outside of it:
public void Main()
{
string m_FileId = Dts.Variables["User::varFileId"].Value.ToString();
string m_RemoteUrl = "https://docs.google.com/spreadsheets/d/" + m_FileId + "/export?format=xlsx";
string m_FilePath = null;
WebClient client = new WebClient();
try
{
m_FilePath = Dts.Variables["User::varFilePath"].Value.ToString() + Dts.Variables["User::varFileName"].Value.ToString();
client.DownloadFile(new System.Uri(m_RemoteUrl), m_FilePath);
m_FilePath = "";
m_FileId = Dts.Variables["User::varFileId2"].Value.ToString();
m_RemoteUrl = "https://docs.google.com/spreadsheets/d/" + m_FileId + "/export?format=xlsx";
m_FilePath = Dts.Variables["User::varFilePath"].Value.ToString() + Dts.Variables["User::varFileName2"].Value.ToString();
client.DownloadFile(new System.Uri(m_RemoteUrl), m_FilePath);
}
catch(Exception e)
{
Dts.Events.FireError(0, "FileDownload", e.Message
+ "\r" + e.StackTrace
+ " \rUrl: " + m_RemoteUrl
+ " \rFilePath: " + m_FilePath
+ " \rPath: " + Dts.Variables["User::varFilePath"].Value.ToString()
+ " \rFileName2: " + Dts.Variables["User::varFileName2"].Value.ToString()
, string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
Dts.TaskResult = (int)ScriptResults.Success;
}
Problem occurs exactly on every second time I run this code and I don't know how to get rid of it. There's just exception in my script task. I'm printing all variables that are used in this code, and as you can see there's something wrong with m_FilePath, it's like multiplied despite of being printed just once.
[FileDownload] Error: An exception occurred during a WebClient request.
at System.Net.WebClient.DownloadFile(Uri address, String fileName)
at ST_84b63d1593dd449886eb2b32dff40b2d.ScriptMain.Main()
Url: https://docs.google.com/spreadsheets/d/----------/export?format=xlsx
FilePath: C:\Google Drive extract\ga_manual_cost_file.xlsxC:\Google Drive extract\ga_manual_cost_file.xlsx
Path: C:\Google Drive extract\ga_manual_cost_file.xlsx
FileName2: ga_manual_cost_file.xlsx
SSIS variables that I'm using are ReadOnly, and are used only in this script task(I tried running only this part of control flow), and their values are as follows:

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