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");
}
}
}
}

}

}

}

 

March 30, 2017

C# Active Directory Management using custom built App!

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

c

This is just another reference example post, on how you can use C# code to connect with active directory in order to perform some basic tasks , using one window operation approach. It’s simple, fast, and works well enough to cater the OP requirements. You can add your own functions in it as required. You can use use/modify/redistribute this code freely. no obligations.

stackoverflow


Task:

A simple program which can display all Active Directory users in a Drop down List menu, and based on the selection, it can perform various actions like

  • Check Status of User
  • Disable Account
  • Enable Account
  • While preventing any access to Admin account(s)

Something like below …

logo

Requirements:

  • Target framework is 4.x. [Latest is good because of its extensive support for various  enormous operations.]
  • Reference of Active Directory Modules

To add refrence to proect, Goto PROJECTS > ADD REFERENCE  > FRAMEWORK

Add following …

  • System.DirectoryServices
  • System.DirectoryServices.ActiveDirectory
  • System.DirectoryServices.AccountManagement

reference.PNG

The program must be run via Administrator account or account with admin privileges

CODE:

Here is the full code. Based on this code, we can add many other functions, this is just for example purposes.

Form1.cs


// C# code to manage Active Directory functions
// like enable/disable user account via drop down menu list
// Syed Jahanzaib / aacable at hotmail dot com
// March, 2017
using System;
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.Windows.Forms;
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using System.DirectoryServices.AccountManagement;
using System.Configuration;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
new ToolTip().SetToolTip(comboBox1, "Click here to see user list");
}
private void button1_Click(object sender, EventArgs e)
{
String _ADUserName = comboBox1.Text; // <-- The textbox you enter your username?
if (string.IsNullOrEmpty(comboBox1.Text) || comboBox1.Text == "0")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Please Enter Username!\n\r");
return;
}
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, comboBox1.Text.Trim());
if (comboBox1.Text == "ADMIN1" | comboBox1.Text == "ADMIN2")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Dont get over smart. You are 'NOT' authorized to change admin accounts state!\n\r");
return;
}
if (user == null)
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - not found in AD!\n\r");
return;
}
if (user.Enabled == false)
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - User is already DISABLED.\n\r");
return;
}
if (user.Enabled == true)
DiableADUserUsingUserPrincipal(_ADUserName);
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - is now DISABLED.\n\r");
}
private static bool DiableADUserUsingUserPrincipal(string username)
{
try
{
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
(principalContext, username);
userPrincipal.Enabled = false;
userPrincipal.Save();
return true;
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
return false;
}
private static bool EnableADUserUsingUserPrincipal(string username)
{
try
{
PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
UserPrincipal userPrincipal = UserPrincipal.FindByIdentity
(principalContext, username);
userPrincipal.Enabled = true;
userPrincipal.Save();
return true;
}
catch (Exception ex)
{
//Console.WriteLine(ex.Message);
}
return false;
}
private void button2_Click(object sender, EventArgs e)
{
{
String _ADUserName = comboBox1.Text; // <-- The textbox you enter your username?
if (string.IsNullOrEmpty(comboBox1.Text) || comboBox1.Text == "0")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Please Enter Username!\n\r");
return;
}
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, comboBox1.Text.Trim());

if (comboBox1.Text == "ADMIN1" | comboBox1.Text == "ADMIN2")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Dont get over smart. You are 'NOT' authorized to change admin accounts state!\n\r");
return;
}
if (user == null)
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - not found in AD!\n\r");
return;
}
if (user.Enabled == true)
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - User is already ENABLED.\n\r");
return;
}
if (user.Enabled == false)
EnableADUserUsingUserPrincipal(_ADUserName);
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - is now ENABLED.\n\r");
}
}
private void UserStatusButton_Click(object sender, EventArgs e)

{
String _ADUserName = comboBox1.Text; // <-- The textbox you enter your username?
if (string.IsNullOrEmpty(comboBox1.Text) || comboBox1.Text == "0")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Please Enter Username!\n\r");
return;
}
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, comboBox1.Text.Trim());

if (comboBox1.Text == "ADMIN1" | comboBox1.Text == "ADMIN2")
{
this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Dont get over smart. You are 'NOT' authorized to change admin accounts state!\n\r");
return;
}
if (user.Enabled == true) this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Status is ENABLED.\n\r");
else this.StatusTextBox.AppendText("\r\n" + _ADUserName + " - Status is DISABLED.\n\r"); ;
}
private void Form1_Load(object sender, EventArgs e)
{
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
UserPrincipal qbeUser = new UserPrincipal(ctx);
PrincipalSearcher srch = new PrincipalSearcher(qbeUser);
foreach (var found in srch.FindAll())
{
UserPrincipal foundUser = found as UserPrincipal;
if (foundUser != null)
{
comboBox1.Items.Add(foundUser.SamAccountName);
}
}
}
private void linkLabel1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("https://aacable.wordpress.com");
}

private void comboBox1_MouseHover(object sender, EventArgs e)
{
//ToolTip tt = new ToolTip();
//tt.Show("Click here to see user list", this.comboBox1, 2000);
}
}
}
// Code Ends Here. Take Care

Form1.Designer.cs


namespace WindowsFormsApplication2
{
partial class Form1
{
///
<summary>
/// Required designer variable.
/// </summary>

private System.ComponentModel.IContainer components = null;

///
<summary>
/// Clean up any resources being used.
/// </summary>

/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

///
<summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>

private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.StatusTextBox = new System.Windows.Forms.TextBox();
this.UserStatusButton = new System.Windows.Forms.Button();
this.comboBox1 = new System.Windows.Forms.ComboBox();
this.linkLabel1 = new System.Windows.Forms.LinkLabel();
this.pictureBox1 = new System.Windows.Forms.PictureBox();
this.toolTip1 = new System.Windows.Forms.ToolTip(this.components);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit();
this.SuspendLayout();
//
// button1
//
this.button1.Location = new System.Drawing.Point(157, 70);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(88, 23);
this.button1.TabIndex = 0;
this.button1.Text = "Disable User";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Location = new System.Drawing.Point(157, 41);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(88, 23);
this.button2.TabIndex = 2;
this.button2.Text = "Enable User";
this.button2.UseVisualStyleBackColor = true;
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// StatusTextBox
//
this.StatusTextBox.BackColor = System.Drawing.Color.Black;
this.StatusTextBox.Cursor = System.Windows.Forms.Cursors.Arrow;
this.StatusTextBox.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.StatusTextBox.ForeColor = System.Drawing.SystemColors.Window;
this.StatusTextBox.Location = new System.Drawing.Point(263, 12);
this.StatusTextBox.Margin = new System.Windows.Forms.Padding(1);
this.StatusTextBox.Multiline = true;
this.StatusTextBox.Name = "StatusTextBox";
this.StatusTextBox.ReadOnly = true;
this.StatusTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.StatusTextBox.Size = new System.Drawing.Size(276, 216);
this.StatusTextBox.TabIndex = 3;
this.StatusTextBox.Text = "Status Box ...";
//
// UserStatusButton
//
this.UserStatusButton.Location = new System.Drawing.Point(157, 12);
this.UserStatusButton.Name = "UserStatusButton";
this.UserStatusButton.Size = new System.Drawing.Size(88, 23);
this.UserStatusButton.TabIndex = 4;
this.UserStatusButton.Text = "Check Status";
this.UserStatusButton.UseVisualStyleBackColor = true;
this.UserStatusButton.Click += new System.EventHandler(this.UserStatusButton_Click);
//
// comboBox1
//
this.comboBox1.AllowDrop = true;
this.comboBox1.BackColor = System.Drawing.SystemColors.Info;
this.comboBox1.DropDownHeight = 215;
this.comboBox1.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.comboBox1.ForeColor = System.Drawing.Color.Black;
this.comboBox1.FormattingEnabled = true;
this.comboBox1.IntegralHeight = false;
this.comboBox1.ItemHeight = 13;
this.comboBox1.Location = new System.Drawing.Point(6, 12);
this.comboBox1.Name = "comboBox1";
this.comboBox1.Size = new System.Drawing.Size(136, 21);
this.comboBox1.Sorted = true;
this.comboBox1.TabIndex = 5;
this.comboBox1.MouseHover += new System.EventHandler(this.comboBox1_MouseHover);
//
// linkLabel1
//
this.linkLabel1.AutoSize = true;
this.linkLabel1.Location = new System.Drawing.Point(260, 232);
this.linkLabel1.Name = "linkLabel1";
this.linkLabel1.Size = new System.Drawing.Size(279, 13);
this.linkLabel1.TabIndex = 7;
this.linkLabel1.TabStop = true;
this.linkLabel1.Text = "Management of Active Directory in C# by Syed.Jahanzaib";
this.linkLabel1.Click += new System.EventHandler(this.linkLabel1_Click);
//
// pictureBox1
//
this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image")));
this.pictureBox1.Location = new System.Drawing.Point(6, 156);
this.pictureBox1.Name = "pictureBox1";
this.pictureBox1.Size = new System.Drawing.Size(239, 72);
this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.pictureBox1.TabIndex = 6;
this.pictureBox1.TabStop = false;
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(544, 248);
this.Controls.Add(this.linkLabel1);
this.Controls.Add(this.pictureBox1);
this.Controls.Add(this.comboBox1);
this.Controls.Add(this.UserStatusButton);
this.Controls.Add(this.StatusTextBox);
this.Controls.Add(this.button2);
this.Controls.Add(this.button1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "Form1";
this.Text = "Active Directory Management Panel !";
this.Load += new System.EventHandler(this.Form1_Load);
((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();

}

#endregion

private System.Windows.Forms.Button button1;
private System.Windows.Forms.Button button2;
private System.Windows.Forms.TextBox StatusTextBox;
private System.Windows.Forms.Button UserStatusButton;
private System.Windows.Forms.ComboBox comboBox1;
private System.Windows.Forms.LinkLabel linkLabel1;
private System.Windows.Forms.PictureBox pictureBox1;
private System.Windows.Forms.ToolTip toolTip1;
}
}


0fb310fdff985ec27edf24c236b1e2f3

Regard’s
Syed Jahanzaib


Contact !

 

March 20, 2017

C# PPPoE Dialer Application Code

Filed under: Programming — Tags: , , , , , — Syed Jahanzaib / Pinochio~:) @ 4:35 PM

vc.png

pppoe dialer ver 2

Video of code working (old v1 dialer) is available at YT !
> https://youtu.be/SlryR7ykSqw

[Watch in 720p HD or above to view proper text]


~ Sharing Knowledge ~
~ For Any One Who Wants to Learn ~

I am writing this post to share PPPoE Dialer program which I made using Visual Studio 2012 C#.

