Syed Jahanzaib Personal Blog to Share Knowledge !

April 27, 2017

iBBi Switcher – Cisco Management Tool

Filed under: Cisco Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 4:29 PM


iBBi Switcher – Cisco Monitoring Tool

This is another application I made in C# using Visual Studio 2012. I generally use Cisco Configuration Assistant tool to Manage/Monitor our Cisco switches. Its great , works flawlessly, but still sometimes I need some thing quick to just monitor port status without  using full sized apps , above all the biggest advantage for our local environment is that I can give this app to local support staff and technician easily without giving them any further access to any panel.

Development is Powerful & Fun as well ~

Functions:

This app uses SNMPSHARPNET  library to query remove device by SNMP. It performs following actions …

  • Once Start button is pressed, It will first check if remote device or its SNMP is responding, if not give error (without freezing User Interface), If Response is OK, then continue further
  • Query all 24 ports with there description dynamically, Update the labels and Up/Down image according to the status.
  • Update Timer Label to see when last update on ports were made
  • Strip Menu for info/Exit Function.
  • Exit button on top right corner to exit the app immediately
  • Display progress bar to indicate process is active
  • Display CPU progress bar with temperature as well
  • Once START button is pushed, disable it to prevent duplication, added error as well.
  • STOP button to stop monitoring and timer and revert labels/images to default.
  • In Status Box window, display any ports UP / DOWN Status As showed in the image below

port down


the Code:

First download SNMPSHARPNET library and import it.

