|
When i call the AsinSearch Amazon web service, i get the following error
"An unhandled exception of type 'System.NullReferenceException' occurred in SellerSearch.exe
Additional information: Object reference not set to an instance of an object."
I've narrowed it down to the following piece of code:
ProdInfo = Doc.ChildNodes[1]
["ProductInfo"]
["ThirdPartyProductInfo"];
dsInventory.Tables["tblSellerData"].Rows.Clear();
for (Counter = 0; Counter < ProdInfo.ChildNodes.Count; Counter ++)
{
Details = ProdInfo.ChildNodes[Counter];
DR = dsInventory.Tables["tblSellerData"].NewRow();
DR["Asin"] = Details["BrowseName"].InnerText;
//DR["Asin"] = Details["Asin"].InnerText;
//DR["Price"] = Details["ExchangePrice"].InnerText;
//DR["ListingID"] = Details["ExchangeId"];
//DR["ProductName"] = Details["
dsInventory.Tables["tblSellerData"].Rows.Add(DR);
}
}
ProdInfo is an xmlNode.
The XML is coming through just fine. You can see it by putting the following uri in a browser:
http://xml.amazon.com/onca/xml2?t=webservices-20&dev-t=099CQN95JW6909V9T8R2&AsinSearch=B00005JKDR&type=heavy&offer=Used&offerpage=1&f=xml
I'm stuck and can't figure out what the problem is.
any ideas?
Thomas Barker
|
|
|
|
|
Hi Thomas,
Without looking at it too closely, can you not narrow down where the exception occurs by stepping through the code in the debugger. Presumably the error arises from either parsing the xml document or populating the table row.
Regards,
Rob Philpott.
|
|
|
|
|
when the code breaks, it highlights exactly the following line:
ProdInfo = Doc.ChildNodes[1]
["ProductInfo"]
["ThirdPartyProductInfo"];
the problem is that i'm not sure how to fix the problem because it compiles fine. Perhaps it is my incomplete knowledge of how to manipulate xml or even the amazon wsdl correctly. (I started learning C# on monday)
As far as i can tell i've got the xml field names correct and the datagrid field names correct. I also think my nodes are named right. I'm just not experienced enough to figure this one out.
thanks for your help!
Thomas Barker
|
|
|
|
|
Hi Thomas,
It's getting close to my bedtime (beauty sleep and that) but I'll have a look at this in the morning and get back to you. I take it you are loading the whole content into an XmlDocument?
Regards,
Rob Philpott.
|
|
|
|
|
yes. you can see the xml document by just plugging the url i mentioned in the original post into a browser.
thanks for your help.
Thomas Barker
|
|
|
|
|
Hi Thomas,
I meant were you loading the xml content into an object of class System.Xml.XmlDocument? My guess is that you are. (an alternate is to use a class hierarchy built automatically from the wsdl/schema). How are you making the Http request?
I think the problem possibly lies in the way you are navigating the document. This line:
ProdInfo = Doc.ChildNodes[1]["ProductInfo"]["ThirdPartyProductInfo"];
is going to fail because ThirdPartyProductInfo is not a child node of ProductInfo (just looking at the xml in the browser) - it is a child node of Details which is a child node of ProductInfo.
I'd argue that this isn't a good way to go about navigating around an xml document. By chaining indexers together like this, if you get the path wrong in one of them is going to return null, and when you call the next indexer on a null reference you're going to get a NullReferenceException - what I believe is happening presently. It's not clear what part failed.
Instead, you could use XmlDocument.SelectSingleNode passing it an XPath expression for the node you are seeking.
Hope that helps!
Regards,
Rob Philpott.
|
|
|
|
|
I noticed a problem with this program I made. It basically just opens database files using the OleDbDataAdapter, and for some odd reason, it cannot open database files that are outside of its own directory. For example, if the project is in D:\project, and the database file is in D:\project\database.csv. It will work, but on the other hand if the database file is in C:\database.csv, it will not open it. I was wondering if anyone could help me with this.
Here is my code:
<br />
oleDbConnection1.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + @";Extended Properties=""text;HDR=Yes;FMT=Delimited""";<br />
oleDbConnection1.Open();<br />
<br />
|
|
|
|
|
The way to make this work is as follows
string dir = @"C:\database.csv"
or
string dir = @"\\myremotepc\sharefolder\database.csv"
oleDbConnection1.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir";Extended Properties=""text;HDR=Yes;FMT=Delimited""";
|
|
|
|
|
Thanks for your reply, it turned out it was whitespace. I had whitespace in my connection string. That is why it was crashing.
Sincerely,
The Major Rager
|
|
|
|
|
I have a Sockets based client using the Async model under C# .NET (i.e. BeginReceive, EndReceive, etc w/ non-blocking socket). I have noticed that under intensive I/O scenarios that the TCP logic (in CLR?) seems to overflowing my buffer. This happens only when I build for release, as you could image when building for debug the extra stack, heap, and instrutions executed tend to mask the problem.
I was wondering if anyone has developed a I/O intensive packet handling hunk of code and what pitfalls, and/or recommendations do you have? Open to suggestions...
Mike
|
|
|
|
|
|
That does not surprise me, when I was using TcpClient I was not please with the level of control I wanted without restoring to lots of translation to the underlying Sockets interface. So... I switched to System.Net.Sockets interface and use the Berkely/Winsock approach. All goes well until heavy load when for some strange reason the BeginReceive() function chokes with a corrupted arg list.
Note, my app uses a 2 stage read. Stage 1 is read the fixed length Message Header which contains the Type and Length of the payload. Stage 2 is read the variable length payload.
I am wondering if I need to do any special initialization to accomodate a data stream that is flinging messages in size from (12 bytes to roughly 6K) at a real time rate proportional to the the number of calls handled per second across a call center with roughly 500 agents, i.e. the firehose I alluded to earlier. Typically we are talking 1.5 to 3 calls per second, plus all sorts of other events such as Agent State changes, Monitors, etc.
Mike
|
|
|
|
|
I need to read certain data from an external source for the duration of an application's run time. In order to do that, I set up a thread that starts as soon as the first form on the application loads and that will continue to run until that form is null.
Now, for most of the application run time, the values that I'm reading from the external source should be static (or nearly so), but the operator of the software will initiate a process (a test) during which the values I need to read will change. Ideally, I would still get those values from the external source from the separate thread, but I encountered some serious reduction in program efficiency when I did that.
The test itself runs on its own thread so that the operator can switch between different forms on the application while the test is running. When the test thread and the other thread that runs for the duration of the application were both competing to read from/write to the external source, I had the slowdown mentioned previously.
I solved the reduction in efficiency problem by having the test thread suspend the execution of the other thread until it finished its work, but encountered some problems after doing that which aren't obviously related to the thread suspension, but may be the culprit behind the problems I'm encountering. Is there a problem with one thread (not the main thread) suspending and then resuming the execution of a different thread (that is also not the main thread)?
|
|
|
|
|
You can certainly use multiple threads but using the Suspend and Resume requires more management and overhead than keeping your threads event driven. Personally I prefer using mutexes and semaphores which under C# translate to AutoResetEvent/ManualResetEvent and Synhronized.Queue. The basic idea is to keep you recv thread doing one thing very well: reading packets. But how do you process those packets and keep performance decent. You have a couple options. For one you could use a Synchronized Queue where the Receiver reads and enqueues raw messages and the signal readiness via the Auto/ManualResetEvent.Set() function. This causes a worker thread to wake up from a Auto/ManualResetEvent.WaitOne().
Now depending on your architecture you can even pool threads to do concurrent processing of the messages and their payloads. I'd be careful about the total amout of worker threads as there is a point of diminish returns plus CPU overhead. But the basic idea is to pre-allocate a pool of threads that would wakeup and process a message. There is a good article and code example you can find under TCP Servers QIO.
Now the other thing to consider is using the Async architecture instead of a multi-threaded architecture. Many people subscribe to this model for I/O intensive apps such as Web servers. From a code standpoint, you may be able to reduce the complexity of the app by moving to a Async Model. Again there are numerous examples under the TCP Server topic.
Ultimately you need to choose the model that fits your requirements and the intended hardware. Too much threading and you can hog a CPU pretty quick. Besides when you use C# sockets they are multi-threaded under the hood and designed for optimum efficiency. At the end of the day I generally prefer Async but use QIO for specialized situations such as discovery processing, DB interfaces, etc.
Mike
|
|
|
|
|
Hi All
I need some help urgently with the Server Client Chat Program i wrote. The interface isn't up to scratch, i just use it to test my classes. I have two classes one named server and the other named client.
They communicate fine with each other, but for some reason, the information i am receiving from the NetworkStream is current, it seems like old data.
Some one please help...
Please test with multiple clients connected to the server.
Here are the classes:
*******************************
SERVER.cs
*******************************
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Messenger;
namespace Messenger
{
/// <summary>
/// Represents the method that handles the Connected event.
/// </summary>
public delegate void ConnectedEventHandler(Client sender, EventArgs e);
/// <summary>
/// Represents the method that handles the Disconnected event.
/// </summary>
public delegate void DisconnectedEventHandler(Client sender, string message);
/// <summary>
/// Represents the method that handles the MessageReceived event.
/// </summary>
public delegate void MessageReceivedEventHandler(Client sender, string message);
/// <summary>
/// Represents the method that handles the MessageSent event.
/// </summary>
public delegate void MessageSentEventHandler(Client sender, string message);
/// <summary>
/// The Client class connects to a server, to send and receive messages.
/// </summary>
public class Client
{
/// <summary>
/// The object that connects to the TCP network client.
/// </summary>
private TcpClient client;
/// <summary>
/// The Name of the machine that the client runs on.
/// </summary>
private string _hostName;
/// <summary>
/// The IP Address of the machine that the client runs on.
/// </summary>
private IPAddress _iPAddress;
/// <summary>
/// The Port that the client listens on.
/// </summary>
private int _port;
/// <summary>
/// The IP and Port of the remote server.
/// </summary>
private EndPoint _remoteEndPoint;
/// <summary>
/// A value indicating if the client is connected or not.
/// </summary>
private bool _isConnected = false;
/// <summary>
/// Temporarily stores messages that are sent to/received from the server in byte format.
/// </summary>
private byte[] messageBytes;
/// <summary>
/// The char used for splitting messages.
/// </summary>
private readonly char splitter;
/// <summary>
/// The event triggered when a client is connected to the server.
/// </summary>
public event ConnectedEventHandler Connected;
/// <summary>
/// The event triggered when a client disconnects from the server.
/// </summary>
public event DisconnectedEventHandler Disconnected;
/// <summary>
/// The event triggered when a client receives a message.
/// </summary>
public event MessageReceivedEventHandler MessageReceived;
/// <summary>
/// The event triggered when a client sends a message.
/// </summary>
public event MessageSentEventHandler MessageSent;
/// <summary>
/// Creates a new Client instance.
/// </summary>
/// <param name="hostName">Name of the machine that the client runs on.</param>
/// <param name="port">Port that the client listens on.</param>
public Client(TcpClient client, string hostName, int port)
{
// Assign private members to contructor values
this.client = client;
this._hostName = hostName;
this._iPAddress = Dns.GetHostByName(_hostName).AddressList[0];
this._port = port;
this._remoteEndPoint = new IPEndPoint(_iPAddress, _port);
// Set isconnected
_isConnected = true;
// Raise Connected event
if(Connected != null) Connected(this, null);
// Set the message splitter char
splitter = Convert.ToChar(19);
// Set message byte array to receive buffer size
messageBytes = new byte[client.ReceiveBufferSize];
// Read the clients network stream for incoming messages
client.GetStream().BeginRead(messageBytes, 0, client.ReceiveBufferSize, new AsyncCallback(ReceiveMessage), null);
}
/// <summary>
/// Creates a new Client instance.
/// </summary>
/// <param name="hostName">Name of the machine that the client runs on.</param>
/// <param name="port">Port that the client listens on.</param>
public Client(string hostName, int port)
{
// Assign private members to contructor values
this._hostName = hostName;
this._iPAddress = Dns.GetHostByName(_hostName).AddressList[0];
this._port = port;
this._remoteEndPoint = new IPEndPoint(_iPAddress, _port);
// Set the message splitter char
splitter = Convert.ToChar(19);
}
/// <summary>
/// Creates a new Client instance.
/// </summary>
/// <param name="iPAddress">IP Address of the machine that the client runs on.</param>
/// <param name="port">Port that the client listens on.</param>
public Client(IPAddress iPAddress, int port)
{
// Assign private members to contructor values
this._iPAddress = iPAddress;
this._hostName = Dns.GetHostByAddress(_iPAddress).HostName;
this._port = port;
this._remoteEndPoint = new IPEndPoint(_iPAddress, _port);
// Set the message splitter char
splitter = Convert.ToChar(19);
}
/// <summary>
/// Gets or sets the Name of the machine that the client runs on.
/// </summary>
public string HostName
{
get
{
return _hostName;
}
set
{
// Don't allow _hostName to be changed if the client is running
if(_isConnected)
throw new Exception("Can not change the HostName of the client while it is running.");
// If the client is not running
else
{
_hostName = value;
// Refresh the IP based on the _hostName
_iPAddress = Dns.GetHostByName(_hostName).AddressList[0];
// Set the _remoteEndPoint
_remoteEndPoint = new IPEndPoint(_iPAddress, _port);
}
}
}
/// <summary>
/// Gets or sets the IP Address of the machine that the client runs on.
/// </summary>
public IPAddress IP
{
get
{
return _iPAddress;
}
set
{
// Don't allow _iPAddress to be changed if the client is running
if(_isConnected)
throw new Exception("Can not change the IP of the client while it is running.");
// If the client is not running
else
{
_iPAddress = value;
// Refresh the HostName based on the _iPAddress
_hostName = Dns.GetHostByAddress(_iPAddress).HostName;
// Set the _remoteEndPoint
_remoteEndPoint = new IPEndPoint(_iPAddress, _port);
}
}
}
/// <summary>
/// Gets or sets the Port that the client listens on.
/// </summary>
public int Port
{
get
{
return _port;
}
set
{
// Don't allow the _port to be changed if the client is running
if(_isConnected)
throw new Exception("Can not change the Port of the client while it is running.");
else
{
_port = value;
// Set the _remoteEndPoint
_remoteEndPoint = new IPEndPoint(_iPAddress, _port);
}
}
}
/// <summary>
/// Gets the Server End Point.
/// </summary>
public EndPoint RemoteEndPoint
{
get
{
return _remoteEndPoint;
}
}
/// <summary>
/// Gets a value indicating if the client is running or not.
/// </summary>
public bool IsConnected
{
get
{
return _isConnected;
}
}
/// <summary>
/// Connects the client to the server.
/// </summary>
public void Connect()
{
// Do not allow connection if already connected
if(_isConnected)
throw new Exception("Can not connect again. Client is already connected.");
// If not connected
else
{
// Creates a new TCP client instance
client = new TcpClient();
// Connect to the server
client.Connect(_hostName, _port);
// Raise Connected event
if(Connected != null) Connected(this, null);
// Set isconnected
_isConnected = true;
// Set message byte array to receive buffer size
messageBytes = new byte[client.ReceiveBufferSize];
// Read the clients network stream for incoming messages
client.GetStream().BeginRead(messageBytes, 0, client.ReceiveBufferSize, new AsyncCallback(ReceiveMessage), null);
}
}
/// <summary>
/// Disconnects the client from the server.
/// </summary>
public void Disconnect()
{
// Do not allow connection if already connected
if(_isConnected)
throw new Exception("Invalid Operation. Can not disconnect from the server when not connected.");
// If not connected
else
{
// Disconnect from the server
client.GetStream().Close();
client.Close();
// Raise Connected event
if(Disconnected != null) Disconnected(this, "User disconnected.");
// Set isconnected
_isConnected = false;
}
}
/// <summary>
/// Sends a message to the server.
/// </summary>
/// <param name="message">The message to send to the server.</param>
public void SendMessage(string message)
{
// Gets the stream to send data on
NetworkStream networkStream = client.GetStream();
// Convert message to byte array
messageBytes = Encoding.ASCII.GetBytes(message);
// Write the message bytes to the stream
networkStream.Write(messageBytes, 0, messageBytes.Length);
// Flush the data
networkStream.Flush();
// Raise MessageSent event
if(MessageSent != null) MessageSent(this, message);
}
/// <summary>
/// Processes incoming messages from the server.
/// </summary>
private void ReceiveMessage(IAsyncResult iAsyncResult)
{
try
{
// Get the length of the received data
int messageBytesLength = client.GetStream().EndRead(iAsyncResult);
// If no data
if(messageBytesLength < 1)
{
// Raise Disconnected event
if(Disconnected != null) Disconnected(this, "Server disconnected.");
// Set _isConnected
_isConnected = false;
return;
}
// Get the message string
string message = Encoding.ASCII.GetString(messageBytes, 0, messageBytesLength);
// Raise MessageReceived event
if(MessageReceived != null) MessageReceived(this, message);
// Set message byte array size
messageBytes = new byte[client.ReceiveBufferSize];
// Continue reading for more messages
client.GetStream().BeginRead(messageBytes, 0, client.ReceiveBufferSize, new AsyncCallback(ReceiveMessage), null);
}
catch(Exception error)
{
// Raise Disconnected event
if(Disconnected != null) Disconnected(this, "Server disconnected. " + error.Message);
// Set _isConnected
_isConnected = false;
}
}
}
}
*******************************
CLIENT.cs
*******************************
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using Messenger;
namespace Messenger
{
/// <summary>
/// Represents the method that handles the Connected event.
/// </summary>
public delegate void ConnectedEventHandler(Client sender, EventArgs e);
/// <summary>
/// Represents the method that handles the Disconnected event.
/// </summary>
public delegate void DisconnectedEventHandler(Client sender, string message);
/// <summary>
/// Represents the method that handles the MessageReceived event.
/// </summary>
public delegate void MessageReceivedEventHandler(Client sender, string message);
/// <summary>
/// Represents the method that handles the MessageSent event.
/// </summary>
public delegate void MessageSentEventHandler(Client sender, string message);
/// <summary>
/// The Client class connects to a server, to send and receive messages.
/// </summary>
public class Client
{
/// <summary>
/// The object that connects to the TCP network client.
/// </summary>
private TcpClient client;
/// <summary>
/// The Name of the machine that the client runs on.
/// </summary>
private string _hostName;
/// <summary>
/// The IP Address of the machine that the client runs on.
/// </summary>
private IPAddress _iPAddress;
/// <summary>
/// The Port that the client listens on.
/// </summary>
private int _port;
/// <summary>
/// The IP and Port of the remote server.
/// </summary>
private EndPoint _remoteEndPoint;
/// <summary>
/// A value indicating if the client is connected or not.
/// </summary>
private bool _isConnected = false;
/// <summary>
/// Temporarily stores messages that are sent to/received from the server in byte format.
/// </summary>
private byte[] messageBytes;
/// <summary>
/// The char used for splitting messages.
/// </summary>
private readonly char splitter;
/// <summary>
/// The event triggered when a client is connected to the server.
/// </summary>
public event ConnectedEventHandler Connected;
/// <summary>
/// The event triggered when a client disconnects from the server.
/// </summary>
public event DisconnectedEventHandler Disconnected;
/// <summary>
/// The event triggered when a client receives a message.
/// </summary>
public event MessageReceivedEventHandler MessageReceived;
/// <summary>
/// The event triggered when a client sends a message.
/// </summary>
public event MessageSentEventHandler MessageSent;
/// <summary>
/// Creates a new Client instance.
/// </summary>
/// <param name="hostName">Name of the machine that the client runs on.</param>
/// <param name="port">Port that the client listens on.</param>
public Client(TcpClient client, string hostName, int port)
{
// Assign private members to contructor values
this.client = client;
this._hostName = hostName;
this._iPAddress = Dns.GetHostByName(_hostName).AddressList[0];
this._port = port;
this._remoteEndPoint = new IPEndPoint(_iPAddress, _port);
// Set isconnected
_isConnected = true;
// Raise Connected event
if(Connected != null) Connected(this, null);
// Set the message splitter char
splitter = Convert.ToChar(19);
// Set message byte array to receive buffer size
messageBytes = new byte[client.ReceiveBufferSize];
// Read the clients network stream for incoming messages
client.GetStream().BeginRead(messageBytes, 0, client.ReceiveBufferSize, new AsyncCallback(ReceiveMessage), null);
}
/// <summary>
/// Creates a new Client instance.
/// </summary>
/// <param name="hostName">Name of the machine that the client runs on.</param>
/// <param name="port">Port that the client listens on.</param>
public Client(string hostName, int port)
{
// Assign private members to contructor values
this._hostName = hostName;
this._iPAddress = Dns.GetHostByName(_hostName).AddressList[0];
this._port = port;
this._remoteEndPoint = new IPEndPoint(_iPAddress, _port);
// Set the message splitter char
splitter = Convert.ToChar(19);
}
/// <summary>
/// Creates a new Client instance.
/// </summary>
/// <param name="iPAddress">IP Address of the machine that the client runs on.</param>
/// <param name="port">Port that the client listens on.</param>
public Client(IPAddress iPAddress, int port)
{
// Assign private members to contructor values
this._iPAddress = iPAddress;
this._hostName = Dns.GetHostByAddress(_iPAddress).HostName;
this._port = port;
this._remoteEndPoint = new IPEndPoint(_iPAddress, _port);
// Set the message splitter char
splitter = Convert.ToChar(19);
}
/// <summary>
/// Gets or sets the Name of the machine that the client runs on.
/// </summary>
public string HostName
{
get
{
return _hostName;
}
set
{
// Don't allow _hostName to be changed if the client is running
if(_isConnected)
throw new Exception("Can not change the HostName of the client while it is running.");
// If the client is not running
else
{
_hostName = value;
// Refresh the IP based on the _hostName
_iPAddress = Dns.GetHostByName(_hostName).AddressList[0];
// Set the _remoteEndPoint
_remoteEndPoint = new IPEndPoint(_iPAddress, _port);
}
}
}
/// <summary>
/// Gets or sets the IP Address of the machine that the client runs on.
/// </summary>
public IPAddress IP
{
get
{
return _iPAddress;
}
set
{
// Don't allow _iPAddress to be changed if the client is running
if(_isConnected)
throw new Exception("Can not change the IP of the client while it is running.");
// If the client is not running
else
{
_iPAddress = value;
// Refresh the HostName based on the _iPAddress
_hostName = Dns.GetHostByAddress(_iPAddress).HostName;
// Set the _remoteEndPoint
_remoteEndPoint = new IPEndPoint(_iPAddress, _port);
}
}
}
/// <summary>
/// Gets or sets the Port that the client listens on.
/// </summary>
public int Port
{
get
{
return _port;
}
set
{
// Don't allow the _port to be changed if the client is running
if(_isConnected)
throw new Exception("Can not change the Port of the client while it is running.");
else
{
_port = value;
// Set the _remoteEndPoint
_remoteEndPoint = new IPEndPoint(_iPAddress, _port);
}
}
}
/// <summary>
/// Gets the Server End Point.
/// </summary>
public EndPoint RemoteEndPoint
{
get
{
return _remoteEndPoint;
}
}
/// <summary>
/// Gets a value indicating if the client is running or not.
/// </summary>
public bool IsConnected
{
get
{
return _isConnected;
}
}
/// <summary>
/// Connects the client to the server.
/// </summary>
public void Connect()
{
// Do not allow connection if already connected
if(_isConnected)
throw new Exception("Can not connect again. Client is already connected.");
// If not connected
else
{
// Creates a new TCP client instance
client = new TcpClient();
// Connect to the server
client.Connect(_hostName, _port);
// Raise Connected event
if(Connected != null) Connected(this, null);
// Set isconnected
_isConnected = true;
// Set message byte array to receive buffer size
messageBytes = new byte[client.ReceiveBufferSize];
// Read the clients network stream for incoming messages
client.GetStream().BeginRead(messageBytes, 0, client.ReceiveBufferSize, new AsyncCallback(ReceiveMessage), null);
}
}
/// <summary>
/// Disconnects the client from the server.
/// </summary>
public void Disconnect()
{
// Do not allow connection if already connected
if(_isConnected)
throw new Exception("Invalid Operation. Can not disconnect from the server when not connected.");
// If not connected
else
{
// Disconnect from the server
client.GetStream().Close();
client.Close();
// Raise Connected event
if(Disconnected != null) Disconnected(this, "User disconnected.");
// Set isconnected
_isConnected = false;
}
}
/// <summary>
/// Sends a message to the server.
/// </summary>
/// <param name="message">The message to send to the server.</param>
public void SendMessage(string message)
{
// Gets the stream to send data on
NetworkStream networkStream = client.GetStream();
// Convert message to byte array
messageBytes = Encoding.ASCII.GetBytes(message);
// Write the message bytes to the stream
networkStream.Write(messageBytes, 0, messageBytes.Length);
// Flush the data
networkStream.Flush();
// Raise MessageSent event
if(MessageSent != null) MessageSent(this, message);
}
/// <summary>
/// Processes incoming messages from the server.
/// </summary>
private void ReceiveMessage(IAsyncResult iAsyncResult)
{
try
{
// Get the length of the received data
int messageBytesLength = client.GetStream().EndRead(iAsyncResult);
// If no data
if(messageBytesLength < 1)
{
// Raise Disconnected event
if(Disconnected != null) Disconnected(this, "Server disconnected.");
// Set _isConnected
_isConnected = false;
return;
}
// Get the message string
string message = Encoding.ASCII.GetString(messageBytes, 0, messageBytesLength);
// Raise MessageReceived event
if(MessageReceived != null) MessageReceived(this, message);
// Set message byte array size
messageBytes = new byte[client.ReceiveBufferSize];
// Continue reading for more messages
client.GetStream().BeginRead(messageBytes, 0, client.ReceiveBufferSize, new AsyncCallback(ReceiveMessage), null);
}
catch(Exception error)
{
// Raise Disconnected event
if(Disconnected != null) Disconnected(this, "Server disconnected. " + error.Message);
// Set _isConnected
_isConnected = false;
}
}
}
}
Someone, please help!
Please create a form to use these classes, their methods and events.
|
|
|
|
|
Try setting a breakpoint on the Server's RecieveMessage() function after you convert the message to ASCII. You can see if the message is changing. Or if u prefer just look at the raw bytes in the messageBytes array. Main thing is rule out one program at a time. Once you are sure the server is working properly then you can address the client. Depending on how comfortable you are with debugging async apps, i would consider running some canned data thru the server to make sure your comm mechnism is good.
Good luck!
Mike
|
|
|
|
|
Hi There
The client application that sends the message, sends it properly to the server. The server then sends it to all the clients and the first time around, the server sends and receives the message properly. The second time around when the client sends a message, the server distributes the previous message each time, but the client that sent the original message receives it properly.
Please help!
I've looked through everything and i can't understand why its doing that.
|
|
|
|
|
Hi,
In my project I use a TreeView in which all nodes are supposed to be sorted in alphabetical order. When the user edits a node label I want the TreeView to automatically sort itself. Using the following code I am able to make it work for the top level nodes but not their children.
<br />
protected override void WndProc(ref Message m)<br />
{<br />
base.WndProc(ref m);<br />
<br />
if (m.Msg == 0x004E)
{ <br />
SendMessage(treeView.Handle, 0x1113, 1, 0);
}<br />
}<br />
Any help would be greatly appriciated!
|
|
|
|
|
Can you use the TreeView.Sorted property and set it to true ?
"we must lose precision to make significant statements about complex systems."
-deKorvin on uncertainty
|
|
|
|
|
Unfortunately not, setting the TreeView.Sorted to true makes the TreeView sort the nodes upon insertion but not after editing a node label.
|
|
|
|
|
Cool. That makes sense.
Then, how about setting the Sorted value to true , subscribing to the TreeView.AfterLabelEdit event, and, after the label gets edited, do something like:
public void EventHandler( object o, NodeLabelEditEventArgs nleea )
{
TreeNode node = ( TreeNode ) o;
if( TreeNode.Parent != null )
{
TreeNode.Parent.Remove( node );
TreeNode.Parent.Add( node );
}
}
<pre>
"we must lose precision to make significant statements about complex systems."
-deKorvin on uncertainty
|
|
|
|
|
Hi
How do I compare 2 strings, ignoring their case. For instance, I want to achieve the following result:
bt = BT > true
GD = BT > False
bT = Bt > true
regards
|
|
|
|
|
Use the string.Compare method:
string.Compare(string strA, string strB, bool ignoreCase)
---
b { font-weight: normal; }
|
|
|
|
|
Read everything I can find on .dll's but I'm still stuck -
I recently purchased a usb device controller (PC BEE) online and have managed to get it working ok, however I want to talk to it with Matlab 7.0.
I've been provided with .dll file - 'bee.dll' and a .def file - bee.def. However as I've no header I cant use the loadlibrary command in matlab
Apparently there are only two functions:
typedef BOOL (*TypeBeeInit)();
typedef void (*TypeBeeOut)(unsigned long bits);
So the header should be quite small, but I have no idea how to write it!!!
Can anyone help!?!
---------------------------------------------------------------------
I've included the .def file if that's any use:
; bee.def : Declares the module parameters for the DLL.
LIBRARY "bee"
DESCRIPTION 'bee Windows Dynamic Link Library'
EXPORTS
BeeInit
BeeOut
Wicker
|
|
|
|
|
Hi all i have developed a dll in VC++7.0
and want to use it in C# code but i got exception:
" Unable to load DLL 'HookLib.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E) "
my Dll code is:
////////////////////////"HookLib.cpp"
#include "stdafx.h"
extern HINSTANCE g_appInstance;
BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD ul_reason_for_call, LPVOID lpReserved)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
//
// Capture the application instance of this module to pass to
// hook initialization.
//
if (g_appInstance == NULL)
{
g_appInstance = hinstDLL;
}
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
break;
default:
//OutputDebugString("Not sure what just happened.\n");
break;
}
return TRUE;
}
/////////////////////
//////////////////////////"HookCore.h"
#pragma once
LRESULT CALLBACK GetMessageProc(int nCode, WPARAM wParam, LPARAM lParam);
bool InitializeHook();
void UninitializeHook();
////////////////
//////////////////////////"HookCore.cpp"
#include "stdafx.h"
#include <windows.h>
#include "HookCore.h"
#include "MessageFilter.h"
HHOOK hookMsg = NULL;
HINSTANCE g_appInstance = NULL;
LRESULT CALLBACK GetMessageProc(int nCode, WPARAM wParam, LPARAM lParam){
if (nCode == HC_ACTION) {
MSG *msg = (MSG *) lParam;
if(msg->message == WM_PAINT){
//Beep debug
Beep(1000,1);
//Write file debug
}
//Process message
//...
}
return CallNextHookEx (hookMsg, nCode, wParam, lParam);
}
bool InitializeHook()
{
if (g_appInstance == NULL)
{
return false;
}
hookMsg = SetWindowsHookEx(WH_CALLWNDPROC, (HOOKPROC)GetMessageProc,
g_appInstance, 0);
return hookMsg != NULL;
}
void UninitializeHook()
{
if(hookMsg != NULL)
{
UnhookWindowsHookEx(hookMsg);
}
hookMsg = NULL;
}
/////////////////////////////////////////////////
///////////////////////"HookCore.def"
LIBRARY "HookLib"
EXPORTS
InitializeHook
UninitializeHook
//////////////////////////////////////////////////////////////////////////
and my C# code to import dll functions is
DllImport("HookLib.dll", EntryPoint="InitializeHook", SetLastError=true,
CharSet=CharSet.Unicode, ExactSpelling=true,
CallingConvention=CallingConvention.StdCall)]
private static extern bool InitializeHook();
[DllImport("HookLib.dll", EntryPoint="UninitializeHook", SetLastError=true,
CharSet=CharSet.Unicode, ExactSpelling=true,
CallingConvention=CallingConvention.StdCall)]
private static extern void UninitializeHook();
then i use the InitializeHook() method i got the above exception
can somebody tell me how i can get rid of this
Thanx for ur response.
|
|
|
|
|