GetPrivateQueuesByMachine error when being called - c#

I am trying to simply get a list of all the Private Queues on the Server from my PC.
The error I am getting is "Access to Message Queuing system is denied."
I have given full access to (Everyone, NETWORK SERVICE and Anonymous Logon) the queue on the as there is only 1 queue....
Please see attached error and code below:-
try
{
MessageQueue[] queueList =
MessageQueue.GetPrivateQueuesByMachine("xxx.xxx.x.xxx");//Error
occurs here
foreach (MessageQueue queueItem in queueList)
{
Console.WriteLine(queueItem.Path);
}
return created;
}
catch (MessageQueueException m)
{
Console.WriteLine(m.Message + m.MessageQueueErrorCode);
}
catch (SystemException s)
{
Console.WriteLine(s.Message + s.StackTrace);
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}

On the computer manager of the target machine ("xxx.xxx.x.xxx" in your example) select "Services and applications" and then "Message Queuing". Right click on "Message Queuing", go to secuirty tab and add your account with full control. Thsi should give you access to the private queues on that machine

Related

WindowsService FileSystemWatcher Crash on InputOnChanged call

I have a Windows Service that I successfully deploys, successfully works when debugging, but crashes when a file is added to the monitored directory.
I thought it was an issue with my impersonator being used between the OnStart and InputOnChanged, but the crash still happens when I run the service under my own domain user.
I have EventLog set to write to it's own application source, but none of my WriteEntrys are called except the one in the OnStart function. I've been trying different tweaks and feel like I need another set of eyes to see something i'm not:
protected override void OnStart(string[] args)
{
//using(Impersonator context = new Impersonator("XXXXX", "XXXXXXXX", "XXXXXXXXXX"))
//{
try
{
this.fileWatcherService = new FileSystemWatcher(baseFilePath, "*.txt")
{
NotifyFilter = NotifyFilters.LastWrite
};
fileWatcherService.Changed += InputOnChanged;
fileWatcherService.EnableRaisingEvents = true;
eventLog.WriteEntry("XXXX-XXXXX-Service Started");
}
catch (Exception ex)
{
eventLog.WriteEntry($"{baseFilePath} was not accessible to monitor because {ex.Message}", EventLogEntryType.Error);
}
}
protected void InputOnChanged(object source, FileSystemEventArgs e)
{
if (e.ChangeType == WatcherChangeTypes.Changed)
{
eventLog.WriteEntry($"Change Detected - File {e.Name}", EventLogEntryType.Information);
try
{
fileWatcherService.EnableRaisingEvents = false;
eventLog.WriteEntry("Starting process for file: " + e.Name);
if (!File.Exists(e.FullPath))
{
eventLog.WriteEntry($"{e.Name} was not accessible", EventLogEntryType.Error);
}
//Copy File to backup copy before formatting
File.Copy(e.FullPath
, Path.Combine(#"\\XXXXXX\XXXXXX\XXXXXXXX\XXXXXXXXXX XXX XXXXXXXXX\XXX\XXXX\XXXX\BackupFiles", GetBackupFileName(e.Name))
, false);
//Save formatted file to directory
List<string> lines = System.IO.File.ReadAllLines(e.FullPath).ToList();
File.WriteAllText(Path.Combine(#"\\XXXXXX\XXXXXX\XXXXXXXX\XXXXXXXXXX XXX XXXXXXXXX\XXX\XXXX\XXXX\FormattedFiles", GetFormattedFileName(e.Name))
, CSVFormatService.FormatLines(lines));
//Remove file from base path to prevent re-processing
File.Delete(e.FullPath);
eventLog.WriteEntry($"Successfully moved {e.FullPath}", EventLogEntryType.Information);
}
catch (Exception ex)
{
eventLog.WriteEntry("XXXX-XXXXX-Service exception: " + ex.Message, EventLogEntryType.Error);
}
finally
{
fileWatcherService.EnableRaisingEvents = true;
}
}
}
Would expect eventLog.WriteEntry("Starting process for file: " + e.Name); to update the Application log at least because that is before any attempt to touch a file, but I don't see that in the log. However, the service runs until I place a test file in the monitored directory, and then crashes with a unhandled exception of file does not exist
When building out these services, make sure you reference a shared project correctly. This issue was caused by adding a reference to a class library to the project, but the .dll was missing when deploying the service. So when the service tried to access the .dll to process data a FileNotFound exception was being thrown. This also make sense as to why the exception was marked as unhandled.

ServiceController Exception (Cannot control service on computer '.'.)

I am trying to send a command to my service TestService from a program running as administrator, I am able to start/stop it just fine, but whenever I try to ExecuteCommand() I encounter an Exception:
Cannot control service on computer '.'.
try
{
System.ServiceProcess.ServiceController service = new System.ServiceProcess.ServiceController("TestService");
if (service.Status == ServiceControllerStatus.Stopped)
{
service.Start();
service.WaitForStatus(ServiceControllerStatus.Running);
}
service.ExecuteCommand(100); // Causes Exception every time
}
catch (Exception e)
{
MessageBox.Show(e.Message);
throw e;
}
This is happening is because ExecuteCommand only accepts integers: 128-256, anything under 128 is system reserved and since 100 is being passed the Exception occurs.
Replacing service.ExecuteCommand(100) with something like service.ExecuteCommand(130) will work just fine.

How to programmatically retrieve reason code from a XMS XMSException

I have a XMS MQ Client app that is pulling off messages from a series of MQ endpoints. There are certain reason codes for which the process can continue, and for some that it should abort. For example a MQRC_Q_MGR_NOT_AVAILABLE 2059 for one endpoint shouldn't abort the whole process. Consequently I would like to check for this reason code.
cf = factoryFactory.CreateConnectionFactory();
foreach (Endpoint e in env.GetEndpoints())
{
Console.WriteLine("Consuming messages from endpoint {0}({1})", e.host, e.port);
// Set the properties
SetConnectionProperties(cf, e);
try
{
ReceiveMessagesFromEndpoint(cf);
}
catch (XMSException ex)
{
Console.WriteLine("XMSException caught: {0}", ex);
Console.WriteLine("Error Code: {0}", ex.ErrorCode);
Console.WriteLine("Error Message: {0}", ex.Message);
}
}
Problem is that the only attributes available on the XMSException to examine are ex.ErrorCode and ex.Message, which are respectively:
Error Code: CWSMQ0006
and
Error Message: CWSMQ0006E: An exception was received during the call to the method ConnectionFactory.CreateConnection: CompCode: 2, Reason: 2059.
I can see the Reason in the Message, but can't find a method or attribute to retrieve it.
There are probably 2 ways to do it
1) You can use the LinkedException
Something like the following
try
{
}
catch (XMSException e)
{
if(e.LinkedException!=null)
Console.WriteLine(e.LinkedException.Message);
else
Console.WriteLine(e);
}
2) Reference amqmdnet.dll as well to the project and use MQException.Something like
try
{
}
catch (XMSException e)
{
if(e.LinkedException!=null)
{
IBM.WMQ.MQException inner = (IBM.WMQ.MQException)e.LinkedException;
Console.WriteLine("Reason:"+ inner.ReasonCode);
}
else
Console.WriteLine(e);
}
Solution by OP
Based on accepted answer, a 'working' code is:
cf = factoryFactory.CreateConnectionFactory();
foreach (Endpoint e in env.GetEndpoints())
{
Console.WriteLine("Consuming messages from endpoint {0}({1})", e.host, e.port);
// Set the properties
SetConnectionProperties(cf, e);
try
{
ReceiveMessagesFromEndpoint(cf);
}
catch (XMSException ex)
{
Console.WriteLine("XMSException caught: {0}", ex);
Console.WriteLine("Error Code: {0}", ex.ErrorCode);
Console.WriteLine("Error Message: {0}", ex.Message);
if (ex.LinkedException != null &&
IBM.XMS.MQC.MQRC_Q_MGR_NOT_AVAILABLE.ToString().Equals(ex.LinkedException.Message))
{
Console.WriteLine("Queue Manager on this endpoint is not available");
Console.WriteLine("Moving onto next endpoint");
continue;
}
Console.WriteLine("Unexpected Error - Aborting");
throw;
}
}