 This program can create / dial / disconnect a broadband pppoe connection on Windows 7 base Operating System. I have added many functions according to the local requirements. It was all built for my local lab testing purposes therefore there is a lot of room for improvements in it. Just to remind myself, I am not even a programmer, but a simple low level network support personnel. This is my first Try code in C# programming. It took me full two weeks late night working to develop this code.

Google search and Stack-overflow queries made it possible to create such program for a dumb person like Me.

Moment of Truth!

In general ISP/Networks, nowadays everyone is using WiFi routers therefore this dialer won’t be useful in such scenarios. but still its good to have some branding stuff for clients who directly use desktop / laptop computers to dial in to your server for the internet access.

Very Sadly ! Most of the programmers / knowledgeable persons I know in my  contacts clearly denied to share any code / working solution with the public & advised me NOT to share such code freely, like the Joker once said in a movie scene.

if u r good.png

We shouldn’t have any issue with this approach in practical, because Obviously if some one works hard to design a solution that can be utilized commercially , its his right to ask for money. I expect no one bound to agree with my statement here.

But here I am. sharing my basic knowledge for anyone who wants to learn from it ! ~

If anyone want customized branding with there Logo / Numbers in this dialer, you know my email.

~z@iB


Components Used:

  • OS: Windows 7 (64bit)
  • Launching Pad: Visual Studio 2012
  • Language: C Sharp (C#)
  • Support Libraries: Dotras 1.3 (https://dotras.codeplex.com/)
  • .Net Framework 4.x Library for Dotras

Requirements at Client PC:

  • the code targets .net framework 4.5 library support, & the bundled setup i made, already have .Net Framework 4.5 bundled . So if its not installed at client computer , it will auto deploy it.

DOWNLOAD !!!

Internet Dialer Complete Program ! [pppoe broadband dialer]

 


Code Working Workflow Example:

  • Username / Password Boxes: This must be filled first time, & the code will save it in the registry. Next time the dialer is launched , it will  read the credentials to avoid entering the id password again im boxes)
  • Auto Redial Check box: If selected, the system will auto redial in case of disconnection.
  • Dial Button: which will basically dial the pppoe connection & upon successfull connection, it will minimize the window. It will also check if dialer is already connected.
  • Disconnect Button: You know what disconnect means :). It will disconnect the dialer only if the dialer is really connected. Plus it will will not auto redial because the user have manually disconnected the connection.
  • Exit: This will close this application.
  • Create internet Dialer Button: This will create pppoe dialer connection in Network Connections plus its shortcut on current user desktop, and if connection already exists, then it will inform user accordingly.
  • Dialer LAN Status Button: It will check if the dialer is connected or not in the status text box.
  • Balloon Texts / Notifications: When application is minimized to System Tray, connect / disconnect events.
  • Auto Minimize: on connect / manual disconnect
  • Tray Icon Menu Strip Menu Context to Show/Exit app. Example to show function.
  • Total Data Download/Upload in labels for current session.
  • Dialer Connected Time.
  • Display Dialer Internet IP.
  • Picture box to show connectivity
  • Check Gateway Button.
  • The code will keep checking the dialer status (every 5sec) /net status  (every 10sec) and update the text label accordingly.
  • Many other small enhancements

I must be missing some other functions but this was all required at a moment.

I will update more later if got the chance…

Ok lets hit the Road , and view the code …


the SOURCE-CODE Journey !

// PPPoE Internet Dialer - Broadband PPPoE Dialer V 2.0
// Dear Humans, You are absolutely free to use it as you like
// This PPPoE dialer program is made in C#
// using Visual Studio 2012 with .Net Framework 4.5 & Dotras Library
// Syed Jahanzaib / aacable @ hotmail . com
// http : // aacable . wordpress . com
// March, 2017
using System;
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.Windows.Forms;
using DotRas;
using Microsoft.Win32;
using System.Net;
using System.IO;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Diagnostics;
namespace pppoe_dialer___zaib_last
{
public partial class Form1 : Form
{
public class Globals
{
public static string PPPNAME = "Internet-Dialer";
public static string dcmanual = "0";
public static string RedialCheckValue = "0";
NetworkInterface networkInterface;
long lngBytesSend;
long lngBtyesReceived;

}
private Timer _timer;
private DateTime _startTime = DateTime.MinValue;
private TimeSpan _currentElapsedTime = TimeSpan.Zero;
private TimeSpan _totalElapsedTime = TimeSpan.Zero;
private bool _timerRunning = false;

DateTime _started = DateTime.UtcNow;
DateTime startTime = new DateTime();
private NetworkInterface[] nicArr;
int lanInterval = 2; //3 sec
int netInterval = 10; //10 sec
private Timer timer;
private const double timerUpdate = 1000;

//private bool willClose;
private bool connected;
private RasHandle handle = null;
private RasHandle Rashandler = null;
private RasConnection connection = null;
//DateTime startTime = new DateTime();

public Form1()
{
InitializeComponent();
if (RedialCheckBox.Checked)
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n", "System will auto Redial if get disconnected."));
Globals.RedialCheckValue = "YES";
}
InitializeNetworkInterface();
InitializeTimer();
_timer = new Timer();
_timer.Interval = 1000;
_timer.Tick += new EventHandler(_timer_Tick);

Timer t = new Timer();
t.Interval = 1000; //1 sec
t.Tick += new EventHandler(t_Tick);
t.Start();

var conns = RasConnection.GetActiveConnections();
var conn = conns.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (conn != null)
{
startelptimer();
}
if (conn != null)
{
var local = NetworkInterface.GetAllNetworkInterfaces().Where(i => i.Name == Globals.PPPNAME).FirstOrDefault();
var stringAddress = local.GetIPProperties().UnicastAddresses[0].Address.ToString();
var ipAddress1 = IPAddress.Parse(stringAddress);
pppip.Text = ipAddress1.ToString();
notifyIcon1.Icon = Resource1.icon_online;
this.pictureBox2.Image = Resource1.net_conn_image_1;

}
else
{
this.pictureBox2.Image = Resource1.net_disconnected_image_2;
sl2.Text = "Disconnected";
}

}

void _timer_Tick(object sender, EventArgs e)
{
var timeSinceStartTime = DateTime.Now - _startTime;
timeSinceStartTime = new TimeSpan(timeSinceStartTime.Hours,
timeSinceStartTime.Minutes,
timeSinceStartTime.Seconds);
_currentElapsedTime = timeSinceStartTime + _totalElapsedTime;
sl2.Text = timeSinceStartTime.ToString();
}

private void timerdialer_Tick(object sender, EventArgs e)
{
var timeSinceStartTime = DateTime.Now - _startTime;
timeSinceStartTime = new TimeSpan(timeSinceStartTime.Hours,
timeSinceStartTime.Minutes,
timeSinceStartTime.Seconds);
_currentElapsedTime = timeSinceStartTime + _totalElapsedTime;
sl2.Text = timeSinceStartTime.ToString();
}

private void timerStart_Click(object sender, EventArgs e)
{
// If the timer isn't already running
// Set the start time to Now
_startTime = DateTime.Now;

// Store the total elapsed time so far
//_totalElapsedTime = _currentElapsedTime;

_timer.Start();
_timerRunning = true;

}

private void InitializeNetworkInterface()
{

// Grab all local interfaces to this computer
nicArr = NetworkInterface.GetAllNetworkInterfaces();
// Add each interface name to the combo box
for (int i = 0; i < nicArr.Length; i++)
cmbInterface.Items.Add(nicArr[i].Name);
// Change the initial selection to the first interface
cmbInterface.SelectedIndex = 0;
}

private void InitializeTimer()
{
timer = new Timer();
timer.Interval = (int)timerUpdate;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
}

void t_Tick(object sender, EventArgs e)
{
lanInterval--;
netInterval--;

if (lanInterval == 0)
{
checkpppstatus();
lanInterval = 2; //reset to base value
}

if (netInterval == 0)
{
// checknetstatus();
netInterval = 10; //reset to base value
}
}
protected void checkpppstatus()
{
this.Invoke((MethodInvoker)delegate
{
var conns = RasConnection.GetActiveConnections();
var conn = conns.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (conn != null)
{
dialerStatus.Text = "Connected !";
//connstatus.ForeColor = System.Drawing.Color.Green;
}
else
{
dialerStatus.Text = "Disconnected !";
connstatus.ForeColor = System.Drawing.Color.Red;
pppip.Text = "---";
sl2.Text = "Dicsonnected !";
}
});
}

protected void checknetstatus()
{
if (IsOnline(textBox1.Text) == true)
{
//internetStatusLabel.ForeColor = System.Drawing.Color.Green;
string Status = "Connected !";
// internetStatus.Text = Status;
}
else
{
// internetStatusLabel.ForeColor = System.Drawing.Color.Red;
string Status = "DOWN";
// internetStatus.Text = Status;
}
}

protected void Displaynotify()
{
try
{
notifyIcon1.BalloonTipTitle = "You have successfully connected to the Internet ...";
notifyIcon1.BalloonTipText = "Internet Connected ...";
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(5000);
}
catch (Exception ex)
{
}
}

protected void stopelptimer()
{
// If the timer isn't already running
// Set the start time to Now
_startTime = DateTime.Now;

// Store the total elapsed time so far

//_totalElapsedTime = _currentElapsedTime;

_timer.Stop();
_timerRunning = false;
TimeSpan _currentElapsedTime = TimeSpan.Zero;
TimeSpan _totalElapsedTime = TimeSpan.Zero;
_totalElapsedTime = _currentElapsedTime;

_timer.Stop();
_timerRunning = false;

}

protected void startelptimer()
{
// If the timer isn't already running
// Set the start time to Now
_startTime = DateTime.Now;

// Store the total elapsed time so far
//_totalElapsedTime = DateTime.Now;
_timer.Start();
_timerRunning = true;
}

protected void Displaynotifyfordisconnect()
{
try
{
notifyIcon1.BalloonTipTitle = "Internet Dialer DISCONNECTED !!!";
notifyIcon1.BalloonTipText = "Internet Disconnected !!!";
notifyIcon1.Visible = true;
notifyIcon1.ShowBalloonTip(5000);
// MessageBox.Show("DC");
{
this.Invoke((MethodInvoker)delegate
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "\r\nDialer Disconnected !"));
});
}
}
catch (Exception ex)
{
}
}

