×
Short Notes for C#



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

 


Declare Global Variables

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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 !

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 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

1
2
3
4
5
// Some coloring fun
private void ColorRed()
{
StatusTextBox.SelectionColor = Color.Red;
}

Adding Bold Text

1
2
3
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

1
2
3
if ((Globals.Variable1 == "0") && (Globals.Variable2 == "0"))
 
// then do this or that

Message Box with Warning sign & OK button

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

Running thread separately without hanging UI

1
2
3
4
5
6
7
await Task.Run(() =>
{
 
// your task
 
});
}

Testing Remote TCP Port Status

1
2
3
4
5
6
7
8
9
10
11
{
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
// 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");
}
}
}
}
 
}
 
}
 
}

×

Notice!!

All Quantic user are requested to use our hybrid cloud drive for you project and Data base . We had added new module of cronjob to schedule and optimise your backup .