System.Messaging.MessageQueueException (0x80004005) error while start and stop window services - c#

Actually, I have window service that read MSMQ queuw at an interval. My MSMQ queue is working without an issue but problem is when I stop or start windows service then it's throws an error. The complete error is given below:
**ERROR 65 DAL.MsmqImportListener - A MSMQ error occured
System.Messaging.MessageQueueException (0x80004005)
at System.Messaging.MessageQueue.AsynchronousRequest.End()
at DAL.MsmqImportListener.PeekCompleted(Object sender, PeekCompletedEventArgs e)**
private static void PeekCompleted(object sender, PeekCompletedEventArgs e)
{
var msmq = sender as MessageQueue;
var messageProcessor = e.AsyncResult.AsyncState as MessageProcessorMethod;
try
{
using (var scope = new TransactionScope())
{
msmq.EndPeek(e.AsyncResult);
var message = msmq.ReceiveById(
e.Message.Id,
TimeSpan.FromSeconds(double.Parse(ConfigurationManager.AppSettings["MsmqReceiveTimeout"])),
MessageQueueTransactionType.Automatic);
messageProcessor(message);
scope.Complete();
}
}
catch (MessageQueueException mqe)
{
// Check if timeout...no action if timeout, else log error
if (mqe.MessageQueueErrorCode != MessageQueueErrorCode.IOTimeout)
{
Logger.Error("A MSMQ error occured", mqe);
EmailDispatcher.SendInformationEmail("A MSMQ error occured" + Environment.NewLine + mqe);
}
}
catch (Exception ex)
{
Logger.Error(
string.Format(
CultureInfo.InvariantCulture,
"An unexpected error was encountered, message with id {0} was put in error queue: {1}",
e.Message.Id,
success),
ex);
}
finally
{
msmq.BeginPeek(TimeSpan.FromSeconds(double.Parse(ConfigurationManager.AppSettings["MsmqPeekTimeout"])), messageProcessor);
}
}

Related

C# - Signalr client connection is causing performance issue Windows Service

Signalr client code is causing performance issue is Windows Service. Windows service is acting as signalr client.
What we are trying to do:
Windows service is having one timer, which executes the method(ConnectToSignalRServer). If somehow the connection gets closed, there is one event (Connection.Closed += Connection_Closed), which will again try to establish the connection by calling the method(ConnectToSignalRServer). A while loop is being used in the event (Connection.Closed += Connection_Closed) to try reconnecting.
Please find the sample code below and let me know if any issues with the code.
private static HubConnection Connection = null;
//When the service starts, this method would be called.
public static bool ConnectToSignalRServer()
{
try
{
string Url = "http://www.samplesignalrserver.com";
Connection = new HubConnection(Url);
var myHub = Connection.CreateHubProxy("SignalHub");
Connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
}
else
{
Connection.Closed += Connection_Closed;
}
}).Wait();
//Method(RequestData) would be called upon receiveng message from server
myHub.On<string>("GetMessgeFromServer", type =>
{
Task.Run(() => RequestData(type));
});
//Method(GetHostName) would be called in server
myHub.Invoke<string>("GetHostName", BLConstants.strHostName);
return true;
}
catch (Exception ex)
{
//capturing Stacktrace and Message from ex object
}
return false;
}
//Establish the connection, if the the connection would be closed
private static void Connection_Closed()
{
try
{
while (true)
{
Thread.Sleep(10000);
bool connected = ConnectToSignalRServer();
if (connected)
{
break;
}
}
}
catch (Exception ex)
{
//capturing Stacktrace and Message from ex object
}
}

QueueClient.OnMessage throws StackOverflowException during Worker Role Start up

