/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Web.Mail;
public class FancyMailTest
{
public static void Main()
{
MailMessage mm = new MailMessage();
mm.From = "haley@myisp.net";
mm.To = "riley@yourisp.net;rich@shadrach.ispnet1.net";
mm.Cc = "matthew@anotherisp.net;chris@hisisp.net";
mm.Bcc = "katie@herisp.net;jessica@herisp.net";
mm.Subject = "This is a fancy test message";
mm.Headers.Add("Reply-To", "haley@myisp.net");
mm.Headers.Add("Comments", "This is a test HTML message");
mm.Priority = MailPriority.High;
mm.BodyFormat = MailFormat.Html;
mm.Body = "<html><body><h1>This is a test message</h1><h2>This message should have HTML-type formatting</h2>Please use an HTML-capable viewer.";
try
{
SmtpMail.Send(mm);
} catch (System.Web.HttpException)
{
Console.WriteLine("This device is unable to send Internet messages");
}
}
}
Month: February 2011
A POP3 e-mail checker
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;
public class PopCheck : Form
{
private TextBox hostname;
private TextBox username;
private TextBox password;
private TextBox status;
private ListBox messages;
private TcpClient mailclient;
private NetworkStream ns;
private StreamReader sr;
private StreamWriter sw;
public PopCheck()
{
Text = "popcheck - A POP3 e-mail checker";
Size = new Size(400, 380);
Label label1 = new Label();
label1.Parent = this;
label1.Text = "Hostname:";
label1.AutoSize = true;
label1.Location = new Point(10, 33);
hostname = new TextBox();
hostname.Parent = this;
hostname.Size = new Size(200, 2 * Font.Height);
hostname.Location = new Point(75, 30);
Label label2 = new Label();
label2.Parent = this;
label2.Text = "User name:";
label2.AutoSize = true;
label2.Location = new Point(10, 53);
username = new TextBox();
username.Parent = this;
username.Size = new Size(200, 2 * Font.Height);
username.Location = new Point(75, 50);
Label label3 = new Label();
label3.Parent = this;
label3.Text = "Password:";
label3.AutoSize = true;
label3.Location = new Point(10, 73);
password = new TextBox();
password.Parent = this;
password.PasswordChar = '*';
password.Size = new Size(200, 2 * Font.Height);
password.Location = new Point(75, 70);
Label label4 = new Label();
label4.Parent = this;
label4.Text = "Status:";
label4.AutoSize = true;
label4.Location = new Point(10, 325);
status = new TextBox();
status.Parent = this;
status.Text = "Not connected";
status.Size = new Size(200, 2 * Font.Height);
status.Location = new Point(50, 322);
messages = new ListBox();
messages.Parent = this;
messages.Location = new Point(10, 108);
messages.Size = new Size(360, 16 * Font.Height);
messages.DoubleClick += new EventHandler(getmessagesDoubleClick);
Button login = new Button();
login.Parent = this;
login.Text = "Login";
login.Location = new Point(295, 32);
login.Size = new Size(5 * Font.Height, 2 * Font.Height);
login.Click += new EventHandler(ButtonloginOnClick);
Button close = new Button();
close.Parent = this;
close.Text = "Close";
close.Location = new Point(295, 62);
close.Size = new Size(5 * Font.Height, 2 * Font.Height);
close.Click += new EventHandler(ButtoncloseOnClick);
}
void ButtonloginOnClick(object obj, EventArgs ea)
{
status.Text = "Checking for messages...";
Thread startlogin = new Thread(new ThreadStart(loginandretr));
startlogin.IsBackground = true;
startlogin.Start();
}
void ButtoncloseOnClick(object obj, EventArgs ea)
{
if (ns != null)
{
sw.Close();
sr.Close();
ns.Close();
mailclient.Close();
}
Close();
}
void loginandretr()
{
string response;
string from = null;
string subject = null;
int totmessages;
try
{
mailclient = new TcpClient(hostname.Text, 110);
} catch (SocketException)
{
status.Text = "Unable to connect to server";
return;
}
ns = mailclient.GetStream();
sr = new StreamReader(ns);
sw = new StreamWriter(ns);
response = sr.ReadLine(); //Get opening POP3 banner
sw.WriteLine("User " + username.Text); //Send username
sw.Flush();
response = sr.ReadLine();
if (response.Substring(0,4) == "-ERR")
{
status.Text = "Unable to log into server";
return;
}
sw.WriteLine("Pass " + password.Text); //Send password
sw.Flush();
try
{
response = sr.ReadLine();
} catch (IOException)
{
status.Text = "Unable to log into server";
return;
}
if (response.Substring(0,3) == "-ER")
{
status.Text = "Unable to log into server";
return;
}
sw.WriteLine("stat"); //Send stat command to get number of messages
sw.Flush();
response = sr.ReadLine();
string[] nummess = response.Split(' ');
totmessages = Convert.ToInt16(nummess[1]);
if (totmessages > 0)
{
status.Text = "you have " + totmessages + " messages";
} else
{
status.Text = "You have no messages" ;
}
for (int i = 1; i <= totmessages; i++)
{
sw.WriteLine("top " + i + " 0"); //read header of each message
sw.Flush();
response = sr.ReadLine();
while (true)
{
response = sr.ReadLine();
if (response == ".")
break;
if (response.Length > 4)
{
if (response.Substring(0, 5) == "From:")
from = response;
if (response.Substring(0, 8) == "Subject:")
subject = response;
}
}
messages.Items.Add(i + " " + from + " " + subject);
}
}
void getmessagesDoubleClick(object obj, EventArgs ea)
{
string text = (string)messages.SelectedItem;
string[] textarray = text.Split(' ');
ShowMessage sm = new ShowMessage(ns, textarray[0]);
sm.ShowDialog();
}
public static void Main()
{
Application.Run(new PopCheck());
}
}
class ShowMessage : Form
{
public ShowMessage(NetworkStream ns, string messnumber)
{
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
string response;
Text = "Message " + messnumber;
Size = new Size(400, 380);
ShowInTaskbar = false;
TextBox display = new TextBox();
display.Parent = this;
display.Multiline = true;
display.Dock = DockStyle.Fill;
display.ScrollBars = ScrollBars.Both;
sw.WriteLine("retr " + messnumber); //Retrieve entire message
sw.Flush();
response = sr.ReadLine();
while (true)
{
response = sr.ReadLine();
if (response == ".")
break;
display.Text += response + "
";
}
}
}
Mail Test
using System;
using System.Net;
using System.Web.Mail;
public class MailTest
{
public static void Main()
{
string from = "from@from.net";
string to = "to@to.net";
string subject = "This is a test mail message";
string body = "Hi .";
SmtpMail.SmtpServer = "192.168.1.150";
SmtpMail.Send(from, to, subject, body);
}
}
SmtpClient: From, Subject, Body, Attachments, To
using System;
using System.Net;
using System.Net.Mail;
class MainClass {
public static void Main(string[] args) {
SmtpClient client = new SmtpClient("mail.somecompany.com", 25);
client.Credentials = new NetworkCredential("user@somecompany.com", "password");
using (MailMessage msg = new MailMessage()) {
msg.From = new MailAddress("author@visual-csharp-recipes.com");
msg.Subject = "Greetings";
msg.Body = "This is a message.";
msg.Attachments.Add(new Attachment("7.cs", "text/plain"));
msg.Attachments.Add(new Attachment("7.exe", "application/octet-stream"));
foreach (string str in args) {
try {
msg.To.Add(new MailAddress(str));
} catch (FormatException ex) {
Console.WriteLine("{0}: Error -- {1}", str, ex.Message);
continue;
}
}
client.Send(msg);
}
}
}
Get Mac Address
/*
C# Network Programming
by Richard Blum
Publisher: Sybex
ISBN: 0782141765
*/
using System.Net;
using System.Net.Sockets;
using System.Text;
using System;
public class MacAddress
{
public static void Main(string[] argv)
{
int commlength, miblength, datastart, datalength;
string nextmib, value;
SNMP conn = new SNMP();
string mib = "1.3.6.1.2.1.17.4.3.1.1";
int orgmiblength = mib.Length;
byte[] response = new byte[1024];
nextmib = mib;
while (true)
{
response = conn.get("getnext", argv[0], argv[1], nextmib);
commlength = Convert.ToInt16(response[6]);
miblength = Convert.ToInt16(response[23 + commlength]);
datalength = Convert.ToInt16(response[25 + commlength + miblength]);
datastart = 26 + commlength + miblength;
value = BitConverter.ToString(response, datastart, datalength);
nextmib = conn.getnextMIB(response);
if (!(nextmib.Substring(0, orgmiblength) == mib))
break;
Console.WriteLine("{0} = {1}", nextmib, value);
}
}
}
class SNMP
{
public SNMP()
{
}
public byte[] get(string request, string host, string community, string mibstring)
{
byte[] packet = new byte[1024];
byte[] mib = new byte[1024];
int snmplen;
int comlen = community.Length;
string[] mibvals = mibstring.Split('.');
int miblen = mibvals.Length;
int cnt = 0, temp, i;
int orgmiblen = miblen;
int pos = 0;
// Convert the string MIB into a byte array of integer values
// Unfortunately, values over 128 require multiple bytes
// which also increases the MIB length
for (i = 0; i < orgmiblen; i++)
{
temp = Convert.ToInt16(mibvals[i]);
if (temp > 127)
{
mib[cnt] = Convert.ToByte(128 + (temp / 128));
mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128));
cnt += 2;
miblen++;
} else
{
mib[cnt] = Convert.ToByte(temp);
cnt++;
}
}
snmplen = 29 + comlen + miblen - 1; //Length of entire SNMP packet
//The SNMP sequence start
packet[pos++] = 0x30; //Sequence start
packet[pos++] = Convert.ToByte(snmplen - 2); //sequence size
//SNMP version
packet[pos++] = 0x02; //Integer type
packet[pos++] = 0x01; //length
packet[pos++] = 0x00; //SNMP version 1
//Community name
packet[pos++] = 0x04; // String type
packet[pos++] = Convert.ToByte(comlen); //length
//Convert community name to byte array
byte[] data = Encoding.ASCII.GetBytes(community);
for (i = 0; i < data.Length; i++)
{
packet[pos++] = data[i];
}
//Add GetRequest or GetNextRequest value
if (request == "get")
packet[pos++] = 0xA0;
else
packet[pos++] = 0xA1;
packet[pos++] = Convert.ToByte(20 + miblen - 1); //Size of total MIB
//Request ID
packet[pos++] = 0x02; //Integer type
packet[pos++] = 0x04; //length
packet[pos++] = 0x00; //SNMP request ID
packet[pos++] = 0x00;
packet[pos++] = 0x00;
packet[pos++] = 0x01;
//Error status
packet[pos++] = 0x02; //Integer type
packet[pos++] = 0x01; //length
packet[pos++] = 0x00; //SNMP error status
//Error index
packet[pos++] = 0x02; //Integer type
packet[pos++] = 0x01; //length
packet[pos++] = 0x00; //SNMP error index
//Start of variable bindings
packet[pos++] = 0x30; //Start of variable bindings sequence
packet[pos++] = Convert.ToByte(6 + miblen - 1); // Size of variable binding
packet[pos++] = 0x30; //Start of first variable bindings sequence
packet[pos++] = Convert.ToByte(6 + miblen - 1 - 2); // size
packet[pos++] = 0x06; //Object type
packet[pos++] = Convert.ToByte(miblen - 1); //length
//Start of MIB
packet[pos++] = 0x2b;
//Place MIB array in packet
for(i = 2; i < miblen; i++)
packet[pos++] = Convert.ToByte(mib[i]);
packet[pos++] = 0x05; //Null object value
packet[pos++] = 0x00; //Null
//Send packet to destination
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
ProtocolType.Udp);
sock.SetSocketOption(SocketOptionLevel.Socket,
SocketOptionName.ReceiveTimeout, 5000);
IPHostEntry ihe = Dns.Resolve(host);
IPEndPoint iep = new IPEndPoint(ihe.AddressList[0], 161);
EndPoint ep = (EndPoint)iep;
sock.SendTo(packet, snmplen, SocketFlags.None, iep);
//Receive response from packet
try
{
int recv = sock.ReceiveFrom(packet, ref ep);
} catch (SocketException)
{
packet[0] = 0xff;
}
return packet;
}
public string getnextMIB(byte[] mibin)
{
string output = "1.3";
int commlength = mibin[6];
int mibstart = 6 + commlength + 17; //find the start of the mib section
//The MIB length is the length defined in the SNMP packet
// minus 1 to remove the ending .0, which is not used
int miblength = mibin[mibstart] - 1;
mibstart += 2; //skip over the length and 0x2b values
int mibvalue;
for(int i = mibstart; i < mibstart + miblength; i++)
{
mibvalue = Convert.ToInt16(mibin[i]);
if (mibvalue > 128)
{
mibvalue = (mibvalue/128)*128 + Convert.ToInt16(mibin[i+1]);
i++;
}
output += "." + mibvalue;
}
return output;
}
}
JSON (JavaScript Object Notation) Utility Methods.
using System.Collections.Generic;
using System.Text;
namespace Facebook.Utility
{
/// <summary>
/// JSON (JavaScript Object Notation) Utility Methods.
/// </summary>
public static class JSONHelper
{
///<summary>
/// Converts a Dictionary to a JSON-formatted Associative Array.
///</summary>
///<param name="dict">Source Dictionary collection [string|string].</param>
///<returns>JSON Associative Array string.</returns>
public static string ConvertToJSONAssociativeArray(Dictionary<string, string> dict)
{
var elements = new List<string>();
foreach (var pair in dict)
{
if(!string.IsNullOrEmpty(pair.Value))
{
elements.Add(string.Format(""{0}":{2}{1}{2}", EscapeJSONString(pair.Key), EscapeJSONString(pair.Value), IsJSONArray(pair.Value) || IsBoolean(pair.Value) ? string.Empty : """));
}
}
return "{" + string.Join(",", elements.ToArray()) + "}";
}
/// <summary>
/// Determines if input string is a formatted JSON Array.
/// </summary>
/// <param name="test">string</param>
/// <returns>bool</returns>
public static bool IsJSONArray(string test)
{
return test.StartsWith("{") && !test.StartsWith("{*") || test.StartsWith("[");
}
/// <summary>
/// Determines if input string is a boolean value.
/// </summary>
/// <param name="test">string</param>
/// <returns>bool</returns>
public static bool IsBoolean(string test)
{
return test.Equals("false") || test.Equals("true");
}
/// <summary>
/// Converts a List collection of type string to a JSON Array.
/// </summary>
/// <param name="list">List of strings</param>
/// <returns>string</returns>
public static string ConvertToJSONArray(List<string> list)
{
if (list == null || list.Count == 0)
{
return "[]";
}
StringBuilder builder = new StringBuilder();
builder.Append("[");
foreach (var item in list)
{
builder.Append(string.Format("{0}{1}{0},", IsJSONArray(item) || IsBoolean(item) ? string.Empty : """, EscapeJSONString(item)));
}
builder.Replace(",", "]", builder.Length - 1, 1);
return builder.ToString();
}
/// <summary>
/// Converts a List collection of type long to a JSON Array.
/// </summary>
/// <param name="list">List of longs</param>
/// <returns>string</returns>
public static string ConvertToJSONArray(List<long> list)
{
if (list == null || list.Count == 0)
{
return "[]";
}
StringBuilder builder = new StringBuilder();
builder.Append("[");
foreach (var item in list)
{
builder.Append(string.Format("{0}{1}{0},", IsJSONArray(item.ToString()) || IsBoolean(item.ToString()) ? string.Empty : """, EscapeJSONString(item.ToString())));
}
builder.Replace(",", "]", builder.Length - 1, 1);
return builder.ToString();
}
/// <summary>
/// Converts a JSON Array string to a List collection of type string.
/// </summary>
/// <param name="array">JSON Array string</param>
/// <returns>List of strings</returns>
public static List<string> ConvertFromJSONArray(string array)
{
if (!string.IsNullOrEmpty(array))
{
array = array.Replace("[", "").Replace("]", "").Replace(""", "");
return new List<string>(array.Split(','));
}
return new List<string>();
}
/// <summary>
/// Converts a JSON Array string to a Dictionary collection of type string, string.
/// </summary>
/// <param name="array">JSON Array string</param>
/// <returns>Dictionary of string, string</returns>
public static Dictionary<string, string> ConvertFromJSONAssoicativeArray(string array)
{
var dict = new Dictionary<string, string>();
if (!string.IsNullOrEmpty(array))
{
array = array.Replace("{", "").Replace("}", "").Replace("":", "|").Replace(""", "").Replace("/", "/");
var pairs = new List<string>(array.Split(','));
foreach (var pair in pairs)
{
if (!string.IsNullOrEmpty(pair))
{
var pairArray = pair.Split('|');
dict.Add(pairArray[0], pairArray[1]);
}
}
return dict;
}
return new Dictionary<string, string>();
}
/// <summary>
/// Escape backslashes and double quotes of valid JSON content string.
/// </summary>
/// <param name="originalString">string</param>
/// <returns>string</returns>
public static string EscapeJSONString(string originalString)
{
return IsJSONArray(originalString) ? originalString : originalString.Replace("/", "/").Replace("/", "/").Replace(""", """).Replace(""", """).Replace("
", "
").Replace("
", "
");
}
}
}
IPHostEntry.HostName
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
//DnsLookup
class Program {
static void Main(string[] args) {
IPHostEntry ipHostEntry = Dns.GetHostEntry("www.google.com");
Console.WriteLine("Host: {0}", ipHostEntry.HostName);
if (ipHostEntry.Aliases.Length > 0) {
Console.WriteLine("
Aliases:");
foreach (string alias in ipHostEntry.Aliases) {
Console.WriteLine(alias);
}
}
Console.WriteLine("
Address(es):");
foreach (IPAddress address in ipHostEntry.AddressList) {
Console.WriteLine("Address: {0}", address.ToString());
}
}
}