private void saveCredential(string username, string password, bool remember, bool auto)
{
RegistryKey hkcu = Registry.CurrentUser;
RegistryKey software = hkcu.OpenSubKey("Software", true);
RegistryKey zaib = software.CreateSubKey("zaib");
zaib.SetValue("username", username, RegistryValueKind.String);
zaib.SetValue("password", password, RegistryValueKind.String);
if (Globals.RedialCheckValue == "YES")
{
zaib.SetValue("autoredial", "YES", RegistryValueKind.String);
}
else
{
zaib.SetValue("autoredial", "NO", RegistryValueKind.String);
}

zaib.Close();
}

private void readCredential()
{
RegistryKey hkcu = Registry.CurrentUser;
RegistryKey software = hkcu.OpenSubKey("Software", true);
RegistryKey zaib = software.CreateSubKey("zaib");
try
{
textBox1.Text = (string)zaib.GetValue("username", "");
textBox2.Text = (string)zaib.GetValue("password", "");
textBox3.Text = (string)zaib.GetValue("autoredial", "");
if (textBox3.Text == "YES")
{
RedialCheckBox.Checked = true;
}
else
{
RedialCheckBox.Checked = false;
}

}
catch (Exception ex)
{
// never saved
}
zaib.Close();
}

private void Form1_Move_1(object sender, EventArgs e)
{
if (this.WindowState == FormWindowState.Minimized)
{
this.Hide();
notifyIcon1.ShowBalloonTip(2000, "Internet Dialer - Broadband PPPoE Dialer V 2.0", "The App has be moved to the tray.", ToolTipIcon.Info);
checkpppstatus();
}
}

private void button1_Click(object sender, EventArgs e)
{
string path;
path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
using (RasPhoneBook pbk = new RasPhoneBook())
{
pbk.Open(path);
RasEntry entry = RasEntry.CreateBroadbandEntry(Globals.PPPNAME, RasDevice.GetDeviceByName("PPPOE", RasDeviceType.PPPoE, false));
// Configure any options for your entry here via entry.Options
entry.RedialCount = 99;
// Finally Add the PPPOE Dialer in the network connection , hurrahhhh , zaib
// If Preiovus Entry found, delete, and reacreate
var conns = RasConnection.GetActiveConnections();
var conn = conns.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (conn != null)
{
//MessageBox.Show("Same Dialer Already connected ! First Disconnect it to re-create new.");
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Dialer Already connected ! First Disconnect it to update/recreate", Globals.PPPNAME));
return;
}
if (pbk.Entries.Contains(Globals.PPPNAME))
{
//MessageBox.Show("DIALER ALREADY Exists!, Updating Credentials Done.",Globals.PPPNAME);
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n","Dialer already Exists!, Saving current Credentials to registry Done.",Globals.PPPNAME, "{0}\r\n\r\n"));
saveCredential(textBox1.Text, textBox2.Text, true, true);
}
else
{
//pbk.Entries.Clear();
rasDialer1.Credentials = new System.Net.NetworkCredential(textBox1.Text, textBox2.Text);
rasDialer1.AllowUseStoredCredentials = true;

pbk.Entries.Add(entry);
// If Dialer Create, show successfull message.
MessageBox.Show("Internet Dialer created Successfully.");
saveCredential(textBox1.Text, textBox2.Text, true, true);

}
}
}
private void Form1_Load(object sender, EventArgs e)
{

}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void textBox2_TextChanged(object sender, EventArgs e)
{
}
private void textBox1_Click(object sender, EventArgs e)
{
// textBox1.Clear();
}
private void Button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void textBox2_Click(object sender, EventArgs e)
{
//textBox2.Clear();
}

private void pictureBox2_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("https://aacable.wordpress.com");
}
private void button2_Click_1(object sender, EventArgs e)
{
RasHandle handle = null;
using (RasDialer dialer = new RasDialer())
{
dialer.StateChanged += new EventHandler<StateChangedEventArgs>(rasDialer1_StateChanged);
dialer.EntryName = (Globals.PPPNAME);
{
// this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "OK ...", "{0}\r\n\r\n"));
};
//this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Connection in progress ...", "{0}\r\n\r\n"));
dialer.StateChanged += new EventHandler<StateChangedEventArgs>(rasDialer1_StateChanged);
dialer.EntryName = (Globals.PPPNAME);
string username = textBox1.Text;
string passwd = textBox2.Text;
dialer.Credentials = new System.Net.NetworkCredential(textBox1.Text, textBox2.Text);
dialer.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
dialer.Timeout = 1000;
dialer.AllowUseStoredCredentials = true;
dialer.EntryName = (Globals.PPPNAME);
rasDialer1.EntryName = (Globals.PPPNAME);
rasDialer1.Credentials = new System.Net.NetworkCredential(textBox1.Text, textBox2.Text);
rasDialer1.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);

// If username or password window is empty , post error
if (string.IsNullOrWhiteSpace(textBox1.Text))
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r", "You must enter username/password in order to dial", "{0}\r\n"));
//MessageBox.Show("Enter username.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}

// // //
// // // CHECK IF DIAL is press but the pppoe connection is not alreay in network connections, CReate new connection if not created earlier.
string path;
path = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
using (RasPhoneBook pbk = new RasPhoneBook())
{
pbk.Open(path);
RasEntry entry = RasEntry.CreateBroadbandEntry(Globals.PPPNAME, RasDevice.GetDeviceByName("PPPOE", RasDeviceType.PPPoE, false));
// Configure any options for your entry here via entry.Options
entry.RedialCount = 99;

//pbk.Entries.Clear();
rasDialer1.Credentials = new System.Net.NetworkCredential(textBox1.Text, textBox2.Text);
rasDialer1.AllowUseStoredCredentials = true;

if (pbk.Entries.Contains(Globals.PPPNAME))
{
//MessageBox.Show("DIALER ALREADY Exists!, Updating Credentials Done.",Globals.PPPNAME);
// this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Dialer already Exists!", Globals.PPPNAME, "{0}\r\n\r\n"));
//saveCredential(textBox1.Text, textBox2.Text, true, true);
var conns = RasConnection.GetActiveConnections();
var conn = conns.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (conn != null)
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Dialer already connected !"));
}
else

handle = rasDialer1.DialAsync();
}
else
{

pbk.Entries.Add(entry);
// If Dialer Create, show successfull message.
//MessageBox.Show("Internet Dialer created Successfully.");
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "It seems the Dialer App is executed first time therefore we need to create pppoe connection in networkk connections to be used by this DIALER program ...", Globals.PPPNAME, "{0}\r\n\r\n"));
saveCredential(textBox1.Text, textBox2.Text, true, true);
///// SHORTCUT BEGINE

string destDir = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string destFileName = @"Connect To My Internet Dialer.lnk";

// Create .lnk file
string path2 = System.IO.Path.Combine(destDir, destFileName);
FileStream fs = File.Create(path2);
fs.Close();

// Instantiate a ShellLinkObject that references the .lnk we created
Shell32.Shell shell = new Shell32.Shell();
Shell32.Folder shellFolder = shell.NameSpace(destDir);
Shell32.FolderItem shellFolderItem = shellFolder.Items().Item(destFileName);
Shell32.ShellLinkObject shellLinkObject = (Shell32.ShellLinkObject)shellFolderItem.GetLink;

// Set .lnk properties
shellLinkObject.Arguments = "-d pppoe2";
shellLinkObject.Description = Globals.PPPNAME;
shellLinkObject.Path = @"%windir%\System32\rasphone.exe";
shellLinkObject.WorkingDirectory = "%windir%";

shellLinkObject.Save(path2);
//// SHORTCUT END
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Dialer created successfully, now attempting to connect suing this new pppoe connection !"));
handle = rasDialer1.DialAsync();
}
}
}
}

private void StatusTextBox_TextChanged(object sender, EventArgs e)
{
//
}

private void rasDialer1_StateChanged(object sender, StateChangedEventArgs e)
{
this.Invoke((MethodInvoker)delegate
{
this.StatusTextBox.AppendText(string.Format(e.State.ToString() + "\r\n"));
checkpppstatus();
});
}

private void rasDialer1_DialCompleted(object sender, DialCompletedEventArgs e)
{
{
if (e.Cancelled)
{
MessageBox.Show("Cancelled");
}
else if (e.TimedOut)
{
MessageBox.Show("Time out");
}
else if (e.Error != null)
{
//MessageBox.Show(e.Error.ToString(), "Error");
this.Invoke((MethodInvoker)delegate
{
this.StatusTextBox.AppendText(string.Format(e.Error.ToString() + "\r\n"));
});
if (Globals.RedialCheckValue == "YES")
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Retry Auto Dialing in 1 Second ..."));
rasDialer1.DialAsync();
}
else if (e.Connected)
{
//
this.Invoke((MethodInvoker)delegate
{

//MessageBox.Show("Connection successful zaib!");
var conn = RasConnection.GetActiveConnections().Where(c => c.EntryName == Globals.PPPNAME).FirstOrDefault();
RasIPInfo ipAddresses = (RasIPInfo)conn.GetProjectionInfo(RasProjectionType.IP);
this.StatusTextBox.AppendText(string.Format("{0}\r\n", "Your internet ip is", ipAddresses.IPAddress.ToString()));
this.StatusTextBox.AppendText(string.Format("{0} ", ipAddresses.IPAddress.ToString()));
saveCredential(textBox1.Text, textBox2.Text, true, true);
var local = NetworkInterface.GetAllNetworkInterfaces().Where(i => i.Name == Globals.PPPNAME).FirstOrDefault();
var stringAddress = local.GetIPProperties().UnicastAddresses[0].Address.ToString();
var ipAddress1 = IPAddress.Parse(stringAddress);
//sl2.Text = timeSinceStartTime.ToString();
pppip.Text = ipAddress1.ToString();
//gwLabel.Text = "Gateway is : " + ";
ShowInTaskbar = true;
this.Hide();
InitializeNetworkInterface();
//Displaynotify();
UpdateNetworkInterface();
stopelptimer();
startelptimer();
});
}
}
}

