Syed Jahanzaib Personal Blog to Share Knowledge !

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 !

Advertisements

October 8, 2013

PPPoE Dialer via DOS Batch File

Filed under: Microsoft Related — Tags: , , , — Syed Jahanzaib / Pinochio~:) @ 1:53 PM

Changelog:

8th Oct , 2013 9:30pm : Entry added  to create network profile folder if not already there (usually on fresh win7)
9th Oct , 2013 01:45pm : Entry added  to create new phonbook profile, it will not overwrite or delete previous one 🙂

Following is a simple and quickest method to create pppoe dialer using MSDOS batch file made for Windows 7, which create a new rasphone profile for PPPoE Dialer. Usually this sort of work is done using VB , or VB/VC# .NET with Dotras type programming languages which does the job nicely with lots of options and fancy look menus etc, but due to my limited knowledge towards programming, I decided to go with my traditional CLI method. I created this batch program in a very short time without much googling.

Phonebook Location to store profiles (new and old)

%userprofile%\AppData\Roaming\Microsoft\Network\Connections\Pbk\

This is just an example, you can modify at as per your requirements , The issue i faced while adding multiple lines was white space at the end, and if there are additional white spaces in the file , rasphone will not detect the new entry. therefore I later used algorithm to remove white spaces.

Any suggestion to improve the method will be highly appreciable . . . Please psot your comment if this batch file is working ok for you . . .

Let’s Start.

Create a new batch file like

notepad c:\dialer.bat

Paste following data and save.

@echo off
rem
rem #########################################
rem ### PPPoE Dialer Script for Windows 7
rem ### Syed Jahanzaib / aacable@hotmail.com
rem ### http://aacablw.wordpress.com
rem #########################################

