c# Reading event log of remote server - c#

I'm following this post and trying to run the code (copied below), and I'm having a slightly different problem. I can remote connect to the server and view the event log through the Event Viewer program, but I can't iterate through the events in the code. I get an InvalidOperationException saying "Cannot open log EventLogName on machine . Windows has not provided an error code." There is also an inner exception of type System.ComponentModel.Win32Exception that says "Access is denied."
private static bool GetEventLogData(DateTime start)
{
var log = new EventLog("EventLogName", "SERVER.domain.net");
bool errorFound = false;
foreach (EventLogEntry entry in log.Entries)
{
if ((entry.EntryType == EventLogEntryType.Error) &&
(entry.TimeGenerated >= start))
{
Console.WriteLine("Error in Event Log:\n" + entry.Message + "\n");
errorFound = true;
}
}
return errorFound;
}
Any ideas?
EDIT:
The exception data is as follows. I can't post the server name as it is company information. I receive the error when trying to read the event log. I am absolutely sure I can read the log because I can remote connect with my account and read the log using the Event Viewer.
System.InvalidOperationException was unhandled
Message=Cannot open log EventLogName on machine SERVER.domain.net. Windows has not provided an error code.
Source=System
StackTrace:
at System.Diagnostics.EventLogInternal.OpenForRead(String currentMachineName)
at System.Diagnostics.EventLogInternal.GetEntryAtNoThrow(Int32 index)
at System.Diagnostics.EventLogEntryCollection.EntriesEnumerator.MoveNext()
at System.Linq.Enumerable.<CastIterator>d__b1`1.MoveNext()
at System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext()
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)
at MyApp.Program.GetEventLogData(String machineName, DateTime start) in c:\users\me\documents\visual studio 2010\Projects\MyApp\MyApp\Program.cs:line 45
at MyApp.Program.Main(String[] args) in c:\users\me\documents\visual studio 2010\Projects\MyApp\MyApp\Program.cs:line 28
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException: System.ComponentModel.Win32Exception
Message=Access is denied
ErrorCode=-2147467259
NativeErrorCode=5
InnerException:

This is most likely a policy permission issue. See the Giving Non Administrators permission to read Event Logs Windows 2003 and Windows 2008 blog entry on TechNet. I was able to make your code work once I did this. In the case of Windows 2008 Server and higher, it's simply a matter of adding the user to the Event Log Readers local security group. Until I did that I was getting the same error.

Related

Strange bug in different compilation mode

I'm encountering a very strange bug which appears only when compiling in Release mode, while in Debug mode the code runs perfectly. Moreover, the bug is encountered only in one machine (a user reported this).
This is the stack trace:
System.IO.FileNotFoundException: Unable to find file 'C:\Users...\FileName.txt'.
File name: 'C:\Users...\FileName.txt'
in System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
in System.IO.FileInfo.get_Length()
in PatcherNET4.FileHandler.LocalFile.get_Size()
in PatcherNET4.FileHandler.CachedFile.IsLocalValid(LocalFile file)
in PatcherNET4.FileHandler.FileManager.<>c__DisplayClassd.b__9(CachedFile file)
in System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable1 source, Func2 predicate)
in PatcherNET4.FileHandler.FileManager.RemoveLocalFiles()
in PatcherNET4.FileHandler.FileManager.DownloadMissingFiles()
in System.Threading.ThreadHelper.ThreadStart_Context(Object state)
in System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
in System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
in System.Threading.ThreadHelper.ThreadStart()
And this is the code:
// CachedFile
...
public bool IsLocalValid(LocalFile file)
{
var checkName = file.Name == Name;
var checkSize = file.Size == Size;
var checkLastWrite = file.LastWriteTime == LastWriteTime;
return checkName && checkSize && checkLastWrite;
}
...
//LocalFile
...
public uint Size
{
get
{
_info.Refresh();
return (uint)_info.Length;
}
}
...
How is this possible? I can assure you that there is no difference in the interested pieces of code between the release and debug mode. I don't really know what to do, this is probably the strangest bug I've ever seen.
put FileName.txt in the Unable to find file 'C:\Users...\(here) directory
The first thing I'd try is to verify the file exists at runtime and go from there.
if (!File.Exists(fileName))
{
// do something
}
If the file doesn't exist (I believe you when you say it's missing) then consider the alternatives. Has the file been deleted already? I notice in the stacktrace there's RemoveLocalFiles, so perhaps it's already been run. Maybe a user pressed a button twice? race condition. Separate thread? User is logged in on two machines and has roaming profiles. Or something like that.
Regardless of whether it's a bug or not, it's better to be defensive and include a check to make sure the file exists (or catch the exception if that's your preference).

Unhandled exception of type System.Exception occurred in FM.dll

I'm using WebSync in a .NET application where a client is making calls to connect, subscribe, etc to WebSync. Somewhere along the execution of the code (It's a big app), I get the gray box popup saying the above error message. Because this is a big app, how can I find where in the application this is occurring? The problem is that this application has a lot of threads.
Does this message mean there is a problem in FM.dll (WebSync) or does it mean that I'm missing something in my code that should catch this exception. If the latter, how do I find where in my code this may occur?
Thanks!
Here is the Call Stack to my error. How can I tell if this is an error on my part or if the problem is inside FM.dll (WebSync)?
FM.dll!FM.AsyncException.AsyncThrow.AnonymousMethod__0(object unused) + 0x47 bytes
mscorlib.dll!System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x285 bytes
mscorlib.dll!System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext executionContext, System.Threading.ContextCallback callback, object state, bool preserveSyncCtx) + 0x9 bytes
mscorlib.dll!System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem() + 0x6f bytes
mscorlib.dll!System.Threading.ThreadPoolWorkQueue.Dispatch() + 0x1ea bytes
[Native to Managed Transition]
[Appdomain Transition]
[Native to Managed Transition]
If you have 'Break on All Exceptions' turned on then once you start the debugger, when the exception is thrown, you'll be able to see and navigate the stack trace. This should give you an idea of the path the code is on leading up to the exception. You can also interrogate the exception to check to see if the InnerException property has been set. From that information you should be able to determine what is causing the issue. If not post more details from the information you gather and you can get more help.
Instruction for setting up Visual Studio to break on all exceptions: http://msdn.microsoft.com/en-us/library/d14azbfh.aspx
In FM libraries, AsyncException.AsyncThrow is used when an exception is thrown in an async callback. Try wrapping your FM callback code in try/catch blocks to catch exceptions, e.g.:
client.Connect(new ConnectArgs
{
OnSuccess = (e) =>
{
try
{
// your code
}
catch (Exception ex)
{
// handle exception
}
}
});
If you don't wrap your callback code in a try/catch block, then the FM library will push the exception to a thread where it will be fail loudly rather than swallow/hide it.

Socket error sending message to Service Bus 1.0 queue

I'm following this tutorial, and I keep getting an exception calling QueueClient.Send().
First off, here's my connection string setting in the App.Config (with {computername} replaced by the actual machine name):
<add key="Microsoft.ServiceBus.ConnectionString" value="Endpoint=sb://{computername}/ServiceBusDefaultNamespace;StsEndpoint=https://{computername}:9355/ServiceBusDefaultNamespace;RuntimePort=9354;ManagementPort=9355" />
Here's the code I'm running:
NamespaceManager namespaceManager = NamespaceManager.Create();
TokenProvider nameSpaceManagerTokenProvider = TokenProvider.CreateWindowsTokenProvider(
new List<Uri>() { namespaceManager.Address }, new NetworkCredential(user, password));
TokenProvider messagingToken = TokenProvider.CreateWindowsTokenProvider(
new List<Uri>() { namespaceManager.Address }, new NetworkCredential(user, password));
namespaceManager.Settings.TokenProvider = nameSpaceManagerTokenProvider;
MessagingFactorySettings messageFactorySettings = new MessagingFactorySettings {TokenProvider = messagingToken};
MessagingFactory messagingFactory = MessagingFactory.Create(namespaceManager.Address, messageFactorySettings);
if (namespaceManager.QueueExists(QueueName))
{
namespaceManager.DeleteQueue(QueueName);
}
QueueDescription qd = new QueueDescription(QueueName);
namespaceManager.CreateQueue(qd);
QueueClient myQueueClient = messagingFactory.CreateQueueClient(QueueName);
BrokeredMessage sendMessage = new BrokeredMessage("Hello, World!");
myQueueClient.Send(sendMessage); // <---- This is where I'm getting the exception
The queue is deleted/created without a problem. Calling the .Send() method gives me the following error:
Microsoft.ServiceBus.Messaging.MessagingCommunicationException
"The socket connection was aborted. This could be caused by an error processing your message or a receive timeout being exceeded by the remote host, or an underlying network resource issue. Local socket timeout was '00:00:59.9579976'."
The inner exception is simply "An existing connection was forcibly closed by the remote host"
Here's the stack trace:
at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.EndSendCommand(IAsyncResult result)
at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.OnEndSend(IAsyncResult result)
at Microsoft.ServiceBus.Messaging.Sbmp.SbmpMessageSender.OnSend(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)
at Microsoft.ServiceBus.Messaging.MessageSender.Send(TrackingContext trackingContext, IEnumerable`1 messages, TimeSpan timeout)
at Microsoft.ServiceBus.Messaging.MessageSender.Send(BrokeredMessage message)
at Microsoft.ServiceBus.Messaging.QueueClient.Send(BrokeredMessage message)
at SBDemo.Program.Main(String[] args) in c:\Users\hartez\Documents\bitbucket\SBDemo\SBDemo\Program.cs:line 51
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
I'm currently running both the client code and the Service Bus on a Windows 7 64-bit dev box. I originally ran Service Bus on a 2012 Server machine and had the same problem.
The problem occurs with both the WindowsTokenProvider and the OauthTokenProvider. The user account is an administrator (in hopes that this was just a permissions issue); that doesn't seem to help. I've also tried this with the Windows Firewall deactivated, but that didn't help, either.
I enabled the Analytic and Debug logs in the Event Viewer, but I'm not seeing an anything in those logs to suggest what the problem might be.
If anyone has any suggestions on what might be wrong, or on other ways to debug this, I'd very much appreciate it.
Glad you have figured this out.
MessagingFactory messagingFactory = MessagingFactory.Create(namespaceManager.Address, messageFactorySettings);
The issue you had in your original code is that it is using the NamespaceManager address for the MessagingFactory. The MessagingFactory uses a different port than the NamespaceManager.
NamespaceManager is used for management (CRUD) operations and SB has a management endpoint for it.
MessagingFactory is used for runtime operations (Send/Receive/..) and SB has a runtime endoiunt for it.
QueueClient.Create(QueueName) internally creates a messaging factory and uses the default address and port for runtime operations.
Finally figured this out, putting this here so anyone else in the same boat can avoid wrestling with this problem:
Apparently, the problem is somewhere in the use of MessagingFactory in the examples. I'm not really sure what it's even for (maybe handling things like AMQP, which isn't really supported by Service Bus yet?), but you don't need it. You can create the client using QueueClient.Create(). I revised the code to look like this, and now it works just fine:
NamespaceManager namespaceManager = NamespaceManager.Create();
TokenProvider nameSpaceManagerTokenProvider = TokenProvider.CreateWindowsTokenProvider(
new List<Uri>() { namespaceManager.Address }, new NetworkCredential(user, password));
namespaceManager.Settings.TokenProvider = nameSpaceManagerTokenProvider;
if (namespaceManager.QueueExists(QueueName))
{
namespaceManager.DeleteQueue(QueueName);
}
QueueDescription qd = new QueueDescription(QueueName);
namespaceManager.CreateQueue(qd);
QueueClient myQueueClient = QueueClient.Create(QueueName);
BrokeredMessage sendMessage = new BrokeredMessage("Hello, World!");
myQueueClient.Send(sendMessage);

How to access an object from a different thread without conflict?

I have a thread named fetchImage that runs startFetch() method, which is
for (int i = 0; !stopFetching && i < 2000; i++) {
control.fetchImage().Save("Fetch_Image\\fetchedFile" + fileName + ".JPG", System.Drawing.Imaging.ImageFormat.Jpeg);
fileName++;
//Thread.Sleep(800);
Console.WriteLine("Filename :" + fileName);
control is another class that has fetchImage() method:
return (System.Drawing.Bitmap)mainForm.imageTemp.Clone();
mainForm is a form that has Image variable named imageTemp. Now startFetch() runs fine when I have Thread.Sleep(800) but it gives me that error without the sleep. Here is the stack trace of the error
System.InvalidOperationException was unhandled
Message=Object is currently in use elsewhere.
Source=System.Drawing
StackTrace:
at System.Drawing.Image.Clone()
at KiPNi.Control.fetchImage() in F:\CMPS285\285-fall10-5\Final working code\WindowsFormsApplication7\Control.cs:line 65
at KiPNi.Form4.startFetch() in F:\CMPS285\285-fall10-5\Final working code\WindowsFormsApplication7\Form4.cs:line 80
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
I do not know much about threads (although I tried after encountering this problem).
How do I get access to the image from the fetchImage thread?
Instead of pulling data from the processing thread, see if it's possible to push data from the UI thread when there's a frame update - that way, you can possibly avoid locking; if you can create a clone of the image data, you avoid sharing the object between threads.
You really only should be invoking methods on UI controls from the main thread anyway (Control.BeginInvoke() exists, but it's better trying to modify your design to avoid it, if possible).

SEHException was unhandled

I have a vs2010 c# solution that was working fine yesterday.
When I try and run a debug instance today I keep getting an SEHException was unhandled.
This error is being thrown in the InitializeComponent method of the startup form.
Any Ideas?
Here's the stacktrace:
System.Runtime.InteropServices.SEHException was unhandled
Message=External component has thrown an exception.
Source=System.Drawing
ErrorCode=-2147467259
StackTrace:
at System.Drawing.SafeNativeMethods.Gdip.GdipCreateFontFromLogfontW(HandleRef hdc, Object lf, IntPtr& font)
at System.Drawing.Font.FromLogFont(Object lf, IntPtr hdc)
at System.Drawing.Font.FromHfont(IntPtr hfont)
at System.Drawing.SystemFonts.get_DefaultFont()
at System.Windows.Forms.Control.get_DefaultFont()
at System.Windows.Forms.Control.GetDefaultFontHandleWrapper()
at System.Windows.Forms.Control.get_FontHandle()
at System.Windows.Forms.ContainerControl.GetFontAutoScaleDimensions()
at System.Windows.Forms.ContainerControl.get_CurrentAutoScaleDimensions()
at System.Windows.Forms.ContainerControl.get_AutoScaleFactor()
at System.Windows.Forms.ContainerControl.PerformAutoScale(Boolean includedBounds, Boolean excludedBounds)
at System.Windows.Forms.ContainerControl.PerformNeededAutoScaleOnLayout()
at System.Windows.Forms.Form.OnLayout(LayoutEventArgs levent)
at System.Windows.Forms.Control.PerformLayout(LayoutEventArgs args)
at System.Windows.Forms.Control.System.Windows.Forms.Layout.IArrangedElement.PerformLayout(IArrangedElement affectedElement, String affectedProperty)
at System.Windows.Forms.ContainerControl.LayoutScalingNeeded()
at System.Windows.Forms.ContainerControl.set_AutoScaleMode(AutoScaleMode value)
at FirstWindow.Form1.InitializeComponent() in C:\Users\Ash\Documents\Visual Studio 2010\Projects\FrameworkClientV2 - No Security\FirstWindow\Form1.designer.cs:line 32
at FirstWindow.Form1..ctor() in C:\Users\Ash\Documents\Visual Studio 2010\Projects\FrameworkClientV2 - No Security\FirstWindow\Form1.cs:line 27
at FirstWindow.Program.Main() in C:\Users\Ash\Documents\Visual Studio 2010\Projects\FrameworkClientV2 - No Security\FirstWindow\Program.cs:line 18
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
On a random note my gf broke my laptop screen last night so Im running on an external monitor... could this have anything to do with it?
Here's the code and the erroneous line..
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
///////////////////The line below throws the exception
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
///////////////////////////////
this.Text = "Form1";
}
This might be the same as the widely reported issue that started occurring yesterday. See
http://forums.asp.net/t/1704958.aspx/9/10?Re+SEHException+thrown+when+I+run+the+application
http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/0f78401b-77b2-4052-a26a-e98d2ec0afa9
Try uninstalling "Trusteer Rapport" if you have it on your machine
To be honest, the answer by zeroid did not fix my problem. So for the sake of completeness, I'd like to add that avira also caused such problems
http://forum.avira.com/wbb/index.php?page=Thread&threadID=123791
This problem can occurs when you load unmanaged functions (from DLL) in the main thread.
I fixed this problem by loading these unmanaged functions in a different thread than the main thread, you can for example use a BackgroundWorker.
I stumbled on this because I suddenly experienced the same problem. It's years after the OP and I'm using VS2015. My solution worked fine at work yesterday, with my laptop hooked up to an an external monitor. Today I'm working from home, and there is no extra monitor. I wouldn't have thought it relevant except for OP's comment about switching screen setup.

Categories

Resources