private void dcButton_Click(object sender, EventArgs e)
{
var conns = RasConnection.GetActiveConnections();
var conn = conns.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (conn != null)
{
//InitializeNetworkInterface();
conn.HangUp();
Globals.dcmanual = "yes";
Globals.RedialCheckValue = "NO";

//MessageBox.Show("Disconnect on User Request");
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "\r\nDisconnected on user request !"));
lblInterfaceType.Text = "---";
lblUpload.Text = "---";
lblDownload.Text = "---";
connstatus.ForeColor = Color.Red;
checkpppstatus();
//this.Hide();
Displaynotifyfordisconnect();

}
else
MessageBox.Show("Dialer is not Active !", Globals.PPPNAME);
}

private void rasDialer1_Error(object sender, System.IO.ErrorEventArgs e)
{
//this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "\r\n AUTO DC DONT KNOW !"));
MessageBox.Show("UNKOWN!!!!!!!!!!!!");
}

private void Form1_Resize(object sender, EventArgs e)
{
notifyIcon1.Text = "My Internet Dialer";
}

private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}

private void notifyIcon1_MouseDoubleClick_1(object sender, MouseEventArgs e)
{
Show();
WindowState = FormWindowState.Normal;
}

private void notifyIcon1_MouseMove(object sender, MouseEventArgs e)
{
notifyIcon1.Text = "Internet Dialer - Broadband PPPoE Dialer V 2.0";
}

private void notifyIcon1_BalloonTipClicked(object sender, EventArgs e)
{

}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{

}

private void notifyIcon1_BalloonTipShown(object sender, EventArgs e)
{
}

private void Form1_Load_1(object sender, EventArgs e)
{
timer4dt.Start();
datelabel.Text = DateTime.Now.ToLongDateString();
timelabel.Text = DateTime.Now.ToLongTimeString();
readCredential();
checkpppstatus();
Timer MyTimer = new Timer();
MyTimer.Interval = 5000;
MyTimer.Tick += new EventHandler(MyTimer_Tick);
MyTimer.Start();
Timer MyTimer10 = new Timer();
MyTimer10.Interval = 5000;
MyTimer10.Tick += new EventHandler(MyTimer_Tick);
MyTimer10.Start();
var conns = RasConnection.GetActiveConnections();
var conn = conns.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (conn != null)
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Dialer already connected !"));
}
private void MyTimer_Tick(object sender, EventArgs e)
{
//checkpppstatus();
}
private void MyTimer10_Tick(object sender, EventArgs e)
{
// // checknetstatus();
}

private void contextMenuStrip1_DoubleClick(object sender, EventArgs e)
{
this.Show();
}

private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
//this.Show();
this.Show();
WindowState = FormWindowState.Normal;
}

private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}

private void notifyIcon1_Click(object sender, EventArgs e)
{
// this.Show();
//WindowState = FormWindowState.Normal;
}

private void label3_Click(object sender, EventArgs e)
{

}

private void connstatus_Click(object sender, EventArgs e)
{

}

private void connstatus_Click_1(object sender, EventArgs e)
{

}

private void rasDialDialog1_Error(object sender, RasErrorEventArgs e)
{
}

private void rasConnectionWatcher1_Disconnected(object sender, RasConnectionEventArgs e)
{
checkpppstatus();
notifyIcon1.Icon = Resource1.icon_standby;
this.pictureBox2.Image = Resource1.net_disconnected_image_2;
Displaynotifyfordisconnect();
stopelptimer();
//MessageBox.Show(Globals.RedialCheckValue);
if (Globals.dcmanual == "YES")
{
//MessageBox.Show("YES MANUAL DISCONNECTED ...");
return;
}
else
{
}

if (Globals.RedialCheckValue == "YES")
this.Invoke((MethodInvoker)delegate
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Retry Auto Dialing in 1 Seconds!"));
});

DateTime Tthen = DateTime.Now;
do
{

Application.DoEvents();
} while (Tthen.AddSeconds(1) > DateTime.Now);

//Waits 5 seconds.
var conns = RasConnection.GetActiveConnections();
var conn = conns.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (conn != null)
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "Dialer already Connected !"));
}
else
{
rasDialer1.EntryName = (Globals.PPPNAME);
rasDialer1.Credentials = new System.Net.NetworkCredential(textBox1.Text, textBox2.Text);
rasDialer1.PhoneBookPath = RasPhoneBook.GetPhoneBookPath(RasPhoneBookType.User);
var conns2 = RasConnection.GetActiveConnections();
var conn2 = conns2.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (Globals.RedialCheckValue == "YES")
handle = rasDialer1.DialAsync();
}
// this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "NO AUTO DIAL CHECK!"));

}

private void rasConnectionWatcher1_Connected(object sender, RasConnectionEventArgs e)
{
Globals.dcmanual = "no";
UpdateNetworkInterface();
Displaynotify();
//startelptimer();
notifyIcon1.Icon = Resource1.icon_online;
this.pictureBox2.Image = Resource1.net_conn_image_1;
}

private void rasConnectionWatcher1_Error(object sender, ErrorEventArgs e)
{
MessageBox.Show("ERR");
}

private void rasPhoneBookDialog1_ChangedEntry(object sender, RasPhoneBookDialogEventArgs e)
{
MessageBox.Show("ENTRY CHANGED");
}

// Tafreeh start

public bool IsOnline(string website)
{
Ping x = new Ping();
PingReply reply = x.Send(IPAddress.Parse("8.8.8.8")); //enter ip of the machine
if (reply.Status == IPStatus.Success) // here we check for the reply status if it is success it means the host is reachable
{
return true;
// status.Text = "Available. And Round Trip Time of the packet is:" + reply.RoundtripTime.ToString();
}
else //if host is not reachable.
return false;
// status.Text = "Not available";
}
//}

private void AboutMeLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("https://aacable.wordpress.com");
}

long lngBytesSend;
long lngBtyesReceived;

private void UpdateNetworkInterface()
{
this.Invoke((MethodInvoker)delegate
{
NetworkInterface nic = nicArr[cmbInterface.SelectedIndex];
IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics();
IPv4InterfaceStatistics status = nic.GetIPv4Statistics();
lblInterfaceType.Text = nic.NetworkInterfaceType.ToString();
int sent_Speed = (int)(status.BytesSent - lngBytesSend) / 1024;
int receive_speed = (int)(status.BytesReceived - lngBtyesReceived) / 1024;
int bytesReceivedSpeed = (int)(interfaceStats.BytesReceived - lngBtyesReceived) / 1024;
int totinmb = (int)(status.BytesReceived) / 1024 / 1024;
lblDownload.Text = totinmb + " MB";
int totSentinmb = (int)(status.BytesSent) / 1024 / 1024;
lblUpload.Text = totSentinmb + " MB";
lngBytesSend = status.BytesSent;
lngBtyesReceived = status.BytesReceived;
});
}

void timer_Tick(object sender, EventArgs e)
{
var conns = RasConnection.GetActiveConnections();
var conn = conns.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (conn != null)
UpdateNetworkInterface();
InitializeNetworkInterface();
}

private void cmbInterface_SelectedIndexChanged(object sender, EventArgs e)
{

}

private void dialerCheck_Click(object sender, EventArgs e)
{
//Gateway IP
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
GatewayIPAddressInformationCollection addresses =
adapterProperties.GatewayAddresses;
if (addresses.Count > 0)
{
foreach (GatewayIPAddressInformation address in addresses)
{
StatusTextBox.Text += "Gateway Address | " +
address.Address.ToString() + "\r\n";

}
}
}
}

private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
// timer.Dispose();
// this.Dispose();
}

private void timer4dt_Tick(object sender, EventArgs e)
{
timelabel.Text = DateTime.Now.ToLongTimeString();
timer4dt.Start();
}

private void resetStats_Click(object sender, EventArgs e)
{

_timer.Stop();
_timerRunning = false;

// Reset the elapsed time TimeSpan objects
_totalElapsedTime = TimeSpan.Zero;
_currentElapsedTime = TimeSpan.Zero;
}

private void timerStart_Click_1(object sender, EventArgs e)
{
// If the timer isn't already running
if (!_timerRunning)
{
// Set the start time to Now
_startTime = DateTime.Now;

// Store the total elapsed time so far

_totalElapsedTime = _currentElapsedTime;

_timer.Start();
_timerRunning = true;
}
else // If the timer is already running
{
_startTime = DateTime.Now;

// Store the total elapsed time so far

_totalElapsedTime = _currentElapsedTime;

_timer.Start();
_timerRunning = true;
}
}

private void timerdialer_Tick_1(object sender, EventArgs e)
{
{
var timeSinceStartTime = DateTime.Now - _startTime;
timeSinceStartTime = new TimeSpan(timeSinceStartTime.Hours,
timeSinceStartTime.Minutes,
timeSinceStartTime.Seconds);
_currentElapsedTime = timeSinceStartTime + _totalElapsedTime;
}
}

private void timerStop_Click(object sender, EventArgs e)
{
_timer.Stop();
_timerRunning = false;
}

// tafreh2 start
protected void checknetstatusBoxMsg()
{
if (IsOnline(textBox1.Text) == true)
{
//internetStatusLabel.ForeColor = System.Drawing.Color.Green;
string Status = "Connected";
// internetStatus.Text = Status;
this.StatusTextBox.AppendText(string.Format("{0}\r\n", Status));
}
else
{
// internetStatusLabel.ForeColor = System.Drawing.Color.Red;
string Status = "Disconnected";
this.StatusTextBox.AppendText(string.Format("{0}\r\n ", Status, "{0}\r\n\r\n"));
}
}

protected void checkpppstatusBoxMsg()
{
this.Invoke((MethodInvoker)delegate
{
var conns = RasConnection.GetActiveConnections();
var conn = conns.FirstOrDefault(o => o.EntryName == Globals.PPPNAME);
if (conn != null)
{
string Status = "PPP Dialer Stauts: Connected";
this.StatusTextBox.AppendText(string.Format("{0}\r\n", Status));
}
else
{
string Status = "PPP Dialer Stauts: Disconnected";
this.StatusTextBox.AppendText(string.Format("{0}\r\n", Status));
}

});
}

// tafreh2 end

private void netStatusButton_Click(object sender, EventArgs e)
{
checknetstatusBoxMsg();
}

private void dialerLanStatus_Click(object sender, EventArgs e)
{
checkpppstatusBoxMsg();
}

