Read all messages in MQ at once - c#

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;
}

Related

Why does it return true when the not display is used in the try and catch?

ok so I am wanting to know if there is an email in the table, so I have written a method to do just that. In the table there is nothing at all so why does it return true?
private bool FilterUserTableByEmail(string email)
{
FilterUserTableByWebElement(_regRep.FilterByNameEmail(), email);
try
{
//_regRep.emailIDInTable(email);
if (!_regRep.noDataFoundText.Displayed)
{
Console.WriteLine("Email for " + email + " was found in the table.");
}
return true;
}
catch (NoSuchElementException ex)
{
// the search result did not come back in the table - return false
Console.WriteLine("Email for " + email + " was NOT found in the table..." + ex.Message);
return false;
}
}
You can move the return statement to inside the if:
if (!_regRep.noDataFoundText.Displayed)
{
Console.WriteLine("Email for " + email + " was found in the table.");
return true;
}
else
{
return false;
}
Which can be simplified (the else is redundant):
if (!_regRep.noDataFoundText.Displayed)
{
Console.WriteLine("Email for " + email + " was found in the table.");
return true;
}
return false;
Doing this means that the method returns true if an email is found, otherwise it returns false. What you had originally always returned true, unless an exception was thrown.
Try this :
Just added this after if statement :
else
{
Console.WriteLine("Email for " + email + " was NOT found in the table..." + ex.Message);
return false;
}
Full Code :
private bool FilterUserTableByEmail(string email)
{
FilterUserTableByWebElement(_regRep.FilterByNameEmail(), email);
try
{
//_regRep.emailIDInTable(email);
if (!_regRep.noDataFoundText.Displayed)
{
Console.WriteLine("Email for " + email + " was found in the table.");
}
else
{
Console.WriteLine("Email for " + email + " was NOT found in the table..." + ex.Message);
return false;
}
return true;
}
catch (NoSuchElementException ex)
{
// the search result did not come back in the table - return false
Console.WriteLine("Email for " + email + " was NOT found in the table..." + ex.Message);
return false;
}
}

Tcp client in Xamarin.Android