I am trying to deploy my first Azure worker role and I have been running into this error when Run() method is called during service start up.
An unhandled exception of type 'System.StackOverflowException' occurred in Unknown Module.
I've tried to remote debug my code and the error is thrown at this line. MyPublisher is similar to MyQueue but it wraps Topic instead of a Queue. Any idea why QueueClient.OnMessage would cause StackOverflow?
Client.OnMessage(messageHandler, options);
Here is the partial code. My Apology if it is not formatted correctly (will try to format) or anything is missing in code.
public class MyQueue
{
String QueueName;
public QueueClient Client { get; protected set; }
public MyQueue(String queueName)
{
Trace.WriteLine($"Creating service Queue with name : {queueName} ");
QueueName = queueName;
}
public void EstableshConnection(string connectionString = null)
{
Trace.WriteLine($"Establishing connection with service Queue : {QueueName} ");
// Set the maximum number of concurrent connections
ServicePointManager.DefaultConnectionLimit = 12;
connectionString = connectionString ?? CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");
NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
if (!namespaceManager.QueueExists(QueueName))
namespaceManager.CreateQueue(QueueName);
Client = QueueClient.CreateFromConnectionString(connectionString, QueueName);
}
public void Send(BrokeredMessage message)
{
Trace.WriteLine($"Sending brokered message to queue : {QueueName} ");
if (Client != null && !Client.IsClosed)
Client.Send(message);
}
public void OnMessage(Action<BrokeredMessage> messageHandler)
{
Trace.WriteLine($"OnMessage handler: Queue Name : {QueueName} ");
OnMessageOptions options = new OnMessageOptions();
options.AutoComplete = true; // Indicates if the message-pump should call complete on messages after the callback has completed processing.
options.MaxConcurrentCalls = 1; // Indicates the maximum number of concurrent calls to the callback the pump should initiate
options.ExceptionReceived += LogErrors; // Allows users to get notified of any errors encountered by the message pump
//=====================StackOverFlowException on Client.OnMessage======
if (Client != null && !Client.IsClosed)
Client.OnMessage(messageHandler, options); //This is where I get StackOverflowException Error.
}
private void LogErrors(object sender, ExceptionReceivedEventArgs e)
{
if (e.Exception != null)
Trace.WriteLine("Queue client processing error: " + e.Exception.Message);
}
public void Disconnect()
{
Trace.WriteLine($"closing queue {QueueName}");
Client.Close();
}
}
Here is my workerrole implementation.
public class MyWorkerRole : RoleEntryPoint
{
#region Variables
ManualResetEvent CompletedEvent = new ManualResetEvent(false);
MyQueue RequestQueue; //for Request
MyPublisher ResponseTopicClient; //ReponseTopic to notify Subscriber when processing is completed
Public MyWorkerRole()
{
RequestQueue = new MyQueue("JobRequestQueue");
ResponseTopicClient = new MyPublisher("JobCompletedTopic");
}
public override bool OnStart()
{
try
{
RequestQueue.EstableshConnection();
ResponseTopicClient.EstableshConnection();
}
catch (Exception ex)
{
Trace.TraceWarning($"Trace: starting service failed. Error {ex.Message} ");
}
return base.OnStart();
}
public override void OnStop()
{
try
{
RequestQueue.Disconnect();
ResponseTopicClient.Disconnect();
CompletedEvent.Set();
}
catch (Exception ex)
{
Trace.TraceWarning($"Trace: stopping service failed with error. {ex.Message} ");
}
base.OnStop();
}
public override void Run()
{
try
{
Trace.WriteLine("Trace: Starting Message Processing");
//var receivedMessage2 = RequestQueue.Client.Receive(new TimeSpan(hours: 0, minutes: 2, seconds: 0));
RequestQueue.OnMessage((receivedMessage) =>
{
try
{
Guid resultGuid = (Guid)receivedMessage.Properties["CorrelationGuid"];
Trace.TraceWarning($"Trace: processing message with GUID {resultGuid}");
var messageToSend = JobProcessor.ProcessRequest(receivedMessage);
if (messageToSend == null)
{
Trace.TraceError("Trace: > Broken message!");
receivedMessage.Abandon();
return;
}
ResponseTopicClient.Send(messageToSend);
receivedMessage.Complete();
}
catch (Exception ex)
{
Trace.TraceError("Trace: Processing exception: " + ex.Message + "\nStack Trace" + ex.StackTrace);
Logger.Error("Processing exception: " + ex.Message + "\nStack Trace" + ex.StackTrace);
}
});
CompletedEvent.WaitOne();
}
catch (Exception ex)
{
Trace.TraceError("Trace: Run exception: " + ex.Message + "\nStack Trace" + ex.StackTrace);
}
finally
{
CompletedEvent.Set();
}
}
}
When your worker starts, it calls the Run method and in your code, you have :
//var receivedMessage2 = RequestQueue.Client.Receive(new TimeSpan(hours: 0, minutes: 2, seconds: 0));
RequestQueue.OnMessage((receivedMessage) =>
So, The code doesn't wait for a new message because the first line is commented and it calls the OnMessage method which recursibly calls itself again and again till the StackOverflowException gets fired
In all cases, you need to change the implementation because StackOverflowException will happen anyway when a new message is received
Figured it out. So, the issue was not with the code. Following error was reported in WADWindowsEventLogsTable under my storage account.
Faulting application name: WaWorkerHost.exe, version: 2.7.1198.768, time stamp: 0x57159090
Faulting module name: Microsoft.IntelliTrace.Profiler.SC.dll, version: 15.0.27128.1, time stamp: 0x5a1e2eb9
Exception code: 0xc00000fd
Fault offset: 0x000000000008ae7b
Faulting process id: 0xcf4
Faulting application start time: 0x01d3b75ed89dc2f9
Faulting application path: F:\base\x64\WaWorkerHost.exe
Faulting module path: F:\plugins\IntelliTrace\Runtime\x64\Microsoft.IntelliTrace.Profiler.SC.dll
This gave me a hint about disabling the IntelliTrace and it worked just fine. Here is how you can disable while publishing a package through VS 2017.
1.) Right click on your worker role project and select publish from menu
2.) In Settings page->Advanced Settings, uncheck "Enable IntelliTrace" option.