private void gatewayDetails_Click(object sender, EventArgs e)
{
//Gateway IP
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
this.StatusTextBox.AppendText(string.Format("{0}\r\n", "Gateway Details!"));
foreach (NetworkInterface adapter in adapters)
{
IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
GatewayIPAddressInformationCollection addresses =
adapterProperties.GatewayAddresses;
if (addresses.Count > 0)
{
foreach (GatewayIPAddressInformation address in addresses)
{
this.StatusTextBox.AppendText(string.Format(address.Address.ToString() + "\r\n"));
}
}
}
}

private void StatusTextBox_VisibleChanged(object sender, EventArgs e)
{
StatusTextBox.SelectionStart = textBox1.Text.Length;
StatusTextBox.ScrollToCaret();
}

private void label5_Click(object sender, EventArgs e)
{

}

private static void ShowNetworkTraffic()
{
PerformanceCounterCategory performanceCounterCategory = new PerformanceCounterCategory("Network Interface");
string instance = performanceCounterCategory.GetInstanceNames()[0]; // 1st NIC !
PerformanceCounter performanceCounterSent = new PerformanceCounter("Network Interface", "Bytes Sent/sec", instance);
PerformanceCounter performanceCounterReceived = new PerformanceCounter("Network Interface", "Bytes Received/sec", instance);

for (int i = 0; i < 10; i++)
{
Console.WriteLine("bytes sent: {0}k\tbytes received: {1}k", performanceCounterSent.NextValue() / 1024, performanceCounterReceived.NextValue() / 1024);
}
}

// tafreeh starts
private static void RedialAttempt()
{

}

private void pictureBox1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.Start("https://aacable.wordpress.com");
}

private void AboutMeLabel_LinkClicked_1(object sender, LinkLabelLinkClickedEventArgs e)
{
System.Diagnostics.Process.Start("https://aacable.wordpress.com");
}

private void RedialCheckBox_CheckedChanged(object sender, EventArgs e)
{
if (RedialCheckBox.Checked)
{
//this.StatusTextBox.AppendText(string.Format("{0}\r\n", "System will auto Redial if get disconnected."));
Globals.RedialCheckValue = "YES";
RegistryKey hkcu = Registry.CurrentUser;
RegistryKey software = hkcu.OpenSubKey("Software", true);
RegistryKey zaib = software.CreateSubKey("zaib");
zaib.SetValue("autoredial", "YES", RegistryValueKind.String);
zaib.Close();
}
}

private void testb_Click(object sender, EventArgs e)
{
MessageBox.Show(Globals.RedialCheckValue);
}

private void notifyIcon1_DoubleClick(object sender, EventArgs e)
{
this.Show();
WindowState = FormWindowState.Normal;
}

private void RedialCheckBox_CheckStateChanged(object sender, EventArgs e)
{
if (RedialCheckBox.Checked)
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n", "System will auto Redial if get disconnected."));
Globals.RedialCheckValue = "YES";
RegistryKey hkcu = Registry.CurrentUser;
RegistryKey software = hkcu.OpenSubKey("Software", true);
RegistryKey zaib = software.CreateSubKey("zaib");
zaib.SetValue("autoredial", "YES", RegistryValueKind.String);
zaib.Close();
}
else
{
this.StatusTextBox.AppendText(string.Format("{0}\r\n", "System will NOT auto Redial if get disconnected."));
RegistryKey hkcu = Registry.CurrentUser;
RegistryKey software = hkcu.OpenSubKey("Software", true);
RegistryKey zaib = software.CreateSubKey("zaib");
zaib.SetValue("autoredial", "NO", RegistryValueKind.String);
zaib.Close();
}
}

private void AboutMeButton_Click(object sender, EventArgs e)
{
AboutBox1 box = new AboutBox1();
box.ShowDialog();
}

// tafreeh ends

}
}
// The CODE ends Here.
// Any suggestions / modifications are most welcome.
// zaib

i HAVE UPLOADED THE TEST PACKAGE HERE.

https://drive.google.com/open?id=0B8B_P2ljEc2xaGU1MHhsNktsdjg

I am pretty sure that above code will help you in many parts when you will create your own project. I faced many challenges duet first time programming but your situation may be different if you have already working example in ahead of you 🙂

I will be more then happy if someone posts some more advance level of this dialer code for all.


Regard’s

Syed Jahanzaib
https://aacable.wordpress.com
Email: aacable@hotmail.com
Allah Hafiz !

March 8, 2017

MS Project 2016 has stopped working on assign resources

Filed under: Microsoft Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 9:49 AM

microsoft-project-2016-license-key-e1469786312356

Recently we purchased Microsoft Project 2016 licenses for our users. In terms of Functionality – All seems to be working fine except assigning resources

Whenever user tried to assign resources using option `Assign Resources` , project crashed/stopped working with below error …

ms_project_2017_stopped_wroking

 

After little R&D, we found that this is a standard bug in MS Project 2016 and it was fixed with Patch released on February 9, 2016

February 9, 2016, update for Project 2016 (KB3114714)

After updating patch, all went fine.


Advise of the day ! (Golden Rule)

Although we have WSUS (Windows Update Servers) in our organization which regularly update the clients windows , but general patches for MS OFFICE was not selected in the checklist, & that’s the main reason why we had to face this issue. Always keep your Windows and other softwares UP TO DATE. It will keep you away from UNWANTED guests 😉 You know what I mean 🙂

Regard’s
Syed Jahanzaib

March 3, 2017

Cisco Access Point Short Notes !

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

2017-03-03 16.47.48.jpg

 

Last year we replaced our old Cisco Aironet Access Points series with the new Ubiquiti AP-LR/AC model. Old switches were then placed in inventory to be used as a backup. Since these cisco AP were configured 8-10 years ago, therefore I had to reset all of them. I made short notes for the process, just in case I need it again in future or maybe useful for anyone else needing similar.

Syed.Jahanzaib


1- Cisco Aironet AP Reset to Factory Default

Note: I used Cisco Aironet AIR-AP1242AG-E-K9 access point model in this post

  1. Connect Console cable from the AP Console port to your PC COM port.
  2. Open Hyper Terminal and use below mentioned settings
    9600 baud
    8 data bits
    None parity
    1 stop bit
    Xon/Xoff Flow control .If xon/xoff flow control does not work, use no flow control.
  3. Disconnect power from access point
  4. Press and hold the MODE button while you reconnect power to the access point.
  5. Hold the MODE button until the Status LED turns amber (generally for 2-3 seconds max), and release the button
  6. After the AP reboots, it will come to default settings & you can re-configure the access point by using CLI or GUI. Default IP is 10.0.0.1

  7. The default username and password is cisco/Cisco [ 'C'  is capital in password]

As shown below ….


Press RETURN to get started.

Xmodem file system is available.
flashfs[0]: 158 files, 7 directories
flashfs[0]: 0 orphaned files, 0 orphaned directories
flashfs[0]: Total bytes: 15998976
flashfs[0]: Bytes used: 8549888
flashfs[0]: Bytes available: 7449088
flashfs[0]: flashfs fsck took 33 seconds.
Base ethernet MAC Address: 00:1e:be:25:68:d0
Initializing ethernet port 0...
Reset ethernet port 0...
Reset done!
ethernet link up, 100 mbps, full-duplex
Ethernet port 0 initialized: link is up
button pressed for 6 seconds
process_config_recovery: set IP address and config to default 10.0.0.1
Loading "flash:/c1240-k9w7-mx.124-10b.JA/c1240-k9w7-mx.124-10b.JA"...###########
################################################################################
################################################################################
################################################################################
################################################################################
################################################################################
######################################################

File "flash:/c1240-k9w7-mx.124-10b.JA/c1240-k9w7-mx.124-10b.JA" uncompressed and
installed, entry point: 0x3000
executing...

Restricted Rights Legend

Use, duplication, or disclosure by the Government is
subject to restrictions as set forth in subparagraph
(c) of the Commercial Computer Software - Restricted
Rights clause at FAR sec. 52.227-19 and subparagraph
(c) (1) (ii) of the Rights in Technical Data and Computer
Software clause at DFARS sec. 252.227-7013.

cisco Systems, Inc.
170 West Tasman Drive
San Jose, California 95134-1706

Cisco IOS Software, C1240 Software (C1240-K9W7-M), Version 12.4(10b)JA, RELEASE
SOFTWARE (fc2)
Technical Support: http://www.cisco.com/techsupport
Copyright (c) 1986-2007 by Cisco Systems, Inc.
Compiled Wed 24-Oct-07 15:31 by prod_rel_team
Image text-base: 0x00003000, data-base: 0x00859060

Initializing flashfs...

flashfs[1]: 157 files, 7 directories
flashfs[1]: 0 orphaned files, 0 orphaned directories
flashfs[1]: Total bytes: 15998976
flashfs[1]: Bytes used: 8548352
flashfs[1]: Bytes available: 7450624
flashfs[1]: flashfs fsck took 4 seconds.
flashfs[1]: Initialization complete....done Initializing flashfs.
Radio 1 A506 7100 E8000000 A0000000 80000000 3
Radio 1 A506 6700 E8000100 A0040000 80010000 2

This product contains cryptographic features and is subject to United
States and local country laws governing import, export, transfer and
use. Delivery of Cisco cryptographic products does not imply
third-party authority to import, export, distribute or use encryption.
Importers, exporters, distributors and users are responsible for
compliance with U.S. and local country laws. By using this product you
agree to comply with applicable laws and regulations. If you are unable
to comply with U.S. and local laws, return this product immediately.

A summary of U.S. laws governing Cisco cryptographic products may be found at:
http://www.cisco.com/wwl/export/crypto/tool/stqrg.html

If you require further assistance please contact us by sending email to
export@cisco.com.

cisco AIR-AP1242AG-E-K9 (PowerPCElvis) processor (revision A0) with 24566K/81
92K bytes of memory.
Processor board ID FCZ1213815G
PowerPCElvis CPU at 262Mhz, revision number 0x0950
Last reset from power-on
1 FastEthernet interface
2 802.11 Radio(s)

32K bytes of flash-simulated non-volatile configuration memory.
Base ethernet MAC Address: 00:1E:xx:xx:xx:xx
Part Number : 73-10256-06
PCA Assembly Number : 800-xxxxx-05
PCA Revision Number : A0
PCB Serial Number : FOCxxxxNE3
Top Assembly Part Number : 800-xxxx-01
Top Assembly Serial Number : FCZxxxxxxG
Top Revision Number : A0
Product/Model Number : AIR-AP1242AG-E-K9

Press RETURN to get started!


IP Related Configuration …

>

To configure new ip address


en
configure t
ip address 10.0.0.1 255.0.0.0
no ip route-cache

