StreamWriter in server file is in use, but in local works - c#

I have a webservices's project. I'm trying to write a log per each method using StreamWriter, in my local machine everything is working fine.
Something like this:
static StreamWriter sw;
try{
if (File.Exists(Directorio + FILE_NAME))
{
sw = File.AppendText(Directorio + FILE_NAME);
}
else
{
sw = File.CreateText(Directorio + FILE_NAME);
sw.WriteLine("---LOG ");
}
sw.WriteLine(Date);
sw.WriteLine(Header);
sw.WriteLine();
sw.Close();//*/
}catch(Exception){}
But when is uploaded to the server sometimes it throws an error that can't write because the file is in use. But I close it every time and I thought that with the try catch should ignore that part and continue with the method, because I don't want to affect the process of each method.
I know that is little information, and I can't reproduce my problem here but hope that someone who had an error like this could give me a hint.

Web servers typically handle multiple requests at once. The occasional error is most likely due to one request trying to log while another request is already logging, and not yet done.
If you wish do use your own logging framework, you will need to coordinate writes to the file.
You could also use one of the exceptional, open-source logging frameworks such as NLog.

This could be due to multiple requests coming to web server and one request trying to write to this log file while other is trying to open. possible fix could be thread synchronization, which is not good as it would significantly degrade the performance of web service. Alternatively I'd recommend using nLog (http://nlog-project.org/), used in several projects without any issues.

Related

WCF Request/Response logging - Advisable to use Mutex for synchronization

Is this advisable to use Mutex object to synchronize request/response xmls writing for WCF service? Is there any better approach for it?
Background
We have one very old WCF service which uses by some other Java service and thousands of users use that.
To troubleshoot some prod issues I am implementing logging to capture all the request and response xmls so It will have huge logging.
Since multiple process are trying to write on same xml file i am getting IO exception and to resolve that I thought to use Mutex based on below link however my queries are
Is this advisable to use it for my service? thousands of requests would hit service in a day so my service would become slower due to mutex ?
what is the best solution for this type of situation. I am sure this is very common scenario where it is required to log lot to troubleshoot issues in WCF.
OR
LOCK OR Monitor Object should be ok in my case while wrinting to log file? my service is with ConcurrencyMode Multiple OR Mutix is required ?
System.ServiceModel.FaultException - The process cannot access the file 'xxx' because it is being used by another process
Note: Since this is very old service, i don't have an option to use Log4Net library here.
Thanks for your help.
Like below method I have around 30 methods which log request and response xml and for that I am getting IO error - file is in use.
Code
WebMethod1(object Request)
{
string requestId = Guid.newguid().tostring()
LogRequestResponse(Request)
response = CallOtherService();
LogRequestResponse(response);
}
LogRequestResponse(object xmlReqRes)
{
try
{
using(StreamWriter myWriter = new StreamWriter(filePath, true, Encoding.UTF8))
{
xmlSerializer mySerializer = new xmlSerializer(xmlReqRes.GetType())
mySerializer.Serialize(myWriter, xmlReqres);
}
}
catch {}
}

Tamir SharpSSH sometimes constantly fails to download a file that is regularly pulled down by Filezilla

I am downloading files from a client's SFTP.
When I do it from Filezilla it always succeeds in the standard way.
On the other side, when I do it from our app, that uses Tamir SharpSSH library for SFTP communication, periods constantly emerge when our all download attempts for a file fail.
I know the app works as that code has not been changes for several months and it worked much more often then it did not, but the periods keep reemerging when for the whole day or more all file downloads fail only for the app.
The exception I get is Tamir.SharpSsh.jsch.SftpException . Obviously not very helpful.
My guess is the client is doing modifications on their side, or changing permissions, as their side is not live yet, but with the exception message I do not know.
Does anybody has some suggestion? Where could I look for the solution? What should I test/try?
Thank you for the time!
The real message was 'No such file'. The reason was, a slash has been omitted for the root folder path, in one of our config files.
When you open the exception variable in VS Watch you will see all info properties from standard exception are null or simply set to 'Tamir.SharpSsh.jsch.SftpException'.
But, an additional property was apparently added to Tamir.SharpSsh.jsch.SftpException class - "message" and that is where the real message is stored, while Exception.Message is pretty often set to just "Tamir.SharpSsh.jsch.SftpException" .
The issue is the additional property is private and is only visible by VS Watch or similar.
Since our exception propagation mechanism is based on logging Exception.Message I was most of the time getting "Tamir.SharpSsh.jsch.SftpException"

c# read write same file more robust way?