I've created a simple server in raspberry pi 3 running Windows 10 IOT Core with uwp(Universal Windows Platform) with this class>
using System;
using System.Diagnostics;
using System.Text;
using Windows.Networking;
using Windows.Networking.Sockets;
using Windows.Storage.Streams;
namespace UWP_Server
{
public class StreamSocketManager
{
private StreamSocket ConnectionSocket;
public static bool IsServer { get; set; }
private string ServerPort = "8590";
public void Open()
{
StreamSocketListener DataListener = new StreamSocketListener();
DataListener.ConnectionReceived += ConnectionReceived;
DataListener.BindServiceNameAsync(ServerPort).AsTask().Wait();
}
private async void ConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args)
{
DataReader reader;
StringBuilder sb;
string receivedData = null;
using (reader = new DataReader(args.Socket.InputStream))
{
sb = new StringBuilder();
reader.InputStreamOptions = InputStreamOptions.Partial;
reader.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8;
reader.ByteOrder = ByteOrder.LittleEndian;
await reader.LoadAsync(256);
while (reader.UnconsumedBufferLength > 0)
{
sb.Append(reader.ReadString(reader.UnconsumedBufferLength));
await reader.LoadAsync(256);
}
reader.DetachStream();
receivedData = sb.ToString();
}
if (receivedData != null)
{
if (IsServer)
{
MainPage.Current.Show("[SERVER] I've received " + receivedData + " from " +
args.Socket.Information.RemoteHostName);
Debug.WriteLine("[SERVER] I've received " + receivedData + " from " +
args.Socket.Information.RemoteHostName +
"\r\nIp: " + args.Socket.Information.LocalAddress + ":" +
args.Socket.Information.LocalPort +
"\r\nProtectionLevel: " + args.Socket.Information.ProtectionLevel +
"\r\nRemoteHostName: " + args.Socket.Information.RemoteHostName +
"\r\nRemoteIP: " + args.Socket.Information.RemoteAddress + ":" +
args.Socket.Information.RemotePort +
"\r\nRemoteServiceName: " + args.Socket.Information.RemoteServiceName
);
Debug.WriteLine("");
Debug.WriteLine("");
SentResponse(args.Socket.Information.RemoteAddress, "Hello " + args.Socket.Information.RemoteHostName);
}
else
{
Debug.WriteLine("[CLIENT] I've received " + receivedData + " from "
+ args.Socket.Information.RemoteHostName +
"\r\nIp: " + args.Socket.Information.LocalAddress + ":" +
args.Socket.Information.LocalPort +
"\r\nProtectionLevel: " + args.Socket.Information.ProtectionLevel +
"\r\nRemoteHostName: " + args.Socket.Information.RemoteHostName +
"\r\nRemoteIP: " + args.Socket.Information.RemoteAddress + ":" +
args.Socket.Information.RemotePort +
"\r\nRemoteServiceName: " + args.Socket.Information.RemoteServiceName
);
Debug.WriteLine("");
Debug.WriteLine("");
}
}
else
Debug.WriteLine("Received data was empty. Check if you sent data.");
}
public async void SentResponse(HostName address, string message)
{
try
{
Debug.WriteLine("Connecting to " + address + Environment.NewLine);
ConnectionSocket = new StreamSocket();
await ConnectionSocket.ConnectAsync(address, ServerPort);
DataWriter SentResponse_Writer = new DataWriter(ConnectionSocket.OutputStream);
string content = message;
byte[] data = Encoding.UTF8.GetBytes(content);
SentResponse_Writer.WriteBytes(data);
await SentResponse_Writer.StoreAsync();
SentResponse_Writer.DetachStream();
SentResponse_Writer.Dispose();
Debug.WriteLine("Connection has been made and your message " + message + " has been sent." + Environment.NewLine);
ConnectionSocket.Dispose();
ConnectionSocket = new StreamSocket();
}
catch (Exception ex)
{
Debug.WriteLine("Failed to connect ");
ex.Exception("SentResponse");
ConnectionSocket.Dispose();
ConnectionSocket = null;
}
}
}
}
everything seems OK and It's worked in as Server.
I run this code in my Windows 10 mobile (as client) and I can received and send messages between my raspberry pi and windows mobile.
Now I want to send and receive message from my android phone.
I tested a-lot of codes but none of them worked to connect android to raspberry pi.
for android I used this nuget package >
https://github.com/rdavisau/sockets-for-pcl
here is my code:
void Send()
{
var client = new TcpClient();
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("Ramtin"), 8590);
try
{
client.Connect(ipEndPoint);
if (client.Connected)
{
Debug.WriteLine("Connected to server" + "\n");
var reader = new StreamReader(client.GetStream());
var writer = new StreamWriter(client.GetStream());
writer.AutoFlush = true;
WriteLine("Connected: " + client.Connected);
if (client.Connected)
{
writer.WriteLine("HEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEy");
}
else
{
Debug.WriteLine("send failed !");
}
}
}
catch (Exception ex)
{
ex.Exception("Send");
}
}
"Ramtin" is my raspberry pi host name.
How can I solve this?
Thanks.
Note: I tried to create android as Server and other phones as clients and it's works fine(sending/receiving message). but I don't want android as a server!

Get-MailboxPermission exception calling "GetSteppablePipeline"