Now open browser and point to the ip you configured above, & do reset of config using express setup or as required 🙂

cisco aironet eexpres setup zaib.PNG


Howto ADD SSID

cisco-aironet-ssid-after-reset


Howto ENABLE RADIO / WiFi 

cisco-aironet-howto-enable-radio

Note: Enable Both Radio using above step …


To show current IP,

en
show ip interface brief

To Save Config

en
wr

 

Regard’s
Jz!

March 2, 2017

RM Reseller Monthly Report via GMAiL

Filed under: Radius Manager — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 11:07 AM

hosting-by-the-hour

Disclaimer: This is not a reliable method for some OP to acquire the monthly sale report done by reseller. It requires some criteria to match like strict account creation by specific reseller id only. Better to use provided GUI in DMA_RM to inquire the proper report.

This is just a personal way of collecting reporting via automated email which MUST be cross verified by the OP .

Z@iB


BASH:

Following is a bash script which will simply query invoices, categorize it according to reseller account, format it using html coding, sort, total and send email admin.

Logic:

When you will execute this script, it will fetch the reports from rm_users database using last month dates, it will auto calculate last month dates.

Example:

Current month is March,2017. the script will pick Last Month which was February,2017 and will calculate number of days as well using CAL function.

Sample of Report is as follows.

 

1

RM Reseller Monthly Report via email

2

RM Reseller Monthly Report via email

Schelde following script via crontab @monthly. Modify information as per your local network.



#!/bin/bash
# Script to query INVOICES section of Radius manager mysql, and
# categorize it according to resellers , calculate accounts,sort and total it.
# These are my personal way of doing things, and no one is bound to agree with these.
# Created: Year 2014
# set -x
# MYSQL USER ID PASSWORD
SQLUSER="root"
SQLPASS="YOUR_MYSQL_PASSWORD"

# DATE RELATED STUFF
LASTMY=`date +'%Y-%m' -d 'last month'`
LAST_MONTH_DIGIT=`date +'%m' -d 'last month'`
YEAR_DIGIT=`date +'%Y' -d 'last month'`
LAST_MONTH_LAST_DATE=`cal $LAST_MONTH_DIGIT $YEAR_DIGIT |egrep -v [a-z] |wc -w`
START="$LASTMY-01"
END="$LASTMY-$LAST_MONTH_LAST_DATE"
FMONTH=`date +'%B-%Y' -d 'last month'`
DATE=`date`

# EMAIL RELATED STUFF
TO1="YOUR_EMAIL_ID@hotmail.com"
GMAILID="GMAIL_ID_TO_SEND_EMAIL_FROM@gmail.com"
GMAILPASS="GMAIL_PASSWORD"
CONTENT_TYPE="text/html"

# LOG FILES
FILE="/tmp/dealer_renewal_month.html"
FINALFILE="/tmp/dealer_renewal_month_final.html"
COMPANY="ZAIB(Pvt)_Ltd.
This System is powered by Syed_Jahanzaib aacable@hotmail.com"
BODY_TITLE="Report&nbsp;For&nbsp;Dealer&nbsp;Account&nbsp;asof&nbsp;$FMONTH"
> $FILE
> $FINALFILE

# HTML BODY
echo "
<pre>" > $FILE
echo "<b>$BODY_TITLE</b>" >> $FILE
echo "<b>DEALER User's_Activated Used_Amount Balance</b>
" >> $FILE

# QUERY MANAGERS FROM RM_MANAGERS TABLE
mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select managername from rm_managers;" | while read dealer
do
num=$[$num+1]
DEALER=`echo $dealer | awk '{print $1}'`

# GATHER DATA OF ACTIVE USERS, USED AMOUNT, CURRENT BALANCE, (MOBILE NUMBER IF SMS IS REQUIRED TO SEND)
ACTIVEUSERSNO=`mysql -uroot -p$PASS --skip-column-names -e "use radius; SELECT price FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$START' AND date <= '$END' AND (paymode = '0' OR paymode = '1' OR paymode = '2' OR paymode = '3' OR paymode = '4' OR paymode = '5' OR paymode = '6' OR paymode = '7' OR paymode = '8' OR paymode = '9' OR paymode = '10' OR paymode = '11' ) AND (invgroup = '0' ) AND invnum != '' AND rm_users.owner = '$DEALER';" | sed '/credited/d' | wc -l`
USEDAMOUNT=`mysql -uroot -p$PASS --skip-column-names -e "use radius; SELECT price FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$START' AND date <= '$END' AND (paymode = '0' OR paymode = '1' OR paymode = '2' OR paymode = '3' OR paymode = '4' OR paymode = '5' OR paymode = '6' OR paymode = '7' OR paymode = '8' OR paymode = '9' OR paymode = '10' OR paymode = '11' ) AND (invgroup = '0' ) AND invnum != '' AND rm_users.owner = '$DEALER';" | sed '/credited/d' | awk '{ sum+=$1} END {print sum}'`
BALANCE=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select balance from rm_managers WHERE managername = '$DEALER';" |cut -f1 -d"."`
MOBILE=`mysql -u$SQLUSER -p$SQLPASS --skip-column-names -e "use radius; select mobile from rm_managers WHERE managername = '$DEALER';"`
SRV=`mysql -uroot -p$SQLPASS --skip-column-names -e "use radius; SELECT SQL_CALC_FOUND_ROWS rm_invoices.service FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$START' AND date <= '$END' AND (paymode = '0' OR paymode = '2' ) AND (invgroup = '0' OR invgroup = '1' ) AND invnum != '' AND rm_users.owner = '$DEALER' ORDER BY id LIMIT 0, 10000;" | sed '/credited/d' | awk '{print $1}' | sort | uniq -c`

#LOOK FOR ZERO VALUE AMOUNT AND REPLACE IT WITH 0 , IF FOUND
#if [ ! -n "$USEDAMOUNT" ]; then
#if [ "USEDAMOUNT == "" ]; then
#USEDAMOUNT="X"

# PRINT ALL GATHERED DATA INTO FILE
#echo "<b>$DEALER</b> $ACTIVEUSERSNO $USEDAMOUNT - $BALANCE
#------------------------------------------------------------------------" >> $FILE
#else

# PRINT ALL GATHERED DATA INTO FILE
echo "<b>$DEALER</b> $ACTIVEUSERSNO $USEDAMOUNT - $BALANCE

Details&nbsp;of&nbsp;Services&nbsp;Activated:
Qty Service&nbsp;Name

$SRV

------------------------------------------------------------------------" >> $FILE

#fi
done

# MAKE COLUMNS SO THAT IT GETs EASIER TO READS
sed -e 's/\t//g' $FILE | column -t | sed 's/ //g' | sed 's/ User/User/g' > $FINALFILE
# GATHER DATA OF ACTIVE USERS, USED AMOUNT, CURRENT BALANCE, (MOBILE NUMBER IF SMS IS REQUIRED TO SEND)
TOTNO=`mysql -uroot -p$PASS --skip-column-names -e "use radius; SELECT price FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$START' AND date <= '$END' AND (paymode = '0' OR paymode = '1' OR paymode = '2' OR paymode = '3' OR paymode = '4' OR paymode = '5' OR paymode = '6' OR paymode = '7' OR paymode = '8' OR paymode = '9' OR paymode = '10' OR paymode = '11' ) AND (invgroup = '0' ) AND invnum != '';" | sed '/credited/d' | wc -l`
SALES=`mysql -uroot -p$PASS --skip-column-names -e "use radius; SELECT price FROM rm_invoices LEFT JOIN rm_users ON rm_users.username = rm_invoices.username WHERE date >= '$START' AND date <= '$END' AND (paymode = '0' OR paymode = '1' OR paymode = '2' OR paymode = '3' OR paymode = '4' OR paymode = '5' OR paymode = '6' OR paymode = '7' OR paymode = '8' OR paymode = '9' OR paymode = '10' OR paymode = '11' ) AND (invgroup = '0' ) AND invnum != '';" | sed '/credited/d' | paste -sd+ | bc | cut -f1 -d"."`

echo "Total Users Activated/Renewed in $FMONTH = <b>$TOTNO</b>" >> $FINALFILE
echo "Total SALES Done in $FMONTH = <b>$SALES</b>" >> $FINALFILE
echo "
<b>$COMPANY</b>" >> $FINALFILE
echo "Generated on $DATE" >> $FINALFILE
echo "</pre>
" >> $FINALFILE

##Finally send email with all the data gathered USING SEND_EMAIL TOOL
/temp/sendEmail-v1.56/sendEmail -t $TO1 -u "INFO: GT DEALERS MONTHLY BILLING INFO for $FMONTH" -o tls=yes -s smtp.gmail.com:587 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$FINALFILE -o message-content-type=$CONTENT_TYPE
# Type file for view
cat $FINALFILE

 

February 27, 2017

Radius Manager Theme/Skin Collection

Filed under: Radius Manager — Tags: , — Syed Jahanzaib / Pinochio~:) @ 3:33 PM

Following are few customized themes for DMASOFTLAB Radius manager , Designed by various web developers.

  1. Digital Theme [Responsive as well, made by KANGNDO]
  2. Green Theme
  3. Blue Theme

 


General Steps to install theme

I assume you have DMASoftlab Radius Manager 4.1.x version installed and must be fully functional.

  • Download the theme file, unrar it in any temporary folder. you can use `tar zxvf filename.tar.gz /destination_folder`
  • Copy (or let’s say Overwrite) all the contents including files/folders from the (unzipped) folder name radiusmanager in /var/www/radiusmanager (or for CENTOS, its /var/www/html/radiusmanager). You can cp -vr syntax /source /target
  • Clear the browser cache, and reload the ACP administration control panel) page.

.


1- Digital Theme

Download Link: Radius Manager KANGNDO Theme Official Link

🙂

Sample Images:

1

2

3

4


2- Green Theme

Green Theme Download Link

green-1

 


Will update more later

 

Regard’s
Syed Jahanzaib

February 21, 2017

PowerShell Reference [Continued Post]

Filed under: Microsoft Related — Syed Jahanzaib / Pinochio~:) @ 8:34 AM

pwoershell-logo

coffe code.PNG

Following is reference post for Powershell command line usage to achieve different tasks. Recently I had to perform various administration tasks on more than 20 windows based servers , and using scripting it made my life a bit easier and I let the scripting  do the task on my behalf on scheduled basis 😉