rem ### Creating pppoe profile in a temporarily text file
echo. 2>  c:\rstemp.txt
echo [AA_PPPoE_Dialer] >> c:\rstemp.txt
echo Encoding=1 >> c:\rstemp.txt
echo PBVersion=1 >> c:\rstemp.txt
echo Type=5  >> c:\rstemp.txt
echo AutoLogon=0 >> c:\rstemp.txt
echo UseRasCredentials=0 >> c:\rstemp.txt
echo LowDateTime=-582619296 >> c:\rstemp.txt
echo HighDateTime=30327625 >> c:\rstemp.txt
echo DialParamsUID=6326979 >> c:\rstemp.txt
echo Guid=359A05BF4C146640949F56383A0F18F5 >> c:\rstemp.txt
echo VpnStrategy=0 >> c:\rstemp.txt
echo ExcludedProtocols=0 >> c:\rstemp.txt
echo LcpExtensions=1 >> c:\rstemp.txt
echo DataEncryption=8 >> c:\rstemp.txt
echo SwCompression=0 >> c:\rstemp.txt
echo NegotiateMultilinkAlways=0 >> c:\rstemp.txt
echo SkipDoubleDialDialog=0 >> c:\rstemp.txt
echo DialMode=0 >> c:\rstemp.txt
echo OverridePref=15 >> c:\rstemp.txt
echo RedialAttempts=3 >> c:\rstemp.txt
echo RedialSeconds=60 >> c:\rstemp.txt
echo IdleDisconnectSeconds=0 >> c:\rstemp.txt
echo RedialOnLinkFailure=1 >> c:\rstemp.txt
echo CallbackMode=0 >> c:\rstemp.txt
echo CustomDialDll= >> c:\rstemp.txt
echo CustomDialFunc= >> c:\rstemp.txt
echo CustomRasDialDll= >> c:\rstemp.txt
echo ForceSecureCompartment=0 >> c:\rstemp.txt
echo DisableIKENameEkuCheck=0 >> c:\rstemp.txt
echo AuthenticateServer=0 >> c:\rstemp.txt
echo ShareMsFilePrint=0 >> c:\rstemp.txt
echo BindMsNetClient=0 >> c:\rstemp.txt
echo SharedPhoneNumbers=0 >> c:\rstemp.txt
echo GlobalDeviceSettings=0 >> c:\rstemp.txt
echo PrerequisiteEntry= >> c:\rstemp.txt
echo PrerequisitePbk= >> c:\rstemp.txt
echo PreferredPort=PPPoE4-0 >> c:\rstemp.txt
echo PreferredDevice=WAN Miniport (PPPOE) >> c:\rstemp.txt
echo PreferredBps=0 >> c:\rstemp.txt
echo PreferredHwFlow=0 >> c:\rstemp.txt
echo PreferredProtocol=0 >> c:\rstemp.txt
echo PreferredCompression=0 >> c:\rstemp.txt
echo PreferredSpeaker=0 >> c:\rstemp.txt
echo PreferredMdmProtocol=0 >> c:\rstemp.txt
echo PreviewUserPw=1 >> c:\rstemp.txt
echo PreviewDomain=0 >> c:\rstemp.txt
echo PreviewPhoneNumber=0 >> c:\rstemp.txt
echo ShowDialingProgress=1 >> c:\rstemp.txt
echo ShowMonitorIconInTaskBar=1 >> c:\rstemp.txt
echo CustomAuthKey=0 >> c:\rstemp.txt
echo AuthRestrictions=552 >> c:\rstemp.txt
echo IpPrioritizeRemote=1 >> c:\rstemp.txt
echo IpInterfaceMetric=0 >> c:\rstemp.txt
echo IpHeaderCompression=0 >> c:\rstemp.txt
echo IpAddress=0.0.0.0 >> c:\rstemp.txt
echo IpDnsAddress=0.0.0.0 >> c:\rstemp.txt
echo IpDns2Address=0.0.0.0 >> c:\rstemp.txt
echo IpWinsAddress=0.0.0.0 >> c:\rstemp.txt
echo IpWins2Address=0.0.0.0 >> c:\rstemp.txt
echo IpAssign=1 >> c:\rstemp.txt
echo IpNameAssign=1 >> c:\rstemp.txt
echo IpDnsFlags=0 >> c:\rstemp.txt
echo IpNBTFlags=0 >> c:\rstemp.txt
echo TcpWindowSize=0 >> c:\rstemp.txt
echo UseFlags=3 >> c:\rstemp.txt
echo IpSecFlags=0 >> c:\rstemp.txt
echo IpDnsSuffix= >> c:\rstemp.txt
echo Ipv6Assign=1 >> c:\rstemp.txt
echo Ipv6Address=:: >> c:\rstemp.txt
echo Ipv6PrefixLength=0 >> c:\rstemp.txt
echo Ipv6PrioritizeRemote=1 >> c:\rstemp.txt
echo Ipv6InterfaceMetric=0 >> c:\rstemp.txt
echo Ipv6NameAssign=1 >> c:\rstemp.txt
echo Ipv6DnsAddress=:: >> c:\rstemp.txt
echo Ipv6Dns2Address=:: >> c:\rstemp.txt
echo Ipv6Prefix=0000000000000000 >> c:\rstemp.txt
echo Ipv6InterfaceId=0000000000000000 >> c:\rstemp.txt
echo DisableClassBasedDefaultRoute=0 >> c:\rstemp.txt
echo DisableMobility=0 >> c:\rstemp.txt
echo NetworkOutageTime=0 >> c:\rstemp.txt
echo ProvisionType=0 >> c:\rstemp.txt
echo PreSharedKey= >> c:\rstemp.txt

echo NETCOMPONENTS= >> c:\rstemp.txt
echo ms_msclient=0 >> c:\rstemp.txt
echo ms_server=0 >> c:\rstemp.txt

echo MEDIA=rastapi >> c:\rstemp.txt
echo Port=PPPoE4-0 >> c:\rstemp.txt
echo Device=WAN Miniport (PPPOE) >> c:\rstemp.txt

echo DEVICE=PPPoE >> c:\rstemp.txt
echo LastSelectedPhone=0 >> c:\rstemp.txt
echo PromoteAlternates=0 >> c:\rstemp.txt
echo TryNextAlternateOnFail=1 >> c:\rstemp.txt

rem ### Removing white spaces so that it can be readable by phone book /zaib
rem echo. 2>  c:\rscompile.bat
rem if [%1]==[] then echo File name missing & goto :EOF >>
(for /f "tokens=1" %%a in (rstemp.txt) do echo %%a) > %~n1aa-rasphone.pbk

rem ### Location for rasphone.pbk [just for reference] /zaib
rem %userprofile%\AppData\Roaming\Microsoft\Network\Connections\Pbk\

