经过设计现在对宽带连接的引用只是产生具体IDoWork对象的接口,这样降低了很多耦合,下面我们来实现一下该工程,创建工程ADSLService,添加一个类为ADSL,它要做的工作就是连接宽带和检查是否连接到图书馆网站服务器还有当程序退出时断开宽带连接。
这里对宽带的操作是调用系统函数,我们只对外提供三个方法,连接宽带、断开宽带、检查连接状态,在该类的构造函数中我们注册ApplicationExit事件来执行程序退出时是否断开宽带连接。
具体实现如下:
Code
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Windows.Forms;
using LibraryHelper.DALService;
namespace LibraryHelper.ADSLService
{
public class ADSL
{
public ADSL()
{
//当实例化时就注册ApplicationExit事件,到应用程序退出时是否断开网络连接
Application.ApplicationExit += new EventHandler(this.OnApplicationExit);
}
/// <summary>
/// ADSL连接
/// </summary>
/// <param name="connectionName">ADSL连接名</param>
/// <param name="user">帐号</param>
/// <param name="pass">密码</param>
public void Connect(string connectionName, string user, string pass)
{
string arg = string.Format("rasdial \"{0}\" {1} {2}", connectionName, user, pass);
InvokeCmd(arg);
}
//连接之后用Ping命令去Ping是否可以连接到服务器
public Boolean ConnnectState(String strPing)
{
String strPingResult = InvokeCmd(strPing);
Boolean result = true;
if (strPingResult.Contains("Destination host unreachable") || strPingResult.Contains("Request timed out") || strPingResult.Contains("Unknown host"))
{
result = false;
}
return result;
}
/// <summary>
/// 断开ADSL连接
/// </summary>
/// <param name="connectionName">ADSL连接名</param>
public void Disconnect(string connectionName)
{
string arg = string.Format("rasdial \"{0}\" /disconnect", connectionName);
InvokeCmd(arg);
}
/// <summary>
/// 执行RasDial.exe创建连接
/// </summary>
/// <param name="cmdArgs">执行命令字符串</param>
/// <returns></returns>
private static String InvokeCmd(string cmdArgs)
{
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.StartInfo.CreateNoWindow = true;
p.Start();
p.StandardInput.WriteLine(cmdArgs);
p.StandardInput.WriteLine("exit");
String strResult = p.StandardOutput.ReadToEnd();
return strResult;
}
private void OnApplicationExit(object sender, EventArgs e)
{
SettingXMLService settingXMLService = new SettingXMLService();
//0表示断开,1表示不断开
if (settingXMLService.GetDisconnectionADSL() == "0")
{
ADSLXMLService adslXMLService = new ADSLXMLService();
Disconnect(adslXMLService.GetConnectionName());
}
}
}
}