Response.Buffer doesn't work - c#

I'm working on a windows form in which I ping a host.
For some reason, I cant get Response.Buffer to work. I tried using HttpContext.Current, and I also double checked I added a reference to both System.Web, and System.Net.NetworkInformation.
Here is the code :
Ping p = new Ping();
PingReply r;
String s = UserInput;
r = p.Send(s);
HttpContext.Current.Response.Buffer = false;
if (r.Status == IPStatus.Success)
{
string got = "Ping to " + s.ToString() + "[" + r.Address.ToString() + "] successful - " + r.Buffer.Length.ToString() + " bytes in " + r.RoundtripTime.ToString() + " ms." + "\n";
string ToSave = ToSave + got;
}

What you are trying to do does not make sense. Pinging a host is to check whether it is alive, not sending / receiving data, what I think you are trying to do.
When you want to communicate between two clients, then TcpClient is probably what you need. Take a look at the docs and demo here.
When just trying to check connectivity, try this:
Ping p = new Ping();
PingReply reply = p.Send("www.contoso.com");
if (reply.Status == IPStatus.Success)
{
...
}

Related

C# monitor SNMP timeticks from multiple IP addresses

I'm attempting to monitor multiple SNMP agents (timeticks) with SnmpSharpNet across separate networks. The code below works with a single IP address, but when I try and connect to a second IP address the code fails, I'm trying to run this asynchronously but it appears that SnmpSharpNet won't allow me to receive data from more than one agent.
Is this the right way to approach this problem? Is there a better alternative to SmnpSharpNet?
community = new OctetString("public");
// Define agent parameters class
param = new AgentParameters(community);
// Set SNMP version to 1 (or 2)
param.Version = SnmpVersion.Ver1;
for (int i = 0; i < sendsqldatalist.Count(); i++)
{
agent = new IpAddress(sendsqldatalist[i].ip);
target = new UdpTarget((IPAddress)agent, 161, 2000, 1);
// Make SNMP request
resultlist.Add(result = (SnmpV1Packet)target.Request(pdu, param));
// If result is null then agent didn't reply or we couldn't parse the reply.r
if (resultlist[i] != null)
{
// ErrorStatus other then 0 is an error returned by
// the Agent - see SnmpConstants for error definitions
if (resultlist[i].Pdu.ErrorStatus != 0)
{
Console.WriteLine("error on - " + sendsqldatalist[i].oid + " " + sendsqldatalist[i].ip);
// agent reported an error with the request
//- Error status found here http://www.docs.snmpsharpnet.com/docs-0-9-1/
MessageBox.Show("Error in SNMP reply from " + target.Address.ToString() + Environment.NewLine + "Error status " + result.Pdu.ErrorStatus.GetType() + Environment.NewLine + "Error Index " + result.Pdu.ErrorIndex.ToString(), "WARNING!");
}
else
{
Console.WriteLine("ConnectSNMP() CONNECTED - " + sendsqldatalist[i].oid + " - " + sendsqldatalist[i].ip);
}
}
}
Thanks in advance!

How to verify if remote computer is available?

I'm writing a part of a program that shall copy a batch of files from the current computer to a defined list of computers.
If these computers are not available, the code will hang for a long time trying to access them. Is there any functionallity in C# to check if the machine is available and then skip if it's not?
MFWs = File.ReadAllLines(GuiManager.MyConfigManagerConfig.MachinesList);
foreach (string MFW in MFWs)
{
if (MFW != System.Environment.MachineName)
{
String target = #"\\" + MFW + #"\D\IbSi\config\" + Path.GetFileName(ConfigFile);
String backup = #"\\" + MFW + #"\D\IbSi\userdata\" + Path.GetFileName(ConfigFile);
try
{
File.Copy(source, target, true);
File.Copy(source, backup, true);
}
catch (Exception ex)
{
Manager.SendMessage("Failed to copy " + Path.GetFileName(ConfigFile) + " to " + MFW + "\n" + ex.Message);
}
}
}
You could ping the computer before starting the copy (taken from this answer):
using System.Net.NetworkInformation;
public static bool IsHostAvailable(string nameOrAddress)
{
bool pingable = false;
Ping pinger = new Ping();
try
{
PingReply reply = pinger.Send(nameOrAddress);
pingable = reply.Status == IPStatus.Success;
}
catch (PingException)
{
// Discard PingExceptions and return false;
}
return pingable;
}
As noted in the comments you need to make sure the firewall on the servers is open for pings (ICMP echo requests)

Using VSPE tcpclient/tcpserver in C#

I tried to create TcpClients and TcpServers in my C# program using VSPE COM service. Everything seemed okay except the TcpServer/TcpClient created took so much CPU time when running-- 2 of them can take 100% of my cpu time. Anyone can help?
Server creation:
string comName = "COM2";
string tcpPortNum = "5555";
string ipAddr = LocalServerIpAddress.ToString();
string initString = tcpPortNum + ";" + comName.Remove(0, 3) + ";19200,0,8,1,0,0;" + ipAddr + ";0;0";
// Create
int result = vspe.vspe_createDevice("TcpServer", initString);
Client Creation:
string comName = "COM3";
string tcpPortNum = "5555";
string ipAddr = remoteServerIpAddr.ToString();
string initString = ipAddr + ";" + tcpPortNum + ";" + comName.Remove(0, 3) + ";19200,0,8,1,0,0;0;30;;0;0";
// Create
int result = vspe.vspe_createDevice("TcpClient", initString);