rem ### Creating Network Profile Folder to store dialer profile, if its not there already
mkdir %userprofile%\AppData\Roaming\Microsoft\Network
mkdir %userprofile%\AppData\Roaming\Microsoft\Network\Connections
mkdir %userprofile%\AppData\Roaming\Microsoft\Network\Connections\pbk
cls
rem Copy new rasphone.pbk to user network profile /zaib
rem cd %userprofile%\AppData\Roaming\Microsoft\Network\Connections\Pbk\
rem ren rasphone.pbk rasphone.pbk.old
copy c:\aa-rasphone.pbk %userprofile%\AppData\Roaming\Microsoft\Network\Connections\Pbk\

rem ### Create Network Connection Center Icon on Desktop /zaib
rem ### I coulnd't found a way to create shortcut of dialer on desktop, someone please suggest
set linkName=AA-Network Connections
set linkPath=%userprofile%\desktop
set program=C:\WINDOWS\SYSTEM32\ncpa.cpl
set workDir=C:\WINDOWS\system32
set iconfile=%SystemRoot%\system32\SHELL32.dll
set icon=-18
set windowStyle=2
echo Set oWS = WScript.CreateObject("WScript.Shell") > temp.vbs
echo sLinkFile = "%linkPath%\%linkName%.LNK" >> temp.vbs
echo Set oLink = oWS.CreateShortcut(sLinkFile) >> temp.vbs
echo oLink.TargetPath = "%program%" >> temp.vbs
echo oLink.IconLocation = "%iconFile%, %icon%" >> temp.vbs
echo oLink.WindowStyle = "%windowStyle%" >> temp.vbs
echo oLink.WorkingDirectory = "%workdir%" >> temp.vbs
echo oLink.Save >> temp.vbs

WScript.exe temp.vbs
del temp.vbs

rem #
rem ### Show Popup Message box after everything completed /zaib
rem #

mshta javascript:alert("Dialer Installation Completed!!!\n\Please Restart you computern ,Thank You\n\Syed.Jahanzaib! aacable@hotmail.com");close();

rem # THE END #

Now execute it from c:\dialer.bat & then restart your computer. If you dont want to restart the newly created connection will not show in network connections, You have to press F5 in the network connections to display the newly created profile. After restart it will appear auto in network and sharing center.

After successful lab testing, its time to make it a distributable package. To convert it in executable package, you download BATCH to EXE converter.


http://www.f2ko.de/downloads/Bat_To_Exe_Converter.zip

extract and run Bat_To_Exe_Converter.exe

Fill up the required info as shown in teh images below and click on compile.

1- compile

and click on COMPILE , it will create .exe Package. You can also add additional info like ICON file , or product version or info

As showed in the image below . .

2- compile

.

.

End results 🙂

3- info

Regard’s
Syed Jahanzaib

September 27, 2011

Howto create Windows 7 PPPoE Dialer Installer Package using Auto-iT !


PPPoE Dialer Package Sample

THIS IS SOME OLD CODE AND MAY NOT WORK PROPERLY NOW. KINDLY LOOK FOR SOME OTHER SOLUTION. JUST READ IT FOR INFORMATION PURPOSE ONLY BUT IT WILL NOT SERVE ANY GOOD TO YOU I GUESS

THIS IS SOME OLD CODE AND MAY NOT WORK PROPERLY NOW. KINDLY LOOK FOR SOME OTHER SOLUTION. JUST READ IT FOR INFORMATION PURPOSE ONLY BUT IT WILL NOT SERVE ANY GOOD TO YOU I GUESS

THIS IS SOME OLD CODE AND MAY NOT WORK PROPERLY NOW. KINDLY LOOK FOR SOME OTHER SOLUTION. JUST READ IT FOR INFORMATION PURPOSE ONLY BUT IT WILL NOT SERVE ANY GOOD TO YOU I GUESS

 

Following is a guide on howto to create Windows 7 PPPoE DIALER Installer Package.  It is based on same principles as my previous Winxp PPPoE Dialer Script.

Being a Linux Lover, I am publishing these codes under GPL (General Public License). You can modify it as per your requirements, redistribute it. Don’t forget to give credit if it helps you :~) Remember it’s not a standard, neat and clean way but It’s very simple and it do the job nicely:)

This script is made for Windows 7 Operating System Only, For windows XP/200x, please follow the below link.
https://aacable.wordpress.com/2011/09/01/howto-create-pppoe-dialer-installer-package-using-auto-it/