I'm developing a progress tracking and monitoring type of an application(c# .net 4.5) A single file both gets written and read from a network location.
I'm having trouble (unresponsive UI / Crashes) reading writing that file in such cases:
if network location is momentarily not responding,
if network location is reached over internet and there is considerable lag,
at startup while client firewall kicks in, it grants delayed access to network resources,
So I'm in need of a more robust way of reading and writing rather than
using (StreamWriter wfile = File.AppendText(path))
{
//...
}
using (StreamReader rfile = new StreamReader(path))
{
//...
}
Async methods seem to conflict reader and writer threads. What is the best practice and your suggestions over this issue? Thanks
You need a service to resolve the issue where the service does the reading and writing of the file. Windows does not properly handle the conflicts. If you don't want to create a service use a database like SQL Server which automatically resolves the conflicts. By the way, SQL Server is a service.

Catching exceptions in console application C#

I have a console application written in C#. This application runs as automation to test a web service.
Flow:
Log in to network share (impersonate user)
copy mp3 file to local disc
convert mp3 to wav
downsample
trim wave
extract some useful data from wav
send http request
delete local files
write out some stuff to tsv
The application will run great for several hours (usually takes about 24 hours to complete the test). but every once and a while I will get this message: "The application has stopped working. I have been running this is VS 2012 in debug mode so, I can see what line throws any error. problem is, that I have not been able to catch the line (or method) that is throwing the error. I originally thought that the Domain controller was causing this issue due to power settings.
How can I capture exactly what error is bubbling its way up the stack?
Does all that run in a loop of some kind? Or on a timer?
Perhaps put a try-catch around the body of the loop or the method that runs all your code, add a logging framework of your choice (log4net or nlog seem good) and then in the catch log the exception. Most logging frameworks allow you to include the exception and will include stacktrace, etc.
Putting debug logging throughout the process can also help to narrow down where it's happening.
You can go to the Event Viewer on the operating system the console application is running on and then click on "Application". Event viewer logs and displays all exceptions thrown on any application running on the operating system.
try
{
// your code
}
catch (Exception e)
{
System.IO.File.WriteAllText(#"Z:\err.txt", e.ToString());
}
Note that access to windows drives are denied for non administrators so replace Z: with your choice.
I recommend you using a logging framework.
I use log4net in almost all applications. Its very simple to use and configure.
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
try
{
// do whatever
}
catch(Exception ex)
{
// Log an error with an exception
log.Error("Exception thrown", ex);
}
By using these kind of libraries you can get your log data output to file, database or even written to the windows event-viewer for instance.
It looks like the exception code you are getting happens when you try to use something that is already been garbage collected. Are you using anything after it is disposed?
Knowledge Base Article for 0xc0000005

Read Event Log Remotely with .NET

I want to read the Event Log on a remote computer to check for errors during testing. Here's some relevant code:
public bool CheckEventLogs(DateTime start)
{
EventLog myEventLog = new EventLog("CustomLog", "ServerName");
bool errorFound = false;
foreach (EventLogEntry entry in myEventLog.Entries)
{
if (entry.EntryType == EventLogEntryType.Error && entry.TimeGenerated >= start)
{
Console.WriteLine("Error in Event Log:\n" + entry.Message + "\n");
errorFound = true;
}
}
return errorFound;
}
Currently, this code throws an exception (Attempted to perform an unauthorized operation). According to MSDN, I need EventLogPermission, but I have been struggling to find any examples of how to use this permission. Does anyone have an example of how to do this?
Edit: Response to Comments
Thank you all for the comments - here is the additional information requested:
The exception is thrown from the foreach statement. Specifically, when stepping through the code it thrown in the step after when in is highlighted. It seems that I was able to create the event log object but I'm not able to access the entries in the event log.
My account does not have permission to read the event log on the target system, but I have credentials for an account which does. When connecting manually through the event viewer there is an option to connect as another user. After doing this manually, then my code ran without a problem. However, I cannot rely doing it manually every time this program runs. What I need is a way to connect as another user programmaticly. I thought that the EventLogPermission would be the way to do that, but maybe there is another way. If anyone knows how to connect to a remote log as a different user in C#, that would be exactly what I was looking for.
WMI is incredibly useful for this, a snippet like
SELECT Logfile,TimeGenerated,Type,SourceName,Message FROM Win32_NTLogEvent
Would allow you to query the logs. This utility from MS will allow you to explore WMI and will even build the .net code to invoke the queries.
Another benefit to this is that its going to get all the events and bring them local to the application where you can parse them at your leisure. Iterating the events in the way you are doing now is prone to failure if the connection is broken while you are processing (incidentally this is the same method that is typically employed with database access).
Thanks to everyone who provided comments on this question. Once I realized that the permissions might not be a part of .NET but part of Windows and the Event Viewer itself, I had some new direction for my own investigations.
It looks like a "net use" command was all that was needed to establish the connection between my local computer and the remote computer. When calling "net use" before using the code I posted in the question, things worked beautifully. It is simple enough to call that from the code before reading from the event log.
Thanks again for your help!

Categories

Resources