// C# / VS2012
// This is another application I made in C# using Visual Studio 2012.
// I generally use Cisco Configuration Assistant tool to Manage/Monitor our Cisco switches.
// Its great , works flawlessly, but still sometimes I need some thing quick to just monitor port status without using full sized apps
// above all the biggest advantage for our local environment is that I can give this app to local support staff and technician easily
// without giving them any further access to any panel.
// Make sure to download the SNMPSHARPNET library before using this code.
// Syed Jahanzaib
// aacable at hotmail dot com
// http:// aacable dot wordpress dot com
// 27-April-2017
using System;
using System.Net;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using SnmpSharpNet;
using System.Threading.Tasks;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public class Globals
{
public static string P1 = "";
public static string P2 = "";
public static string P3 = "";
public static string P4 = "";
public static string P5 = "";
public static string P6 = "";
public static string P7 = "";
public static string P8 = "";
public static string P9 = "";
public static string P10 = "";
public static string P11 = "";
public static string P12 = "";
public static string P13 = "";
public static string P14 = "";
public static string P15 = "";
public static string P16 = "";
public static string P17 = "";
public static string P18 = "";
public static string P19 = "";
public static string P20 = "";
public static string P21 = "";
public static string P22 = "";
public static string P23 = "";
public static string P24 = "";
public static string PL1 = "";
public static string PL2 = "";
public static string PL3 = "";
public static string PL4 = "";
public static string PL5 = "";
public static string PL6 = "";
public static string PL7 = "";
public static string PL8 = "";
public static string PL9 = "";
public static string PL10 = "";
public static string PL11 = "";
public static string PL12 = "";
public static string PL13 = "";
public static string PL14 = "";
public static string PL15 = "";
public static string PL16 = "";
public static string PL17 = "";
public static string PL18 = "";
public static string PL19 = "";
public static string PL20 = "";
public static string PL21 = "";
public static string PL22 = "";
public static string PL23 = "";
public static string PL24 = "";
public static string CPU = "";
public static string TEMPER = "";

}
public Form1()
{
InitializeComponent();
timer1.Stop();
timer1.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
portReset();
datelabel.Text = DateTime.Now.ToLongDateString();
timelabel.Text = DateTime.Now.ToLongTimeString();
}
private void portReset()
{
port1.Image = Properties.Resources.port_nostatus;
port2.Image = Properties.Resources.port_nostatus;
port3.Image = Properties.Resources.port_nostatus;
port4.Image = Properties.Resources.port_nostatus;
port5.Image = Properties.Resources.port_nostatus;
port6.Image = Properties.Resources.port_nostatus;
port7.Image = Properties.Resources.port_nostatus;
port8.Image = Properties.Resources.port_nostatus;
port9.Image = Properties.Resources.port_nostatus;
port10.Image = Properties.Resources.port_nostatus;
port11.Image = Properties.Resources.port_nostatus;
port12.Image = Properties.Resources.port_nostatus;
port13.Image = Properties.Resources.port_nostatus;
port14.Image = Properties.Resources.port_nostatus;
port15.Image = Properties.Resources.port_nostatus;
port16.Image = Properties.Resources.port_nostatus;
port17.Image = Properties.Resources.port_nostatus;
port18.Image = Properties.Resources.port_nostatus;
port19.Image = Properties.Resources.port_nostatus;
port20.Image = Properties.Resources.port_nostatus;
port21.Image = Properties.Resources.port_nostatus;
port22.Image = Properties.Resources.port_nostatus;
port23.Image = Properties.Resources.port_nostatus;
port24.Image = Properties.Resources.port_nostatus;
p1textBox1.Text = null;
p2textBox1.Text = null;
p3textBox1.Text = null;
p4textBox1.Text = null;
p5textBox1.Text = null;
p6textBox1.Text = null;
p7textBox1.Text = null;
p8textBox1.Text = null;
p9textBox1.Text = null;
p10textBox1.Text = null;
p11textBox1.Text = null;
p12textBox1.Text = null;
p13textBox1.Text = null;
p14textBox1.Text = null;
p15textBox1.Text = null;
p16textBox1.Text = null;
p17textBox1.Text = null;
p18textBox1.Text = null;
p19textBox1.Text = null;
p20textBox1.Text = null;
p21textBox1.Text = null;
p22textBox1.Text = null;
p23textBox1.Text = null;
p24textBox1.Text = null;
plabel1.Text = null;
plabel2.Text = null;
plabel3.Text = null;
plabel4.Text = null;
plabel5.Text = null;
plabel6.Text = null;
plabel7.Text = null;
plabel8.Text = null;
plabel9.Text = null;
plabel10.Text = null;
plabel11.Text = null;
plabel12.Text = null;
plabel13.Text = null;
plabel14.Text = null;
plabel15.Text = null;
plabel16.Text = null;
plabel17.Text = null;
plabel18.Text = null;
plabel19.Text = null;
plabel20.Text = null;
plabel21.Text = null;
plabel22.Text = null;
plabel23.Text = null;
plabel24.Text = null;
cpulabel.Text = null;

StatusTextBox1.Text = String.Empty;
this.statusLoadinBar.Image = null;
}
private async void snmpGetFunc()
{
timer1.Enabled = true;
this.Invoke((MethodInvoker)delegate
{
lastUpdateLabel.Text = "Last Updated @" + DateTime.Now.ToLongDateString() + DateTime.Now.ToLongTimeString();
});
OctetString community = new OctetString("PUBLIC");
AgentParameters param = new AgentParameters(community);
param.Version = SnmpVersion.Ver2;
IpAddress agent = new IpAddress("10.0.0.1");
UdpTarget target = new UdpTarget((IPAddress)agent, 161, 1000, 1);
Pdu pdu = new Pdu(PduType.Get);
// Make SNMP request to test if device is responding or not
try
{
//Query Switch name, just for testing if SNMP/Device is reponding or NOT : ~ D / zaib
//pdu.VbList.Add(".1.3.6.1.2.1.1.5.0");
SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
}
catch (SnmpException ex)
{
this.Invoke((MethodInvoker)delegate
{
this.StatusTextBox1.AppendText("\r\n" + ex.Message + "Either Device or SNMP not responding. Retrying again ...");
});
target.Dispose();
return;
}
if (timer1.Enabled == true)
{
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10101");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10102");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10103");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10104");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10105");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10106");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10107");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10108");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10109");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10110");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10111");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10112");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10113");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10114");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10115");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10116");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10117");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10118");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10119");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10120");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10121");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10122");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10123");
pdu.VbList.Add("1.3.6.1.2.1.2.2.1.8.10605");
// Ports End
// Now quering switch port names related data
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10101");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10102");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10103");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10104");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10105");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10106");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10107");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10108");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10109");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10110");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10111");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10112");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10113");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10114");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10115");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10116");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10117");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10118");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10119");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10120");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10121");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10122");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10123");
pdu.VbList.Add("1.3.6.1.2.1.31.1.1.1.18.10605");
// CPU Usage
pdu.VbList.Add("1.3.6.1.4.1.9.2.1.56.0");
// Temprature
pdu.VbList.Add("1.3.6.1.4.1.9.9.13.1.3.1.3.1006");
// Get all data by SNMP query
SnmpV2Packet result = (SnmpV2Packet)target.Request(pdu, param);
// End
// Update Global Variables that will be used for few other functions
Globals.P1 = result.Pdu.VbList[0].Value.ToString();
Globals.P2 = result.Pdu.VbList[1].Value.ToString();
Globals.P3 = result.Pdu.VbList[2].Value.ToString();
Globals.P4 = result.Pdu.VbList[3].Value.ToString();
Globals.P5 = result.Pdu.VbList[4].Value.ToString();
Globals.P6 = result.Pdu.VbList[5].Value.ToString();
Globals.P7 = result.Pdu.VbList[6].Value.ToString();
Globals.P8 = result.Pdu.VbList[7].Value.ToString();
Globals.P9 = result.Pdu.VbList[8].Value.ToString();
Globals.P10 = result.Pdu.VbList[9].Value.ToString();
Globals.P11 = result.Pdu.VbList[10].Value.ToString();
Globals.P12 = result.Pdu.VbList[11].Value.ToString();
Globals.P13 = result.Pdu.VbList[12].Value.ToString();
Globals.P14 = result.Pdu.VbList[13].Value.ToString();
Globals.P15 = result.Pdu.VbList[14].Value.ToString();
Globals.P16 = result.Pdu.VbList[15].Value.ToString();
Globals.P17 = result.Pdu.VbList[16].Value.ToString();
Globals.P18 = result.Pdu.VbList[17].Value.ToString();
Globals.P19 = result.Pdu.VbList[18].Value.ToString();
Globals.P20 = result.Pdu.VbList[19].Value.ToString();
Globals.P21 = result.Pdu.VbList[20].Value.ToString();
Globals.P22 = result.Pdu.VbList[21].Value.ToString();
Globals.P23 = result.Pdu.VbList[22].Value.ToString();
Globals.P24 = result.Pdu.VbList[23].Value.ToString();
Globals.PL1 = result.Pdu.VbList[24].Value.ToString();
Globals.PL2 = result.Pdu.VbList[25].Value.ToString();
Globals.PL3 = result.Pdu.VbList[26].Value.ToString();
Globals.PL4 = result.Pdu.VbList[27].Value.ToString();
Globals.PL5 = result.Pdu.VbList[28].Value.ToString();
Globals.PL6 = result.Pdu.VbList[29].Value.ToString();
Globals.PL7 = result.Pdu.VbList[30].Value.ToString();
Globals.PL8 = result.Pdu.VbList[31].Value.ToString();
Globals.PL9 = result.Pdu.VbList[32].Value.ToString();
Globals.PL10 = result.Pdu.VbList[33].Value.ToString();
Globals.PL11 = result.Pdu.VbList[34].Value.ToString();
Globals.PL12 = result.Pdu.VbList[35].Value.ToString();
Globals.PL13 = result.Pdu.VbList[36].Value.ToString();
Globals.PL14 = result.Pdu.VbList[37].Value.ToString();
Globals.PL15 = result.Pdu.VbList[38].Value.ToString();
Globals.PL16 = result.Pdu.VbList[39].Value.ToString();
Globals.PL17 = result.Pdu.VbList[40].Value.ToString();
Globals.PL18 = result.Pdu.VbList[41].Value.ToString();
Globals.PL19 = result.Pdu.VbList[42].Value.ToString();
Globals.PL20 = result.Pdu.VbList[43].Value.ToString();
Globals.PL21 = result.Pdu.VbList[44].Value.ToString();
Globals.PL22 = result.Pdu.VbList[45].Value.ToString();
Globals.PL23 = result.Pdu.VbList[46].Value.ToString();
Globals.PL24 = result.Pdu.VbList[47].Value.ToString();
Globals.CPU = result.Pdu.VbList[48].Value.ToString();
Globals.TEMPER = result.Pdu.VbList[49].Value.ToString();
this.Invoke((MethodInvoker)delegate
{
//Update Port Description / Names Text Labels
plabel1.Text = Globals.PL1;
plabel2.Text = Globals.PL2;
plabel3.Text = Globals.PL3;
plabel4.Text = Globals.PL4;
plabel5.Text = Globals.PL5;
plabel6.Text = Globals.PL6;
plabel7.Text = Globals.PL7;
plabel8.Text = Globals.PL8;
plabel9.Text = Globals.PL9;
plabel10.Text = Globals.PL10;
plabel11.Text = Globals.PL11;
plabel12.Text = Globals.PL12;
plabel13.Text = Globals.PL13;
plabel14.Text = Globals.PL14;
plabel15.Text = Globals.PL15;
plabel16.Text = Globals.PL16;
plabel17.Text = Globals.PL17;
plabel18.Text = Globals.PL18;
plabel19.Text = Globals.PL19;
plabel20.Text = Globals.PL20;
plabel21.Text = Globals.PL21;
plabel22.Text = Globals.PL22;
plabel23.Text = Globals.PL23;
plabel24.Text = Globals.PL24;
cpulabel.Text = Globals.CPU + " %";
temper_label.Text = Globals.TEMPER + "c";

int cpuint = Int32.Parse(Globals.CPU);
progressBar1.Value = cpuint;

//});
if (Globals.P1 == "1")
{
port1.Image = Properties.Resources.port_up;
p1textBox1.Text = Globals.P1;
}
else
{
port1.Image = Properties.Resources.port_down;
}
if (Globals.P2 == "1")
{
port2.Image = Properties.Resources.port_up;
p2textBox1.Text = Globals.P2;
}
else
{
port2.Image = Properties.Resources.port_down;
}
if (Globals.P3 == "1")
{
port3.Image = Properties.Resources.port_up;
p3textBox1.Text = Globals.P3;
}
else
{
port3.Image = Properties.Resources.port_down;
}
if (Globals.P4 == "1")
{
port4.Image = Properties.Resources.port_up;
p4textBox1.Text = Globals.P4;
}
else
{
port4.Image = Properties.Resources.port_down;
}
if (Globals.P5 == "1")
{
port5.Image = Properties.Resources.port_up;
p5textBox1.Text = Globals.P5;
}
else
{
port5.Image = Properties.Resources.port_down;
}
if (Globals.P6 == "1")
{
port6.Image = Properties.Resources.port_up;
p6textBox1.Text = Globals.P6;
}
else
{
port6.Image = Properties.Resources.port_down;
}
if (Globals.P7 == "1")
{
port7.Image = Properties.Resources.port_up;
}
else
{
port7.Image = Properties.Resources.port_down;
}
if (Globals.P8 == "1")
{
port8.Image = Properties.Resources.port_up;
}
else
{
port8.Image = Properties.Resources.port_down;
}
if (Globals.P9 == "1")
{
port9.Image = Properties.Resources.port_up;
}
else
{
port9.Image = Properties.Resources.port_down;
}
if (Globals.P10 == "1")
{
port10.Image = Properties.Resources.port_up;
}
else
{
port10.Image = Properties.Resources.port_down;
}
if (Globals.P11 == "1")
{
port11.Image = Properties.Resources.port_up;
}
else
{
port11.Image = Properties.Resources.port_down;
}
if (Globals.P12 == "1")
{
port12.Image = Properties.Resources.port_up;
}
else
{
port12.Image = Properties.Resources.port_down;
}
if (Globals.P13 == "1")
{
port13.Image = Properties.Resources.port_up;
}
else
{
port13.Image = Properties.Resources.port_down;
}
if (Globals.P14 == "1")
{
port14.Image = Properties.Resources.port_up;
}
else
{
port14.Image = Properties.Resources.port_down;
}
if (Globals.P15 == "1")
{
port15.Image = Properties.Resources.port_up;
}
else
{
port15.Image = Properties.Resources.port_down;
}
if (Globals.P16 == "1")
{
port16.Image = Properties.Resources.port_up;
}
else
{
port16.Image = Properties.Resources.port_down;
}
if (Globals.P17 == "1")
{
port17.Image = Properties.Resources.port_up;
}
else
{
port17.Image = Properties.Resources.port_down;
}
if (Globals.P18 == "1")
{
port18.Image = Properties.Resources.port_up;
}
else
{
port18.Image = Properties.Resources.port_down;
}
if (Globals.P19 == "1")
{
port19.Image = Properties.Resources.port_up;
}
else
{
port19.Image = Properties.Resources.port_down;
}
if (Globals.P20 == "1")
{
port20.Image = Properties.Resources.port_up;
}
else
{
port20.Image = Properties.Resources.port_down;
}
if (Globals.P21 == "1")
{
port21.Image = Properties.Resources.port_up;
}
else
{
port21.Image = Properties.Resources.port_down;
}
if (Globals.P22 == "1")
{
port22.Image = Properties.Resources.port_up;
}
else
{
port22.Image = Properties.Resources.port_down;
}
if (Globals.P23 == "1")
{
port23.Image = Properties.Resources.port_up;
}
else
{
port23.Image = Properties.Resources.port_down;
}
if (Globals.P24 == "1")
{
port24.Image = Properties.Resources.port_up;
p24textBox1.Text = Globals.P24;
}
else
{
port24.Image = Properties.Resources.port_down;
p24textBox1.Text = Globals.P24;
}
});
ClearTextBox1TimeOnly();
}
}
private static bool isRun = false;
private static readonly object syncLock = new object();
public void ClearTextBox1TimeOnly()
{
lock (syncLock)
{
if (!isRun)
{
this.Invoke((MethodInvoker)delegate
{
StatusTextBox1.Text = String.Empty;
this.StatusTextBox1.Text += string.Format("Starting monitoring of Cisco Switch Ports. Activated [5 sec delay] ... \r\n");
});
isRun = true;
}
}
}
// Start the app. start button
private async void button1_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
this.StatusTextBox1.Text += string.Format("Monitoring already started. Stop it to first to start new instance !\r\n");
}
else
{
startButton.Enabled = false;
isRun = false;
timer1.Enabled = true;
timer1.Start();
this.statusLoadinBar.Image = Properties.Resources.loading_gif;
//await Task.Run(() =>
//{
//await Task.Run(() => snmpGetFunc();
//});
Task.Factory.StartNew(() => snmpGetFunc());
this.StatusTextBox1.Text += string.Format("Starting monitoring of Cisco Switch Ports. \r\n");
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void timer4dt_Tick(object sender, EventArgs e)
{
timelabel.Text = DateTime.Now.ToLongTimeString();
timer4dt.Start();
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void stopButton_Click(object sender, EventArgs e)
{
if (timer1.Enabled == true)
{
startButton.Enabled = true;
timer1.Enabled = false;
timer1.Stop();
portReset();
this.StatusTextBox1.AppendText("\r\nMonitoring of switch have been Stopped on user request \r\n");
}
else
{
this.StatusTextBox1.AppendText("\r\nMonitoring not started yet !\r\n");
startButton.Enabled = true;
}
}
private void timer1_Tick(object sender, EventArgs e)
{
Task.Factory.StartNew(() => snmpGetFunc());
}
private void exitButton_Click(object sender, EventArgs e)
{
this.statusLoadinBar.Image = null;
timer1.Stop();
portReset();
this.StatusTextBox1.AppendText("\r\nExiting on user request \r\n");
Application.Exit();
}
private void StatusTextBox1_TextChanged(object sender, EventArgs e)
{
StatusTextBox1.SelectionStart = StatusTextBox1.Text.Length;
StatusTextBox1.ScrollToCaret();
}
private void p1textBox1_TextChanged(object sender, EventArgs e)
{
if (Globals.P1 == "1")
this.StatusTextBox1.AppendText("\r\nPort 1 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 1 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

private void p2textBox1_TextChanged(object sender, EventArgs e)
{
if (Globals.P2 == "1")
this.StatusTextBox1.AppendText("\r\nPort 2 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 2 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

private void p3textBox1_TextChanged(object sender, EventArgs e)
{
if (Globals.P3 == "1")
this.StatusTextBox1.AppendText("\r\nPort 3 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 3 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

private void p4textBox1_TextChanged(object sender, EventArgs e)
{
if (Globals.P4 == "1")
this.StatusTextBox1.AppendText("\r\nPort 4 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 4 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

private void p5textBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P5 == "1")
this.StatusTextBox1.AppendText("\r\nPort 5 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 5 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p6textBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P6 == "1")
this.StatusTextBox1.AppendText("\r\nPort 6 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 6 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p7textBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P7 == "1")
this.StatusTextBox1.AppendText("\r\nPort 7 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 7 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p8textBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P8 == "1")
this.StatusTextBox1.AppendText("\r\nPort 8 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 8 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p9textBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P9 == "1")
this.StatusTextBox1.AppendText("\r\nPort 9 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 9 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p10textBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P10 == "1")
this.StatusTextBox1.AppendText("\r\nPort 10 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 10 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

private void p11textBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P11 == "1")
this.StatusTextBox1.AppendText("\r\nPort 11is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 11is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

private void p12TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P12 == "1")
this.StatusTextBox1.AppendText("\r\nPort 12 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 12 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

private void p13TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P13 == "1")
this.StatusTextBox1.AppendText("\r\nPort 13 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 13 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p14TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P14 == "1")
this.StatusTextBox1.AppendText("\r\nPort 14 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 14 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p15TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P15 == "1")
this.StatusTextBox1.AppendText("\r\nPort 15 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 15 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p17TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P17 == "1")
this.StatusTextBox1.AppendText("\r\nPort 17 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 17 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p18TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P18 == "1")
this.StatusTextBox1.AppendText("\r\nPort 18 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 18 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

private void p19TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P19 == "1")
this.StatusTextBox1.AppendText("\r\nPort 19 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 19 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p20TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P20 == "1")
this.StatusTextBox1.AppendText("\r\nPort 20 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 20 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p21TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P21 == "1")
this.StatusTextBox1.AppendText("\r\nPort 21 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 21 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p22TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P22 == "1")
this.StatusTextBox1.AppendText("\r\nPort 22 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 22 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}
private void p23TextBox1_TextChanged_1(object sender, EventArgs e)
{
if (Globals.P23 == "1")
this.StatusTextBox1.AppendText("\r\nPort 23 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 23 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

private void p24textBox1_TextChanged(object sender, EventArgs e)
{
if (Globals.P24 == "1")
this.StatusTextBox1.AppendText("\r\nPort 24 is now UP @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
else
this.StatusTextBox1.AppendText("\r\nPort 24 is now DOWN! @" + DateTime.Now.ToLongDateString() + " / " + DateTime.Now.ToLongTimeString());
}

}
}

Regard’s
Syed Jahanzaib

Advertisements

April 12, 2017

Short Notes for C#

Filed under: Programming — Tags: , , , , , — Syed Jahanzaib / Pinochio~:) @ 11:45 AM

Following are few snippets / tips for C# used in various applications I made for personnel usage.

 


Declare Global Variables


namespace WindowsFormsApplication3
{

public partial class Form1 : Form
{

public class Globals
{

// defining File name in a folder

public static string LISTFILEPATH = @"C:\temp\list.txt";

// defining General variable to hold any result

public static string NETSTATUS = "";
}


Check if app is already running, if yes, then inform accordingly and EXIT the app !


private void Form1_Load(object sender, EventArgs e)
{
Process aProcess = Process.GetCurrentProcess();
string aProcName = aProcess.ProcessName;
if (Process.GetProcessesByName(aProcName).Length > 1)
{

MessageBox.Show("This APP is already running. Close previously running instance first!", "This APP  App Already Running !",
MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Windows.Forms.Application.Exit();
Application.ExitThread();
Application.Exit();
}


Check for Folder / file, if not exists then create


// Check if directory exists
if (Directory.Exists(@"C:\temp\)"))
{
// IF IT EXISTS, DO NOTHING
}
else
// IF ITS NOT , CREATE IT
{
Directory.CreateDirectory(@"C:\temp\");
}
// IF IT EXISTS, DO NOTHING
if (File.Exists(Globals.LISTFILEPATH))
{
// Do nothing
}
else
// IF ITS NOT , CREATE IT
{
//File.Create(Globals.LISTFILEPATH);
using (StreamWriter sw = new StreamWriter(Globals.LISTFILEPATH, true))
{
//
}
}

Add some colors to your output text


// Some coloring fun
private void ColorRed()
{
StatusTextBox.SelectionColor = Color.Red;
}


Adding Bold Text


StatusTextBox.SelectionFont = new Font(StatusTextBox.Font, StatusTextBox.Font.Style | FontStyle.Bold);
this.StatusTextBox.AppendText("\r\n- Processing ...\r\n");
StatusTextBox.SelectionFont = new Font(StatusTextBox.Font, StatusTextBox.Font.Style | FontStyle.Regular);


Multiple IF Statement matching


if ((Globals.Variable1 == "0") && (Globals.Variable2 == "0"))

// then do this or that


Message Box with Warning sign & OK button

MessageBox.Show("Error on ping:", MessageBoxButtons.OK, MessageBoxIcon.Warning);

Running thread separately without hanging UI

await Task.Run(() =>
{

// your task

});
}

Testing Remote TCP Port Status

{
using(TcpClient tcpClient = new TcpClient())

try {
tcpClient.Connect("1.1.1.1", 80);
// Succeed OK ! show the result, you can update text box, variable etc anything of your choice

} catch (Exception) {
// FAILED ! show the result, you can update text box, variable etc anything of your choice
}
}

Getting Default Gateway(s) bypassing few types of interfaces


foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet);
{
if ((ni.Description.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Loopback", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Loopback", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Isatap", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Isatap", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Tunnel", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Tunnel", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Microsoft 6to4 Adapter", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Microsoft 6to4 Adapter", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

this.StatusTextBox.AppendText("\r\n" + ni.Name + "\r\n");
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
// Console.WriteLine(ip.Address.ToString());
this.StatusTextBox.AppendText("\r\n" + ip.Address.ToString() + "\r\n");
}
}
}
}


 ~iBBi – Pinger  ¯\_(ツ)_/¯   – Customized Ping App  for My 3 Kids ~

iBBi PINGER application code I made to continuously ping any remote host by ip or dns name, and output any error with some style colors and images. I made it for my kids who uses computers and occasionally my PTCL Evo gets hangs or internet stopped working and the kids have no idea whats going on this application runs in background and popup yellow or green icon and iconic message so kids can understand internet is not working. the task was very simple and it worked ok, but later I was bitten by an dangerous animal as known as ‘curiosity‘ which forcefully made to add do some late night testings to add/enhance some additional features which were totally useless or not required 😛 lol.

Following is unfinished product and contains some bugs as well. Still posting it as reference for myself , just in case I managed to burn my PC.


// iBBi Pinger program, small app that can ping remote host
// and shows any error in fancy style , colors, icons, trayicon notifications, etc etc
// April, 2017

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Windows.Forms;
using System.Net;
using System.Net.NetworkInformation;
using System.IO;
using System.Runtime.InteropServices;
using System.Net.Sockets;
using System.Reflection;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication3
{

public partial class Form1 : Form
{

public class Globals
{

public static string LISTFILEPATH = @"C:\temp\list.txt";
public static string DnsError = "0";
public static string currentNetStatus = "0";
public static string TCP_STATUS = "0";
public static string TCP_PORT = "80";
public static string GHOST = "";
public static string GOPING = "";
public static string PIP = "";
public static string LAN = "";
public static string NETSTATUS = "";
public static string DGW = "";
}

public Form1()
{
InitializeComponent();
Globals.NETSTATUS = "0";
StatusTextBox.SelectionColor = Color.Black;
pictureBox1.Image = null;
timer1.Stop();
timer2.Stop();
timer1.Enabled = false;
}
private void Form1_Load(object sender, EventArgs e)
{
Process aProcess = Process.GetCurrentProcess();
string aProcName = aProcess.ProcessName;
if (Process.GetProcessesByName(aProcName).Length > 1)
{

MessageBox.Show("Pinger is already running. Close previously running instance first!", "Pinger App Already Running !",
MessageBoxButtons.OK, MessageBoxIcon.Error);
System.Windows.Forms.Application.Exit();
Application.ExitThread();
Application.Exit();
}

// Check if directory exists
if (Directory.Exists(@"C:\temp\)"))
{
// Do nothing
}
else
{
Directory.CreateDirectory(@"C:\temp\");
}
if (File.Exists(Globals.LISTFILEPATH))
{
// Do nothing
}
else
{
//File.Create(Globals.LISTFILEPATH);
using (StreamWriter sw = new StreamWriter(Globals.LISTFILEPATH, true))
{
//
}
}
string[] lineOfContents = File.ReadAllLines(Globals.LISTFILEPATH);
foreach (var line in lineOfContents)
{
string[] tokens = line.Split(',');
if (!comboBox1.Items.Contains(tokens[0]))
comboBox1.Items.Add(tokens[0]);
}
}
// Some coloring fun
private void ColorRed()
{
this.Invoke((MethodInvoker)delegate
{
StatusTextBox.SelectionColor = Color.Red;
});
}
private void ColorBlack()
{
this.Invoke((MethodInvoker)delegate
{
StatusTextBox.SelectionColor = Color.Black;
});
}
private void ColorBlue()
{
StatusTextBox.SelectionColor = Color.Blue;
}
private void ColorGreen()
{
StatusTextBox.SelectionColor = Color.Green;
}
private void ColorOrange()
{
StatusTextBox.SelectionColor = Color.Orange;
}
private async void PingButton_Click(object sender, EventArgs e)
{
Globals.GOPING = "1";
pictureBox1.Image = null;
ProgressPictureBox1.Image = null;
Globals.GHOST = comboBox1.Text;
StatusTextBox.SelectionFont = new Font(StatusTextBox.Font, StatusTextBox.Font.Style | FontStyle.Bold);
this.StatusTextBox.AppendText("\r\n- Processing ...\r\n");
StatusTextBox.SelectionFont = new Font(StatusTextBox.Font, StatusTextBox.Font.Style | FontStyle.Regular);
if (!comboBox1.Text.Contains('.'))
{
ColorRed();
this.StatusTextBox.AppendText("\r\n" + "Somethign missing ! Please select or enter valid Hostname or IP address !\r\n");
ColorBlack();
return;
}

{
if (string.IsNullOrEmpty(comboBox1.Text) || (comboBox1.Text == "Seleact or type Destination"))
{
ColorRed();
this.StatusTextBox.AppendText("\r\n" + "Please select or enter valid Hostname or IP address !\r\n");
ColorBlack();
pictureBox1.Image = null;
return;
}
else
{
PingButton.Enabled = false;
PingButton.Text = "Pinging...";
// IsNetworkAvailable();
//if (Globals.LAN == "")
//{
//this.StatusTextBox.AppendText("\r\n-PINGBUTTON CHECK- LAN DISCONNECTED!\r\n");
// TIMER_STOP_FUNC();
//return;
// }

//else
//{
//this.StatusTextBox.AppendText("\r\n-LAN OK!\r\n");
//}

TIMER_START_FUNC();
}
}
}




private void OnApplicationExit(object sender, EventArgs e)
{
try
{
if (notifyIcon1 != null)
{
notifyIcon1.Visible = false;
notifyIcon1.Icon = null;
notifyIcon1.Dispose();
notifyIcon1 = null;
}
}
catch { }
}
private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
TIMER_STOP_FUNC();
notifyIcon1.Visible = false;
notifyIcon1.Icon = null;
notifyIcon1.Dispose();
notifyIcon1 = null;
Application.Exit();
}
private void menuStrip1_Click(object sender, EventArgs e)
{
}
private void menuStrip1_MouseClick(object sender, MouseEventArgs e)
{
this.Show();
WindowState = FormWindowState.Normal;
}
private void Form1_Move(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
if ((Globals.currentNetStatus == "0") && (Globals.TCP_STATUS == "0"))
{
this.notifyIcon1.Icon = Properties.Resources.icon_standby;
}
else
{
this.notifyIcon1.Icon = Properties.Resources.icon_online;
}
this.Hide();
}
}
private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
{
TIMER_STOP_FUNC();
notifyIcon1.Visible = false;
notifyIcon1.Icon = null;
notifyIcon1.Dispose();
notifyIcon1 = null;
Application.Exit();
}
private void StopPing_Click(object sender, EventArgs e)
{
this.notifyIcon1.Icon = Properties.Resources.icon_standby;
ProgressPictureBox1.Image = null;
pictureBox1.Image = null;
if (timer1.Enabled == false)
//if (!timer1.Enabled)
{
StatusTextBox.SelectionColor = Color.Red;
this.StatusTextBox.AppendText("\r\n" + "Ping is not running !\r\n");
StatusTextBox.SelectionColor = Color.Black;
}
if (timer1.Enabled == true)
{
TIMER_STOP_FUNC();
ColorBlue();
StatusTextBox.SelectionFont = new Font(StatusTextBox.Font, StatusTextBox.Font.Style | FontStyle.Bold);
this.StatusTextBox.AppendText("\r\n" + "Stopped on User Request !\r\n");
StatusTextBox.SelectionFont = new Font(StatusTextBox.Font, StatusTextBox.Font.Style | FontStyle.Regular);
ColorBlack();
this.notifyIcon1.Icon = Properties.Resources.icon_standby;
ProgressPictureBox1.Image = null;
PingButton.Enabled = true;
PingButton.Text = "Start Ping";
pictureBox1.Image = null;
}
}
//}
private void SaveComboList_Click(object sender, EventArgs e)
{
using (StreamWriter writer = new StreamWriter(Globals.LISTFILEPATH, true))
{
try
{
if (comboBox1.Items.Contains(comboBox1.Text))
{
MessageBox.Show("The task '" + comboBox1.Text + "' already exist in list", "Task already exists");
}
else
{
comboBox1.Items.Add(comboBox1.Text);
writer.WriteLine(comboBox1.Text);
writer.Flush();
writer.Dispose();
}
}
catch
{
MessageBox.Show("The file '" + comboBox1.Text + "' could not be located", "File could not be located");
}
}
}
private void exitToolStripMenuItem1_Click_1(object sender, EventArgs e)
{
TIMER_STOP_FUNC();
notifyIcon1.Visible = false;
notifyIcon1.Icon = null;
notifyIcon1.Dispose();
notifyIcon1 = null;
Application.Exit();
}
private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
private void exitToolStripMenuItem2_Click(object sender, EventArgs e)
{
TIMER_STOP_FUNC();
notifyIcon1.Visible = false;
notifyIcon1.Icon = null;
notifyIcon1.Dispose();
notifyIcon1 = null;
Application.Exit();
}
private void exitToolStripMenuItem3_Click(object sender, EventArgs e)
{
TIMER_STOP_FUNC();
notifyIcon1.Visible = false;
notifyIcon1.Icon = null;
notifyIcon1.Dispose();
notifyIcon1 = null;
Application.Exit();
}
private void restoreToolStripMenuItem_Click_1(object sender, EventArgs e)
{
this.Show();
WindowState = FormWindowState.Normal;
}

private void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(string.Format("Ping failed: {0}", e.Error.ToString()),
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
((AutoResetEvent)e.UserState).Set();
}
DisplayReply(e.Reply);
((AutoResetEvent)e.UserState).Set();
}
public void DisplayReply(PingReply reply)
{
if (timer1.Enabled)
{
string host = Globals.GHOST;
Ping ping = new Ping();
var pingSender = new Ping();
try
{
if (reply.Status == IPStatus.Success)
{
this.Invoke((MethodInvoker)delegate
{
ColorGreen();
this.StatusTextBox.AppendText(string.Format("{0}\r\n", reply.Status + " -- delay ms > " + reply.RoundtripTime.ToString() + " for > " + comboBox1.Text + " - " + Globals.PIP));
ColorBlack();
Globals.currentNetStatus = "1";
pictureBox1.Image = Properties.Resources.online_image;
this.notifyIcon1.Icon = Properties.Resources.icon_online;
});
}
else
{
Globals.currentNetStatus = "0";
Globals.TCP_STATUS = "0";
TestTCPConn();
this.textBox1.Text = Globals.currentNetStatus;
this.textBox2.Text = Globals.TCP_STATUS;
if ((Globals.currentNetStatus == "0") && (Globals.TCP_STATUS == "1"))
{
this.Invoke((MethodInvoker)delegate
{
this.StatusTextBox.AppendText(string.Format("\r\n Ping Timeout but PORT " + Globals.TCP_PORT + " responding > " + comboBox1.Text + " - " + Globals.PIP));
pictureBox1.Image = Properties.Resources.online_image;
});
//this.notifyIcon1.Icon = Properties.Resources.icon_online;
}
if ((Globals.currentNetStatus == "0") && (Globals.TCP_STATUS == "0"))
//}
if ((Globals.currentNetStatus == "0") && (Globals.TCP_STATUS == "0"))
if (timer1.Enabled)
{
this.Invoke((MethodInvoker)delegate
{
pictureBox1.Image = Properties.Resources.offline_image;
this.notifyIcon1.Icon = Properties.Resources.icon_standby;
this.StatusTextBox.AppendText(string.Format("PING + PORT test Failed > " + comboBox1.Text + " - " + Globals.PIP + "\r\n"));
});
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error on ping:" + ex.Message, "Error on ping!", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}

private void timer1_Tick(object sender, EventArgs e)
{
IsNetworkAvailable();
if (Globals.LAN == "")
{
this.StatusTextBox.AppendText("\r\n-Timer1_TICK Section: No Active Local Network Found. Exiting ...\r\n");
this.ProgressPictureBox1.Image = Properties.Resources.ProgressPictureBox1;
gdnslabel.Text = "Warning: LAN is disconnected ...";
Globals.currentNetStatus = "0";
Globals.TCP_STATUS = "0";
pictureBox1.Image = Properties.Resources.lan_disconnected;
//this.notifyIcon1.Icon = Properties.Resources.icon_standby;
return;
}
else
{
TestPInger();
}
}
protected void TIMER_STOP_FUNC()
{
comboBox1.Enabled = true;
Globals.PIP = "";
timer1.Stop();
timer2.Stop();
gdnslabel.Text = null;
timer1.Enabled = false;
ProgressPictureBox1.Image = null;
pictureBox1.Image = null;
PingButton.Enabled = true;
PingButton.Text = "Start Ping";
}
protected void TIMER_START_FUNC()
{
this.Invoke((MethodInvoker)delegate
{
comboBox1.Enabled = false;
PingButton.Enabled = false;
PingButton.Text = "Pinging ...";
ProgressPictureBox1.Image = Properties.Resources.ProgressPictureBox1;
timer1.Start();
//timer2.Start();
});
}
private static IPAddress GetIpFromHost(ref string host)
{
string errMessage = string.Empty;
IPAddress address = null;
try
{
address = Dns.GetHostByName(host).AddressList[0];
}
catch (SocketException ex)
{
}
return address;
}

private void RemoveList_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
File.Create(Globals.LISTFILEPATH).Close();
}
private void ExitImage_Click(object sender, EventArgs e)
{
TIMER_STOP_FUNC();
notifyIcon1.Visible = false;
notifyIcon1.Icon = null;
notifyIcon1.Dispose();
notifyIcon1 = null;
Application.Exit();
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
TIMER_STOP_FUNC();
Application.Exit();
}
private void pictureBox1_Click(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
timer1.Start();
}
private async void TestPInger()
{
//MessageBox.Show(Globals.LAN);
IsNetworkAvailable();
if (Globals.LAN == "")
{
this.StatusTextBox.AppendText("\r\n-Testpinger Section: No Active Local Network Found. Exiting ...\r\n");
this.ProgressPictureBox1.Image = Properties.Resources.ProgressPictureBox1;
gdnslabel.Text = "Warning: Disconnected ...";
Globals.currentNetStatus = "0";
Globals.TCP_STATUS = "0";
pictureBox1.Image = Properties.Resources.lan_disconnected;
//this.notifyIcon1.Icon = Properties.Resources.icon_standby;
return;
}
else
{
//gdnslabel.Text = "INFO: LAN is Connected.";
pictureBox1.Image = null;
}

CheckDGW();
if (Globals.DGW == "")
{
//this.StatusTextBox.AppendText("\r\n- testpinger - OOOOOOOOO No IPV4 Gateway found\r\n");
//TIMER_STOP_FUNC();
return;
}
else
{
//this.StatusTextBox.AppendText("\r\n- LAN Ok. proceeding further ...\r\n");
this.pictureBox1.Image = null;
}
{
await Task.Run(() =>
{
try
{
string host = Globals.GHOST;
int timeout = 1000;
var pingSender = new Ping();
AutoResetEvent waiter = new AutoResetEvent(false);
if (Globals.PIP == "")
{
IPAddress hostAddress = Dns.GetHostByName(host).AddressList[0];
Globals.PIP = hostAddress.ToString();
}
else
{
pingSender.PingCompleted += PingCompletedCallback;
pingSender.SendAsync(Globals.PIP, timeout, waiter);
}
}
catch (SocketException ex)
{
this.notifyIcon1.Icon = Properties.Resources.icon_standby;
this.Invoke((MethodInvoker)delegate
{
ColorRed();
this.StatusTextBox.AppendText("\r\n-DNS ERROR: unable to resolve > " + Globals.GHOST + " - Retrying in few seconds! \r\n");
ProgressPictureBox1.Image = Properties.Resources.ProgressPictureBox1;
pictureBox1.Image = Properties.Resources.dnsproblem_image;
Globals.currentNetStatus = "0";
Globals.TCP_STATUS = "0";
ColorBlack();
});
}
});
}
}
private void TestTCPConn()
{
using(TcpClient tcpClient = new TcpClient())

try {
tcpClient.Connect(Globals.GHOST, 80);
Globals.TCP_STATUS = "1";
} catch (Exception) {
Globals.TCP_STATUS = "0";
}
}
private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
}
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
Keys key = e.KeyCode;
if (key == Keys.Space)
{
e.Handled = true;
}
base.OnKeyDown(e);
}
private void comboBox1_Leave(object sender, EventArgs e)
{
string str = comboBox1.Text;
comboBox1.Text = str.Replace(" ", String.Empty);
//MessageBox.Show("Don't accept Space char in your name");
this.Focus();
}
private void StatusTextBox_TextChanged_1(object sender, EventArgs e)
{
StatusTextBox.SelectionStart = StatusTextBox.Text.Length;
StatusTextBox.ScrollToCaret();
}
public static class ThreadHelperClass
{
delegate void SetTextCallback(Form f, Control ctrl, string text);
public static void SetText(Form form, Control ctrl, string text)
{
if (ctrl.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
form.Invoke(d, new object[] { form, ctrl, text });
}
else
{
ctrl.Text += text;
}
}
}
private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
}
private void timer2_Tick(object sender, EventArgs e)
{
IsOnline();
if (timer1.Enabled)
// if ((Globals.currentNetStatus == "0") && (Globals.TCP_STATUS == "1"))
if (Globals.currentNetStatus == "1")
{
this.notifyIcon1.Icon = Properties.Resources.icon_online;
}
if (timer1.Enabled)
if (Globals.TCP_STATUS == "1")
{
this.notifyIcon1.Icon = Properties.Resources.icon_online;
}
if (timer1.Enabled)
if ((Globals.currentNetStatus == "0") && (Globals.TCP_STATUS == "0"))
{
this.notifyIcon1.Icon = Properties.Resources.icon_standby;
}
}
public static IPAddress GetDefaultGateway()
{
//IsNetworkAvailable();
IPAddress result = null;
var cards = NetworkInterface.GetAllNetworkInterfaces().ToList();
if (cards.Any())
{
foreach (var card in cards)
{
var props = card.GetIPProperties();
if (props == null)
continue;

var gateways = props.GatewayAddresses;
if (!gateways.Any())
continue;
var gateway =
gateways.FirstOrDefault(g => g.Address.AddressFamily.ToString() == "InterNetwork");
if (gateway == null)
continue;
result = gateway.Address;
MessageBox.Show(result.ToString());
//MessageBox.Show(result.ToString());
if (result == null)
//MessageBox.Show("NO GW");
MessageBox.Show(result.ToString());
break;
};
}
// var dgw = result.ToString();
// if (dgw == null)
MessageBox.Show(result.ToString());
return result;
}

public static bool IsNetworkAvailable()
{
return IsNetworkAvailable(0);
}

protected async void IsOnline()
{
IsNetworkAvailable();
if (Globals.LAN == "")
{
ColorRed();
this.StatusTextBox.AppendText("\r\\nIsNetworkAvailable section: WARNING: No Active Local Network Found.");
ColorBlack();
Globals.currentNetStatus = "0";
Globals.TCP_STATUS = "0";
//return;
}
else
{
CheckDGW();
if (Globals.LAN == "")
{
ColorRed();
this.StatusTextBox.AppendText("\r\nisnetworkavailable section: WARNING: No Active Local Network Found...");
ColorBlack();
Globals.currentNetStatus = "0";
Globals.TCP_STATUS = "0";
TIMER_STOP_FUNC();
}
else

if (Globals.DGW == "")
{
this.StatusTextBox.AppendText("\r\n-Error: Cannot continue without valid IPV4 Gateway! Please verify your network settings & make sure it is connected with working network.\r\n");
//TIMER_START_FUNC();
//zaib
return;
}

await Task.Run(() =>
{
{
{
if (Globals.LAN == "" | Globals.DGW == "")
return;
}
try
{
Ping x = new Ping();
PingReply reply = x.Send("8.8.8.8");
if (reply.Status == IPStatus.Success)
{
//return true;
Globals.NETSTATUS = "1";
this.Invoke((MethodInvoker)delegate
{
gdnslabel.Text = "INFO: Google DNS is reachable by ICMP protocol.";
});
}
else
{
//if host is not reachable.
// return false;
Globals.NETSTATUS = "0";
this.Invoke((MethodInvoker)delegate
{
gdnslabel.Text = "Warning: Google DNS is NOT reachable by ICMP protocol!";
});
}
}
catch (SocketException ex)
{
{
//this.notifyIcon1.Icon = Properties.Resources.icon_standby;
}
}
}
});
}
}

public static bool IsNetworkAvailable(long minimumSpeed)
{
//Form1 frm1 = new Form1();
if (!NetworkInterface.GetIsNetworkAvailable())
return false;
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if ((ni.OperationalStatus != OperationalStatus.Up) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Loopback) ||
// (ni.NetworkInterfaceType == NetworkInterfaceType.vir) ||
(ni.NetworkInterfaceType == NetworkInterfaceType.Tunnel))

continue;
if (ni.Speed < minimumSpeed)
continue;

if (ni.Description.Equals("Microsoft Loopback Adapter", StringComparison.OrdinalIgnoreCase))
continue;

if ((ni.Description.IndexOf("Network Bridge", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Network Bridge", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

if ((ni.Description.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

if ((ni.Description.IndexOf("Loopback", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Loopback", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

if ((ni.Description.IndexOf("Isatap", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Isatap", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

if ((ni.Description.IndexOf("Tunnel", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Tunnel", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

if ((ni.Description.IndexOf("Microsoft 6to4 Adapter", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Microsoft 6to4 Adapter", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
//MessageBox.Show("LAN FOUND");
Globals.LAN = "1";
//Form1 frm1 = new Form1();
//this.StatusTextBox.AppendText("\r\n- Section: LAN is ok ...\r\n");
return true;
}
//MessageBox.Show("LAN NOT FOUND");
Form1 frm1 = new Form1();
frm1.StatusTextBox.AppendText("\r\nIsNetworkAvailable(long minimumSpeed) Section: WARNING: No Active Local Network Found...");
frm1.StatusTextBox.AppendText("\r\n-Error: Cannot conitnue without valid IPV4 Gateway/! Please verify your network settings & make sure it is connected with working network.\r\n");
Globals.LAN = "0";
return false;

}

protected async void CheckDGW()
{
IPAddress result = null;
var cards = NetworkInterface.GetAllNetworkInterfaces().ToList();
if (cards.Any())
{
foreach (var card in cards)
{
var props = card.GetIPProperties();
if (props == null)
continue;

var gateways = props.GatewayAddresses;
if (!gateways.Any())
continue;
var gateway =
gateways.FirstOrDefault(g => g.Address.AddressFamily.ToString() == "InterNetwork");
if (gateway == null)
// Globals.DGW = "";
//this.StatusTextBox.AppendText("\r\n- No Network or IPV4 Gateway found. Cannot continue without them!\r\n");
//this.StatusTextBox.AppendText("if gw is null entry Your IPV4 Gateway is >" + Globals.DGW + "\r\n");
continue;

result = gateway.Address;
Globals.DGW = result.ToString();
// this.StatusTextBox.AppendText("Your IPV4 Gateway is >" + Globals.DGW + "\r\n");
break;
//MessageBox.Show("GATEWAY IS NULL2");
};
}
//if (Globals.DGW == "")
// ColorRed();
//this.StatusTextBox.AppendText("\r\n- No Network or IPV4 Gateway found. Cannot continue without them!\r\n");
//ColorBlack();
//return;
//return result;
var regx = new Regex("[:]");
if (regx.IsMatch(Globals.DGW))
{
this.StatusTextBox.AppendText("\r\n- ipv6 detected!\r\n");
MessageBox.Show("IPV6 detected");
Globals.DGW = "";
}
//MessageBox.Show(Globals.DGW);
if (Globals.DGW == "")
{

//this.StatusTextBox.AppendText("NULL Gateway >" + Globals.DGW + "\r\n");
//MessageBox.Show("GATEWAY IS NULL");
Globals.DGW = "";
// TIMER_STOP_FUNC();
//return;

}
else
{
//this.StatusTextBox.AppendText("Your IPV4 Gateway is >" + Globals.DGW + "\r\n");
}
}

private void button2_Click_2(object sender, EventArgs e)
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet);
{
if ((ni.Description.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Loopback", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Loopback", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Isatap", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Isatap", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Tunnel", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Tunnel", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Network Bridge", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Network Bridge", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

if ((ni.Description.IndexOf("Microsoft 6to4 Adapter", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Microsoft 6to4 Adapter", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

this.StatusTextBox.AppendText("\r\n" + ni.Name + "\r\n");
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
// Console.WriteLine(ip.Address.ToString());
this.StatusTextBox.AppendText("\r\n" + ip.Address.ToString() + "\r\n");
}
}
}
}

}

private void button1_Click(object sender, EventArgs e)
{
using (TcpClient tcpClient = new TcpClient())
{
try
{
tcpClient.Connect("dell.com", 80);
Console.WriteLine("Port open");
}
catch (Exception)
{
Console.WriteLine("Port closed");
}
}
}

private void button3_Click(object sender, EventArgs e)
{

}

private void button2_Click_1(object sender, EventArgs e)
{
foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces())
{
if (ni.NetworkInterfaceType == NetworkInterfaceType.Wireless80211 || ni.NetworkInterfaceType == NetworkInterfaceType.Ethernet);
{
if ((ni.Description.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Vmware", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Loopback", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Loopback", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Isatap", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Isatap", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Tunnel", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Tunnel", StringComparison.OrdinalIgnoreCase) >= 0))
continue;
if ((ni.Description.IndexOf("Network Bridge", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Network Bridge", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

if ((ni.Description.IndexOf("Microsoft 6to4 Adapter", StringComparison.OrdinalIgnoreCase) >= 0) ||
(ni.Name.IndexOf("Microsoft 6to4 Adapter", StringComparison.OrdinalIgnoreCase) >= 0))
continue;

this.StatusTextBox.AppendText("\r\n" + ni.Name + "\r\n");
foreach (UnicastIPAddressInformation ip in ni.GetIPProperties().UnicastAddresses)
{
if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
{
// Console.WriteLine(ip.Address.ToString());
this.StatusTextBox.AppendText("\r\n" + ip.Address.ToString() + "\r\n");
}
}
}
}

}

}

}

 

%d bloggers like this: