Environment.MachineName is commonly used to get the machine name in .net. Few days ago, I met a problem with it after renaming a machine and joining a domain: Environment.MachineName returned the old name machine name.
While searching for the reason, I found that Environment.MachineName gets the NetBIOS name, which is stored in the registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Contro l\ComputerName\ComputerName\ComputerName and reflects in the Computername envronment variable.
A big limitation of NetBIOS name in this case is that it's limited to the first 15 characters of the machine name. An alternative is needed to get the full name. Which is System.Net.Dns.GetHostName() method which gets the DNS host name of the local computer, which is not limited to the first 15 characters.
Back to my problem, I edited the registry key to reflect the new machine name. That was good enough for me!!
Sunday, August 24, 2008
Friday, August 1, 2008
Validating SMTP host information
This is a simple class to check if a connection to SMTP host is possible. It can be useful in case of gathering user input and the user is required to enter a valid smtp host.
The idea is simple, open a TCP connection to the host, and read the initial welcome message sent by the smtp host, it should start with response code 220.
I everything is ok, we need to end the sesion by sending QUIT command and close the connection.
For more information check RFC 821 SIMPLE MAIL TRANSFER PROTOCOL
I used Visual C# 2008 Express edition to build this example. You can check the code below, or download the code with a test application from this link:
The idea is simple, open a TCP connection to the host, and read the initial welcome message sent by the smtp host, it should start with response code 220.
I everything is ok, we need to end the sesion by sending QUIT command and close the connection.
For more information check RFC 821 SIMPLE MAIL TRANSFER PROTOCOL
I used Visual C# 2008 Express edition to build this example. You can check the code below, or download the code with a test application from this link:
public static class SmtpChecker
{
public static bool Check(string host,int port,out string welcomeMessage)
{
try
{
using (TcpClient smtp = new TcpClient(host, port))
using (StreamReader reader = new StreamReader(smtp.GetStream()))
{
welcomeMessage = reader.ReadLine();
//validate the reasponse
if (welcomeMessage.StartsWith("220", StringComparison.InvariantCulture))
{
//Send QUIT as recommended by RFC 821
try
{
using (StreamWriter w = new StreamWriter(smtp.GetStream()))
{
w.WriteLine("QUIT");
w.Flush();
string result =reader.ReadLine();
}
}
catch
{}
return true;
}
else
{
welcomeMessage = "";
return false;
}
}
}
catch (Exception)
{
welcomeMessage = "";
return false;
}
}
}
Subscribe to:
Posts (Atom)