These are very common tasks, commands but when you combine them with the Linux shell, they become ultra powerful and best thing is that you can create / add  some ‘ Artificial Intelligence ‘ in it. I have posted just basic level to hide the sensitivity of original tasks.

Following is collection of my own R&D, some commands are picked from Stackoverflow/Spicework forums as well.


General PowerShell Related CMD


Check PowerShell Version

$PSVersionTable.PSVersion
Upgrade PowerShell to Version 4 in Windows 7/2008 - 64bit
https://blogs.technet.microsoft.com/heyscriptingguy/2014/11/09/weekend-scripter-install-powershell-4-0-in-windows-7/

Execute Powershell script from Linux Shell using winexe

winexe -U DOMAIN/ID%’PASSWORD’ //IP_OR_NAME //101.11.12.38 ‘powershell.exe -inputformat none -command “dir”‘

winexe -U DOMAIN/ID%’PASSWORD’ //IP_OR_NAME ‘powershell.exe -inputformat none -command “c:\scripts\script_name.ps1″‘


Check Powershell Version & Process Architecture

#Check PowerShell Version
$PSVersionTable
# Check Processor Architecture
$env:PROCESSOR_ARCHITECTURE
# Get list of installed HOTFIX with details
Get-HotFix | Format-Table

 # Import Active Directory module

import-module activedirectory

Show folders that have not been updated/modified by X Period of Time

In my company I have Windows 2008 R2 [as a file sharing / backup server] with a centralized shared folder structure like this

  • D:\USERS
  • D:\USERS\USER1
    D:\USERS\USER1\AUTOBACKUP
    D:\USERS\USER1\DROP
    D:\USERS\USER1\EXHIBIT
  • D:\USERS\USER2
    D:\USERS\USER2\AUTOBACKUP
    D:\USERS\USER2\DROP
    D:\USERS\USER2\EXHIBIT

There are are around 100+ users folders and all users copy their important data on a daily basis there corresponding AUTOBACKUP folder. Every AUTOBACKUP folder have several sub folders and files in it.

My requirements was to somehow display ONLY the AUTOBACKUP folders name which are not updated in last 1 month, means no file in written in any autobackup or in its subfolders. (I dont requires drop/exhibit folders details as it can be updated by any1 , but autobackup can be updated only by the corresponding user)

Result Something like:

  • D:\USERS\USER1\AUTOBACKUP – Updated
  • D:\USERS\USER2\AUTOBACKUP – ALERT: Not updated since last month …

or show me result only for users whose auto backup have not updated from past month.

I tried to get result by powershell commands, but it shows me results if some one update the drop/exhibit too, and i want to exclude them in search criteria, the search should be done only in autobackup.

So here was the solution :)~

Get-WmiObject Win32_LogicalDisk -Filter "DriveType='3'" `
 -ComputerName SERVER_NAME | `
 Format-Table `
 @{l="Server";e={$_.SystemName}}, `
 @{l="Drive Letter";e={$_.DeviceID}}, `
 @{l="Free Space on Disk (GB)";e={"{0:n2}" -f ($_.freespace/1gb)}}, `
 @{l="Total Disk Space (GB)";e={"{0:n2}" -f ($_.size/1gb)}}, `
 @{l="Percentage Used";e={ "{0:P2}" -f (1 - ([Int64]$_.FreeSpace / [Int64]$_.Size)) }}

$PrettySizeColumn = @{name="Size";expression={
 $size = $_.Size
 if ( $size -lt 1KB ) { $sizeOutput = "$("{0:N2}" -f $size) B" }
 ElseIf ( $size -lt 1MB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1KB)) KB" }
 ElseIf ( $size -lt 1GB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1MB)) MB" }
 ElseIf ( $size -lt 1TB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1GB)) GB" }
 ElseIf ( $size -lt 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1TB)) TB" }
 ElseIf ( $size -ge 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1PB)) PB" } 
 $sizeOutput
}}

# change the folder name here ...
Get-ChildItem 'D:\USERS' -Directory | ForEach-Object {

$RecentAutoBackupFiles = @(
# change the folder name here too ...
 Get-ChildItem -Path "D:\USERS\$($_.Name)\autobackup" -File -Recurse | 
 Where-Object { $_.LastWriteTime -ge [datetime]::Now.AddMonths(-1) }
)

if (0 -eq $RecentAutoBackupFiles.Count)
 {
 "$($_.Name) "
 }
}

Result of above Script (which was executed using Linux bash script as usual:) )

1

 

2


Show Folder Size (in GB) | Sort by Size | Select top 10

This was intense task for me, and I was not able to sort it on my own. so I have to take help from stackoverflow and spicework forums.

Scenario:

We have a Windows 2008 R2  base file server where users have there shared folders.
Example:

  • D:\USERS
  • D:\USERS\USER1
  • D:\USERS\USER2
  • D:\USERS\USER3
  • D:\USERS\USER4
  • D:\USERS\USER5

All users folders have several hundreds sub folders in it.

Task:

Execute functions from Linux base system , which should remote to file server by winexe, execute powershell script, which should perform functions like

  • List all users folder name
  • Last modified time
  • Size conversion auto in kb/mb/gb ( order by size)
  • Email the result [customized] using sendEmail / gmail.

First the powershell script name foldersize.ps1 which will actually perform the functions on file server. we will copy this script in c:\temp on remote file server.

foldersize.ps1


param ($Path = ".")
$disk = ([wmi]"\\FILESERVER\root\cimv2:Win32_logicalDisk.DeviceID='D:'")
"D: GB Total = {0:#.0}
D: GB Used {2:#.0}
D: GB Free {1:#.0} " -f ($disk.Size/1GB),($disk.FreeSpace/1GB),($disk.Size/1GB-$disk.FreeSpace/1GB) | write-output

Get-WmiObject Win32_LogicalDisk -Filter "DriveType='3'" `
-ComputerName FILESERVER&nbsp;| `
Format-Table `
@{l="Server";e={$_.SystemName}}, `
@{l="Drive Letter";e={$_.DeviceID}}, `
@{l="Free Space on Disk (GB)";e={"{0:n2}" -f ($_.freespace/1gb)}}, `
@{l="Total Disk Space (GB)";e={"{0:n2}" -f ($_.size/1gb)}}, `
@{l="Percentage Used";e={ "{0:P2}" -f (1 - ([Int64]$_.FreeSpace / [Int64]$_.Size)) }}

$PrettySizeColumn = @{name="Size";expression={
$size = $_.Size
if ( $size -lt 1KB ) { $sizeOutput = "$("{0:N2}" -f $size) B" }
ElseIf ( $size -lt 1MB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1KB)) KB" }
ElseIf ( $size -lt 1GB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1MB)) MB" }
ElseIf ( $size -lt 1TB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1GB)) GB" }
ElseIf ( $size -lt 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1TB)) TB" }
ElseIf ( $size -ge 1PB ) { $sizeOutput = "$("{0:N2}" -f ($size / 1PB)) PB" }
$sizeOutput
}}

Get-ChildItem -Path $Path | Where-Object {$_.PSIsContainer} | ForEach-Object {
$size = ( Get-ChildItem -Path $_.FullName -Recurse -Force | where {!$_.PSIsContainer} | Measure-Object -Sum Length).Sum
$obj = new-object -TypeName psobject -Property @{
Path = $_.Name
Time = $_.LastWriteTime
Size = $size
}
$obj
} | Sort-Object -Property Size -Descending | Select-Object Path, Time, $PrettySizeColumn

try to execute this file on the file server from powershell terminal. It should give you proper results. JUST BE VERY SURE TO READ THE SCRIPT VERY WELL, AS IT SHOULD BE MODIFIED AS PER YOUR REQUIREMENTS, PLUS I USED DOMAIN ADMIN ID, SO I HAD ALL THE ACCESS ON ALL THE COMPUTERS FROM MY PC /REMOTELY AS WELL.

.\foldersize.ps1 -Path  \\FILESERVER\C$\Softwares\IMAGES_ISO

Once done,  make a bash script in your linux (ubuntu) system  which will execute the above script remotely and will customized the result and email to the admin.

BASH FILE / folder_iquiry.sh which will run the ps file from linux terminal


#!/bin/bash
#set -x
# This bash script will query remote file server storage using Powershell Commands.
# It will send report via email with relevant details like top used folders , Very useful some times.
# Syed Jahanzaib / aacableAThotmailDOTcom
# http://aacableDOTwordpressDOTcom
# 20-feb-2017
start=`date +%s`
COMPANY="ZAIB"
SRVNAME="SRV01"
SRV_FRIENDLY_NAME="File Server D:Drive"
IP="10.0.0.1"
DOMAIN="DC.LOCAL"
PASS="PASSWORD"
ID="ADMIN"
#TARGET DIRECTORY
TDIR="d:\users"
TEMP_HOLDER="/tmp/xdrive_temp_raw_report.txt"
TEMP_HOLDER_FINAL="/tmp/xdrive_final_mail_report.txt"
&gt; $TEMP_HOLDER
&gt; $TEMP_HOLDER_FINAL
DATE=`date`

# GMAIL DETAILS to send EMAIL alert
SENDMAILAPP="/temp/sendEmail-v1.56/sendEmail"
GMAILID="ADMIN_GMAIL_ID@gmail.com"
GMAILPASS="GMAIL_PASS"
# Add recipient email address below
ADMINMAIL1="aacableAThotmailDOTcom"

MSG_SUB="$COMPANY $SRV_FRIENDLY_NAME - $SRVNAME - / Weekly Report @ $DATE"
MSG_BODY="$COMPANY $SRV_FRIENDLY_NAME - $SRVNAME - Weekly Report for Users D: drive folder's sorted by size
@ $DATE
"

FOOTER="Automated Weekly Report Generated using Linux Powered Powershell !!
Sys. Admin
$COMPANY IS Dept."

echo "
$MSG_BODY
" &gt; $TEMP_HOLDER

#QUERY SERVER X: DRIVE
winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "c:\temp\foldersize.ps1 -Path '"$TDIR"' ' &gt;&gt; $TEMP_HOLDER

# Remove Junk Line with unknonw character, which is unique or specific occured in my lab test

end=`date +%s`
echo "It took $(($end - $start)) seconds to complete this task..." &gt;&gt; $TEMP_HOLDER
echo "
$FOOTER" &gt;&gt; $TEMP_HOLDER

#Print result
cat $TEMP_HOLDER
#send email
sendemail -u "$MSG_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$TEMP_HOLDER -o message-content-type=text

# Script ends here