Stop IIS website from its own thread

I am using the following code to stop my WCF service from its own thread to update some files that are used by my service.
try
{
var server = new ServerManager();
var site = server.Sites.FirstOrDefault(s => s.Name == "Default Web Site");
if (site != null)
{
Thread.Sleep(1000);
site.Stop();
if (site.State == ObjectState.Stopped)
{
Thread.Sleep(5000);
}
site.Start();
}
else
{
throw new FaultException("Server Are Trying To Stop Is not Found");
}
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
But I get following error when I execute the code:
"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"
I think you should run Powershell script for such case, as you want to stop the process which is self as I understand. Meaning that after stop, your process will be killed and no update can be performed. With power shell you could stop process, copy over files and start over
Import-Module WebAdministration
Stop-WebSite 'Default Web Site'
#... copy files here
Start-WebSite 'Default Web Site'

Consumer service not dequeuing all messages from ActiveMQ queue

I have a windows service that is attempting to consume messages from some activemq queue's. However, it is only getting some of the messages and others are getting stuck in 'messages pending' in the queue. ActiveMQ tells me it has enqueued lets say 500 messages to the consumer but only 300 were dequeued. There is more than one listener being set up in the service. Here's the important part of the code:
private void setupListener(string queue, string brokerUri)
{
try
{
ISession session = connectionConsumers[brokerUri].CreateSession();
session.CreateConsumer(session.GetQueue(queue))
.Listener += new MessageListener(consumer_Listener);
}
catch (Exception ex)
{
Log.Error("An exception has occured setting up listener for " + queue + " on " + brokerUri + ": {0}, {1}", ex, ex.Message);
}
}
void consumer_Listener(IMessage message)
{
try
{
processLog((message as ITextMessage).Text);
message.Acknowledge();
}
catch (NMSException ex)
{
Log.Error("ActiveMQ Connection Failure: {0}, {1}", ex, ex.Message);
}
catch (Exception ex)
{
Log.Error("An exception has occured trying to process a message: {0}, {1}", ex, ex.Message);
}
}
Is there something wrong with the way I'm acknowledging messages that would cause certain ones to not be acknowledged? Is it a concurrency issue? I'm not sure if they are all still going through the processLog function (added to my database).
EDIT: I think it has more to do with acknowledgements not happening properly (for some reason). I am not getting exceptions thrown in my logs. However, activemq shows the following:
From what I've read, the dispatch queue is being filled with messages that were sent to the consumer but not acknowledged. Why could this be?
The problem had to do with our queues being virtual destinations.

Categories