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
Related
this is my first question in here.
So I have this app that connects to a remote database using Npgsql library.
I have a method that connects to the db, execute a query, and finally it closes the connection.
It work fine, but the problem is that if, while the program is running but not calling the method, I disconnect the WiFi to simulate the inability to connect to the server, and then run the method, the connection method still is able to open the connection. This causes the query to get stuck.
I can't seem to find a way to check if I can connect to server because, even if I disconnect the internet, the NpgsqlConnection.Open() method still opens it.
Sorry about my english
public static NpgsqlConnection ConnectRemote()
{
try
{
remoteConnection = new NpgsqlConnection("Server = " + remoteData.server + "; " +
"Port = " + remoteData.port + "; " +
"User Id = " + remoteData.user + "; " +
"Password = " + remoteData.password + "; " +
"Database = " + remoteData.dataBase + "; ");
remoteConnection.Open();
}
catch (NpgsqlException ex)
{
throw;
}
catch (Exception ex)
{
remoteConnection.Close();
remoteConnection = null;
}
return remoteConnection;
}
public static bool CheckRemote()
{
if (remoteConnection != null)
{
if (remoteConnection.FullState.Equals(ConnectionState.Open))
return true;
return false;
}
return false;
}
public bool AddNewProduct(Product product)
{
try
{
DBManager.ConnectLocal();
DBManager.ConnectRemote();
object[] parameters;
if (DBManager.CheckRemote())
{
if (!DBManager.isSyncronized)
{
DBManager.Syncronize();
}
parameters = new object[8];
parameters[0] = 1;
parameters[1] = product.id;
parameters[2] = product.description;
parameters[3] = (decimal)product.salePrice;
parameters[4] = (decimal)product.cost;
parameters[5] = product.minStock;
parameters[6] = product.providerName;
parameters[7] = product.category;
DBManager.RunFunction(DBManager.remoteConnection, DBProcedures.createProduct, parameters);
}
else
{
string sql = "select * from createproduct(1, " + product.id + ", '" + product.description + "', " + (decimal)product.salePrice + ", "
+ (decimal)product.cost + ", " + product.minStock + ", '" + product.providerName + "', '" + product.category + "'); ";
parameters = new object[1];
parameters[0] = sql;
DBManager.RunFunction(DBManager.localConnection, "addsync", parameters);
DBManager.isSyncronized = false;
}
parameters = new object[6];
parameters[0] = product.description;
parameters[1] = (decimal)product.salePrice;
parameters[2] = (decimal)product.cost;
parameters[3] = product.minStock;
parameters[4] = product.providerName;
parameters[5] = product.category;
DataTable result = DBManager.RunFunction(DBManager.localConnection, DBProcedures.createProduct, parameters);
DBManager.DisconnectLocal();
DBManager.DisconnectRemote();
return true;
}
catch (Npgsql.NpgsqlException ex)
{
return false;
}
}
A few things -- one unrelated, and two related. I am hopeful that some combination of these will help.
First, the unrelated comment. The NpgSqlStringBuilder class is a nice tool to help demystify the connection strings. I realize yours works, but as you have to make edits (as I will suggest in a minute), I find it much easier to use than navigating String.Format, just as Query Parameters are easier (on top of being more secure) than trying to string.Format your way through passing arguments to a query. Also, declare the ApplicationName in your connection string to help diagnose what exactly is happening on the server, like you will read in the next comment.
If you are using connection pooling, When a connection is closed, I don't think it's really closed -- not even on the database. If you open server admin, you will see what I mean -- it kind of dangles out there, waiting to be reused. Try setting pooled=false in your connection string to ensure that when you close a connection you really close it.
If this doesn't work, try a trivial query. The cost will be minimal in cases where you don't need it and will undoubtedly fix your use case when you do need it.
All three suggestions are reflected here:
public static NpgsqlConnection ConnectRemote()
{
NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
sb.ApplicationName = "Connection Tester";
sb.Host = remoteData.server;
sb.Port = remoteData.port;
sb.Username = remoteData.user;
sb.Password = remoteData.password;
sb.Database = remoteData.database;
sb.Pooling = false;
remoteConnection = new NpgsqlConnection(sb.ToString());
try
{
remoteConnection.Open();
NpgSqlCommand test = new NpgSqlCommand("select 1", remoteConnection);
test.ExecuteScalar();
}
catch (NpgsqlException ex)
{
throw;
}
catch (Exception ex)
{
remoteConnection.Close();
remoteConnection = null;
}
return remoteConnection;
}
I have taken some code from MSDN to read emails using IMAP Client. I have changed little bit code so i can only read unseen email.
I am writing all response in Richtextbox.
The problems is format of Body text of Email is unreadable while all other text is fine.
void ReadEmail()
{
try
{
// there should be no gap between the imap command and the \r\n
// ssl.read() -- while ssl.readbyte!= eof does not work because there is no eof from server
// cannot check for \r\n because in case of larger response from server ex:read email message
// there are lot of lines so \r \n appears at the end of each line
//ssl.timeout sets the underlying tcp connections timeout if the read or write
//time out exceeds then the undelying connection is closed
tcpc = new System.Net.Sockets.TcpClient("imap.gmail.com", 993);
ssl = new System.Net.Security.SslStream(tcpc.GetStream());
ssl.AuthenticateAsClient("imap.gmail.com");
receiveResponse("");
username = "charlie#gmail.com";
password = "********";
receiveResponse("$ LOGIN " + username + " " + password + " \r\n");
receiveResponse("$ LIST " + "\"\"" + " \"*\"" + "\r\n");
receiveResponse("$ SELECT INBOX\r\n");
receiveResponse("$ UID SEARCH UNSEEN\r\n");
MatchCollection collection= Regex.Matches(Result,#" (\d{1,4})");
foreach (Match m in collection)
{
UNREAD_UID.Add(int.Parse(m.Groups[1].Value));
}
foreach (int x in UNREAD_UID)
{
receiveResponse("$ FETCH " +x + " body[header]\r\n");
richTextBox1.Text += Environment.NewLine+"-----------------------------------------------------------------------------------------------------------------------"+Environment.NewLine;
receiveResponse("$ FETCH " +x + " body[text]\r\n");
richTextBox1.Text += Environment.NewLine + "###########################################################2" + Environment.NewLine;
richTextBox1.Update();
}
//receiveResponse("$ STATUS INBOX (MESSAGES)\r\n");
// int number = 1;
receiveResponse("$ LOGOUT\r\n");
}
catch (Exception ex)
{
Console.WriteLine("error: " + ex.Message);
}
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
}
if (ssl != null)
{
ssl.Close();
ssl.Dispose();
}
if (tcpc != null)
{
tcpc.Close();
}
}
}
void receiveResponse(string command)
{
try
{
if (command != "")
{
if (tcpc.Connected)
{
dummy = Encoding.ASCII.GetBytes(command);
ssl.Write(dummy, 0, dummy.Length);
}
else
{
throw new ApplicationException("TCP CONNECTION DISCONNECTED");
}
}
ssl.Flush();
buffer = new byte[5120];
bytes = ssl.Read(buffer, 0, 5120);
sb.Append(Encoding.ASCII.GetString(buffer));
Result = sb.ToString();
richTextBox1.Text += Environment.NewLine + Environment.NewLine + Environment.NewLine + Environment.NewLine + sb.ToString();
sb = new StringBuilder();
}
catch (Exception ex)
{
throw new ApplicationException(ex.Message);
}
}
Here is Sample of what i am getting
108 FETCH (BODY[TEXT] {25656}
DQoNCg0KDQo8IURPQ1RZUEUgaHRtbD4NCjxodG1sPg0KPGhlYWQ+DQo8dGl0bGU+TWlj
cm9zb2Z0IHR1cm5zIChhbG1vc3QpIGFueSBjYW1lcmEgaW50byBhIEtpbmVjdDwvdGl0
bGU+DQo8bWV0YSBodHRwLWVxdWl2PSJDb250ZW50LVR5cGUiIGNvbnRlbnQ9InRleHQv
aHRtbDsgY2hhcnNldD1VVEYtOCI+DQo8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVu
dD0id2lkdGg9ZGV2aWNlLXdpZHRoIj4NCjwhLS0gRWZmaW5nIFdpbmRvd3MgOCBNYWls
IGNsaWVudC4gQWRkIC13ZWJraXQtbWluLWRldmljZS1waXhlbC1yYXRpbzogMSB0byBz
Y2FyZSBpdCBhd2F5IGZyb20gdGhpcyBiaXQuIC0tPg0KPHN0eWxlIHR5cGU9InRleHQv
Y3NzIj4NCkBtZWRpYSBzY3JlZW4gYW5kIChtYXgtZGV2aWNlLXdpZHRoOiA1MDBweCkg
YW5kICgtd2Via2l0LW1pbi1kZXZpY2UtcGl4ZWwtcmF0aW86IDEpIHsNCgkuYm9keS1j
b250YWluZXIgeyB3aWR0aDoxMDAlICFpbXBvcnRhbnQ7IH0NCgkuYmFubmVyICAgICAg
ICAgeyBkaXNwbGF5OiBub25lICFpbXBvcnRhbnQ7IH0NCgkubW9iaWxlLWJhbm5lciAg
eyBkaXNwbGF5OiBibG9jayAhaW1wb3J0YW50OyB3aWR0aDozNDBweCAhaW1wb3J0YW50
OyBiYWNrZ3JvdW5kOiB1cmwoaHR0cDovL3d3dy5jb2RlcHJvamVjdC5jb20vc2NyaXB0
L21haWxvdXRzL3RlbXBsYXRlcy9uZXdzbGV0dGVyLWluc2lkZXIucG5nKSBuby1yZXBl
YXQgdG9wIGxlZ
Kindly help me.
You need to examine the Content-Transfer-Encoding header to undo Transfer encoding (in this case, that's Base64. Other alternatives are 7-bit or Quoted Printable). Or, better, download the entire message (Body[]) and apply a MIME parser/decoder to it to get an object representation of the headers, body, and attachments.
Max's answer above is correct, but I'm going to illustrate how to implement his suggestion using my MailKit library:
using (var client = new ImapClient ()) {
client.Connect ("imap.gmail.com", 993, true);
// since we're not using an OAuth2 token, remove it from the set
// of possible authentication mechanisms to try:
client.AuthenticationMechanisms.Remove ("XOAUTH2");
client.Authenticate ("charlie#gmail.com", "*****");
// SELECT the INBOX folder
client.Inbox.Open (FolderAccess.ReadWrite);
foreach (var uid in client.Inbox.Search (SearchQuery.NotSeen)) {
var message = client.Inbox.GetMessage (uid);
// at this point, 'message' is a MIME DOM that you can walk
// over to get the particular MIME-part that you want. For
// example, we could get a body part with a filename of
// "test.txt" using LINQ like this:
var attachment = message.BodyParts.OfType<MimePart> ()
.FirstOrDefault (x => x.FileName == "test.txt");
// decode the content to a MemoryStream:
using (var memory = new MemoryStream ()) {
attachment.ContentObject.DecodeTo (memory);
}
// since the attachment is probably a TextPart
// (based on the file extension above), we can actually
// use a simpler approach:
var textPart = attachment as TextPart;
if (textPart != null) {
// decode the content and convert into a 'string'
var text = textPart.Text;
}
}
client.Disconnect (true);
}
I am connecting to an IBM Websphere MQ server in my .Net code and I wanted to make sure that I am following best practice when using "finally".
I currently have the below code block which I believe can be modified to just have the close portion in the finally clause. Is that correct? (I am catching errors in the calling portion of the application).
Hashtable properties = new Hashtable();
properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
properties.Add(MQC.CHANNEL_PROPERTY, channel);
properties.Add(MQC.HOST_NAME_PROPERTY, host);
properties.Add(MQC.PORT_PROPERTY, port);
MQQueueManager qmgr = new MQQueueManager(queueManager, properties);
try
{
var queueDepth = qmgr.AccessQueue(userQueue,
MQC.MQOO_INPUT_AS_Q_DEF +
MQC.MQOO_FAIL_IF_QUIESCING +
MQC.MQOO_INQUIRE).CurrentDepth;
if (qmgr.IsOpen)
qmgr.Close();
return queueDepth;
}
finally
{
if (qmgr.IsOpen)
qmgr.Close();
}
Is now this
Hashtable properties = new Hashtable();
properties.Add(MQC.TRANSPORT_PROPERTY, MQC.TRANSPORT_MQSERIES_CLIENT);
properties.Add(MQC.CHANNEL_PROPERTY, channel);
properties.Add(MQC.HOST_NAME_PROPERTY, host);
properties.Add(MQC.PORT_PROPERTY, port);
MQQueueManager qmgr = new MQQueueManager(queueManager, properties);
try
{
var queueDepth = qmgr.AccessQueue(userQueue,
MQC.MQOO_INPUT_AS_Q_DEF +
MQC.MQOO_FAIL_IF_QUIESCING +
MQC.MQOO_INQUIRE).CurrentDepth;
return queueDepth;
}
finally
{
if (qmgr.IsOpen)
qmgr.Close();
}
EDIT: Renan made a good suggestion. I didn't think the MQQueueManger was disposable. Sounds like I could potentially do this:
using(MQQueueManager qmgr = new MQQueueManager(queueManager, properties))
{
var queueDepth = qmgr.AccessQueue(userQueue,
MQC.MQOO_INPUT_AS_Q_DEF +
MQC.MQOO_FAIL_IF_QUIESCING +
MQC.MQOO_INQUIRE).CurrentDepth;
return queueDepth;
}
Edit: I did some research after reading Renan's suggestion and found the below. Sounds like they did in fact make it disposable.
MQ.Net
You are right. The finally clause will execute even if the code in the try block returns an exception.
You could also use the "using" construct for the connection (if it implements IDisposable, which it should).
using(qmgr){
//do stuff
}
That is fine.
A finally block is guaranteed by the CLR to be called (except in some very very rare edge cases, which IIRC are internal CLR errors, such as a call to FailFast or an ExecutingEngineException). By removing it from the try, you are removing redundant code.
First of all, there is no valid reason that an application needs to know the depth of a queue. Applications should process ALL messages in the queue until it is empty.
Secondly, do NOT use IsOpen methods as they do not work as you might expect. The IsOpen method does not actually check if the queue handle is open - it only checks an internal flag. Hence, do not use it.
Third, you do NOT close a queue manager object but rather you disconnect from a queue manager.
Fourth, when connecting to a queue manager, that statement needs to be in a try/catch because it will throw an MQException if the connection fails.
Here is a better layout of the code which will catch and handle errors:
MQQueueManager qMgr = null;
MQQueue queue = null;
int openOptions = MQC.MQOO_INPUT_AS_Q_DEF + MQC.MQOO_FAIL_IF_QUIESCING + MQC.MQOO_INQUIRE;
try
{
qMgr = new MQQueueManager(qMgrName);
System.Console.Out.WriteLine("Successfully connected to " + qMgrName);
queue = qMgr.AccessQueue(qName, openOptions, null, null, null);
System.Console.Out.WriteLine("Successfully opened " + qName);
System.Console.Out.WriteLine("Current queue depth is " + queue.CurrentDepth);
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("Exception CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
catch (System.IO.IOException ioex)
{
System.Console.Out.WriteLine("Exception ioex=" + ioex);
}
finally
{
try
{
if (queue !=null)
{
queue.Close();
System.Console.Out.WriteLine("Successfully closed " + qName);
}
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("Exception on close CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
try
{
if (qMgr !=null)
{
qMgr.Disconnect();
System.Console.Out.WriteLine("Disconnected from " + qMgrName);
}
}
catch (MQException mqex)
{
System.Console.Out.WriteLine("Exception on disconnect CC=" + mqex.CompletionCode + " : RC=" + mqex.ReasonCode);
}
}
I have code below in global asax now, I want to store exception log in database, is this good practice? because if sql error happens there, I want to log it too. So I am thinking changing the code below to write text log instead email, then on sql error, write text log.
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
string testEnvironment = ConfigurationSettings.AppSettings["isTestEnvironment"];
if (testEnvironment == "0")
{
Exception ex = Server.GetLastError();
if (ex is HttpException && ex.InnerException is ViewStateException)
{
Response.Redirect(Request.Url.AbsoluteUri)
return
}
StringBuilder theBody = new StringBuilder();
theBody.Append("URL: " + Request.Url + "\n");
theBody.Append("Referer: " + Request.ServerVariables["HTTP_REFERER"] + "\n");
theBody.Append("IP: " + Request.ServerVariables["REMOTE_HOST"] + "\n");
theBody.Append("Error Message: " + ex.ToString() + "\n");
if (User.Identity.IsAuthenticated)
theBody.Append("User: " + User.Identity.Name + "\n");
else
theBody.Append("User is not logged in." + "\n");
theBody.Append("Form Values: " + "\n");
foreach (string s in Request.Form.AllKeys)
{
if (s != "__VIEWSTATE")
theBody.Append(s + ":" + Request.Form[s] + "\n");
}
theBody.Append("Session Values: " + "\n");
foreach (string s in Session.Keys)
theBody.Append(s + ":" + Session[s] + "\n");
System.Net.Mail.MailMessage email = new System.Net.Mail.MailMessage();
email.IsBodyHtml = false;
email.From = new System.Net.Mail.MailAddress("errors#karpach.com", "ErrorManager");
email.To.Add(new System.Net.Mail.MailAddress("errornotification#karpach.com", "Developer"));
email.Subject = Request.Url.ToString().Split('/')[2] + " has ASP.NET error";
email.Body = theBody.ToString();
try
{
System.Net.Mail.SmtpClient emailProvider = new System.Net.Mail.SmtpClient();
emailProvider.Send(email);
}
catch (Exception anException)
{
}
finally
{
if (Request.Url.Segments[Request.Url.Segments.Length - 1].ToLower() != "error.aspx")
Response.Redirect("~/error.aspx?msg=4");
else
{
Response.Write(#"We encountered an internal error. We apologize for any inconvenience
but know that our staff gets emailed EVERY error that occurs so that we can solve it promptly.");
Response.End();
}
}
}
}
You could log it to the EventLog. System admins can setup monitoring to see when new events are added and be alerted to potential problems.
Here's an example from MSDN for the EventLog class:
if(!EventLog.SourceExists("MySource"))
{
//An event log source should not be created and immediately used.
//There is a latency time to enable the source, it should be created
//prior to executing the application that uses the source.
//Execute this sample a second time to use the new source.
EventLog.CreateEventSource("MySource", "MyNewLog");
Console.WriteLine("CreatedEventSource");
Console.WriteLine("Exiting, execute the application a second time to use the source.");
// The source is created. Exit the application to allow it to be registered.
return;
}
// Create an EventLog instance and assign its source.
EventLog myLog = new EventLog();
myLog.Source = "MySource";
// Write an informational entry to the event log.
myLog.WriteEntry("Writing to event log.");
I trying to capture packets using SharpPcap library.
I'm able to return the packets details but I'm having problem to get what the message content inside the packet.
the packet using .Data to return the message and when I use it it is returning (System.Byte[]).
here is the library website:
http://www.codeproject.com/KB/IP/sharppcap.aspx
here is my code:
string packetData;
private void packetCapturingThreadMethod()
{
Packet packet = null;
int countOfPacketCaptures = 0;
while ((packet = device.GetNextPacket()) != null)
{
packet = device.GetNextPacket();
if (packet is TCPPacket)
{
TCPPacket tcp = (TCPPacket)packet;
myPacket tempPacket = new myPacket();
tempPacket.packetType = "TCP";
tempPacket.sourceAddress = Convert.ToString(tcp.SourceAddress);
tempPacket.destinationAddress = Convert.ToString(tcp.DestinationAddress);
tempPacket.sourcePort = Convert.ToString(tcp.SourcePort);
tempPacket.destinationPort = Convert.ToString(tcp.DestinationPort);
tempPacket.packetMessage = Convert.ToString(tcp.Data);
packetsList.Add(tempPacket);
packetData =
"Type= TCP" +
" Source Address = "+ Convert.ToString(tcp.SourceAddress)+
" Destination Address =" +Convert.ToString(tcp.DestinationAddress)+
" SourcePort =" + Convert.ToString(tcp.SourcePort)+
" SourcePort =" +Convert.ToString(tcp.DestinationPort)+
" Messeage =" + Convert.ToString(tcp.Data);
txtpackets.Invoke(new UpdatetxtpacketsCallback(this.Updatetxtpackets),
new object[] { packetData });
string[] row = { packetsList[countOfPacketCaptures].packetType, packetsList[countOfPacketCaptures].sourceAddress, packetsList[countOfPacketCaptures].destinationAddress, packetsList[countOfPacketCaptures].sourcePort, packetsList[countOfPacketCaptures].destinationPort, packetsList[countOfPacketCaptures].packetMessage };
try { //dgwPacketInfo.Rows.Add(row); countOfPacketCaptures++;
//lblCapturesLabels.Text = Convert.ToString(countOfPacketCaptures);
}
catch (Exception e) { }
}
else if (packet is UDPPacket)
{
UDPPacket udp = (UDPPacket)packet;
myPacket tempPacket = new myPacket();
tempPacket.packetType = "UDP";
tempPacket.sourceAddress = Convert.ToString(udp.SourceAddress);
tempPacket.destinationAddress = Convert.ToString(udp.DestinationAddress);
tempPacket.sourcePort = Convert.ToString(udp.SourcePort);
tempPacket.destinationPort = Convert.ToString(udp.DestinationPort);
tempPacket.packetMessage = udp.Data.ToArray() + "\n";
packetsList.Add(tempPacket);
packetData =
"Type= UDP" +
" Source Address = "+ Convert.ToString(udp.SourceAddress)+
" Destination Address =" +Convert.ToString(udp.DestinationAddress)+
" SourcePort =" + Convert.ToString(udp.SourcePort)+
" SourcePort =" +Convert.ToString(udp.DestinationPort)+
" Messeage =" + udp.Data.ToArray() + "\n";
string[] row = { packetsList[countOfPacketCaptures].packetType, packetsList[countOfPacketCaptures].sourceAddress, packetsList[countOfPacketCaptures].destinationAddress, packetsList[countOfPacketCaptures].sourcePort, packetsList[countOfPacketCaptures].destinationPort, packetsList[countOfPacketCaptures].packetMessage };
try {
//dgwPacketInfo.Rows.Add(row);
//countOfPacketCaptures++;
//lblCapturesLabels.Text = Convert.ToString(countOfPacketCaptures);
txtpackets.Invoke(new UpdatetxtpacketsCallback(this.Updatetxtpackets),
new object[] { packetData });
}
catch (Exception e) { }
}
}
}
I found the answer...
Data is a byte array so I need to use bit converter and instead of using:
Convert.ToString(tcp.Data);
I should use:
BitConverter.ToString(tcp.Data)
The parser isn't that complex...
I looked at the Packet.Net code (which is the parse for SharpPcap) and all of the fields are stored in commonly used formats.
The IP Addresses are stored in System.Net.IPAddress format so you can just call .ToString on them to get a text string that properly includes the dot marks.
The port numbers are stored as ushort which can be printed the same as any other integer.
The only part that needs to be interpreted in its binary form is the Data field because that changes based on what protocol is being used on the next layer up. SharpPcap/Packet.Net does most of the work for you already and fields are stored in the most convenient or identical forms to those found in the protocol specification. Just use intellisense to check the field's type and if it's not one you're familiar with (such as System.Net.IPAddress or System.NetworkInformation.PhysicalAddress (For MAC addresses)) just google it.