I am getting an Exception while running the following PoweShell command:
Get-mailboxPermission -Identity MAILBOX_EMAIL |
fl User,AccessRights,IsInherited,Deny | Out-String -Width 300
Exception:
Exception calling "GetSteppablePipeline" with "1" argument(s): "Cannot find the type for custom attribute 'Parameter'.
Make sure that the assembly that contains this type is loaded."
Followed by this
Get-mailboxPermission -Identity "mailboxidentity" |
fl User,AccessRights,IsInherited,Deny | Out-String -Width 300
Which is getting me a ParameterBindingException
A parameter cannot be found that matches parameter name 'CommandName'.
This is the part of my code:
I will send the above command to executeRemoteCommand function for all the users one by one.
private void initializeRunspace() {
runSpace = RunspaceFactory.CreateRunspace();
runSpace.Open();
createRemotePowershell();
executeRemoteCommand("Set-ExecutionPolicy -ExecutionPolicy RemoteSigned",true);
executeRemoteCommand("Import-PSSession -Session $session -CommandName 'Get-MailboxPermission' ,'Get-MailboxDatabase','Add-ADPermission', 'Get-ADPermission', 'Set-EventLogLevel', 'Get-EventLogLevel'",true);
log("Remote powershell initialization ends");
}
public void createRemotePowershell() {
powershell = PowerShell.Create();
powershell.Runspace = runSpace;
PSCommand rmcommand = new PSCommand();
rmcommand.AddCommand("New-PSSession");
rmcommand.AddParameter("ConfigurationName", "Microsoft.Exchange");
rmcommand.AddParameter("ConnectionUri", uri);
if (creds != null) {
rmcommand.AddParameter("Credential", creds);
}
rmcommand.AddParameter("Authentication", "kerberos");
PSSessionOption sessionOption = new PSSessionOption();
sessionOption.SkipCACheck = true;
sessionOption.SkipCNCheck = true;
sessionOption.SkipRevocationCheck = true;
rmcommand.AddParameter("SessionOption", sessionOption);
powershell.Commands = rmcommand;
Collection<PSSession> result = powershell.Invoke<PSSession>();
log("Remote Powershell Count: "+result.Count);
if (result.Count != 1) {
throw new Exception("Unexpected number of Remote Runspace connections returned.");
}
rmcommand = new PSCommand();
rmcommand.AddCommand("Set-Variable");
rmcommand.AddParameter("Name", "session");
rmcommand.AddParameter("Value", result[0]);
powershell.Commands = rmcommand;
powershell.Invoke();
}
private String executeRemoteCommand(String shellcommand,bool retryOnSessionExpiry) {
try {
if (runSpace == null) {
initializeRunspace();
}
rmcommand = new PSCommand();
rmcommand.AddScript(shellcommand);
rmcommand.Commands.Add("Out-String");
powershell.Commands = rmcommand;
Collection<PSObject> results = powershell.Invoke();
StringBuilder sb = new StringBuilder();
foreach (PSObject obj in results) {
sb.Append(obj.ToString());
}
return sb.ToString();
} catch (CmdletInvocationException ex) {
log("RemotePowershell: CmdletInvocationException - " + shellcommand + " - " +ex.Message);
return "Invalid";
} catch (ParseException ex) {
log("RemotePowershell: ParseException - " + shellcommand + " - " +ex.Message);
return "Invalid";
} catch (ParameterBindingException ex) {
log("RemotePowershell: ParameterBindingException - " + shellcommand + " - " +ex.Message);
return "Invalid";
} catch (CommandNotFoundException ex) {
log("RemotePowershell: CommandNotFoundException - " + shellcommand + " - " +ex.Message);
return "Invalid";
} catch (PSArgumentException ex) {
log("RemotePowershell: PSArgumentException - " + shellcommand + " - " +ex.Message);
return "EMS";
} catch (Exception e) {
if(e.Message.Equals("Unexpected number of Remote Runspace connections returned.")) {
log("remoteShell cannot be established");
return "remoteShell Failed";
} else if(e.Message.Contains("PromptForCredential") && retryOnSessionExpiry) {
log("Session Expired reinitializing runspace");
try {
closeRunSpace();
initializeRunspace();
log("Session Expired runspace reinitialized");
executeRemoteCommand(shellcommand,false);
} catch(Exception ex) {
if(ex.Message.Equals("Unexpected number of Remote Runspace connections returned.")) {
log("Session Expired: remoteShell cannot be established - " + shellcommand + " - " +ex.Message);
closeRunSpace();
return "remoteShell Failed";
}
}
}
log("RemotePowershell: Exception - " + shellcommand + " - " +e.Message);
return "EMSError" + e;
}
}

Multi attach files from DB row

