I have included the code from a second year project that I would like some advice on. Basically it utilises WMI to query a NIC card from a selection (depending how many are installed in the host machine) and shows various settings such as IP info, DHCP info etc. It also has a ping function.
How can I improve this to make it a more professional application? I'm looking for things like code structure, functionalities (bearing in mind mark 2 will have the ability to actually interact with the NIC to turn DHCP off and change addresses, plus I hope to incorporate a TRACERT function).
This project is now finished so I'm not cheating by asking this. I just want to take the step from creating a rough but working piece of code to a polished professional one.
The program is written in Visual Studio 2010.
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Management;
using System.Management.Instrumentation;
/////////////////////////////////////
using System.Net;
using System.Net.NetworkInformation;
using System.ComponentModel;
using System.Threading;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
private int pingsSent;
AutoResetEvent resetEvent = new AutoResetEvent(false);
public Form1()
{
{
InitializeComponent();
}
// win32 class
//http://msdn.microsoft.com/en-us/library/aa394216(v=vs.85).aspx
try
{
ManagementObjectSearcher query = new ManagementObjectSearcher(@"SELECT * FROM Win32_NetworkAdapter WHERE Manufacturer != 'Microsoft' AND NOT PNPDeviceID LIKE 'ROOT\\%'");
ManagementObjectCollection queryCollection = query.Get();
foreach (ManagementObject mo in queryCollection)
{
if (mo["MacAddress"] != null)
{
comboBox1.Items.Add(mo["Description"].ToString());
}
}
}
catch (Exception ex)
{
}
}
string[] availabilityArray = new string[] { "", "Other", "Unknown", "Running or Full Power", "Warning", "In Test", "Not Applicable", "Power Off", "Off Line", "Off Duty", "Degraded", "Not Installed", "Install Error", "Power Save - Unknown" + "\n" + "The device is known to be in a power save state, but its exact status is unknown.", "Power Save - Low Power Mode" + "/n" + "The device is in a power save state, but still functioning, and may exhibit degraded performance.", "Power Save - Standby" + "/n" + "The device is not functioning, but could be brought to full power quickly.", "Power Cycle", "Power Save - Warning" + "/n" + "The device is in a warning state, though also in a power save state.", };
string[] errorArray = new string[] { "Device is working properly.", "Device is not configured correctly.", "Windows cannot load the driver for this device.", "Driver for this device might be corrupted, or the system may be low on memory or other resources.", "Device is not working properly. One of its drivers or the registry might be corrupted.", "Driver for the device requires a resource that Windows cannot manage.", "Boot configuration for the device conflicts with other devices.", "Cannot filter.", "Driver loader for the device is missing.", "Device is not working properly. The controlling firmware is incorrectly reporting the resources for the device.", "Device cannot start.", "Device failed.", "Device cannot find enough free resources to use.", "Windows cannot verify the device's resources.", "Device cannot work properly until the computer is restarted.", "Device is not working properly due to a possible re-enumeration problem.", "Windows cannot identify all of the resources that the device uses.", "Device is requesting an unknown resource type.", "Device drivers must be reinstalled.", "Failure using the VxD loader.", "Registry might be corrupted.", "System failure. If changing the device driver is ineffective, see the hardware documentation. Windows is removing the device.", "Device is disabled.", "System failure. If changing the device driver is ineffective, see the hardware documentation.", "Device is not present, not working properly, or does not have all of its drivers installed.", "Windows is still setting up the device.", "Windows is still setting up the device.", "Device does not have valid log configuration.", "Device drivers are not installed", "Device is disabled. The device firmware did not provide the required resources.", "Device is using an IRQ resource that another device is using.", "Device is not working properly. Windows cannot load the required device drivers.", };
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
ManagementObjectSearcher intquery = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'");
ManagementObjectCollection queryCollection = intquery.Get();
foreach (ManagementObject mo in queryCollection)
{
string Dev = (mo["DeviceID"].ToString());
txtMacAdd.Text = (" " + mo["MacAddress"].ToString());
TxtAdapter.Text = (" " + mo["AdapterType"].ToString());
txtAvailability.Text = (" " + mo["Availability"].ToString());
txtCaption.Text = (" " + mo["Caption"].ToString());
txtDeviceID.Text = (" " + mo["DeviceID"].ToString());
txtErrorCode.Text = (mo["ConfigManagerErrorCode"].ToString());
ManagementObjectSearcher intquery1 = new ManagementObjectSearcher("ASSOCIATORS OF {Win32_NetworkAdapter.DeviceID='" + Dev + "'}WHERE ResultClass=Win32_NetworkAdapterConfiguration");
ManagementObjectCollection queryCollection1 = intquery1.Get();
queryCollection1 = intquery1.Get();
foreach (ManagementObject mo1 in queryCollection1)
{
string[] addresses = (string[])mo1["IPAddress"];
string[] gateways = (string[])mo1["DefaultIPGateway"];
string[] Subnets = (string[])mo1["IPSubnet"];
foreach (string ipaddress in addresses)
{
listIp.Items.Add(ipaddress);
}
foreach (string gateway in gateways)
{
TxtGateway.Text = (gateway);
}
foreach (string subnet in Subnets)
{
listSubnet.Items.Add(subnet);
}
/////// SHOW DCHP CONFIG/////////
if ((bool)mo1["DHCPEnabled"] == true)
{
checkBox1.Checked = true;
}
if ((bool)mo1["DHCPEnabled"] != true)
{
checkBox1.Checked = !true;
}
DateTime dt = System.Management.ManagementDateTimeConverter.ToDateTime(mo1["DHCPLeaseExpires"].ToString());
txtDHCPExpires.Text = dt.ToString();
DateTime dte = System.Management.ManagementDateTimeConverter.ToDateTime(mo1["DHCPLeaseObtained"].ToString());
txtDHCPObtained.Text = dte.ToString();
txtDHCPServer.Text = (mo1["DHCPServer"].ToString());
//////////////////////Security////////////////////////////
if ((bool)mo1["IPFilterSecurityEnabled"] == true)
{
chkboxIPFilter.Checked = true;
}
if ((bool)mo1["IPFilterSecurityEnabled"] != true)
{
chkboxIPFilter.Checked = !true;
}
string[] IPSecProtocols = (string[])mo1["IPSecPermitIPProtocols"];
string[] IPSecPermitTCPPorts = (string[])mo1["IPSecPermitTCPPorts"];
string[] IPSecPermitUDPPorts = (string[])mo1["IPSecPermitUDPPorts"];
foreach (string IPSecProtocol in IPSecProtocols)
{
//richTextBox1.AppendText(IPSecProtocol);
listPermitIP.Items.Add(IPSecProtocol);
}
foreach (string TCPPort in IPSecPermitTCPPorts)
{
listPermitTCP.Items.Add(TCPPort);
}
foreach (string UDPPort in IPSecPermitUDPPorts)
{
listPermitUDP.Items.Add(UDPPort);
}
///////////////////DNS/////////////////////////////
try
{
txtDNSDomain.Text = (mo1["DNSDomain"].ToString());
txtDNShostName.Text = (mo1["DNSHostName"].ToString());
string[] DNSDomainSuffSearch = (string[])mo1["DNSDomainSuffixSearchOrder"];
string[] DNSServerSearchOrder = (string[])mo1["DNSServerSearchOrder"];
foreach (string domainSuff in DNSDomainSuffSearch)
{
listDomainSuffSearchOrder.Items.Add(domainSuff);
}
foreach (string DNSServer in DNSServerSearchOrder)
{
listDNSServerSearchOrder.Items.Add(DNSServer);
}
if ((bool)mo1["DNSEnabledForWINSResolution"] == true)
{
chkDNSWinsResolution.Checked = true;
}
if ((bool)mo1["DNSEnabledForWINSResolution"] != true)
{
chkDNSWinsResolution.Checked = !true;
}
if ((bool)mo1["DomainDNSRegistrationEnabled"] == true)
{
chkDNSRegEnabled.Checked = true;
}
if ((bool)mo1["DomainDNSRegistrationEnabled"] != true)
{
chkDNSRegEnabled.Checked = !true;
}
}
catch (Exception ex3)
{ }
}
}
}
private void button2_Click(object sender, EventArgs e)
{
try
{
ManagementObjectSearcher intquery;
intquery = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'");
ManagementObjectCollection queryCollection = intquery.Get();
queryCollection = intquery.Get();
foreach (ManagementObject mo in queryCollection)
{
string thisstring = (mo["ConfigManagerErrorCode"].ToString());
int error;
int.TryParse(thisstring, out error);
MessageBox.Show(errorArray[error]);
}
}
catch (Exception ex1)
{
MessageBox.Show("Please Select a Device");
}
}
private void BtnAvailability_Click(object sender, EventArgs e)
{
try
{
ManagementObjectSearcher intquery;
intquery = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'");
ManagementObjectCollection queryCollection = intquery.Get();
queryCollection = intquery.Get();
foreach (ManagementObject mo in queryCollection)
{
string thisstring = (mo["Availability"].ToString());
int Avail;
int.TryParse(thisstring, out Avail);
MessageBox.Show(availabilityArray[Avail]);
}
}
catch (Exception ex2)
{
MessageBox.Show("Please Select a Device");
}
}
private void btnPing_Click(object sender, EventArgs e)
{
// Reset the number of pings
pingsSent = 0;
// Clear the textbox of any previous content
txtResponse.Clear();
txtResponse.Text += "Pinging " + txtIP.Text + " with 32 bytes of data:\r\n\r\n";
// Send the ping
SendPing();
}
private void SendPing()
{
System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping();
// Create an event handler for ping complete
pingSender.PingCompleted += new PingCompletedEventHandler(pingSender_Complete);
// Create a buffer of 32 bytes of data to be transmitted.
byte[] packetData = Encoding.ASCII.GetBytes("................................");
// Jump though 50 routing nodes tops, and don't fragment the packet
PingOptions packetOptions = new PingOptions(50, true);
// Send the ping asynchronously
pingSender.SendAsync(txtIP.Text, 5000, packetData, packetOptions, resetEvent);
}
private void pingSender_Complete(object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
txtResponse.Text += "Ping was canceled...\r\n";
// The main thread can resume
((AutoResetEvent)e.UserState).Set();
}
else if (e.Error != null)
{
txtResponse.Text += "An error occured: " + e.Error + "\r\n";
// The main thread can resume
((AutoResetEvent)e.UserState).Set();
}
else
{
PingReply pingResponse = e.Reply;
// Call the method that displays the ping results, and pass the information with it
ShowPingResults(pingResponse);
}
}
public void ShowPingResults(PingReply pingResponse)
{
if (pingResponse == null)
{
// We got no response
txtResponse.Text += "There was no response.\r\n\r\n";
return;
}
else if (pingResponse.Status == IPStatus.Success)
{
// We got a response, let's see the statistics
txtResponse.Text += "Reply from " + pingResponse.Address.ToString() + ": bytes=" + pingResponse.Buffer.Length + " time=" + pingResponse.RoundtripTime + " TTL=" + pingResponse.Options.Ttl + "\r\n";
}
else
{
// The packet didn't get back as expected, explain why
txtResponse.Text += "Ping was unsuccessful: " + pingResponse.Status + "\r\n\r\n";
}
// Increase the counter so that we can keep track of the pings sent
string strpings = txtNumPackets.Text;
int numbpings = int.Parse(strpings);
if (txtNumPackets.Text == null)
{
numbpings = 4;
}
pingsSent++;
// Send 4 pings
if (pingsSent < numbpings)
{
SendPing();
}
}
private void panel2_Paint(object sender, PaintEventArgs e)
{
}
//////////////////////////////////////////////////////////////////////////////////////////
}
}