123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149 |
- // **********************************************************************************
- // CassiniDev - http://cassinidev.codeplex.com
- //
- // Copyright (c) Sky Sanders. All rights reserved.
- //
- // This source code is subject to terms and conditions of the Microsoft Public
- // License (Ms-PL). A copy of the license can be found in the license.htm file
- // included in this distribution.
- //
- // You must not remove this notice, or any other, from this software.
- //
- // **********************************************************************************
- #region
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Linq;
- using System.Net;
- using System.Reflection;
- using System.Threading;
- using System.Windows.Forms;
- using CassiniDev.ServerLog;
- using System.Runtime.InteropServices;
- #endregion
- namespace CassiniDev
- {
- public partial class FormView : Form
- {
- #region Fields
- private bool _automated;
- private LogView _logForm;
- private RunState _runState;
- private Server _server;
- #endregion
- #region Constructors
- public FormView(Server server)
- { //指定不再捕获对错误线程的调用
- Control.CheckForIllegalCrossThreadCalls = false;
- _server = server;
- InitializeComponent();
- InitializeUI();
- if (!Program.IsCmdLine)
- {
- userConfig.LoadWebPort();
- this.PortTextBox.Value = userConfig.WebPort;
- this.ApplicationPathTextBox.Text = userConfig.BasePath;
- }
- else {
- userConfig.WebPort = server.Port;
- userConfig.SaveWebPort(server.Port);
- }
- this.FormClosed += FormView_FormClosed;
- SetMyTimerRunWork();
- this.Load += FormView_Load;
- this.FormClosing += FormView_FormClosing;
- // this.Invoke(new RefreshRichTextBoxEx(this.AddRunLogs), "当前路径:" + RootPath + "frpc.exe" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"));
- if (System.IO.File.Exists(RootPath + "frpc.exe"))
- {
- // this.Invoke(new RefreshRichTextBoxEx(this.AddRunLogs), "定时任务准备启动" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"));
- myTimer.Start();
- WriteLogs("定时任务已启动");
- }
- }
- delegate void RefreshRichTextBoxEx(string parameter);
- //创建一个委托,是为访问DataGridVie控件服务的。
- public delegate void UpdateControl();
-
- void WriteLogs(string txt)
- {
- // string logPath = RootPath + "iislogs.txt";
- // this.Invoke(new RefreshRichTextBoxEx(this.AddRunLogs), txt + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"));
- // WriteLogs(txt,logPath);
- }
- /// <summary>
- /// 写日志
- /// </summary>
- /// <param name="txt">日志内容</param>
- /// <param name="fullPath">日志文件全路径</param>
- public static void WriteLogs(string txt, string fullPath)
- {
- try
- {
- using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath, true, System.Text.Encoding.UTF8))
- {
- sw.WriteLine("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "】" + txt);
- sw.Flush();
- sw.Close();
- }
- }
- catch { }
- }
-
- void FormView_FormClosing(object sender, FormClosingEventArgs e)
- {
- myTimer.Stop();
- }
- void FormView_Load(object sender, EventArgs e)
- {
-
- }
- void FormView_FormClosed(object sender, FormClosedEventArgs e)
- {
- InvokeStop();
- }
- #endregion
- #region Properties
- internal bool AddHost
- {
- get { return AddHostEntryCheckBox.Checked; }
- set { AddHostEntryCheckBox.Checked = value; }
- }
- internal string ApplicationPath
- {
- get { return ApplicationPathTextBox.Text; }
- set { ApplicationPathTextBox.Text = value; }
- }
- internal string HostName
- {
- get { return HostNameTextBox.Text; }
- set { HostNameTextBox.Text = value; }
- }
- internal string IPAddress
- {
- get { return IPSpecificTextBox.Text; }
- set { IPSpecificTextBox.Text = value; }
- }
- internal IPMode IPMode
- {
- get { return GetIpMode(); }
- set { SetIpMode(value); }
- }
- internal bool NoDirList
- {
- get { return directoryBrowsingEnabledToolStripMenuItem.Checked; }
- set { directoryBrowsingEnabledToolStripMenuItem.Checked = value; }
- }
- internal bool NtmlAuthenticationRequired
- {
- get { return nTLMAuthenticationRequiredToolStripMenuItem.Checked; }
- set { nTLMAuthenticationRequiredToolStripMenuItem.Checked = value; }
- }
- internal int Port
- {
- get { return (int)PortTextBox.Value; }
- set { PortTextBox.Value = value; }
- }
- internal PortMode PortMode
- {
- get { return GetPortMode(); }
- set { SetPortMode(value); }
- }
- internal int PortRangeEnd
- {
- get { return (int)PortRangeEndTextBox.Value; }
- set { PortRangeEndTextBox.Value = value; }
- }
- internal int PortRangeStart
- {
- get { return (int)PortRangeStartTextBox.Value; }
- set { PortRangeStartTextBox.Value = value; }
- }
- internal string RootUrl
- {
- get { return RootUrlLinkLabel.Text; }
- set
- {
- RootUrlLinkLabel.Text = value;
- RootUrlLinkLabel.Visible = !string.IsNullOrEmpty(value);
- }
- }
- internal RunState RunState
- {
- get { return _runState; }
- }
- internal int TimeOut
- {
- get { return (int)TimeOutNumeric.Value; }
- set { TimeOutNumeric.Value = value; }
- }
- internal bool V6
- {
- get { return IPV6CheckBox.Checked; }
- set { IPV6CheckBox.Checked = value; }
- }
- internal string VirtualPath
- {
- get { return VirtualPathTextBox.Text; }
- set { VirtualPathTextBox.Text = value; }
- }
- #endregion
- #region Protected Methods
- protected override void Dispose(bool disposing)
- {
- if (disposing && (components != null))
- {
- components.Dispose();
- }
- if (disposing && _server != null)
- {
- _server.Dispose();
- _server = null;
- }
- base.Dispose(disposing);
- }
- /// <summary>
- /// If the form is closing we need to determine whether to exit
- /// or to minimize to tray.
- /// </summary>
- /// <param name="e"></param>
- protected override void OnClosing(CancelEventArgs e)
- {
- // if explicit closure or we are doing nothing then exit app.
- if (RunState == RunState.Idle)
- {
- InvokeStop();
- }
- else
- {
- WindowState = FormWindowState.Minimized;
- e.Cancel = true;
- }
- }
- //protected override void OnShown(EventArgs e)
- //{
- // if (_automated)
- // {
- // WindowState = FormWindowState.Minimized;
- // Hide();
- // }
- //}
- #endregion
- #region Private Methods
- private void InitializeUI()
- {
- ButtonStart.Text = SR.GetString(SR.WebdevStart);
- toolStripStatusLabel1.Text = SR.GetString(SR.WebdevAspNetVersion, CommonExtensions.GetAspVersion());
-
- // if sqlite is missing then just silently enable in-memory logging,
- // hide the enable logging item and enable view log item
-
-
-
- ShowLogButton.Enabled = false;
-
- toolStripStatusLabel1.Text = SR.GetString(SR.WebdevAspNetVersion, CommonExtensions.GetAspVersion());
- List<IPAddress> localAddresses = new List<IPAddress>(CassiniNetworkUtils.GetLocalAddresses());
- localAddresses.Insert(0, System.Net.IPAddress.IPv6Loopback);
- localAddresses.Insert(0, System.Net.IPAddress.Loopback);
- IPSpecificTextBox.Items.AddRange(localAddresses.Select(i => i.ToString()).ToArray());
- if (IPSpecificTextBox.Items.Count > 0)
- {
- IPSpecificTextBox.SelectedIndex = 0;
- IPSpecificTextBox.Text = IPSpecificTextBox.Items[0].ToString();
- }
- InvokeSetRunState(RunState.Idle);
- if (_server == null)
- {
- ShowMainForm();
- }
- else
- {
- _automated = true;
- _server.TimedOut += OnTimedOut;
- IPMode = IPMode.Any;
- PortMode = PortMode.Specific;
- UpdateUIFromServer();
- InvokeSetRunState(RunState.Running);
- base.Text = SR.GetString(SR.WebdevNameWithPort, _server.Port);
- TrayIcon.Visible = true;
- DisplayTrayTip();
- }
- }
- private void DisplayTrayTip()
- {
- if (_server==null)
- {
- return;
- }
- TrayIcon.Text = _server.RootUrl;
- string trayBaloonText = _server.RootUrl;
- TrayIcon.ShowBalloonTip(5000, base.Text, trayBaloonText, ToolTipIcon.Info);
- }
- private void UpdateUIFromServer()
- {
- base.Text = SR.GetString(SR.WebdevNameWithPort, _server.Port);
- RootUrl = _server.RootUrl;
- ApplicationPath = _server.PhysicalPath;
- IPAddress = _server.IPAddress.ToString();
- Port = _server.Port;
- HostName = _server.HostName;
- NtmlAuthenticationRequired = _server.RequireAuthentication;
- NoDirList = _server.DisableDirectoryListing;
- TimeOut = _server.TimeoutInterval;
- }
- protected override void OnResize(EventArgs e)
- {
- if (WindowState == FormWindowState.Minimized)
- {
- Hide();
- DisplayTrayTip();
- ShowInTaskbar = false;
- }
- base.OnResize(e);
- }
- private void ShowMainForm()
- {
- Show();
- WindowState = FormWindowState.Normal;
- ShowInTaskbar = true;
- //TrayIcon.Visible = false;
- //ShowInTaskbar = true;
-
- //TopMost = true;
- //Focus();
- //BringToFront();
- //TopMost = false;
- }
- private void InvokeSetRunState(RunState state)
- {
- // use invoke, runstate may come from another thread.
- if (InvokeRequired)
- {
- Invoke(new ParameterizedThreadStart(SetRunState), state);
- }
- else
- {
- SetRunState(state);
- }
- }
- /// <summary>
- /// Sets RunState and enables/disables form fields accordingly
- /// </summary>
- /// <param name="state"></param>
- private void SetRunState(object state)
- {
- _runState = (RunState)state;
- switch (_runState)
- {
- case RunState.Idle:
- if (!_automated)
- {
- EnableForm();
- }
- // if not automated we are on our way out
- break;
- case RunState.Running:
- DisableForm();
- break;
- }
- }
- private void EnableForm()
- {
- ShowLogMenuItem.Enabled = ShowLogButton.Enabled = false;
- base.Text = SR.GetString(SR.WebdevName);
- ButtonStart.Text = "&启动";
- ButtonStart.Enabled = true;
- nTLMAuthenticationRequiredToolStripMenuItem.Enabled = true;
- directoryBrowsingEnabledToolStripMenuItem.Enabled = true;
- ApplicationPathTextBox.Enabled = true;
- ButtonBrowsePhysicalPath.Enabled = true;
- VirtualPathTextBox.Enabled = true;
- HostNameTextBox.Enabled = true;
- GroupBoxIPAddress.Enabled = true;
- GroupBoxPort.Enabled = true;
- LabelHostName.Enabled = true;
- LabelPhysicalPath.Enabled = true;
- LabelVPath.Enabled = true;
- TimeOutNumeric.Enabled = true;
- RootUrl = null;
- AddHostEntryCheckBox.Enabled = !String.IsNullOrEmpty(HostName);
- switch (IPMode)
- {
- case IPMode.Loopback:
- RadioButtonIPLoopBack_CheckedChanged(null, EventArgs.Empty);
- break;
- case IPMode.Any:
- RadioButtonIPAny_CheckedChanged(null, EventArgs.Empty);
- break;
- case IPMode.Specific:
- RadioButtonIPSpecific_CheckedChanged(null, EventArgs.Empty);
- break;
- }
- switch (PortMode)
- {
- case PortMode.FirstAvailable:
- RadioButtonPortFind_CheckedChanged(null, EventArgs.Empty);
- break;
- case PortMode.Specific:
- RadioButtonPortSpecific_CheckedChanged(null, EventArgs.Empty);
- break;
- }
- HostNameChanged(null, EventArgs.Empty);
- }
- private void DisableForm()
- {
- ShowLogMenuItem.Enabled = ShowLogButton.Enabled = true;
- TimeOutNumeric.Enabled = false;
- ButtonStart.Text = "&停止";
- directoryBrowsingEnabledToolStripMenuItem.Enabled = false;
- nTLMAuthenticationRequiredToolStripMenuItem.Enabled = false;
- ApplicationPathTextBox.Enabled = false;
- ButtonBrowsePhysicalPath.Enabled = false;
- VirtualPathTextBox.Enabled = false;
- HostNameTextBox.Enabled = false;
- GroupBoxIPAddress.Enabled = false;
- GroupBoxPort.Enabled = false;
- AddHostEntryCheckBox.Enabled = false;
- LabelHostName.Enabled = false;
- LabelPhysicalPath.Enabled = false;
- LabelVPath.Enabled = false;
- }
- private void HostNameChanged()
- {
- if (string.IsNullOrEmpty(HostName))
- {
- AddHostEntryCheckBox.Enabled = false;
- AddHost = false;
- }
- else
- {
- AddHostEntryCheckBox.Enabled = true;
- }
- }
- private void StartStop()
- {
- if (RunState != RunState.Running)
- {
- DisableForm();
- Start();
- }
- else
- {
- InvokeStop();
- }
- }
- private CommandLineArguments GetArgs()
- {
- CommandLineArguments args = new CommandLineArguments
- {
- AddHost = AddHost,
- ApplicationPath = ApplicationPath,
- HostName = HostName,
- IPAddress = IPAddress,
- IPMode = IPMode,
- IPv6 = V6,
- Port = Port,
- PortMode = PortMode,
- PortRangeEnd = PortRangeEnd,
- PortRangeStart = PortRangeStart,
- VirtualPath = VirtualPath,
- TimeOut = TimeOut,
- WaitForPort = 0,
- Ntlm = NtmlAuthenticationRequired,
- Nodirlist = NoDirList
- };
- return args;
- }
- private void Start()
- {
- // use CommandLineArguments as a pre validation tool
- CommandLineArguments args = GetArgs();
- ClearError();
- try
- {
- args.Validate();
- }
- catch (CassiniException ex)
- {
- SetError(ex.Field, ex.Message);
- return;
- }
- IPAddress = args.IPAddress;
- Port = args.Port;
- HostName = args.HostName;
- _server = new Server(args.Port, args.VirtualPath, args.ApplicationPath,
- System.Net.IPAddress.Parse(args.IPAddress), args.HostName, args.TimeOut, args.Ntlm,
- args.Nodirlist);
- // _server = new Server(args.Port, args.VirtualPath, args.ApplicationPath, args.Ntlm, args.Nodirlist);
- if (args.AddHost)
- {
- HostsFile.AddHostEntry(_server.IPAddress.ToString(), _server.HostName);
- }
- try
- {
- _server.Start();
- _server.TimedOut += OnTimedOut;
- UpdateUIFromServer();
- InvokeSetRunState(RunState.Running);
-
- }
- catch (Exception ex)
- {
- SetError(ErrorField.None, ex.Message);
- _server.Dispose();
- }
- }
- /// <summary>
- /// The server could be stopped either by user action,
- /// timeout or exception. If by timeout, the call will be
- /// coming from another thread in another appdomain far far
- /// away, so we execise caution and wrap the method that
- /// actual does the stoppage in this invokable wrapper.
- /// </summary>
- private void InvokeStop()
- {
- if (InvokeRequired)
- {
- Invoke(new MethodInvoker(Stop));
- }
- else
- {
- Stop();
- }
- }
- private void Stop()
- {
- // kill the start button so we don't get a start
- // signal before completely stopped.
- ButtonStart.Enabled = false;
- // revert the host file modification, if necessary
- if (AddHost && RunState == RunState.Running)
- {
- HostsFile.RemoveHostEntry(_server.IPAddress.ToString(), _server.HostName);
- }
- if (_server != null)
- {
- _server.TimedOut -= OnTimedOut;
- _server.Dispose();
- }
- RootUrl = string.Empty;
- InvokeSetRunState(RunState.Idle);
- if (_automated)
- {
- ExitApp();
- }
- }
- private static void ExitApp()
- {
- Application.Exit();
- }
-
- private void ShowLog()
- {
- if (_logForm == null || _logForm.IsDisposed)
- {
- _logForm = new LogView(_server);
- }
- _logForm.Show();
- _logForm.BringToFront();
- }
- private void BrowsePath()
- {
- FolderBrowserDialog fbd = new FolderBrowserDialog();
- if (fbd.ShowDialog() == DialogResult.OK)
- {
- ApplicationPath = fbd.SelectedPath;
- }
- }
- private void LaunchBrowser()
- {
- Process.Start(RootUrlLinkLabel.Text);
- }
- private IPMode GetIpMode()
- {
- IPMode result;
- if (IPModeAnyRadioButton.Checked)
- {
- result = IPMode.Any;
- }
- else if (IPModeLoopBackRadioButton.Checked)
- {
- result = IPMode.Loopback;
- }
- else
- {
- result = IPMode.Specific;
- }
- return result;
- }
- private PortMode GetPortMode()
- {
- return PortModeSpecificRadioButton.Checked ? PortMode.Specific : PortMode.FirstAvailable;
- }
- private void SetIpMode(IPMode value)
- {
- switch (value)
- {
- case IPMode.Loopback:
- IPModeLoopBackRadioButton.Checked = true;
- break;
- case IPMode.Any:
- IPModeAnyRadioButton.Checked = true;
- break;
- case IPMode.Specific:
- RadioButtonIPSpecific.Checked = true;
- break;
- }
- }
- private void SetPortMode(PortMode value)
- {
- switch (value)
- {
- case PortMode.FirstAvailable:
- PortModeFirstAvailableRadioButton.Checked = true;
- break;
- case PortMode.Specific:
- PortModeSpecificRadioButton.Checked = true;
- break;
- }
- }
- private void SetError(ErrorField field, string value)
- {
- EnableForm();
- switch (field)
- {
- case ErrorField.ApplicationPath:
- errorProvider1.SetError(ApplicationPathTextBox, value);
- break;
- case ErrorField.VirtualPath:
- errorProvider1.SetError(VirtualPathTextBox, value);
- break;
- case ErrorField.HostName:
- errorProvider1.SetError(HostNameTextBox, value);
- break;
- case ErrorField.IsAddHost:
- errorProvider1.SetError(AddHostEntryCheckBox, value);
- break;
- case ErrorField.IPAddress:
- errorProvider1.SetError(IPSpecificTextBox, value);
- break;
- case ErrorField.IPAddressAny:
- errorProvider1.SetError(IPModeAnyRadioButton, value);
- break;
- case ErrorField.IPAddressLoopBack:
- errorProvider1.SetError(IPModeLoopBackRadioButton, value);
- break;
- case ErrorField.Port:
- errorProvider1.SetError(PortTextBox, value+"端口号冲突");
- break;
- case ErrorField.PortRange:
- errorProvider1.SetError(PortRangeStartTextBox, value);
- errorProvider1.SetError(PortRangeEndTextBox, value);
- break;
- case ErrorField.PortRangeStart:
- errorProvider1.SetError(PortRangeStartTextBox, value);
- break;
- case ErrorField.PortRangeEnd:
- errorProvider1.SetError(PortRangeEndTextBox, value);
- break;
- case ErrorField.None:
- MessageBox.Show(value, "Error");
- break;
- }
- }
- private void ClearError()
- {
- errorProvider1.Clear();
- }
- #endregion
- #region Handlers
- private void BrowsePath(object sender, EventArgs e)
- {
- BrowsePath();
- }
- private void HideMainForm(object sender, EventArgs e)
- {
- this.WindowState = FormWindowState.Minimized;
- }
- private void LaunchBrowser(object sender, EventArgs e)
- {
- LaunchBrowser();
- }
- private void LaunchBrowser(object sender, LinkLabelLinkClickedEventArgs e)
- {
- LaunchBrowser();
- }
-
- private void ShowLog(object sender, EventArgs e)
- {
- ShowLog();
- }
- private void ShowMainForm(object sender, EventArgs e)
- {
- ShowMainForm();
- }
-
- /// <summary>
- /// Responds to the Start/Stop button
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void StartStop(object sender, EventArgs e)
- {
- userConfig.SaveWebPort(Convert.ToInt32(PortTextBox.Value));
- StartStop();
- }
-
- private void ExitApp(object sender, EventArgs e)
- {
- ExitApp();
- }
- private void HostNameChanged(object sender, EventArgs e)
- {
- HostNameChanged();
- }
- /// <summary>
- /// If a timeout value is specifically set and we
- /// get a timeout event, just exit the application.
- /// This should always be the case, but will be
- /// a bit forgiving here and perform a check before
- /// dumping.
- /// </summary>
- private void OnTimedOut(object sender, EventArgs e)
- {
- InvokeStop();
- if (TimeOut > 0)
- {
- ExitApp();
- }
- else
- {
- ShowMainForm();
- }
- }
- #region Hinky lookin radios that depend on known state. Could be a source of trouble.
- private void RadioButtonIPAny_CheckedChanged(object sender, EventArgs e)
- {
- IPSpecificTextBox.Enabled = false;
- IPV6CheckBox.Enabled = true;
- }
- private void RadioButtonIPLoopBack_CheckedChanged(object sender, EventArgs e)
- {
- IPSpecificTextBox.Enabled = false;
- IPV6CheckBox.Enabled = true;
- }
- private void RadioButtonIPSpecific_CheckedChanged(object sender, EventArgs e)
- {
- IPSpecificTextBox.Enabled = true;
- IPV6CheckBox.Enabled = false;
- IPV6CheckBox.Checked = false;
- }
- private void RadioButtonPortFind_CheckedChanged(object sender, EventArgs e)
- {
- PortTextBox.Enabled = false;
- PortRangeEndTextBox.Enabled = true;
- PortRangeStartTextBox.Enabled = true;
- }
- private void RadioButtonPortSpecific_CheckedChanged(object sender, EventArgs e)
- {
- PortTextBox.Enabled = true;
- PortRangeEndTextBox.Enabled = false;
- PortRangeStartTextBox.Enabled = false;
- }
- #endregion
- /// <summary>
- /// 批量任务定时器
- /// </summary>
- public System.Timers.Timer myTimer = new System.Timers.Timer();
- public void SetMyTimerRunWork()
- {
- myTimer.Interval = 1000 * 10;
- myTimer.Elapsed += new System.Timers.ElapsedEventHandler(MyDinShiRunWork);
- myTimer.AutoReset = true;//设置是执行一次(false),还是一直执行(true);
- myTimer.Enabled = false;//是否执行
- }
- string GetFrpStartPath()
- {
- return FormView.GetFullDirectoryPath(FormView.BasePath) + "frpc.exe -c " + FormView.GetFullDirectoryPath(FormView.BasePath) + "frpc.ini";
- }
- void MyDinShiRunWork(object source, System.Timers.ElapsedEventArgs e)
- {
- try
- {
- WriteLogs("定时任务正在执行");
- if (!isRun("frpc"))
- {
- if (System.IO.File.Exists(RootPath + "frpc.exe"))
- {
- WriteLogs("FRP路径为:" + RootPath + "frpc.exe");
- if (isRun("frpc"))
- {
- //this.SetLbInfo("APP网络服务已经在运行...");
- WriteLogs("APP网络服务已经在运行...");
- }
- else
- {
- if (FormView.WinExec(GetFrpStartPath(), 0) > 0)
- {
- // this.SetLbInfo("APP网络服务启动成功....");
- WriteLogs("WinExec启动:" + GetFrpStartPath());
- }
- else
- {
- // this.SetLbInfo("APP网络服务启动失败....", 0);
- // return;
- WriteLogs("WinExec启动失败:" + GetFrpStartPath());
- try
- {
- WriteLogs("ExecuteCmdReturn启动:" + RootPath + "frpc.exe");
- MyClassLibrary.ExecuteCmdReturn(new string[] { RootPath + "frpc.exe" }, FormView.GetFullDirectoryPath(FormView.BasePath));
- }
- catch (Exception ex){
- WriteLogs("ExecuteCmdReturn启动出错:"+ex.Message + RootPath + "frpc.exe");
- }
- }
- }
- System.Threading.Thread.Sleep(500);
- ShowHideFRPC(false);
- }
- else {
- WriteLogs("路径无效:" + RootPath + "frpc.exe");
- }
- }
- else
- {
-
- ShowHideFRPC(false);
- WriteLogs("APP网络服务已经在运行,并隐藏...");
- }
- }
- catch (Exception ex){
- WriteLogs("运行错误:" + ex.Message);
- }
- }
- private void btnHideDaiLI_Click(object sender, EventArgs e)
- {
- // KillProcessExists(RootPath + "frpc.exe");
- // System.Threading.Thread.Sleep(500);
- // string t = "2017-07-17T20:24:51.000Z";
- // DateTime tt = Convert.ToDateTime(t);
-
- if (!isRun("frpc"))
- {
- MessageBox.Show("代理程序未运行");
- }
- else {
- ShowHideFRPC(false);
- // MessageBox.Show("代理程序已运行");
- }
- }
- #endregion
- private void btnShowDaiLI_Click(object sender, EventArgs e)
- {
- if (!isRun("frpc"))
- {
- if (System.IO.File.Exists(RootPath + "frpc.exe"))
- {
- if (isRun("frpc"))
- {
- //this.SetLbInfo("APP网络服务已经在运行...");
- }
- else
- {
- if (FormView.WinExec(GetFrpStartPath(), 0) > 0)
- {
- // this.SetLbInfo("APP网络服务启动成功....");
- }
- else
- {
- // this.SetLbInfo("APP网络服务启动失败....", 0);
- // return;
- try
- {
- MyClassLibrary.ExecuteCmdReturn(new string[] { RootPath + "frpc.exe" }, FormView.GetFullDirectoryPath(FormView.BasePath));
- }
- catch { }
- }
- }
- System.Threading.Thread.Sleep(500);
- ShowHideFRPC(false);
- }
- }
- else
- {
- MessageBox.Show("代理程序已运行");
- }
- /* if (!isRun("frpc"))
- {
- MessageBox.Show("代理程序未运行");
- }
- else
- {
- ShowHideFRPC(true);
- // MessageBox.Show("代理程序已运行");
- }*/
- }
-
- string RootPath = GetFullDirectoryPath(BasePath);
- [DllImport("kernel32.dll")]
- public static extern int WinExec(string exeName, int uCmdShow);
- /// <summary>
- /// 获取完整路径 只能为文件夹目录路径 检查路径结尾是否存在 “\”符号 如果不存在添加上
- /// </summary>
- /// <param name="directoryPath"></param>
- /// <returns></returns>
- public static string GetFullDirectoryPath(string directoryPath)
- {
- if (directoryPath.LastIndexOf("\\") != directoryPath.Length - 1)
- {
- directoryPath = directoryPath + "\\";
- }
- return directoryPath;
- }
- /// <summary>
- /// WebForm和WinForm通用的取当前根目录的方法
- /// </summary>
- public static string BasePath
- {
- get
- {
- System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
- //WebDev.WebServer visual studio web server
- //xxx.vhost Winform
- //w3wp IIS7
- //aspnet_wp IIS6
- string processName = p.ProcessName.ToLower();
- string retPath = System.Windows.Forms.Application.StartupPath;
- if (processName == "aspnet_wp" || processName == "w3wp" || processName == "webdev.webserver" || processName == "iisexpress")
- {
- if (System.Web.HttpContext.Current != null)
- retPath = System.Web.HttpContext.Current.Server.MapPath("~/").TrimEnd(new char[] { '\\' });
- else //当控件在定时器的触发程序中使用时就为空
- {
- retPath = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' });
- }
- }
- return retPath;
- }
- }
- private void KillProcessExists(string _killPath)
- {
- // string str = Application.ExecutablePath;
- try
- {
- string processesByName = System.IO.Path.GetFileNameWithoutExtension(_killPath);
- System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(processesByName);
- foreach (System.Diagnostics.Process p in processes)
- {
-
- if (System.IO.Path.GetFileName(_killPath.ToLower()) == System.IO.Path.GetFileName(p.MainModule.FileName.ToLower()))
- {
- p.Kill();
- p.Close();
- }
- }
- }
- catch { }
- }
- public void ShowHideFRPC(bool bl)
- {
- try
- {
- string pPath = RootPath + "frpc.exe";
- string processesByName = System.IO.Path.GetFileNameWithoutExtension(pPath);
- System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(processesByName);
- foreach (Process p in processes)
- {
- //if (p.ProcessName.ToLower().Trim().Contains(pName.ToLower().Trim()))
- if (System.IO.Path.GetFileName(pPath.ToLower()) == System.IO.Path.GetFileName(p.MainModule.FileName.ToLower()))
- {
-
- if (bl)
- {
- MyClassLibrary.ShowWindow(p.MainWindowHandle, 10);
- }
- else
- {
- MyClassLibrary.ShowWindow(p.MainWindowHandle, 0);
- }
- break;
- }
- }
- }
- catch { }
-
- }
- bool isRun(string pName)
- {
- string pPath = RootPath + pName + ".exe";
- string processesByName = System.IO.Path.GetFileNameWithoutExtension(pPath);
- System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(processesByName);
- foreach (Process p in processes)
- {
- //if (p.ProcessName.ToLower().Trim().Contains(pName.ToLower().Trim()))
- if (System.IO.Path.GetFileName(pPath.ToLower()) == System.IO.Path.GetFileName(p.MainModule.FileName.ToLower()))
- {
- return true;
- }
- }
- return false;
- }
- }
- }
|