How I can't attach to splited string file name from DB row (I need for "mode = 2" and "case 2:").
In my log file error:
FILE TO ATTACH ERR : Could not find file
'C:\inetpub\wwwroot\PLATFORM_700_NTFSRV\PLATFORM_700_NTFSRV_LAB\Attachments\text.txt,text2.txt'.
Here my example code and my row in DB
Row in db:
|FILE_TO_ATTACH |
|text1.txt,text2.txt|
public DataTable GetAttachmentFiles(int mode , string fileIDList)
{
try
{
DataTable DTB = new DataTable();
if (mode == 1)
{
SqlCommand TheCommand = GetCommand("application_MessageAttachFiles", CommandType.StoredProcedure,
GetConnection("APP"));
TheCommand.Parameters.Add("FILEIDLIST", SqlDbType.VarChar, 8000);
TheCommand.Parameters["FILEIDLIST"].Value = fileIDList;
SqlDataAdapter SDA = new SqlDataAdapter();
SDA.SelectCommand = TheCommand;
SDA.Fill(DTB);
}
else if(mode == 2)
{
try
{
DTB.Columns.Add("FILENAME");
string[] fileList = fileIDList.Split(',');
for (int c = 0; c < fileList.Length; c++)
{
DataRow DR = DTB.NewRow();
DR["FILENAME"] = fileList[c];
DTB.Rows.Add(DR);
}
}
catch (Exception ex)
{
RecordLine("ERROR Reading GetAttachmentFiles: " + ex.Message);
}
}
return DTB;
}
catch (Exception eX)
{
RecordLine("ERROR GetAttachmentFiles : " + eX.Message);
return null;
}
}
public Attachment AttachmentFile(int mode, string fileNameString, int fileID, DataRow DRA)
{
// mode.ToString(ConfigurationSettings.AppSettings["MODE"]);
try
{
switch (mode)
{
case 1: /*from Database*/
if (DRA != null)
{
Attachment messageAttachment;
int fileDataSize = int.Parse(DRA["FileSize"].ToString());
string fileType = DRA["FileType"].ToString();
string fileName = DRA["FileName"].ToString();
byte[] fileBuffer = (DRA["FileData"]) as byte[];
MemoryStream ms = new MemoryStream(fileBuffer);
RecordLine("DEBUG 2 - " + fileName + " " + fileType + " " + fileDataSize.ToString() + " " + ms.Length.ToString() + " buffer size:" + fileBuffer.Length.ToString());
messageAttachment = new Attachment(ms, fileName, fileType);
return messageAttachment;
}
break;
case 2: /*from Local Machin */
{
Attachment messageAttachment;
try
{
fileNameString = String.Format("{0}\\{1}", ConfigurationSettings.AppSettings["SOURCE_FILE"],
fileNameString);
messageAttachment = new Attachment(fileNameString);
RecordLine("DEBUG 2.1 - " + messageAttachment.Name);
return messageAttachment;
}
catch (Exception ex)
{
RecordLine("FILE TO ATTACH ERR : " + ex.Message);
}
}
break;
default:
return null;
break;
}
return null;
}
catch (Exception eX)
{
RecordLine("ERROR AttachmentFile : " + eX.Message);
return null;
}
}
I had add this code and it is worked:
foreach (DataRow DRA in DTBA.Rows)
{
message.Attachments.Add(AttachmentFile(2, DRA["FILENAME"].ToString().Trim(), 0, null));
RecordLine("DEBUG 3.1 - " + message.Attachments.Count.ToString());
}

Unable to catch the exception from selenium in C#