Following functions will be performed.

# First it will ask you if you want to continue to install the Dialer.
# Then it will minimize all opened Window to Let user focus the installation,
# Then it will show you the Logo in front(dialer.jpg which is customizable according to your need),
# in Background it will open the Network and sharing center and create new entry for pppoe dialer,
# After creating dialer, it will close the Logo and will show you the message that Dialer have been installed.

This is not fully final Script, Few things have been left intentionally, Following functions will not be performed.

# It will not check Duplicate entries. For example, If you have installed the dialer, and want to re.install it again, It will not check duplicate entries, and will stop on DUPLICATE NAME FOUND, So please Delete Previously Created Dialer with the same name.

Please check and Do Let me know the results.

I have checked It on Windows 7 several times and working fine. The speed of executing functions in program can be + or – in some cases, It can be tuned with the $DELAY variable.

So Here we go . . .

First of all you have to download ‘Auto-it‘ software from its website at

http://www.autoitscript.com/cgi-bin/getfile.pl?autoit3/autoit-v3-setup.exe

I used Latest version: v3.3.6.1, Do full installation of AutoiT.

After installation, launch it by  Goto Start / Programs / Autoit v3  and select SciTE Script Editor

Now an advance Notepad type windows will open, Just paste the following code in it.

(Note: FOR SOME REASONS, Sometimes CODE Does not displayed PROPERLY IN THIS BLOG, IF you face syntax errors,  you can copy the raw code from following location) http://pastebin.com/BhNSMeKx

#cs ----------------------------------------------------------------------------
AutoIt Version : 3.3.6.1
Author : SYED JAHANZAIB
Email : aacable@hotmail.com
Web : https://aacable.wordpress.com
Script Function: Template AutoIt script. for PPPoE Dialer Installer
OS Supported   : Windows 7
Dated          : 27/09/2011
#ce ----------------------------------------------------------------------------
; Script Start - Add your code below here

$DELAY = 300
$answer = MsgBox(4, "PPPOE Connection", "This script will create a PPPOE DIALER, Do you want to Continue?")
If $answer = 7 Then
Exit
EndIf

WinMinimizeAll ( )
; Put Logo in front and do installation in background, place dialer.jpg in the same folder
; From you have launched dialer.
SplashImageOn("Please wait Few Seconds While Installer Installs PPPoE Dialer ", "dialer.jpg", 800,650)

$COMPANY_NAME = ("Type Your pppoe service name here")
; Example $COMPANY_NAME = ("MY_ISP")
$DELAY = 300

; Run Windows 7 Network Setup
Run("control.exe /name Microsoft.NetworkAndSharingCenter")
Sleep($DELAY)

; Send TAB 7 times to Select 'setup a new connection'
Send("{TAB 7}")

; Send Enter to Launch 'setup a new connection'
Send("{ENTER}")

; Send Next to select 'Connect to Internet'
Sleep($DELAY)
Send("!n")

; Send 'S' to select 'Setup a new connection anyway
Sleep($DELAY)
Send("!s")

;Check Duplicate Connection ???

Sleep($DELAY)
Send("!n")

; Send 'r' to select 'Broadband PPPoE'
Sleep($DELAY)
Send("!r")

; Send TAB 4 times to Enter 'ISP NAME'
Sleep($DELAY)
Send("{TAB 4}")
Send($COMPANY_NAME)
Sleep($DELAY)

; Send 'c' to connect $COMPANY_NAME service to contiue further
Sleep($DELAY)
Send("!c")

; Send 's' to skip connect '$comapany name' service to contiue further
Sleep($DELAY)
Send("!s")

; Send 'c' to close.
Sleep($DELAY)
Send("!c")

WinClose("Network Connections")
Run("control.exe /name Microsoft.NetworkAndSharingCenter")
Sleep($DELAY)
Send("!F")
Send("c")
SplashOff ( )
Sleep($DELAY)
Run("control ncpa.cpl")
WinWaitActive("Network Connections")
Sleep($DELAY)
;send ( "!{TAB}" )
Sleep($DELAY)
MsgBox(0, "Setup Complete", "Your Dialer have been installed , Click Connect on  " & $COMPANY_NAME & " to initiate Dialing")

Now Open File / Save and name it ‘pppoe-win7-dialer-installer’