Pinging using ARP always return host offline

I'm trying to check if computer on the net is online by using code which supposedly to check it by using ARP packets.
I am always getting message that host is offline even when I'm sure that it's online. I have checked on my localhost IP and on some always working IPs such as google.
That could be wrong with this code?
[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(IPAddress DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);
private byte[] macAddr = new byte[6];
private uint macAddrLen;
private void Ping(IPAddress address)
{
if (SendARP(address, 0, new byte[6], ref macAddrLen) == 0)
{
open++;
txtDisplay.AppendText("Host " + address + " is open." + Environment.NewLine);
}
else
{
closed++;
txtDisplay.AppendText("Host " + address + " is closed." + Environment.NewLine);
}
}
By using previous code I'm basically trying to do something like following code. But the problem with this code is that when host is closed that it takes like 2 seconds to get the respond which I want to eliminate. Someone suggested to use ARP ping:
private void Ping(IPAddress address)
{
Ping pingSender = new Ping();
PingOptions options = new PingOptions();
if (cbDontFragment.Checked) options.DontFragment = true;
else options.DontFragment = false;
string dataa = string.Empty;
int dataCounter = 0;
options.Ttl = (int)nudTTL.Value;
for (int i = 0; i < nudData.Value; i++)
{
dataCounter++;
if (dataCounter == 10) dataCounter = 0;
dataa += dataCounter.ToString();
}
byte[] buffer = Encoding.ASCII.GetBytes(dataa);
int timeout = 120;
try
{
PingReply reply = pingSender.Send(address, timeout, buffer, options);
if (reply.Status == IPStatus.Success)
{
open++;
txtDisplay.AppendText("Host " + address + " is open. ");
if (cbDontFragment.Checked) txtDisplay.AppendText(" Don't fragment. ");
txtDisplay.AppendText(" TTL: " + options.Ttl.ToString() + " ");
txtDisplay.AppendText(" Bytes: " + nudData.Value + " ");
txtDisplay.AppendText(Environment.NewLine);
}
else
{
closed++;
txtDisplay.AppendText("Host " + address + " is closed. ");
if (cbDontFragment.Checked) txtDisplay.AppendText(" Don't fragment. ");
txtDisplay.AppendText(" TTL: " + options.Ttl.ToString() + " ");
txtDisplay.AppendText(" Bytes: " + nudData.Value + " ");
txtDisplay.AppendText(Environment.NewLine);
}
}
catch (Exception ex)
{
txtDisplay.SelectedText += Environment.NewLine + ex.Message;
}
}
ARP cannot be used for what you are trying to do. It only works over a local network.
It's purpose is to resolve an IP address (which is routed) to a MAC address (which is not). It is never sent beyond a network segment (a lan)

Exchange Server Error: The remote server returned an error: (440) Login Timeout

I'm creating a window based program to retrieve emails in Exchange Server 2003 using webDAV.
im getting the error on loResponse = (HttpWebResponse)loRequest.GetResponse();
Here's the code:
lsRootUri = p_strServer + "/Exchange//" + p_strAlias + "//" + p_strInboxURL + "//";
lsQuery = "<?xml version=\"1.0\"?>"
+ "<D:searchrequest xmlns:D = \"DAV:\" xmlns:m=\"urn:schemas:httpmail:\">"
+ "<D:sql>SELECT \"urn:schemas:httpmail:hasattachment\", \"DAV:displayname\", "
+ "\"urn:schemas:httpmail:from\", \"urn:schemas:httpmail:subject\", "
+ "\"urn:schemas:httpmail:htmldescription\" FROM \"" + lsRootUri
+ "\" WHERE \"DAV:ishidden\" = false "
+ "AND \"DAV:isfolder\" = false "
+ "AND \"urn:schemas:httpmail:hasattachment\" = true "
+ "AND \"urn:schemas:httpmail:read\" = false"
+ "</D:sql></D:searchrequest>";
loRequest = (HttpWebRequest)WebRequest.Create(lsRootUri);
loRequest.Credentials = new NetworkCredential(p_strUserName, p_strPassword);
loRequest.Method = "SEARCH";
laBytes = System.Text.Encoding.UTF8.GetBytes(lsQuery);
loRequest.ContentLength = laBytes.Length;
loRequestStream = loRequest.GetRequestStream();
loRequestStream.Write(laBytes, 0, laBytes.Length);
loRequestStream.Close();
loRequest.ContentType = "text/xml";
loRequest.Headers.Add("Translate", "F");
loResponse = (HttpWebResponse)loRequest.GetResponse();
loResponseStream = loResponse.GetResponseStream();
loXmlDoc.Load(loResponseStream);
loResponseStream.Close();
i remove the domain name from the user name and it is now working...
There are various things that could be going wrong here:
You can't establish a connection to the actual server.
You can't establish a connection to the mail server.
I'd check that the network credentials you have are valid and give you the access you need.
Something else that's just sprung to mind is to check that you're trying to connect on the correct port. Connecting interactively will do this as the programs you use will have the ports set up, however in your program you'll need to set the port. The server could be set up to reject connections on the "wrong" ports.

Categories