Now execute file from linux terminal like this…

/temp/folder_inquiry.sh

SAMPLE:

userreport.PNG


Show Folder Size (in GB) | Sort by Size | Select top 10

[This method have one BIG disadvantage, dueto 260 characters limit in windows, it may not show files/folders above then this limit. so it may not give your correct result if you have some deep folder structure/long files name in it.]

#Windows PS Version
ls c:\temp | select Name, @{Name="Type";Expression={if($_.psIsContainer){"---Directory---"}else{"---File---"}}}, @{Name="Size(GB)";Expression={[Math]::Round($(ls $_.FullName -recurse| measure Length -sum).Sum/1GB, 2)}}| sort -property "Size(GB)" -desc | Select -First 10

# Linux Winexe format
winexe -U DC/ID%PASS //IP 'powershell.exe -inputformat none -command "ls c:\backup\ | select Name, @{Name='"'"'"Type"'"'"';Expression={if($_.psIsContainer){'"'"'"Directory"'"'"'}else{'"'"'"File"'"'"'}}}, @{Name='"'"'"Size(GB)"'"'"';Expression={[Math]::Round($(ls $_.FullName -recurse| measure Length -sum).Sum/1GB, 3)}}| sort -property '"'"'"Size(GB)"'"'"' -desc | Select -First 10"'

Example of C:\temp contents …

  • C:\TEMP
  • C:\TEMP\FOLDER1
  • C:\TEMP\FOLDER-1\SUB_FOLDER
  • C:\TEMP\FOLDER-1\SUB_FOLDER_MORE
  • C:\TEMP\FOLDER2
  • C:\TEMP\FOLDER3

This will query all folders/sub-folders inside the c:\temp folder, and display only the main folders name including sizes of subfolder as well ..

Name Type Size(GB)
---- ---- --------
Win2008_test Directory 28.9
Ubuntu-PHP-API Directory 2.75
ubuntu-freeradius Directory 2.15
zaib_temp_radius Directory 2.09
MIKROTIK-1 - Copy Directory 0.39


Show files with Name & Size greater than 5 GB

[This was required in a script where I schedule it to email the top users in mail server by querying the folder directly]

Following command is formatted to be executed by WINEXE [Linux]

winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "Get-ChildItem -Path '"$TDIR"' | Where-Object {$_.length -gt 5GB} | Sort-Object -descending -Property Length | Format-Table Name,@{name='"'"'Size GB'"'"';expression={$_.length/1GB};FormatString='"'"'N1'"'"'}"' | sed -e "$DEL_LINE" | sed '/^\s*$/d' |nl &gt;&gt; $TEMP_HOLDER

Script to get specific folder files and specific  folder total size, sort and email to admin on every Monday / Weekly

#!/bin/bash
#set -x
# This bash script will query remote lotus domino mail server storage using Powershell Commands.
# It will send report via email with erelevant details, Very useful some times.
# Syed Jahanzaib / aacableAThotmailDOTcom
# http://aacableDOTwordpressDOTcom
# 20-feb-2017
COMPANY="ZAIB"
SRVNAME="MYSRV"
IP="10.0.0.1"
DOMAIN="DC_NAME"
PASS="PASSWORD"
ID="ADMINISTRATOR"
TDIR="D:\lotus\domino\data\mail"
TDIR_FULL="D:\lotus"
TDIR_MAIL="D:\lotus\domino\data\mail"
TDIR_ARCH="D:\lotus\domino\data\archive"
# How many lines to be dleeted from winexe output for top users section
DEL_LINE="1,3d"
TEMP_HOLDER="/tmp/mail_top_users.txt"
TEMP_HOLDER_FULL="/tmp/mail_lotus_folder_size.txt"
&gt; $TEMP_HOLDER
DATE=`date`

# GMAIL DETAILS to send EMAIL alert
SENDMAILAPP="/temp/sendEmail-v1.56/sendEmail"
GMAILID="ADMIN_GMAIL_ID@gmail.com"
GMAILPASS="GMAIL_PASSWORD"
# Add recipient email address below
ADMINMAIL1="aacableAThotmailDOTcom"

MSG_SUB="$COMPANY Lotus Mail Server / Weekly Report @ $DATE"
MSG_BODY="$COMPANY - $SRVNAME - Lotus Mail Server Weekly Report for Total Usage and TOP users exceeding 5GB mailbox size
@ $DATE
"
FOOTER="Automated Weekly Report Generated using Linux Powered Powershell !!
Sys. Admin
$COMPANY IS Dept."

echo "
$MSG_BODY
" &gt; $TEMP_HOLDER

#Full size of Lotus Folder - Overall
FULL_SIZE=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command " "\"{0:N0}"\" -f ( (Get-ChildItem -Path '"$TDIR_FULL"' -Recurse | Measure-Object -Property Length -Sum ).Sum / 1GB)"' |sed '/^\s*$/d'`
echo "Lotus Total DATA size in GB = $FULL_SIZE" &gt;&gt; $TEMP_HOLDER

#Full size of Lotus MAIL Folder only
FULL_SIZE_MAIL=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command " "\"{0:N0}"\" -f ( (Get-ChildItem -Path '"$TDIR_MAIL"' -Recurse | Measure-Object -Property Length -Sum ).Sum / 1GB)"' |sed '/^\s*$/d'`
echo "Lotus Total User Inbox MAIL SIZE in GB = $FULL_SIZE_MAIL" &gt;&gt; $TEMP_HOLDER

#Full size of Lotus ARCHIVE Folder only
FULL_SIZE_ARCH=`winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command " "\"{0:N0}"\" -f ( (Get-ChildItem -Path '"$TDIR_ARCH"' -Recurse | Measure-Object -Property Length -Sum ).Sum / 1GB)"' |sed '/^\s*$/d'`
echo "Lotus User's ARCHIVE Folder SIZE in GB = $FULL_SIZE_ARCH" &gt;&gt; $TEMP_HOLDER

echo "----------------------------------------------
Lotus Users List whose inbox is exceeding 5 GB" &gt;&gt; $TEMP_HOLDER

#Only Top users exceeding 5GB
winexe -U $DOMAIN/$ID%"$PASS" //$IP 'powershell.exe -inputformat none -command "Get-ChildItem -Path '"$TDIR"' | Where-Object {$_.length -gt 5GB} | Sort-Object -descending -Property Length | Format-Table Name,@{name='"'"'Size GB'"'"';expression={$_.length/1GB};FormatString='"'"'N1'"'"'}"' | sed -e "$DEL_LINE" | sed '/^\s*$/d' |nl &gt;&gt; $TEMP_HOLDER

echo "

$FOOTER" &gt;&gt; $TEMP_HOLDER
# Display result by cat
cat $TEMP_HOLDER
# Send email
sendemail -u "$MSG_SUB" -o tls=yes -s smtp.gmail.com:587 -t $ADMINMAIL1 -xu $GMAILID -xp $GMAILPASS -f $GMAILID -o message-file=$TEMP_HOLDER -o message-content-type=text

Result of above script …

1.PNG


PowerShell Get Folder / File ACL list

Get-Acl c:\temp | select -Expand Access

Sample Result:


PS C:\&gt; Get-Acl c:\temp | select -Expand Access
FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : 268435456
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly

FileSystemRights : FullControl
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : 268435456
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly

FileSystemRights : ReadAndExecute, Synchronize
AccessControlType : Allow
IdentityReference : BUILTIN\Users
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : None

FileSystemRights : Modify, Synchronize
AccessControlType : Allow
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited : True
InheritanceFlags : None
PropagationFlags : None

FileSystemRights : -536805376
AccessControlType : Allow
IdentityReference : NT AUTHORITY\Authenticated Users
IsInherited : True
InheritanceFlags : ContainerInherit, ObjectInherit
PropagationFlags : InheritOnly

PS C:\&gt;


Regard’s
Syed Jahanzaib

February 16, 2017

Modifying ‘tombstoneLifetime’ value in Active Directory

Filed under: Microsoft Related — Tags: , , — Syed Jahanzaib / Pinochio~:) @ 9:40 AM

Default lifetime for tombstone.jpg


What is tombstone Lifetime?

The AD tombstone lifetime determines how long deleted items exist in AD before they are purged, for example users  or other objects. The default value in Windows 2008 is 180 Days.

Why I need to modify its default value,  ?

We want to increase it for some audit purpose, specially to track deleted objects (example how many Users were deleted in last 1 or 2 years)

Let’s Start …

METHOD # 1 – Using GUI Method

Execute ADSIEdit tool by

%SystemRoot%\system32\adsiedit.msc

  • Now using ADSIEdit tool, connect to your domain controller.
  • Navigate to CN=Directory Services , Right click and select Properties.
  • Find tombstoneLifetime and Click Edit,
  • Now define value in days for how long you want to increase the value. I wanted 2 years so I put 630 . This values must be in DAYS.

As showed in the image below …

tombstone.PNG

Note: By Some mistake, i typed 630, whereas the actual number for 2 years is 730, so change it accordingly


METHOD # 2 – Using PowerSHELL Command

Setting Two Years Tombstone Lifetime

Import-Module ActiveDirectory
$ConfNameContext = Get-ADRootDSE | Select-Object -Expandproperty configurationNamingContext
Set-ADObject -Identity "CN=Directory Service,CN=Windows NT,CN=Services,$ConfNameContext" -Replace @{'tombstonelifetime'='730'}

Querying tombstoneLifetime value via command

 

# Using dsquery command

dsquery * " cn=Directory Service,cn=Windows NT,cn=Services,cn=Configuration,dc=agp1" -scope base -attr tombstonelifetime

[COMMAND RESULT OUTPUT]

tombstonelifetime
730

# Using POWERSHELL 

#1

(get-adobject “cn=Directory Service,cn=Windows NT,cn=Services,$(([adsi](“LDAP://RootDSE”)).configurationNamingContext)” -properties “tombstonelifetime”).tombstonelifetime

#2

Import-Module ActiveDirectory
$ConfNameContext = Get-ADRootDSE | Select-Object -Expandproperty configurationNamingContext
Get-ADObject -Identity “CN=Directory Service,CN=Windows NT,CN=Services,$ConfNameContext” -properties tombstonelifetime |Format-List

Note / z@iB:

I found out that all commands doesn’t show default tombstoneLifetime. Once I modify the value, then I was able to see the value using above commands.

Regard’s
Syed Jahanzaib

« Newer PostsOlder Posts »

%d bloggers like this: