I am trying to use multiple threads to open an IBM MQ queue manager and get message from it from every thread.
I have encountered a couple of problems with the code.
When the threads are started, the first one or two threads will fail
with "Object not set to an instance" error near the "pnrQ.Get(msg,
gmo);"
When the subsequent threads are started, only one thread is reading messages from the queue, the other threads will all have the
"MQC.MQRC_NO_MSG_UNDER_CURSOR" error
Does this have something to do with the "openOptions" I declare for the Queue Manager? Or something to do with the "MQGetMessageOptions" I declare?
Where can I refer to some sample codes for IBM MQ Unmanaged Client multithread sample codes?
using System;
using System.Collections;
using IBM.WMQ;
using System.Configuration;
using System.Text;
using System.IO;
using System.Threading;
using System.Globalization;
namespace MqClientUnmanaged
{
class MqClientUnmanaged
{
static void Main(string[] args)
{
Hashtable prop = new Hashtable();
prop.Add(MQC.HOST_NAME_PROPERTY, ConfigurationManager.AppSettings.Get("host"));
prop.Add(MQC.PORT_PROPERTY, ConfigurationManager.AppSettings.Get("port"));
prop.Add(MQC.CHANNEL_PROPERTY, ConfigurationManager.AppSettings.Get("channel"));
prop.Add(MQC.CONNECT_OPTIONS_PROPERTY, MQC.MQCNO_RECONNECT);
prop.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
prop.Add(MQC.SSL_CERT_STORE_PROPERTY, ConfigurationManager.AppSettings.Get("sslKeyRepository"));
prop.Add(MQC.SSL_CIPHER_SPEC_PROPERTY, ConfigurationManager.AppSettings.Get("cipherSpec"));
prop.Add(MQC.CERT_LABEL_PROPERTY, ConfigurationManager.AppSettings.Get("certLabel"));
foreach (DictionaryEntry de in prop)
{
Console.WriteLine("Property: {0}, Value: {1}", de.Key, de.Value);
}
//MQQueueManager[] queueManager = new MQQueueManager[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
//MQQueue[] pnrQueue = new MQQueue[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
try
{
var queueManager = new MQQueueManager[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
var pnrQueue = new MQQueue[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
int openOptions = MQC.MQGMO_SYNCPOINT | MQC.MQOO_FAIL_IF_QUIESCING | MQC.MQOO_INPUT_SHARED | MQC.MQOO_BROWSE;
Thread[] threads = new Thread[int.Parse(ConfigurationManager.AppSettings["number_of_thread"])];
for(int thread_array_count = 0; thread_array_count < int.Parse(ConfigurationManager.AppSettings["number_of_thread"]); thread_array_count++)
{
try
{
queueManager[thread_array_count] = new MQQueueManager(ConfigurationManager.AppSettings.Get("queue_manager"), prop);
pnrQueue[thread_array_count] = queueManager[thread_array_count].AccessQueue(ConfigurationManager.AppSettings.Get("queue"), openOptions);
Console.WriteLine("Thread #" + thread_array_count.ToString() + " successfully connected to " + ConfigurationManager.AppSettings.Get("queue"));
threads[thread_array_count] = new Thread(() => LoopMessage(thread_array_count, pnrQueue[thread_array_count]));
threads[thread_array_count].Name = string.Concat("Threads ", (thread_array_count).ToString());
threads[thread_array_count].Start();
Thread.Sleep(Convert.ToInt32(ConfigurationManager.AppSettings["thread-sleep"]));
}
catch (MQException mqe)
{
Console.WriteLine("An IBM MQ error occurred: {0}, {1}", mqe.Message.ToString(), mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error StackTrace: {0}, {1}", mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error reason code: {0}", mqe.ReasonCode);
Console.WriteLine("An IBM MQ error reason: {0}", mqe.Reason);
}
catch (System.Exception ex)
{
Console.WriteLine("A System error occurred: {0}, {1}", ex.Message.ToString(), ex.StackTrace.ToString());
}
finally
{
try
{
if (pnrQueue[thread_array_count] != null)
pnrQueue[thread_array_count].Close();
Console.WriteLine("Thread #" + thread_array_count.ToString() + " " + ConfigurationManager.AppSettings.Get("queue") + " is closed");
}
catch (MQException mqe)
{
Console.WriteLine("An IBM MQ error occurred: {0}, {1}", mqe.Message.ToString(), mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error StackTrace: {0}, {1}", mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error reason code: {0}", mqe.ReasonCode);
Console.WriteLine("An IBM MQ error reason: {0}", mqe.Reason);
}
try
{
if (queueManager[thread_array_count] != null)
queueManager[thread_array_count].Disconnect();
Console.WriteLine("Thread #" + thread_array_count.ToString() + " " + ConfigurationManager.AppSettings.Get("queue_manager") + " is disconnected");
}
catch (MQException mqe)
{
Console.WriteLine("An IBM MQ error occurred: {0}, {1}", mqe.Message.ToString(), mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error StackTrace: {0}, {1}", mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error reason code: {0}", mqe.ReasonCode);
Console.WriteLine("An IBM MQ error reason: {0}", mqe.Reason);
}
}
}
}
catch (MQException mqe)
{
Console.WriteLine("An IBM MQ error occurred: {0}, {1}", mqe.Message.ToString(), mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error StackTrace: {0}, {1}", mqe.StackTrace.ToString());
Console.WriteLine("An IBM MQ error reason code: {0}", mqe.ReasonCode);
Console.WriteLine("An IBM MQ error reason: {0}", mqe.Reason);
}
catch (System.Exception ex)
{
Console.WriteLine("A System error occurred: {0}, {1}", ex.Message.ToString(), ex.StackTrace.ToString());
}
Console.WriteLine("Press any key to EXIT.......");
Console.ReadKey();
}
private static void LoopMessage(int thread_num, MQQueue pnrQ)
{
bool flag = true;
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.Options = MQC.MQGMO_WAIT | MQC.MQGMO_BROWSE_FIRST;
gmo.WaitInterval = int.Parse(ConfigurationManager.AppSettings.Get("wait_interval")); //1 to 2 second wait time or MQC.MQEI_UNLIMITED
while (flag)
{
try
{
//IMPORTANT: must declare a new message here
MQMessage msg = new MQMessage();
pnrQ.Get(msg, gmo);
Console.WriteLine("Thread # ", thread_num.ToString() + "; Message Length = " + msg.MessageLength.ToString());
if(msg.MessageLength > 0)
{
string newMessage = msg.ReadString(msg.MessageLength);
string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssffff", CultureInfo.InvariantCulture);
string guid = Guid.NewGuid().ToString();
Console.WriteLine("Thread # ", thread_num.ToString() + "; Message Id = " + ByteArrayToString(msg.MessageId));
//write to text file
using (StreamWriter writer = new StreamWriter(string.Concat(ConfigurationManager.AppSettings.Get("pnr_file_path"), "sbr.", thread_num.ToString(), ".", timestamp, ".", guid, ".", ByteArrayToString(msg.MessageId), ".txt")))
{
writer.WriteLine(newMessage);
}
Console.WriteLine(string.Concat("Writing PNR file with name = ", string.Concat(ConfigurationManager.AppSettings.Get("pnr_file_path"), "sbr.", thread_num.ToString(), ".", timestamp, ".", guid, ".", ByteArrayToString(msg.MessageId), ".txt")));
Console.WriteLine(new string('*', 100));
}
// set te cursor to remove the message from the queue
gmo.Options = MQC.MQGMO_MSG_UNDER_CURSOR;
pnrQ.Get(msg, gmo);
gmo.Options = MQC.MQGMO_WAIT | MQC.MQGMO_BROWSE_NEXT;
}
catch (MQException mqex)
{
if (mqex.Reason == MQC.MQRC_NO_MSG_AVAILABLE || mqex.Reason == MQC.MQRC_NO_MSG_UNDER_CURSOR)
{
//no meesage - life is good - loop again
Console.WriteLine("Thread # " + thread_num.ToString() + "; MqClientUnmanaged reason code = " + mqex.ReasonCode + "; MqClientUnmanaged reason = " + mqex.Message);
}
else
{
Console.WriteLine("MqClientUnmanaged reason code = " + mqex.ReasonCode);
Console.WriteLine("MqClientUnmanaged error message = " + mqex.Message);
Console.WriteLine("MqClientUnmanaged StackTrace = " + mqex.StackTrace);
flag = false; //severe error - time to exit
}
}
catch (Exception ex)
{
Console.WriteLine("MqClientUnmanaged error message = " + ex.Message);
Console.WriteLine("MqClientUnmanaged stack trace = " + ex.StackTrace);
flag = false; //severe error - time to exit
}
}
}
private static string ByteArrayToString(byte[] ba)
{
StringBuilder hex = new StringBuilder(ba.Length * 2);
foreach (byte b in ba)
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
}
}
Related
I'm catching an error in an action method as there are currently a couple different things that could go wrong (working on it). There are a number of people testing the app and I'd like them to be able to see the exact error. Here is the try block in the action method for creating a new employee:
try
{
db.Employees.Add(employee);
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
var err = validationError.ErrorMessage;
System.Diagnostics.Debug.WriteLine("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
System.Diagnostics.Debug.WriteLine("err: " + err);
RedirectToAction("ErrorMessage", new { message = err });
}
}
}
This does successfully print the error message to my console in Visual Studio but it does not redirect the user to the ErrorMessage screen. Rather, the catch block simply moves on. I do not want this to happen.
Any time an error occurs I want the error message to be saved to the string err and then sent to the Error Message page.
ErrorMessage Action Result
public ActionResult ErrorMessage(string message)
{
ViewBag.ErrorMessage = message;
System.Diagnostics.Debug.WriteLine("Error message: " + message);
return View(message);
}
What do I need to change?
EDIT: Based on the first answer I added the return (my mistake) but I'm still not redirected to the correct error page. Instead I am directed to this:
This is the try/catch block now:
catch (DbEntityValidationException ex)
{
var err = new StringBuilder();
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
err.AppendLine(validationError.ErrorMessage);
System.Diagnostics.Debug.WriteLine("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
System.Diagnostics.Debug.WriteLine("err: " + err);
}
}
return RedirectToAction("ErrorMessage", new { message = err.ToString()});
}
EDIT 2:
This is what I have right now:
try
{
db.Employees.Add(employee);
db.SaveChanges();
}
catch (DbEntityValidationException ex)
{
var err = new StringBuilder();
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
err.AppendLine(validationError.ErrorMessage);
System.Diagnostics.Debug.WriteLine("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
System.Diagnostics.Debug.WriteLine("err: " + err);
return RedirectToAction("ErrorMessage", "Employees", (object)err.ToString());
}
}
}
Which actually does redirect me to the ErrorMessage.cshtml page. However, I'm not quite sure how to retrieve (object)err.ToString() on the ErrorMessage ActionResult. This is what I am trying right now:
public ActionResult ErrorMessage(object err)
{
ViewBag.ErrorMessage = err.ToString();
System.Diagnostics.Debug.WriteLine("Error message: " + err.ToString());
return View(err);
}
And the actual view:
#{
ViewBag.Title = "ErrorMessage";
}
<h2>Error message page.</h2>
<p>#ViewBag.ErrorMessage</p>
But it simply gives me System.Object instead of the actual error message.
It is necessary to return result object to be able make the RedirectToAction() working:
var err = new StringBuilder();
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
Response.Write("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
err.AppendLine(validationError.ErrorMessage);
System.Diagnostics.Debug.WriteLine("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
System.Diagnostics.Debug.WriteLine("err: " + err);
}
}
return RedirectToAction("ErrorMessage", (object)err.ToString());
I am trying to read messages from MQ all at once by iterating through it. Currently I am only able to read one message at a time. I want to have a counter which will control how many times the loop will get executed or something like a while loop which will terminate when the queue is empty or else will continue reading message.
public string ReadMessages()
{
MQQueue mqDestination;
String Readmessage = null;
QueueManagerName = ConfigurationManager.AppSettings["QueueManagername"];
Hashtable properties = new Hashtable();
properties.Add(MQC.HOST_NAME_PROPERTY, ConfigurationManager.AppSettings["Connection"]);
properties.Add(MQC.PORT_PROPERTY, ConfigurationManager.AppSettings["PortNo"]);
properties.Add(MQC.CHANNEL_PROPERTY, ConfigurationManager.AppSettings["Channelname"]);
properties.Add(MQC.MQCA_TOPIC_NAME, ConfigurationManager.AppSettings["Queuename"]);
properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
queueManager = new MQQueueManager(QueueManagerName, properties);
int openOptionsForGet = (MQC.MQSO_CREATE
+ (MQC.MQSO_FAIL_IF_QUIESCING
+ (MQC.MQSO_MANAGED
+ (MQC.MQSO_NON_DURABLE + MQC.MQMO_NONE))));
MQGetMessageOptions Gmo;
MQMessage RetrievedMessage;
RetrievedMessage = new MQMessage();
try
{
RetrievedMessage = new MQMessage();
Gmo = new MQGetMessageOptions();
//Queue Name
mqDestination = queueManager.AccessQueue(ConfigurationManager.AppSettings["QueueName"], openOptionsForGet);
mqDestination.Get(RetrievedMessage, Gmo);
string message = RetrievedMessage.ReadString(RetrievedMessage.MessageLength);
queueManager.Disconnect();
}
catch (MQException ex)
{
switch (ex.ReasonCode)
{
case IBM.WMQ.MQC.MQRC_NO_MSG_AVAILABLE:
Library.ErrorLogs("error" + "No message available.");
break;
case IBM.WMQ.MQC.MQRC_Q_MGR_QUIESCING:
case IBM.WMQ.MQC.MQRC_Q_MGR_STOPPING:
Library.ErrorLogs("error" + "Queue Manager Stopping: " + ConfigurationManager.AppSettings["QueueManagername"] + "\t" + ex.Message);
break;
case IBM.WMQ.MQC.MQRC_Q_MGR_NOT_ACTIVE:
case IBM.WMQ.MQC.MQRC_Q_MGR_NOT_AVAILABLE:
Library.ErrorLogs("error" + "Queue Manager not available: " + ConfigurationManager.AppSettings["QueueManagername"] + "\t" + ex.Message);
break;
default:
Library.ErrorLogs("error" + " Error reading topic: " + ConfigurationManager.AppSettings["Queuename"] + "\t" + ex.Message);
break;
}
}
catch (Exception ex)
{
// Console.WriteLine("MQException caught. " + mqE.ToString());
Library.ErrorLogs("error" + ex.Message);
queueManager.Disconnect();
}
return Readmessage;
}
(1) You cannot get all the messages from a queue at once. You need to retrieve each message individually. MQ is not a database.
(2) You have topic code in your sample. Are you getting messages from a queue or topic. There is a difference.
Here is a fully functioning CS/.NET/MQ sample program to retrieve all messages on a queue:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using IBM.WMQ;
/// <summary> Program Name
/// MQTest72
///
/// Description
/// This C# class will connect to a remote queue manager
/// and get messages from a queue using a managed .NET environment.
///
/// </summary>
/// <author> Roger Lacroix
/// </author>
namespace MQTest72
{
class MQTest72
{
private Hashtable qMgrProp = null;
private System.String qManager;
private System.String inputQName;
/*
* The constructor
*/
public MQTest72()
: base()
{
}
/// <summary> Make sure the required parameters are present.</summary>
/// <returns> true/false
/// </returns>
private bool allParamsPresent()
{
bool b = false;
if ( (ConfigurationManager.AppSettings["ConnectionName"] != null) &&
(ConfigurationManager.AppSettings["Port"] != null) &&
(ConfigurationManager.AppSettings["ChannelName"] != null) &&
(ConfigurationManager.AppSettings["QMgrName"] != null) &&
(ConfigurationManager.AppSettings["QueueName"] != null) )
{
try
{
System.Int32.Parse(ConfigurationManager.AppSettings["Port"]);
b = true;
}
catch (System.FormatException e)
{
b = false;
}
}
return b;
}
/// <summary> Extract the configuration applicaiton settings and initialize the MQ variables.</summary>
/// <param name="args">
/// </param>
/// <throws> IllegalArgumentException </throws>
private void init(System.String[] args)
{
if (allParamsPresent())
{
qManager = ConfigurationManager.AppSettings["QMgrName"];
inputQName = ConfigurationManager.AppSettings["QueueName"];
qMgrProp = new Hashtable();
qMgrProp.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
qMgrProp.Add(MQC.HOST_NAME_PROPERTY, ConfigurationManager.AppSettings["ConnectionName"]);
qMgrProp.Add(MQC.CHANNEL_PROPERTY, ConfigurationManager.AppSettings["ChannelName"]);
try
{
qMgrProp.Add(MQC.PORT_PROPERTY, System.Int32.Parse(ConfigurationManager.AppSettings["Port"]));
}
catch (System.FormatException e)
{
qMgrProp.Add(MQC.PORT_PROPERTY, 1414);
}
if (ConfigurationManager.AppSettings["UserId"] != null)
qMgrProp.Add(MQC.USER_ID_PROPERTY, ConfigurationManager.AppSettings["UserId"]);
if (ConfigurationManager.AppSettings["Password"] != null)
qMgrProp.Add(MQC.PASSWORD_PROPERTY, ConfigurationManager.AppSettings["Password"]);
logger("Parameters:");
logger(" QMgrName ='" + qManager + "'");
logger(" Queue Name ='" + inputQName + "'");
logger("Connection values:");
foreach (DictionaryEntry de in qMgrProp)
{
logger(" " + de.Key + " = '" + de.Value + "'");
}
}
else
{
throw new System.ArgumentException();
}
}
/// <summary> Connect, open queue, retrieve all messages, close queue and disconnect.</summary>
/// <throws> MQException </throws>
private void handleIt()
{
MQQueueManager qMgr = null;
MQQueue inQ = null;
int openOptions = MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING;
try
{
qMgr = new MQQueueManager(qManager, qMgrProp);
logger("MQTest72 successfully connected to " + qManager);
inQ = qMgr.AccessQueue(inputQName, openOptions);
logger("MQTest72 successfully opened " + inputQName);
retrieveAll(inQ);
}
catch (MQException mqex)
{
logger("MQTest72 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
catch (System.IO.IOException ioex)
{
logger("MQTest72 ioex=" + ioex);
}
finally
{
try
{
if (inQ != null)
{
inQ.Close();
logger("MQTest72 closed: " + inputQName);
}
}
catch (MQException mqex)
{
logger("MQTest72 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
try
{
if (qMgr != null)
{
qMgr.Disconnect();
logger("MQTest72 disconnected from " + qManager);
}
}
catch (MQException mqex)
{
logger("MQTest72 CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
}
}
/// <summary> Retrieve all messages from a queue or until a 'QUIT' message is received.</summary>
/// <param name="inQ">
/// </param>
private void retrieveAll(MQQueue inQ)
{
bool flag = true;
MQGetMessageOptions gmo = new MQGetMessageOptions();
gmo.Options |= MQC.MQGMO_NO_WAIT | MQC.MQGMO_FAIL_IF_QUIESCING;
MQMessage msg = null;
while (flag)
{
try
{
msg = new MQMessage();
inQ.Get(msg, gmo);
if (msg.Feedback == MQC.MQFB_QUIT)
{
flag = false;
logger("received quit message - exiting loop");
}
else
logger("Message Data: " + msg.ReadString(msg.MessageLength));
}
catch (MQException mqex)
{
logger("CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
if (mqex.Reason == MQC.MQRC_NO_MSG_AVAILABLE)
{
// no meesage - life is good
flag = false;
logger("no more meesages - exiting loop");
}
else
{
flag = false; // severe error - time to exit
}
}
catch (System.IO.IOException ioex)
{
logger("ioex=" + ioex);
}
}
}
/// <summary> Output the log message to stdio.</summary>
/// <param name="data">
/// </param>
private void logger(String data)
{
DateTime myDateTime = DateTime.Now;
System.Console.Out.WriteLine(myDateTime.ToString("yyyy/MM/dd HH:mm:ss.fff") + " " + this.GetType().Name + ": " + data);
}
/// <summary> main line</summary>
/// <param name="args">
/// </param>
// [STAThread]
public static void Main(System.String[] args)
{
MQTest72 mqt = new MQTest72();
try
{
mqt.init(args);
mqt.handleIt();
}
catch (System.ArgumentException e)
{
System.Console.Out.WriteLine("Usage: MQTest72 -h host -p port -c channel -m QueueManagerName -q QueueName [-u userID] [-x passwd]");
System.Environment.Exit(1);
}
catch (MQException e)
{
System.Console.Out.WriteLine(e);
System.Environment.Exit(1);
}
System.Environment.Exit(0);
}
}
}
Modify the code to read the messages in loop as below. Also note that the options you have used for opening queue are not correct.
public string ReadMessages()
{
MQQueue mqDestination;
String Readmessage = null;
QueueManagerName = ConfigurationManager.AppSettings["QueueManagername"];
Hashtable properties = new Hashtable();
properties.Add(MQC.HOST_NAME_PROPERTY, ConfigurationManager.AppSettings["Connection"]);
properties.Add(MQC.PORT_PROPERTY, ConfigurationManager.AppSettings["PortNo"]);
properties.Add(MQC.CHANNEL_PROPERTY, ConfigurationManager.AppSettings["Channelname"]);
properties.Add(MQC.MQCA_TOPIC_NAME, ConfigurationManager.AppSettings["Queuename"]);
properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_MANAGED);
try
{
queueManager = new MQQueueManager(QueueManagerName, properties);
int openOptionsForGet = MQC.MQOO_INPUT + MQC.MQSO_FAIL_IF_QUIESCING;
//Queue Name
mqDestination = queueManager.AccessQueue(ConfigurationManager.AppSettings["QueueName"],openOptionsForGet);
//Read messages with a wait of 30 seconds. Break out of the loop when there are no messages (MQRC 2033) or any other reason code is received.
while (true) {
try {
MQGetMessageOptions Gmo = new MQGetMessageOptions();
Gmo.WaitInterval = 30
Gmo.Options |= MQC.MQGMO_WAIT;
MQMessage RetrievedMessage = new MQMessage();
mqDestination.Get(RetrievedMessage, Gmo);
string message = RetrievedMessage.ReadString(RetrievedMessage.MessageLength);
} catch(MQException ex) {
// Display the exception and break;
break;
}
}
mqDestination.Close();
queueManager.Disconnect();
}
catch (MQException ex)
{
switch (ex.ReasonCode)
{
case IBM.WMQ.MQC.MQRC_NO_MSG_AVAILABLE:
Library.ErrorLogs("error" + "No message available.");
break;
case IBM.WMQ.MQC.MQRC_Q_MGR_QUIESCING:
case IBM.WMQ.MQC.MQRC_Q_MGR_STOPPING:
Library.ErrorLogs("error" + "Queue Manager Stopping: " + ConfigurationManager.AppSettings["QueueManagername"] + "\t" + ex.Message);
break;
case IBM.WMQ.MQC.MQRC_Q_MGR_NOT_ACTIVE:
case IBM.WMQ.MQC.MQRC_Q_MGR_NOT_AVAILABLE:
Library.ErrorLogs("error" + "Queue Manager not available: " + ConfigurationManager.AppSettings["QueueManagername"] + "\t" + ex.Message);
break;
default:
Library.ErrorLogs("error" + " Error reading topic: " + ConfigurationManager.AppSettings["Queuename"] + "\t" + ex.Message);
break;
}
}
catch (Exception ex)
{
// Console.WriteLine("MQException caught. " + mqE.ToString());
Library.ErrorLogs("error" + ex.Message);
queueManager.Disconnect();
}
return Readmessage;
}
I have a problem in activemq. I want to receive a special message from my activemq queue. I have there over 300 Messages, and I want one of the message. I solved this with a multiselectcombobox. In this box I have all messages with all properties I need.
When I click on the 247 item, I want do select the item to receive the message, after them I want to send the message but first I have a problem with the receive.
I don't know why it doesn't work. Maybe someone has an idea?
ErrorMessageProperty prop = new ErrorMessageProperty();
IMessage message = null;
try
{
string MsgID = MSGID;
string desinationque = sourceQueue;
string selector = "ProducerId = '" + MsgID + "'";
IDestination dest = MQSession.GetDestination(desinationque);
Uri _activeMQURI = new Uri(conf.ActiveMqURL);
MQConnectionFactory = new NMSConnectionFactory(_activeMQURI);
using (MQConnection = MQConnectionFactory.CreateConnection(conf.ActiveMqUser, conf.ActiveMqPWD))
using (MQSession = MQConnection.CreateSession(AcknowledgementMode.AutoAcknowledge))
{
try
{
MQConnection.Start();
}
catch (Exception ex)
{
myLogger.NLogger.Info("MQReceiveTextMessage Connection fehlgeschlagen: " + ex.Message);
}
using (IMessageConsumer consumer = this.MQSession.CreateConsumer(dest, selector,false))
{
if (shallwait)
{
try
{
message = consumer.Receive();
}
catch (Exception ex)
{
myLogger.NLogger.Error("Error in consumer Receive (MQReceiveTextMessage): Message" + message + " Fehler-Exception: " + ex.Message);
}
}
else
{
message = consumer.Receive(TimeSpan.FromSeconds(1));
}
}
}
}
catch (Exception ex)
{
myLogger.NLogger.Error("Error in MQReceiveTextMessage: Parameter: sourceQueue: " + sourceQueue + " MSGID: " + MSGID + " Message: " + message + " Fehler-Exception: " + ex.Message);
}
return message;
}
My ProducerID is correct. But why doesn't this work? It stops at the line
message = consumer.receive();
I don't know anymore
With the selector ProducerId = 'MsgIDValue', the operation consumer.receive() is searching a Message in the queue with a custom property "ProducerId" with the value of the variable MsgID. If the message is not found the consumer waits new messages.
If you want to search for a default message field, message header field references are restricted to JMSDeliveryMode, JMSPriority, JMSMessageID, JMSTimestamp, JMSCorrelationID, and JMSType. JMSMessageID, JMSCorrelationID, and JMSType values may be null and if so are treated as a NULL value.
Source Message Selectors
I used Apache.NMS and Apache.NMS.ActiveMQ (1.7.1.3924)
is it possible to u se this api than the jms?
I try this since 1 Week and the selector does'nt work....
Maybe someone othe
I have a windows service in C# .NET 4.6.1 that is building SSRS reports and sending the report to various network printers. All printers are installed locally on the server where the service is installed. All this was working on a Windows Server 2008R2 server and recently the client upgraded to Windows Server 2012R2 and now no printouts. I am getting no errors and when checking the job status on the printer I can see the job count on the printer increase by 1 and the PrintJobStatus.Spooling is true but nothing comes out on the printer.
private bool PrintSheet(AppPrintRequest model, PackagingEntities db)
{
try
{
var oPrinter = db.AppPrinters.Where(x => x.AppPrinterID == model.AppPrinterID).FirstOrDefault();
var lpsPrintServer = new LocalPrintServer();
var psPrintServer = new PrintServer();
var sbLog = new StringBuilder();
byte[] reportBytes = BuildSSRSReport(model);
PrintQueueCollection pqcAvailablePrinters;
if (!string.IsNullOrEmpty(oPrinter.AppPrinterServer))
{
pqcAvailablePrinters = lpsPrintServer.GetPrintQueues();
}
else
{
pqcAvailablePrinters = psPrintServer.GetPrintQueues();
}
sbLog.AppendFormat("System: {0} ", model.AppPrintRequestSystem);
sbLog.AppendFormat("Printer: {0} ", oPrinter.AppPrinterAddress);
foreach(var oAvailablePrinter in pqcAvailablePrinters)
{
sbLog.AppendFormat("Printer FullName: {0} ", oAvailablePrinter.FullName);
sbLog.AppendFormat("Printer Name: {0} ", oAvailablePrinter.Name);
sbLog.AppendFormat("Printer Description: {0} ", oAvailablePrinter.Description);
}
var oLaserPrinter = pqcAvailablePrinters.FirstOrDefault(pqCurrent => pqCurrent.Name.ToUpper() == oPrinter.AppPrinterAddress.ToUpper());
sbLog.AppendFormat("Report Bytes is null = {0} ", reportBytes == null);
sbLog.AppendFormat("Laser Print is null = {0} ", oLaserPrinter == null);
if (reportBytes != null && oLaserPrinter != null)
{
sbLog.AppendFormat("Report Bytes Length: {0} ", reportBytes.Length);
sbLog.AppendFormat("Laser Printer: {0} ", oLaserPrinter.Name);
sbLog.AppendFormat("Laser Printer Busy: {0} ", oLaserPrinter.IsBusy);
PrintSystemJobInfo oPrintJob = oLaserPrinter.AddJob();
sbLog.AppendFormat("Laser Printer Job Count: {0} ", oLaserPrinter.NumberOfJobs);
GetPrintJobStatus(oPrintJob, sbLog);
oPrintJob.JobStream.Write(reportBytes, 0, reportBytes.Length);
oPrintJob.JobStream.Close();
oPrintJob.Refresh();
sbLog.AppendFormat("Job Completed: {0} ", oPrintJob.IsCompleted);
NLogger.Debug(string.Format("Print Sheet: {0}", sbLog.ToString()));
return true;
}
NLogger.Debug(string.Format("Print Sheet: {0}", sbLog.ToString()));
return false;
}
catch (Exception ex)
{
NLogger.Fatal("PrintEngine_PrintSheet", ex);
return false;
}
}
I have been trying to get all the users from the SP site. I have the code working for getting the groups adn group names but am getting an exception when I try to access the users from the groups. I initialized all the components before I used it and I think this is a classical case of CSOM hell. But even after a lot of changes I was not able to solve it. Any inputs are appreciated..
Exception Details:
Microsoft.SharePoint.Client.CollectionNotInitializedException was caught
HResult=-2146233079
Message=The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested.
Source=Microsoft.SharePoint.Client.Runtime
StackTrace:
at Microsoft.SharePoint.Client.ClientObjectCollection`1.d__0.MoveNext()
at GetUsersInGroupCSOM.Program.Main(String[] args)
InnerException:
Code"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Security;
namespace GetUsersInGroupCSOM
{
class Program
{
static void Main(string[] args)
{
//Replace it with the url of your tenant or your site-collection
string SiteUrl = "The Website";
System.Uri oUri = new System.Uri(SiteUrl);
using (ClientContext oClientContext = new ClientContext(SiteUrl))
{
//Replace it with your user id for SharePoint Online
string UserName = XXXXXXX;
//Replace it with your password
string Password = XXXXXXXXXXXXXX;
//Create a SecureString object from password string, needed for SharePointOnlineCredentials class
//SecureString SecurePassword = GetSecureString(Password);
//Old Credential code
//oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);
oClientContext.Credentials = new NetworkCredential(UserName, Password);
//Load the site-collection groups using CSOM
Console.WriteLine(oClientContext.Web.SiteGroups);
oClientContext.Load(oClientContext.Web.SiteGroups);
try
{
oClientContext.ExecuteQuery();
Console.WriteLine("Connected");
}
catch (Exception e)
{
Console.WriteLine("The error is \n" + e.Message);
Console.WriteLine("The source is \n" + e.Source);
Console.WriteLine("The Stack Trace is \n" + e.StackTrace);
}
GroupCollection oSiteCollectionGroups = oClientContext.Web.SiteGroups;
oClientContext.Load(oSiteCollectionGroups);
Console.WriteLine("List of groups in the site collection");
Console.WriteLine("-------------------------------------");
Console.WriteLine(oSiteCollectionGroups.AreItemsAvailable);
foreach (Group oGroup in oSiteCollectionGroups)
{
Console.WriteLine(oGroup.Title);
}
Console.WriteLine("<<<<<<<<<<===================|End of Groups|========================>>>>>>>");
//Load the users collection in the Group 1
Console.WriteLine(oSiteCollectionGroups[1].Users);
oClientContext.Load(oSiteCollectionGroups[1].Users);
try
{
oClientContext.ExecuteQuery();
Console.WriteLine("Got the users >-->");
}
catch (Exception e)
{
Console.WriteLine("The error is \n" + e.Message);
Console.WriteLine("The source is \n" + e.Source);
Console.WriteLine("The Stack Trace is \n" + e.StackTrace);
}
Console.WriteLine("List of users in the first group of site-collection");
Console.WriteLine("-------------------------------------------------------");
//Console.WriteLine(oSiteCollectionGroups[1].Users);
//Console.WriteLine(oSiteCollectionGroups[1].AllowMembersEditMembership);
//Console.WriteLine(oSiteCollectionGroups[1].CanCurrentUserViewMembership);
//Console.WriteLine(oSiteCollectionGroups[1].Context);
//Console.WriteLine(oSiteCollectionGroups[1].Description);
//Console.WriteLine(oSiteCollectionGroups[1].LoginName);
//Console.WriteLine(oSiteCollectionGroups[1].Title);
//Console.WriteLine(oSiteCollectionGroups[1].ToString());
for (int i = 1; i < oSiteCollectionGroups.Count; i++)
{
//Group oGroup = oClientContext.Web.SiteGroups.GetById(i);
oClientContext.Load(oSiteCollectionGroups[i].Users);
Console.WriteLine("Items Available =>"+oSiteCollectionGroups[i].Users.AreItemsAvailable);
Console.WriteLine(oSiteCollectionGroups[i].Description);
Console.WriteLine(oSiteCollectionGroups[i].LoginName);
Console.WriteLine(oSiteCollectionGroups[i].Title);
Console.WriteLine("Owner Title =>"+oSiteCollectionGroups[i].OwnerTitle);
oClientContext.Load(oSiteCollectionGroups[i].Users);
try
{
foreach (User oUser in oSiteCollectionGroups[i].Users)
{
Console.WriteLine(oUser.Title);
Console.WriteLine("n");
}
}
catch (Exception e)
{
Console.WriteLine("Exception Occured");
Console.WriteLine("The error is \n" + e.Message);
Console.WriteLine("The source is \n" + e.Source);
Console.WriteLine("The Stack Trace is \n" + e.StackTrace);
}
}
Console.WriteLine("<<<<<<<<<<===================|End of Memebers|========================>>>>>>>");
Console.ReadLine();
}
}
private static SecureString GetSecureString(String Password)
{
SecureString oSecurePassword = new SecureString();
foreach (Char c in Password.ToCharArray())
{
oSecurePassword.AppendChar(c);
}
return oSecurePassword;
}
}
}
You have to load the Properties in CSOM.
string SiteUrl = "The Website";
System.Uri oUri = new System.Uri(SiteUrl);
using (ClientContext oClientContext = new ClientContext(SiteUrl))
{
//Replace it with your user id for SharePoint Online
string UserName = XXXXXXX;
//Replace it with your password
string Password = XXXXXXXXXXXXXX;
oClientContext.Credentials = new NetworkCredential(UserName, Password);
Console.WriteLine(oClientContext.Web.SiteGroups);
oClientContext.Load(oClientContext.Web, w => w.SiteGroups.Include(o => o.Users.Include(l => l.LoginName), o => o.Title, o => o.Description, o => o.OwnerTitle));
try
{
oClientContext.ExecuteQuery();
Console.WriteLine("Connected");
}
catch (Exception e)
{
Console.WriteLine("The error is \n" + e.Message);
Console.WriteLine("The source is \n" + e.Source);
Console.WriteLine("The Stack Trace is \n" + e.StackTrace);
}
GroupCollection oSiteCollectionGroups = oClientContext.Web.SiteGroups;
Console.WriteLine("List of groups in the site collection");
Console.WriteLine("-------------------------------------");
Console.WriteLine(oSiteCollectionGroups.AreItemsAvailable);
foreach (Group oGroup in oSiteCollectionGroups)
{
Console.WriteLine(oGroup.Title);
}
Console.WriteLine("<<<<<<<<<<===================|End of Groups|========================>>>>>>>");
Console.WriteLine("List of users in the first group of site-collection");
Console.WriteLine("-------------------------------------------------------");
for (int i = 1; i < oSiteCollectionGroups.Count; i++)
{
Console.WriteLine("Items Available =>" + oSiteCollectionGroups[i].Users.AreItemsAvailable);
Console.WriteLine(oSiteCollectionGroups[i].Description);
Console.WriteLine(oSiteCollectionGroups[i].LoginName);
Console.WriteLine(oSiteCollectionGroups[i].Title);
Console.WriteLine("Owner Title =>" + oSiteCollectionGroups[i].OwnerTitle);
try
{
foreach (User oUser in oSiteCollectionGroups[i].Users)
{
Console.WriteLine(oUser.Title);
Console.WriteLine("n");
}
}
catch (Exception e)
{
Console.WriteLine("Exception Occured");
Console.WriteLine("The error is \n" + e.Message);
Console.WriteLine("The source is \n" + e.Source);
Console.WriteLine("The Stack Trace is \n" + e.StackTrace);
}
}
Console.WriteLine("<<<<<<<<<<===================|End of Memebers|========================>>>>>>>");
Console.ReadLine();
}
Try this.