I have written some code which deals with C# reflections and selenium to automate the build process of a URL.
But I am unable to catch the exception. What I did is , I exported into .html format from selenium IDE. and parsed and it automatically calls the function related to it from c# code.
but I am unable to catch it. I need help in this regard? Any guesses why it is unable to catch the exception..
I am using Visual Studio Microsoft Visual C# 2010 Express.
And the code is as follows.
using System;
using System.Text;
using System.Text.RegularExpressions;
using NUnit.Framework;
using Selenium;
using System.Reflection;
using System.IO;
namespace SeleniumTests
{
public class Program
{
public ISelenium selenium;
public void SetupTest()
{
selenium = new DefaultSelenium("localhost", 4444, "*chrome", "URL");
selenium.Start();
}
//[TearDown]
public void TeardownTest()
{
try
{
selenium.Stop();
}
catch (Exception)
{
}
}
public void myFun(string file)
{
bool flag = false;
string targetString = "", valueString = "", commandString = "";
string subString1, subString2;
HtmlAgilityPack.HtmlNode commandNode=null;
HtmlAgilityPack.HtmlNode targetNode=null;
HtmlAgilityPack.HtmlNode valueNode=null;
HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
doc.Load(file);
doc.OptionCheckSyntax = true;
doc.OptionFixNestedTags = true;
doc.OptionAutoCloseOnEnd = true;
doc.OptionOutputAsXml = true;
doc.OptionDefaultStreamEncoding = Encoding.Default;
HtmlAgilityPack.HtmlNode table = doc.DocumentNode.SelectSingleNode("//table");
foreach (var row in table.SelectNodes("//tr"))
{
commandNode = row.SelectSingleNode("td[1]");
commandString = commandNode.InnerHtml.ToString();
subString1 = commandString.Substring(0, 1);
subString1 = subString1.ToUpper();
subString2 = commandString.Substring(1, commandString.Length - 1);
commandString = subString1 + subString2;
targetNode = row.SelectSingleNode("td[2]");
if (targetNode != null)
{
targetString = targetNode.InnerHtml.ToString();
if (targetString.Length == 0)
{
targetNode = null;
}
}
valueNode = row.SelectSingleNode("td[3]");
if (valueNode != null)
{
valueString = valueNode.InnerHtml.ToString();
if (valueString.Length == 0)
{
valueNode = null;
}
}
MethodInfo SeleniumMethod = typeof(ISelenium).GetMethod(commandString);
if (SeleniumMethod == null)
{
// Console.WriteLine(" \n NULL " + commandString);
continue;
}
if (targetNode == null && valueNode == null)
continue;
if (targetNode != null && valueNode != null)
{
String[] SeleniumArgs = new String[2];
SeleniumArgs[0] = targetNode.InnerHtml.ToString();
SeleniumArgs[1] = valueNode.InnerHtml.ToString();
try
{
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
catch (System.Reflection.TargetInvocationException)
{
}
catch (Selenium.SeleniumException se)
{
flag = true;
string lines = "\n Selenium Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
}
catch (Exception e)
{
flag = true;
string lines = "\n Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
}
}
else if (targetNode != null && valueNode == null)
{
String[] SeleniumArgs = new String[1];
SeleniumArgs[0] = targetNode.InnerHtml.ToString();
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
else if (valueNode != null)
{
String[] SeleniumArgs = new String[1];
SeleniumArgs[0] = valueNode.InnerHtml.ToString();
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
}// end of for
string line = "\n Script executed successfully ";
if (flag == false)
{
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(line);
writer.Flush();
writer.Close();
}
}
}
}
public class TestProgram
{
static void Main(string[] args)
{
try
{
Program p = new Program();
p.SetupTest();
string file = #"1.html";
p.myFun(file);
p.TeardownTest();
}
catch { }
}
}
}
If you are trying to catch the exception in your Main() method, you need to bubble your exceptions up in your myFun method. At the moment you are drowning any exceptions in your myFun method.
e.g.
try
{
SeleniumMethod.Invoke(selenium, SeleniumArgs);
}
catch (System.Reflection.TargetInvocationException)
{
throw; //make this bubble up to the calling method.
}
catch (Selenium.SeleniumException se)
{
flag = true;
string lines = "\n Selenium Exception: Caught an exception while executing the script : " + file + " with the command : " + commandNode.InnerHtml.ToString() + " and the XPath is: " + targetNode.InnerHtml.ToString() + " and the value is : " + valueNode.InnerHtml.ToString() + " and the exception is as follows : ";
using (StreamWriter writer = new StreamWriter("Log.txt", true))
{
writer.WriteLine(lines);
writer.Flush();
writer.Close();
}
throw se; //bubble up to calling method
}
//etc...

Categories