How to catch all exceptions in try catch block in Xamarin.Android

How to catch all exceptions in try catch block in Xamarin.Android
I am very frustrated on how Xamarin.Android handles unhandled exception which is very weird, I added three exceptions for all api queries respectively:
try
{
// api query using `refit`
// json parsing using `newtonsoft`
}
catch(System.OperationCanceledException e)
{
// user cancelled the query, show option to retry
}
catch(ApiException apiException)
{
// theres an api exception , show error message to users , show option to retry
}
catch(Exception e)
{
// unknown exception ignore , show error message to users , show option to retry
}
This try catch blocks works most of the time, but there is one certain scenario when our server is down, and it just throws exception and crashes the app over and over again until the server is back up.
This is the exception that keeps on bugging us :
Xamarin caused by: android.runtime.JavaProxyThrowable: Newtonsoft.Json.JsonReaderException
As you can see in JsonReaderException hierarchy, it inherited System.Exception which is the last catch block i used.
and I checked this JsonReaderException it extends from Exception , In which our try catch block should handle it.
Now im wondering is there any way that we can catch all those pesky unhandled exceptions?
I'm getting unhandled exceptions in this way
public void Init()
{
AndroidEnvironment.UnhandledExceptionRaiser += OnAndroidEnvironmentUnhandledExceptionRaiser;
AppDomain.CurrentDomain.UnhandledException += OnCurrentDomainUnhandledException;
TaskScheduler.UnobservedTaskException += OnTaskSchedulerUnobservedTaskException;
var currentHandler = Java.Lang.Thread.DefaultUncaughtExceptionHandler;
var exceptionHandler = currentHandler as UncaughtExceptionHandler;
if (exceptionHandler != null)
{
exceptionHandler.SetHandler(HandleUncaughtException);
}
else
{
Java.Lang.Thread.DefaultUncaughtExceptionHandler = new UncaughtExceptionHandler(currentHandler, HandleUncaughtException);
}
}
private void OnAndroidEnvironmentUnhandledExceptionRaiser(object sender, RaiseThrowableEventArgs e)
{
AndroidEnvironment.UnhandledExceptionRaiser -= OnAndroidEnvironmentUnhandledExceptionRaiser;
_logger.LogFatal($"AndroidEnvironment.UnhandledExceptionRaiser.", e.Exception);
e.Handled = true;
}
private void OnCurrentDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException -= OnCurrentDomainUnhandledException;
var ex = e.ExceptionObject as Exception;
if (ex != null)
{
_logger.LogFatal("AppDomain.CurrentDomain.UnhandledException.", ex);
}
else
{
_logger.LogFatal($"AppDomain.CurrentDomain.UnhandledException. ---> {e.ExceptionObject}");
}
}
private void OnTaskSchedulerUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
_logger.LogFatal("TaskScheduler.UnobservedTaskException.", e.Exception);
}
private bool HandleUncaughtException(Java.Lang.Throwable ex)
{
_logger.LogFatal("Thread.DefaultUncaughtExceptionHandler.", ex);
return true;
}