Now your script with source code is ready to be compiled in .EXE executable format so any user can install it like any other normal application.

Now Open Tools and click on ‘Compile’ and it will compile the script in .exe format and it will save it to the Desktop or whatever Path You have selected.

Now click on pppoe-win7-dialer-installer.exe and it will install the pppoe dialer and place its shortcut on Desktop. Its always better to test the script fully before compiling it, as compilation is done when your program is fully tested and good to go.

Any suggestions on improvements and enhancements / advancements are most welcome and will be appreciable

Regard’s
SYED JAHANZAIB

September 1, 2011

Howto create PPPoE Dialer Installer Package using Auto-iT !


~!~ Article by Syed Jahanzaib ~!~

UPDATED: March, 2017

https://aacable.wordpress.com/2017/03/20/c-pppoe-dialer-program-code/

OLD METHOD of autoit, may not work proeprly so use above mentioned link.

From past few months, I was searching for a method to create a pppoe dialer package installer which can automatically create a new pppoe connection for user,  but I was unable to find any simple method all over the internet. Like the one we can create VPN Dialer Installer Package using Windows 2003 utility called CMAK (Connection management administration kit to

I am basically a Networking type guy who is heavily involved in Microsoft / Linux + Mikrotik Environment and I have no background experience in any programming language , that’s why I asked many people for assistance , but none of any knew about it, and those who knew, didn’t wanted to share the code with general public.

So Finally I decided to do it in my old fashioned style using MS-DOS concepts and logic’s. Today after doing some goggling and thinking about possible solutions in my head, I was able to found a way on how-to do it with the help of a Application name ‘AUTO-IT ‘

Following is a guide on howto to do it in very simple few steps (xp/2000/2003 supported Only at a moment). Being a Linux Lover, I am publishing these codes under GPL (General Public License). You can modify it as per your requirements, redistribute it. Don’t forget to give credit if it helps you :~)

Remember it’s not a standard, neat and clean way but It’s very simple and it does the job nicely:)
[This script was made for Windows 2003/xp Only, I will post Windows Vista/Windows 7 script soon]

Here we go . . .

First of all you have to download ‘Auto-it‘ software from its website at

http://www.autoitscript.com/cgi-bin/getfile.pl?autoit3/autoit-v3-setup.exe

I used Latest version: v3.3.6.1, Do full installation of AutoiT.

After installation, launch it by  Goto Start / Programs / Autoit v3  and select SciTE Script Editor

Now an advance Notepad type windows will open, Just paste the following code in it.

(Note: FOR SOME REASONS, Sometimes CODE Does not displayed PROPERLY IN THIS BLOG, IF you face syntax errors,  you can copy the raw code from following location) http://pastebin.com/jSu5mHmg

#cs ----------------------------------------------------------------------------
AutoIt Version: 3.3.6.1
 Author:         SYED JAHANZAIB
 Email:          aacable@hotmail.com
 Web:            https://aacable.wordpress.com
 OS Supported:   Windows XP
 Script Function:
 Template AutoIt script. for PPPoE Dialer Installer
#ce ----------------------------------------------------------------------------
; Script Start - Add your code below here
#NoTrayIcon
 #compiler_icon=itlifesaver.ico
 #include <GUIConstants.au3>
$COMPANY_NAME = "AACABLE - DIALER SERVICE" ; name of the pppoe icon, friendly description
 $SERVICE_NAME = "aa" ; name of the pppoe service configured in NAS/Mikrotik
$DELAY = 200
 ; change this DELAY value to speedup or slow down the process,
 ;any range between 200-300 is better in my view, too fast will shatter things
;This is for showing your logo for 2 secs
 ;$destination = "C:\Program Files\AutoIt3\Examples\GUI\mslogo.jpg"
 ;SplashImageOn("Splash Screen", $destination,250,50)
 ;Sleep(2000)
 ;SplashOff()
$answer = MsgBox(4, "PPPOE Connection", "This script will create a PPPOE DIALER connection to " & $COMPANY_NAME & ", Ready?")
 If $answer = 7 Then
 Exit
 EndIf
