FormView.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  1. // **********************************************************************************
  2. // CassiniDev - http://cassinidev.codeplex.com
  3. //
  4. // Copyright (c) Sky Sanders. All rights reserved.
  5. //
  6. // This source code is subject to terms and conditions of the Microsoft Public
  7. // License (Ms-PL). A copy of the license can be found in the license.htm file
  8. // included in this distribution.
  9. //
  10. // You must not remove this notice, or any other, from this software.
  11. //
  12. // **********************************************************************************
  13. #region
  14. using System;
  15. using System.Collections.Generic;
  16. using System.ComponentModel;
  17. using System.Diagnostics;
  18. using System.Linq;
  19. using System.Net;
  20. using System.Reflection;
  21. using System.Threading;
  22. using System.Windows.Forms;
  23. using CassiniDev.ServerLog;
  24. using System.Runtime.InteropServices;
  25. #endregion
  26. namespace CassiniDev
  27. {
  28. public partial class FormView : Form
  29. {
  30. #region Fields
  31. private bool _automated;
  32. private LogView _logForm;
  33. private RunState _runState;
  34. private Server _server;
  35. #endregion
  36. #region Constructors
  37. public FormView(Server server)
  38. { //指定不再捕获对错误线程的调用
  39. Control.CheckForIllegalCrossThreadCalls = false;
  40. _server = server;
  41. InitializeComponent();
  42. InitializeUI();
  43. if (!Program.IsCmdLine)
  44. {
  45. userConfig.LoadWebPort();
  46. this.PortTextBox.Value = userConfig.WebPort;
  47. this.ApplicationPathTextBox.Text = userConfig.BasePath;
  48. }
  49. else {
  50. userConfig.WebPort = server.Port;
  51. userConfig.SaveWebPort(server.Port);
  52. }
  53. this.FormClosed += FormView_FormClosed;
  54. SetMyTimerRunWork();
  55. this.Load += FormView_Load;
  56. this.FormClosing += FormView_FormClosing;
  57. // this.Invoke(new RefreshRichTextBoxEx(this.AddRunLogs), "当前路径:" + RootPath + "frpc.exe" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"));
  58. if (System.IO.File.Exists(RootPath + "frpc.exe"))
  59. {
  60. // this.Invoke(new RefreshRichTextBoxEx(this.AddRunLogs), "定时任务准备启动" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"));
  61. myTimer.Start();
  62. WriteLogs("定时任务已启动");
  63. }
  64. }
  65. delegate void RefreshRichTextBoxEx(string parameter);
  66. //创建一个委托,是为访问DataGridVie控件服务的。
  67. public delegate void UpdateControl();
  68. void WriteLogs(string txt)
  69. {
  70. // string logPath = RootPath + "iislogs.txt";
  71. // this.Invoke(new RefreshRichTextBoxEx(this.AddRunLogs), txt + DateTime.Now.ToString("yyyy-MM-dd HH:mm:sss"));
  72. // WriteLogs(txt,logPath);
  73. }
  74. /// <summary>
  75. /// 写日志
  76. /// </summary>
  77. /// <param name="txt">日志内容</param>
  78. /// <param name="fullPath">日志文件全路径</param>
  79. public static void WriteLogs(string txt, string fullPath)
  80. {
  81. try
  82. {
  83. using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath, true, System.Text.Encoding.UTF8))
  84. {
  85. sw.WriteLine("【" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss ") + "】" + txt);
  86. sw.Flush();
  87. sw.Close();
  88. }
  89. }
  90. catch { }
  91. }
  92. void FormView_FormClosing(object sender, FormClosingEventArgs e)
  93. {
  94. myTimer.Stop();
  95. }
  96. void FormView_Load(object sender, EventArgs e)
  97. {
  98. }
  99. void FormView_FormClosed(object sender, FormClosedEventArgs e)
  100. {
  101. InvokeStop();
  102. }
  103. #endregion
  104. #region Properties
  105. internal bool AddHost
  106. {
  107. get { return AddHostEntryCheckBox.Checked; }
  108. set { AddHostEntryCheckBox.Checked = value; }
  109. }
  110. internal string ApplicationPath
  111. {
  112. get { return ApplicationPathTextBox.Text; }
  113. set { ApplicationPathTextBox.Text = value; }
  114. }
  115. internal string HostName
  116. {
  117. get { return HostNameTextBox.Text; }
  118. set { HostNameTextBox.Text = value; }
  119. }
  120. internal string IPAddress
  121. {
  122. get { return IPSpecificTextBox.Text; }
  123. set { IPSpecificTextBox.Text = value; }
  124. }
  125. internal IPMode IPMode
  126. {
  127. get { return GetIpMode(); }
  128. set { SetIpMode(value); }
  129. }
  130. internal bool NoDirList
  131. {
  132. get { return directoryBrowsingEnabledToolStripMenuItem.Checked; }
  133. set { directoryBrowsingEnabledToolStripMenuItem.Checked = value; }
  134. }
  135. internal bool NtmlAuthenticationRequired
  136. {
  137. get { return nTLMAuthenticationRequiredToolStripMenuItem.Checked; }
  138. set { nTLMAuthenticationRequiredToolStripMenuItem.Checked = value; }
  139. }
  140. internal int Port
  141. {
  142. get { return (int)PortTextBox.Value; }
  143. set { PortTextBox.Value = value; }
  144. }
  145. internal PortMode PortMode
  146. {
  147. get { return GetPortMode(); }
  148. set { SetPortMode(value); }
  149. }
  150. internal int PortRangeEnd
  151. {
  152. get { return (int)PortRangeEndTextBox.Value; }
  153. set { PortRangeEndTextBox.Value = value; }
  154. }
  155. internal int PortRangeStart
  156. {
  157. get { return (int)PortRangeStartTextBox.Value; }
  158. set { PortRangeStartTextBox.Value = value; }
  159. }
  160. internal string RootUrl
  161. {
  162. get { return RootUrlLinkLabel.Text; }
  163. set
  164. {
  165. RootUrlLinkLabel.Text = value;
  166. RootUrlLinkLabel.Visible = !string.IsNullOrEmpty(value);
  167. }
  168. }
  169. internal RunState RunState
  170. {
  171. get { return _runState; }
  172. }
  173. internal int TimeOut
  174. {
  175. get { return (int)TimeOutNumeric.Value; }
  176. set { TimeOutNumeric.Value = value; }
  177. }
  178. internal bool V6
  179. {
  180. get { return IPV6CheckBox.Checked; }
  181. set { IPV6CheckBox.Checked = value; }
  182. }
  183. internal string VirtualPath
  184. {
  185. get { return VirtualPathTextBox.Text; }
  186. set { VirtualPathTextBox.Text = value; }
  187. }
  188. #endregion
  189. #region Protected Methods
  190. protected override void Dispose(bool disposing)
  191. {
  192. if (disposing && (components != null))
  193. {
  194. components.Dispose();
  195. }
  196. if (disposing && _server != null)
  197. {
  198. _server.Dispose();
  199. _server = null;
  200. }
  201. base.Dispose(disposing);
  202. }
  203. /// <summary>
  204. /// If the form is closing we need to determine whether to exit
  205. /// or to minimize to tray.
  206. /// </summary>
  207. /// <param name="e"></param>
  208. protected override void OnClosing(CancelEventArgs e)
  209. {
  210. // if explicit closure or we are doing nothing then exit app.
  211. if (RunState == RunState.Idle)
  212. {
  213. InvokeStop();
  214. }
  215. else
  216. {
  217. WindowState = FormWindowState.Minimized;
  218. e.Cancel = true;
  219. }
  220. }
  221. //protected override void OnShown(EventArgs e)
  222. //{
  223. // if (_automated)
  224. // {
  225. // WindowState = FormWindowState.Minimized;
  226. // Hide();
  227. // }
  228. //}
  229. #endregion
  230. #region Private Methods
  231. private void InitializeUI()
  232. {
  233. ButtonStart.Text = SR.GetString(SR.WebdevStart);
  234. toolStripStatusLabel1.Text = SR.GetString(SR.WebdevAspNetVersion, CommonExtensions.GetAspVersion());
  235. // if sqlite is missing then just silently enable in-memory logging,
  236. // hide the enable logging item and enable view log item
  237. ShowLogButton.Enabled = false;
  238. toolStripStatusLabel1.Text = SR.GetString(SR.WebdevAspNetVersion, CommonExtensions.GetAspVersion());
  239. List<IPAddress> localAddresses = new List<IPAddress>(CassiniNetworkUtils.GetLocalAddresses());
  240. localAddresses.Insert(0, System.Net.IPAddress.IPv6Loopback);
  241. localAddresses.Insert(0, System.Net.IPAddress.Loopback);
  242. IPSpecificTextBox.Items.AddRange(localAddresses.Select(i => i.ToString()).ToArray());
  243. if (IPSpecificTextBox.Items.Count > 0)
  244. {
  245. IPSpecificTextBox.SelectedIndex = 0;
  246. IPSpecificTextBox.Text = IPSpecificTextBox.Items[0].ToString();
  247. }
  248. InvokeSetRunState(RunState.Idle);
  249. if (_server == null)
  250. {
  251. ShowMainForm();
  252. }
  253. else
  254. {
  255. _automated = true;
  256. _server.TimedOut += OnTimedOut;
  257. IPMode = IPMode.Any;
  258. PortMode = PortMode.Specific;
  259. UpdateUIFromServer();
  260. InvokeSetRunState(RunState.Running);
  261. base.Text = SR.GetString(SR.WebdevNameWithPort, _server.Port);
  262. TrayIcon.Visible = true;
  263. DisplayTrayTip();
  264. }
  265. }
  266. private void DisplayTrayTip()
  267. {
  268. if (_server==null)
  269. {
  270. return;
  271. }
  272. TrayIcon.Text = _server.RootUrl;
  273. string trayBaloonText = _server.RootUrl;
  274. TrayIcon.ShowBalloonTip(5000, base.Text, trayBaloonText, ToolTipIcon.Info);
  275. }
  276. private void UpdateUIFromServer()
  277. {
  278. base.Text = SR.GetString(SR.WebdevNameWithPort, _server.Port);
  279. RootUrl = _server.RootUrl;
  280. ApplicationPath = _server.PhysicalPath;
  281. IPAddress = _server.IPAddress.ToString();
  282. Port = _server.Port;
  283. HostName = _server.HostName;
  284. NtmlAuthenticationRequired = _server.RequireAuthentication;
  285. NoDirList = _server.DisableDirectoryListing;
  286. TimeOut = _server.TimeoutInterval;
  287. }
  288. protected override void OnResize(EventArgs e)
  289. {
  290. if (WindowState == FormWindowState.Minimized)
  291. {
  292. Hide();
  293. DisplayTrayTip();
  294. ShowInTaskbar = false;
  295. }
  296. base.OnResize(e);
  297. }
  298. private void ShowMainForm()
  299. {
  300. Show();
  301. WindowState = FormWindowState.Normal;
  302. ShowInTaskbar = true;
  303. //TrayIcon.Visible = false;
  304. //ShowInTaskbar = true;
  305. //TopMost = true;
  306. //Focus();
  307. //BringToFront();
  308. //TopMost = false;
  309. }
  310. private void InvokeSetRunState(RunState state)
  311. {
  312. // use invoke, runstate may come from another thread.
  313. if (InvokeRequired)
  314. {
  315. Invoke(new ParameterizedThreadStart(SetRunState), state);
  316. }
  317. else
  318. {
  319. SetRunState(state);
  320. }
  321. }
  322. /// <summary>
  323. /// Sets RunState and enables/disables form fields accordingly
  324. /// </summary>
  325. /// <param name="state"></param>
  326. private void SetRunState(object state)
  327. {
  328. _runState = (RunState)state;
  329. switch (_runState)
  330. {
  331. case RunState.Idle:
  332. if (!_automated)
  333. {
  334. EnableForm();
  335. }
  336. // if not automated we are on our way out
  337. break;
  338. case RunState.Running:
  339. DisableForm();
  340. break;
  341. }
  342. }
  343. private void EnableForm()
  344. {
  345. ShowLogMenuItem.Enabled = ShowLogButton.Enabled = false;
  346. base.Text = SR.GetString(SR.WebdevName);
  347. ButtonStart.Text = "&启动";
  348. ButtonStart.Enabled = true;
  349. nTLMAuthenticationRequiredToolStripMenuItem.Enabled = true;
  350. directoryBrowsingEnabledToolStripMenuItem.Enabled = true;
  351. ApplicationPathTextBox.Enabled = true;
  352. ButtonBrowsePhysicalPath.Enabled = true;
  353. VirtualPathTextBox.Enabled = true;
  354. HostNameTextBox.Enabled = true;
  355. GroupBoxIPAddress.Enabled = true;
  356. GroupBoxPort.Enabled = true;
  357. LabelHostName.Enabled = true;
  358. LabelPhysicalPath.Enabled = true;
  359. LabelVPath.Enabled = true;
  360. TimeOutNumeric.Enabled = true;
  361. RootUrl = null;
  362. AddHostEntryCheckBox.Enabled = !String.IsNullOrEmpty(HostName);
  363. switch (IPMode)
  364. {
  365. case IPMode.Loopback:
  366. RadioButtonIPLoopBack_CheckedChanged(null, EventArgs.Empty);
  367. break;
  368. case IPMode.Any:
  369. RadioButtonIPAny_CheckedChanged(null, EventArgs.Empty);
  370. break;
  371. case IPMode.Specific:
  372. RadioButtonIPSpecific_CheckedChanged(null, EventArgs.Empty);
  373. break;
  374. }
  375. switch (PortMode)
  376. {
  377. case PortMode.FirstAvailable:
  378. RadioButtonPortFind_CheckedChanged(null, EventArgs.Empty);
  379. break;
  380. case PortMode.Specific:
  381. RadioButtonPortSpecific_CheckedChanged(null, EventArgs.Empty);
  382. break;
  383. }
  384. HostNameChanged(null, EventArgs.Empty);
  385. }
  386. private void DisableForm()
  387. {
  388. ShowLogMenuItem.Enabled = ShowLogButton.Enabled = true;
  389. TimeOutNumeric.Enabled = false;
  390. ButtonStart.Text = "&停止";
  391. directoryBrowsingEnabledToolStripMenuItem.Enabled = false;
  392. nTLMAuthenticationRequiredToolStripMenuItem.Enabled = false;
  393. ApplicationPathTextBox.Enabled = false;
  394. ButtonBrowsePhysicalPath.Enabled = false;
  395. VirtualPathTextBox.Enabled = false;
  396. HostNameTextBox.Enabled = false;
  397. GroupBoxIPAddress.Enabled = false;
  398. GroupBoxPort.Enabled = false;
  399. AddHostEntryCheckBox.Enabled = false;
  400. LabelHostName.Enabled = false;
  401. LabelPhysicalPath.Enabled = false;
  402. LabelVPath.Enabled = false;
  403. }
  404. private void HostNameChanged()
  405. {
  406. if (string.IsNullOrEmpty(HostName))
  407. {
  408. AddHostEntryCheckBox.Enabled = false;
  409. AddHost = false;
  410. }
  411. else
  412. {
  413. AddHostEntryCheckBox.Enabled = true;
  414. }
  415. }
  416. private void StartStop()
  417. {
  418. if (RunState != RunState.Running)
  419. {
  420. DisableForm();
  421. Start();
  422. }
  423. else
  424. {
  425. InvokeStop();
  426. }
  427. }
  428. private CommandLineArguments GetArgs()
  429. {
  430. CommandLineArguments args = new CommandLineArguments
  431. {
  432. AddHost = AddHost,
  433. ApplicationPath = ApplicationPath,
  434. HostName = HostName,
  435. IPAddress = IPAddress,
  436. IPMode = IPMode,
  437. IPv6 = V6,
  438. Port = Port,
  439. PortMode = PortMode,
  440. PortRangeEnd = PortRangeEnd,
  441. PortRangeStart = PortRangeStart,
  442. VirtualPath = VirtualPath,
  443. TimeOut = TimeOut,
  444. WaitForPort = 0,
  445. Ntlm = NtmlAuthenticationRequired,
  446. Nodirlist = NoDirList
  447. };
  448. return args;
  449. }
  450. private void Start()
  451. {
  452. // use CommandLineArguments as a pre validation tool
  453. CommandLineArguments args = GetArgs();
  454. ClearError();
  455. try
  456. {
  457. args.Validate();
  458. }
  459. catch (CassiniException ex)
  460. {
  461. SetError(ex.Field, ex.Message);
  462. return;
  463. }
  464. IPAddress = args.IPAddress;
  465. Port = args.Port;
  466. HostName = args.HostName;
  467. _server = new Server(args.Port, args.VirtualPath, args.ApplicationPath,
  468. System.Net.IPAddress.Parse(args.IPAddress), args.HostName, args.TimeOut, args.Ntlm,
  469. args.Nodirlist);
  470. // _server = new Server(args.Port, args.VirtualPath, args.ApplicationPath, args.Ntlm, args.Nodirlist);
  471. if (args.AddHost)
  472. {
  473. HostsFile.AddHostEntry(_server.IPAddress.ToString(), _server.HostName);
  474. }
  475. try
  476. {
  477. _server.Start();
  478. _server.TimedOut += OnTimedOut;
  479. UpdateUIFromServer();
  480. InvokeSetRunState(RunState.Running);
  481. }
  482. catch (Exception ex)
  483. {
  484. SetError(ErrorField.None, ex.Message);
  485. _server.Dispose();
  486. }
  487. }
  488. /// <summary>
  489. /// The server could be stopped either by user action,
  490. /// timeout or exception. If by timeout, the call will be
  491. /// coming from another thread in another appdomain far far
  492. /// away, so we execise caution and wrap the method that
  493. /// actual does the stoppage in this invokable wrapper.
  494. /// </summary>
  495. private void InvokeStop()
  496. {
  497. if (InvokeRequired)
  498. {
  499. Invoke(new MethodInvoker(Stop));
  500. }
  501. else
  502. {
  503. Stop();
  504. }
  505. }
  506. private void Stop()
  507. {
  508. // kill the start button so we don't get a start
  509. // signal before completely stopped.
  510. ButtonStart.Enabled = false;
  511. // revert the host file modification, if necessary
  512. if (AddHost && RunState == RunState.Running)
  513. {
  514. HostsFile.RemoveHostEntry(_server.IPAddress.ToString(), _server.HostName);
  515. }
  516. if (_server != null)
  517. {
  518. _server.TimedOut -= OnTimedOut;
  519. _server.Dispose();
  520. }
  521. RootUrl = string.Empty;
  522. InvokeSetRunState(RunState.Idle);
  523. if (_automated)
  524. {
  525. ExitApp();
  526. }
  527. }
  528. private static void ExitApp()
  529. {
  530. Application.Exit();
  531. }
  532. private void ShowLog()
  533. {
  534. if (_logForm == null || _logForm.IsDisposed)
  535. {
  536. _logForm = new LogView(_server);
  537. }
  538. _logForm.Show();
  539. _logForm.BringToFront();
  540. }
  541. private void BrowsePath()
  542. {
  543. FolderBrowserDialog fbd = new FolderBrowserDialog();
  544. if (fbd.ShowDialog() == DialogResult.OK)
  545. {
  546. ApplicationPath = fbd.SelectedPath;
  547. }
  548. }
  549. private void LaunchBrowser()
  550. {
  551. Process.Start(RootUrlLinkLabel.Text);
  552. }
  553. private IPMode GetIpMode()
  554. {
  555. IPMode result;
  556. if (IPModeAnyRadioButton.Checked)
  557. {
  558. result = IPMode.Any;
  559. }
  560. else if (IPModeLoopBackRadioButton.Checked)
  561. {
  562. result = IPMode.Loopback;
  563. }
  564. else
  565. {
  566. result = IPMode.Specific;
  567. }
  568. return result;
  569. }
  570. private PortMode GetPortMode()
  571. {
  572. return PortModeSpecificRadioButton.Checked ? PortMode.Specific : PortMode.FirstAvailable;
  573. }
  574. private void SetIpMode(IPMode value)
  575. {
  576. switch (value)
  577. {
  578. case IPMode.Loopback:
  579. IPModeLoopBackRadioButton.Checked = true;
  580. break;
  581. case IPMode.Any:
  582. IPModeAnyRadioButton.Checked = true;
  583. break;
  584. case IPMode.Specific:
  585. RadioButtonIPSpecific.Checked = true;
  586. break;
  587. }
  588. }
  589. private void SetPortMode(PortMode value)
  590. {
  591. switch (value)
  592. {
  593. case PortMode.FirstAvailable:
  594. PortModeFirstAvailableRadioButton.Checked = true;
  595. break;
  596. case PortMode.Specific:
  597. PortModeSpecificRadioButton.Checked = true;
  598. break;
  599. }
  600. }
  601. private void SetError(ErrorField field, string value)
  602. {
  603. EnableForm();
  604. switch (field)
  605. {
  606. case ErrorField.ApplicationPath:
  607. errorProvider1.SetError(ApplicationPathTextBox, value);
  608. break;
  609. case ErrorField.VirtualPath:
  610. errorProvider1.SetError(VirtualPathTextBox, value);
  611. break;
  612. case ErrorField.HostName:
  613. errorProvider1.SetError(HostNameTextBox, value);
  614. break;
  615. case ErrorField.IsAddHost:
  616. errorProvider1.SetError(AddHostEntryCheckBox, value);
  617. break;
  618. case ErrorField.IPAddress:
  619. errorProvider1.SetError(IPSpecificTextBox, value);
  620. break;
  621. case ErrorField.IPAddressAny:
  622. errorProvider1.SetError(IPModeAnyRadioButton, value);
  623. break;
  624. case ErrorField.IPAddressLoopBack:
  625. errorProvider1.SetError(IPModeLoopBackRadioButton, value);
  626. break;
  627. case ErrorField.Port:
  628. errorProvider1.SetError(PortTextBox, value+"端口号冲突");
  629. break;
  630. case ErrorField.PortRange:
  631. errorProvider1.SetError(PortRangeStartTextBox, value);
  632. errorProvider1.SetError(PortRangeEndTextBox, value);
  633. break;
  634. case ErrorField.PortRangeStart:
  635. errorProvider1.SetError(PortRangeStartTextBox, value);
  636. break;
  637. case ErrorField.PortRangeEnd:
  638. errorProvider1.SetError(PortRangeEndTextBox, value);
  639. break;
  640. case ErrorField.None:
  641. MessageBox.Show(value, "Error");
  642. break;
  643. }
  644. }
  645. private void ClearError()
  646. {
  647. errorProvider1.Clear();
  648. }
  649. #endregion
  650. #region Handlers
  651. private void BrowsePath(object sender, EventArgs e)
  652. {
  653. BrowsePath();
  654. }
  655. private void HideMainForm(object sender, EventArgs e)
  656. {
  657. this.WindowState = FormWindowState.Minimized;
  658. }
  659. private void LaunchBrowser(object sender, EventArgs e)
  660. {
  661. LaunchBrowser();
  662. }
  663. private void LaunchBrowser(object sender, LinkLabelLinkClickedEventArgs e)
  664. {
  665. LaunchBrowser();
  666. }
  667. private void ShowLog(object sender, EventArgs e)
  668. {
  669. ShowLog();
  670. }
  671. private void ShowMainForm(object sender, EventArgs e)
  672. {
  673. ShowMainForm();
  674. }
  675. /// <summary>
  676. /// Responds to the Start/Stop button
  677. /// </summary>
  678. /// <param name="sender"></param>
  679. /// <param name="e"></param>
  680. private void StartStop(object sender, EventArgs e)
  681. {
  682. userConfig.SaveWebPort(Convert.ToInt32(PortTextBox.Value));
  683. StartStop();
  684. }
  685. private void ExitApp(object sender, EventArgs e)
  686. {
  687. ExitApp();
  688. }
  689. private void HostNameChanged(object sender, EventArgs e)
  690. {
  691. HostNameChanged();
  692. }
  693. /// <summary>
  694. /// If a timeout value is specifically set and we
  695. /// get a timeout event, just exit the application.
  696. /// This should always be the case, but will be
  697. /// a bit forgiving here and perform a check before
  698. /// dumping.
  699. /// </summary>
  700. private void OnTimedOut(object sender, EventArgs e)
  701. {
  702. InvokeStop();
  703. if (TimeOut > 0)
  704. {
  705. ExitApp();
  706. }
  707. else
  708. {
  709. ShowMainForm();
  710. }
  711. }
  712. #region Hinky lookin radios that depend on known state. Could be a source of trouble.
  713. private void RadioButtonIPAny_CheckedChanged(object sender, EventArgs e)
  714. {
  715. IPSpecificTextBox.Enabled = false;
  716. IPV6CheckBox.Enabled = true;
  717. }
  718. private void RadioButtonIPLoopBack_CheckedChanged(object sender, EventArgs e)
  719. {
  720. IPSpecificTextBox.Enabled = false;
  721. IPV6CheckBox.Enabled = true;
  722. }
  723. private void RadioButtonIPSpecific_CheckedChanged(object sender, EventArgs e)
  724. {
  725. IPSpecificTextBox.Enabled = true;
  726. IPV6CheckBox.Enabled = false;
  727. IPV6CheckBox.Checked = false;
  728. }
  729. private void RadioButtonPortFind_CheckedChanged(object sender, EventArgs e)
  730. {
  731. PortTextBox.Enabled = false;
  732. PortRangeEndTextBox.Enabled = true;
  733. PortRangeStartTextBox.Enabled = true;
  734. }
  735. private void RadioButtonPortSpecific_CheckedChanged(object sender, EventArgs e)
  736. {
  737. PortTextBox.Enabled = true;
  738. PortRangeEndTextBox.Enabled = false;
  739. PortRangeStartTextBox.Enabled = false;
  740. }
  741. #endregion
  742. /// <summary>
  743. /// 批量任务定时器
  744. /// </summary>
  745. public System.Timers.Timer myTimer = new System.Timers.Timer();
  746. public void SetMyTimerRunWork()
  747. {
  748. myTimer.Interval = 1000 * 10;
  749. myTimer.Elapsed += new System.Timers.ElapsedEventHandler(MyDinShiRunWork);
  750. myTimer.AutoReset = true;//设置是执行一次(false),还是一直执行(true);
  751. myTimer.Enabled = false;//是否执行
  752. }
  753. string GetFrpStartPath()
  754. {
  755. return FormView.GetFullDirectoryPath(FormView.BasePath) + "frpc.exe -c " + FormView.GetFullDirectoryPath(FormView.BasePath) + "frpc.ini";
  756. }
  757. void MyDinShiRunWork(object source, System.Timers.ElapsedEventArgs e)
  758. {
  759. try
  760. {
  761. WriteLogs("定时任务正在执行");
  762. if (!isRun("frpc"))
  763. {
  764. if (System.IO.File.Exists(RootPath + "frpc.exe"))
  765. {
  766. WriteLogs("FRP路径为:" + RootPath + "frpc.exe");
  767. if (isRun("frpc"))
  768. {
  769. //this.SetLbInfo("APP网络服务已经在运行...");
  770. WriteLogs("APP网络服务已经在运行...");
  771. }
  772. else
  773. {
  774. if (FormView.WinExec(GetFrpStartPath(), 0) > 0)
  775. {
  776. // this.SetLbInfo("APP网络服务启动成功....");
  777. WriteLogs("WinExec启动:" + GetFrpStartPath());
  778. }
  779. else
  780. {
  781. // this.SetLbInfo("APP网络服务启动失败....", 0);
  782. // return;
  783. WriteLogs("WinExec启动失败:" + GetFrpStartPath());
  784. try
  785. {
  786. WriteLogs("ExecuteCmdReturn启动:" + RootPath + "frpc.exe");
  787. MyClassLibrary.ExecuteCmdReturn(new string[] { RootPath + "frpc.exe" }, FormView.GetFullDirectoryPath(FormView.BasePath));
  788. }
  789. catch (Exception ex){
  790. WriteLogs("ExecuteCmdReturn启动出错:"+ex.Message + RootPath + "frpc.exe");
  791. }
  792. }
  793. }
  794. System.Threading.Thread.Sleep(500);
  795. ShowHideFRPC(false);
  796. }
  797. else {
  798. WriteLogs("路径无效:" + RootPath + "frpc.exe");
  799. }
  800. }
  801. else
  802. {
  803. ShowHideFRPC(false);
  804. WriteLogs("APP网络服务已经在运行,并隐藏...");
  805. }
  806. }
  807. catch (Exception ex){
  808. WriteLogs("运行错误:" + ex.Message);
  809. }
  810. }
  811. private void btnHideDaiLI_Click(object sender, EventArgs e)
  812. {
  813. // KillProcessExists(RootPath + "frpc.exe");
  814. // System.Threading.Thread.Sleep(500);
  815. // string t = "2017-07-17T20:24:51.000Z";
  816. // DateTime tt = Convert.ToDateTime(t);
  817. if (!isRun("frpc"))
  818. {
  819. MessageBox.Show("代理程序未运行");
  820. }
  821. else {
  822. ShowHideFRPC(false);
  823. // MessageBox.Show("代理程序已运行");
  824. }
  825. }
  826. #endregion
  827. private void btnShowDaiLI_Click(object sender, EventArgs e)
  828. {
  829. if (!isRun("frpc"))
  830. {
  831. if (System.IO.File.Exists(RootPath + "frpc.exe"))
  832. {
  833. if (isRun("frpc"))
  834. {
  835. //this.SetLbInfo("APP网络服务已经在运行...");
  836. }
  837. else
  838. {
  839. if (FormView.WinExec(GetFrpStartPath(), 0) > 0)
  840. {
  841. // this.SetLbInfo("APP网络服务启动成功....");
  842. }
  843. else
  844. {
  845. // this.SetLbInfo("APP网络服务启动失败....", 0);
  846. // return;
  847. try
  848. {
  849. MyClassLibrary.ExecuteCmdReturn(new string[] { RootPath + "frpc.exe" }, FormView.GetFullDirectoryPath(FormView.BasePath));
  850. }
  851. catch { }
  852. }
  853. }
  854. System.Threading.Thread.Sleep(500);
  855. ShowHideFRPC(false);
  856. }
  857. }
  858. else
  859. {
  860. MessageBox.Show("代理程序已运行");
  861. }
  862. /* if (!isRun("frpc"))
  863. {
  864. MessageBox.Show("代理程序未运行");
  865. }
  866. else
  867. {
  868. ShowHideFRPC(true);
  869. // MessageBox.Show("代理程序已运行");
  870. }*/
  871. }
  872. string RootPath = GetFullDirectoryPath(BasePath);
  873. [DllImport("kernel32.dll")]
  874. public static extern int WinExec(string exeName, int uCmdShow);
  875. /// <summary>
  876. /// 获取完整路径 只能为文件夹目录路径 检查路径结尾是否存在 “\”符号 如果不存在添加上
  877. /// </summary>
  878. /// <param name="directoryPath"></param>
  879. /// <returns></returns>
  880. public static string GetFullDirectoryPath(string directoryPath)
  881. {
  882. if (directoryPath.LastIndexOf("\\") != directoryPath.Length - 1)
  883. {
  884. directoryPath = directoryPath + "\\";
  885. }
  886. return directoryPath;
  887. }
  888. /// <summary>
  889. /// WebForm和WinForm通用的取当前根目录的方法
  890. /// </summary>
  891. public static string BasePath
  892. {
  893. get
  894. {
  895. System.Diagnostics.Process p = System.Diagnostics.Process.GetCurrentProcess();
  896. //WebDev.WebServer visual studio web server
  897. //xxx.vhost Winform
  898. //w3wp IIS7
  899. //aspnet_wp IIS6
  900. string processName = p.ProcessName.ToLower();
  901. string retPath = System.Windows.Forms.Application.StartupPath;
  902. if (processName == "aspnet_wp" || processName == "w3wp" || processName == "webdev.webserver" || processName == "iisexpress")
  903. {
  904. if (System.Web.HttpContext.Current != null)
  905. retPath = System.Web.HttpContext.Current.Server.MapPath("~/").TrimEnd(new char[] { '\\' });
  906. else //当控件在定时器的触发程序中使用时就为空
  907. {
  908. retPath = System.AppDomain.CurrentDomain.BaseDirectory.TrimEnd(new char[] { '\\' });
  909. }
  910. }
  911. return retPath;
  912. }
  913. }
  914. private void KillProcessExists(string _killPath)
  915. {
  916. // string str = Application.ExecutablePath;
  917. try
  918. {
  919. string processesByName = System.IO.Path.GetFileNameWithoutExtension(_killPath);
  920. System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(processesByName);
  921. foreach (System.Diagnostics.Process p in processes)
  922. {
  923. if (System.IO.Path.GetFileName(_killPath.ToLower()) == System.IO.Path.GetFileName(p.MainModule.FileName.ToLower()))
  924. {
  925. p.Kill();
  926. p.Close();
  927. }
  928. }
  929. }
  930. catch { }
  931. }
  932. public void ShowHideFRPC(bool bl)
  933. {
  934. try
  935. {
  936. string pPath = RootPath + "frpc.exe";
  937. string processesByName = System.IO.Path.GetFileNameWithoutExtension(pPath);
  938. System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(processesByName);
  939. foreach (Process p in processes)
  940. {
  941. //if (p.ProcessName.ToLower().Trim().Contains(pName.ToLower().Trim()))
  942. if (System.IO.Path.GetFileName(pPath.ToLower()) == System.IO.Path.GetFileName(p.MainModule.FileName.ToLower()))
  943. {
  944. if (bl)
  945. {
  946. MyClassLibrary.ShowWindow(p.MainWindowHandle, 10);
  947. }
  948. else
  949. {
  950. MyClassLibrary.ShowWindow(p.MainWindowHandle, 0);
  951. }
  952. break;
  953. }
  954. }
  955. }
  956. catch { }
  957. }
  958. bool isRun(string pName)
  959. {
  960. string pPath = RootPath + pName + ".exe";
  961. string processesByName = System.IO.Path.GetFileNameWithoutExtension(pPath);
  962. System.Diagnostics.Process[] processes = System.Diagnostics.Process.GetProcessesByName(processesByName);
  963. foreach (Process p in processes)
  964. {
  965. //if (p.ProcessName.ToLower().Trim().Contains(pName.ToLower().Trim()))
  966. if (System.IO.Path.GetFileName(pPath.ToLower()) == System.IO.Path.GetFileName(p.MainModule.FileName.ToLower()))
  967. {
  968. return true;
  969. }
  970. }
  971. return false;
  972. }
  973. }
  974. }