Quantcast
Channel: Syed Jahanzaib – Personal Blog to Share Knowledge !
Viewing all articles
Browse latest Browse all 409

C# PPPoE Dialer Application Code

$
0
0

vc.png

Video of code working 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 ~

 

On few requests, I have made an an PPPoE Dialer program in Visual C Sharp. This code/program can create / dial a broadband pppoe connection on Windows 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 around one week to develop this code. Google search and Stack-overflow discussion forums helped a lot.

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

if u r good.png

If you are Good at something, never do it for free

But denying the above Joker statement, here I am. sharing my basic knowledge for anyone who wants to learn from IT ~


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

// Code Working Workflow Example //

  • Username / Password Boxes: This must be filled first time, & the code will save it in registry, so next time the dialer is launched , it will be read automatically to avoid entering credentials again)
  • Dial Button: which will basically dial the pppoe connection, 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.
  • 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 delete, and re-create.
  • Dialer LAN Status Button: It will check if the dialer is connected or not. Just to refresh the status.
  • Internet Access Button: It will check ping to specific HOST (8.8.8.8) and if ping success/fails, set status accordingly.
  • Balloon Texts / Notifications: When application is minimized to System Tray
  • Auto Minimize: on connect / manual disconnect
  • Tray Icon Menu Strip Menu Context to Show/Exit app. Example to show function.
  • The code will keep checking the dialer status (every 5sec) /net status  (every 10sec) and update eh text label accordingly.

I have NOT added auto – redial , but you can easily add it in raswatcher section ,if you like 🙂 , i may be missing some other functions like data counters, will add more later, or you can add your own functions too.

I will update more later if get the chance…

Ok lets hit the Road , and view the code …


the CODE!

// C# program for pppoe dialer with DotRas Support
// 20th March - 2017
// By Syed.Jahanzaib
// aacable at hotmail dot com
// http://aacable dot wordpress dot com
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;

namespace pppoe_dialer___zaib_last
{
 public partial class Form1 : Form
 {

int lanInterval = 5; //5 sec
 int netInterval = 10; //10 sec

 //private bool willClose;
 private bool connected;
 private RasHandle handle = null;
 private RasHandle Rashandler = null;
 private RasConnection connection = null;
 public Form1()
 {
 InitializeComponent();
 Timer t = new Timer();
 t.Interval = 1000; //1 sec
 t.Tick += new EventHandler(t_Tick);
 t.Start();
 }
 void t_Tick(object sender, EventArgs e)
 {
 lanInterval--;
 netInterval--;

if (lanInterval == 0)
 {
 checkpppstatus();
 lanInterval = 5; //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 == "pppoe2");
 if (conn != null)
 {
 connstatus.Text = "Dialer Connection Status: Connected!";
 connstatus.ForeColor = System.Drawing.Color.Green;
 }
 else
 {
 connstatus.Text = "Dialer Connection Status: Disconnected!";
 connstatus.ForeColor = System.Drawing.Color.Red;
 }

});
 }

protected void checknetstatus()
 {
 if (IsOnline(textBox1.Text) == true)
 {
 internetStatus.ForeColor = System.Drawing.Color.Green;
 string Status = "Internet Stauts: UP";
 internetStatus.Text = Status;
 }
 else
 {
 internetStatus.ForeColor = System.Drawing.Color.Red;
 string Status = "Internet Stauts: 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 Displaynotifyfordisconnect()
 {
 try
 {
 notifyIcon1.BalloonTipTitle = "My PPPoE Dialer DISCONNECTED !!!";
 notifyIcon1.BalloonTipText = "Internet Disconnected !!!";
 notifyIcon1.Visible = true;
 notifyIcon1.ShowBalloonTip(5000);
 {
 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);
 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", "");
 }
 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, "My PPPoE Dialer", "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("pppoe2", 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 == "pppoe2");
 if (conn != null)
 {
 MessageBox.Show("Dialer Already Connected! Disconnect it first to re-create.");
 return;
 }
 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("test", "test", true, true);
 ///// Create PPPOE Dialer SHORTCUT on desktop begins

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 = "pppoe2";
 shellLinkObject.Path = @"%windir%\System32\rasphone.exe";
 shellLinkObject.WorkingDirectory = "%windir%";

shellLinkObject.Save(path2);
 //// SHORTCUT END

}
 }

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 label1_Click_1(object sender, EventArgs e)
 {
 System.Diagnostics.Process.Start("https://aacable.wordpress.com");
 }
 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 = ("pppoe2");
 {
 };

//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 = ("pppoe2");
 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 = ("pppoe2");
 rasDialer1.EntryName = ("pppoe2");
 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;
 }
 //
 var conns = RasConnection.GetActiveConnections();
 var conn = conns.FirstOrDefault(o => o.EntryName == "pppoe2");
 if (conn != null)
 MessageBox.Show("Dialer - Already connected!");
 else
 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");
 }
 else if (e.Connected)
 {
 var conn = RasConnection.GetActiveConnections().Where(c => c.EntryName == "pppoe2").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("test", "test", true, true);
 ShowInTaskbar = true;
 this.Hide();
 }
 }
 }

 private void dcButton_Click(object sender, EventArgs e)
 {
 try
 {
 var conns = RasConnection.GetActiveConnections();
 var conn = conns.FirstOrDefault(o => o.EntryName == "pppoe2");
 if (conn != null)
 {
 conn.HangUp();

 this.StatusTextBox.AppendText(string.Format("{0}\r\n\r\n", "\r\nDisconnected on user request !"));
 connstatus.ForeColor = Color.Red;
 checkpppstatus();
 this.Hide();
 Displaynotifyfordisconnect();
 }
 }
 catch (Exception ex)
 {

MessageBox.Show(ex.Message);
 }
 }

private void rasDialer1_Error(object sender, System.IO.ErrorEventArgs e)
 {
//
 }

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 = "My Internet Dialer";
 }

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)
 {
 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();
 }
 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();
 }

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 refreshButton_Click(object sender, EventArgs e)
 {
 checkpppstatus();
 }

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

private void rasConnectionWatcher1_Disconnected(object sender, RasConnectionEventArgs e)
 {
 checkpppstatus();
 Displaynotifyfordisconnect();
 }

private void rasConnectionWatcher1_Connected(object sender, RasConnectionEventArgs e)
 {
 Displaynotify();
 }

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 test1_Click(object sender, EventArgs e)
 {
 if (IsOnline(textBox1.Text) == true)
 {
 internetStatus.ForeColor = System.Drawing.Color.Green;
 string Status = "Internet Stauts: UP";
 internetStatus.Text = Status;
 }
 else
 {
 internetStatus.ForeColor = System.Drawing.Color.Red;
 string Status = "Internet Stauts: DOWN";
 internetStatus.Text = Status;
 }

}

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


 

I will upload the complete package with code/debug/exe package later …

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 !


Filed under: Programming

Viewing all articles
Browse latest Browse all 409

Trending Articles