unhandled exception in windows service application

I would like to catch unhandled exceptions in a windows service application in the class that inherits from ServiceBase class.
I have already tried incorporating the code:
AppDomain.CurrentDomain.UnhandledException += (s, e) =>
{
var exception = (Exception)e.ExceptionObject;
Log.Error("Unhandled exception", exception);
};
But that doesn't work.
Try this:
// Starts the application.
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main(string[] args)
{
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// Runs the application.
Application.Run(new ErrorHandlerForm());
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
string errorMsg = "An application error occurred. Please contact the adminstrator " +
"with the following information:\n\n";
// Since we can't prevent the app from terminating, log this to the event log.
if (!EventLog.SourceExists("ThreadException"))
{
EventLog.CreateEventSource("ThreadException", "Application");
}
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "ThreadException";
myLog.WriteEntry(errorMsg + ex.Message + "\n\nStack Trace:\n" + ex.StackTrace);
}
catch (Exception exc)
{
try
{
MessageBox.Show("Fatal Non-UI Error",
"Fatal Non-UI Error. Could not write the error to the event log. Reason: "
+ exc.Message, MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
finally
{
Application.Exit();
}
}
}
You also can take a look at this example: https://msdn.microsoft.com/en-us/library/system.windows.forms.application.threadexception.aspx

Time out has expired and the operation has not been completed in Service manager

I have a windows service manager, I try to stop the service by the manager. However I got the exception:
Time out has expired and the operation has not been completed
private static void StopService()
{
if (!IsInstalled()) return;
try
{
CFEServiceController c = new CFEServiceController();
c.StopService(ServiceName, 500);
}
catch (Exception ex)
{
Console.WriteLine("Error in Stop service " + ex.Message);
}
}
And:
public void StopService(string serviceName, int timeoutMilliseconds)
{
using (ServiceController service = new ServiceController(serviceName))
{
try
{
TimeSpan timeout = TimeSpan.FromMilliseconds(timeoutMilliseconds);
if (service.Status == ServiceControllerStatus.Running)
{
service.Stop();
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
Console.WriteLine("Stop service " + serviceName+" ");
}
}
catch (Exception ex)
{
Console.WriteLine("Error when stop service in code StopService " + ex.Message); // here I got the exception
}
}
}
The problem is because of this:
service.WaitForStatus(ServiceControllerStatus.Stopped, timeout);
This is happening because your service has not stopped within your timeout. You should either set your timeout higher, or don't set a timeout at all.
You could also try open
"Event Viewer" -> "Windows Logs" -> "Application"
There could be Error Level message that could give you a clue if increasing/unset the number of timeout doesn't help as answered by #gleng.

Categories

Resources