; Prompt user for PPPOE login info
 $frmInformation = GUICreate("Enter Information", 287, 194, 193, 115)
 $lblUserName = GUICtrlCreateLabel("User Name:", 16, 40, 60, 17)
 $lblPassword = GUICtrlCreateLabel("Password:", 16, 80, 53, 17)
 $txtUserName = GUICtrlCreateInput("", 112, 40, 153, 21)
 Dim $ES_PASSWORD,$ES_AUTOHSCROLL
 $txtPassword = GUICtrlCreateInput("", 112, 80, 153, 21, BitOR($ES_PASSWORD,$ES_AUTOHSCROLL))
 $lblPassword2 = GUICtrlCreateLabel("Confirm Password:", 16, 120, 91, 17)
 $txtPassword2 = GUICtrlCreateInput("", 112, 120, 153, 21, BitOR($ES_PASSWORD,$ES_AUTOHSCROLL))
 $btnOK = GUICtrlCreateButton("&OK", 200, 160, 75, 25, 0)
 $lblInfo = GUICtrlCreateLabel("Enter your pppoe Login Information Below!", 48, 8, 196, 17)
 GUISetState(@SW_SHOW)
While 1
 $nMsg = GUIGetMsg()
 Switch $nMsg
 Case $btnOK
 If GUICtrlRead($txtPassword) <> GUICtrlRead($txtPassword2) Then
 MsgBox (16, "Error", "Passwords do not match! Try again.")
 Else
 $Username = GUICtrlRead($txtUsername)
 $Password = GUICtrlRead($txtPassword)
 ExitLoop
 EndIf
 Case $GUI_EVENT_CLOSE
 Exit
EndSwitch
 WEnd
 GUISetState(@SW_HIDE)
; Run Network Setup
 Run("control ncpa.cpl")
 WinWaitActive("Network Connections")
; Check if PPPOE dialer by same name already exists, since it'll break script later if Windows add's a number at the end of the name...
 $ControlID = ControlListView("Network Connections", "", "SysListView321", "FindItem", $COMPANY_NAME, "AACABLE - DIALER SERVICE")
 If $ControlID <> -1 Then
 $answer = MsgBox(4404, "Error", "Connection to " & $COMPANY_NAME & " already exists! Remove it and recreate it?")
 If $answer = 6 Then
 ControlListView("Network Connections", "", "SysListView321", "Select", $ControlID)
 Send("{DEL}")
 WinWaitActive("Confirm Connection Delete")
 Send("!y")
 Sleep($DELAY)
 Else
 MsgBox(16, "Exit", "Script stopped by user")
 Exit
 EndIf
 EndIf
; open new connection wizard from file menu
 Send("!f")
 Send("n")
 Sleep($DELAY)
; New Connection Wizard
 Sleep($DELAY)
 Send("!n")
 Sleep($DELAY)
; Choose Conncetion type
 Sleep($DELAY)
 Send("!n")
 Sleep($DELAY)
; setup connectoin manuall
 Send("!m")
 Sleep($DELAY)
 Send("!n")
 Sleep($DELAY)
; Connect using broadband connection with user name n passwd
 Send("!u")
 Sleep($DELAY)
 Send("!n")
 Sleep($DELAY)
; Send Your ISP Name
 Send($COMPANY_NAME)
 Send("!n")
 Sleep($DELAY)
;Donot send id password here, we will set it in End
 Send("!n")
 Sleep($DELAY)
; Wizard Complete, do we want a desktop shortcut?
 Send("!s")
 Sleep($DELAY)
 Send("{ENTER}")
WinWaitClose("New Connection Wizard")
WinWaitActive("Connect " & $COMPANY_NAME)
Send($Username)
 Send("{TAB}")
 Send($Password)
Sleep($DELAY)
Send("!s") ; save password...
Send("!a") ; for anyone who uses this computer, use "!n" for 'Me only'
Sleep($DELAY)
WinClose("Network Connections")
MsgBox(0, "Setup Complete", "Your Dialer have been installed , Click Connect to initiate dialing . . .")

Now Open File / Save and name it ‘aa-dialer-installer’

Now your script with source code is ready to be compiled in .EXE executable format so any user can install it like any other normal application.

Now Open Tools and click on ‘Compile’ and it will compile the script in .exe format and it will save it to the Desktop or whatever Path You have selected.

Now click on ‘aa-dialer-install.exe’ and it will install the pppoe dialer and place its shortcut on Desktop.

Any suggestions on improvements and enhancements / advancements are most welcome  and will be appreciable 🙂
Regrd’s
Syed Jahanzaib

%d bloggers like this: