?文章的目的為了記錄.net mvc學習的經歷。本職為嵌入式軟件開發,公司安排開發文件系統,臨時進行學習開發,系統上線3年未出沒有大問題。開發流程和要點有些記憶模糊,趕緊記錄,防止忘記。?
?嵌入式 .net mvc 開發(一)WEB搭建-CSDN博客
嵌入式 .net mvc 開發(二)網站快速搭建-CSDN博客
嵌入式 .net mvc 開發(三)網站內外網訪問-CSDN博客
嵌入式 .net mvc 開發(四)工程結構、頁面提交顯示-CSDN博客 ?
嵌入式 .net mvc 開發(五)常用代碼快速開發-CSDN博客
?推薦鏈接:
開源 java android app 開發(一)開發環境的搭建-CSDN博客
開源 java android app 開發(二)工程文件結構-CSDN博客
開源 java android app 開發(三)GUI界面布局和常用組件-CSDN博客
開源 java android app 開發(四)GUI界面重要組件-CSDN博客
開源 java android app 開發(五)文件和數據庫存儲-CSDN博客
開源 java android app 開發(六)多媒體使用-CSDN博客
開源 java android app 開發(七)通訊之Tcp和Http-CSDN博客
開源 java android app 開發(八)通訊之Mqtt和Ble-CSDN博客
開源 java android app 開發(九)后臺之線程和服務-CSDN博客
開源 java android app 開發(十)廣播機制-CSDN博客
開源 java android app 開發(十一)調試、發布-CSDN博客
開源 java android app 開發(十二)封庫.aar-CSDN博客
在上個章節里,介紹常用代碼,來開發速度,減少大家查找的時間。
本章的主要內容為特殊且可能用到的代碼。
具體內容如下:
1.服務器上CMD控制臺控制第三方程序運行的辦法。
2.服務器周期任務編寫。
3.服務器中使用搜狐SMTP郵箱發送郵件的辦法。
一、服務器上第三方程序的運行,在有些時候我們需要用到第三方的程序,比如創建記事本,使用編譯器編譯代碼等。這個時候要想讓這些程序運行起來,通常需要用到控制臺,這里就采用.bat腳本調用CMD控制來控制第三方程序。
1.1? 以下為.net mvc源代碼,該函數實現了工程根目錄下運行.bat腳本的功能。
public bool batRun(string path){// 指定批處理文件路徑//string batFilePath = Server.MapPath("~/Scripts/build_keil.bat");;string batFilePath = Server.MapPath("~/File/" + path);// 創建進程啟動信息ProcessStartInfo psi = new ProcessStartInfo{FileName = batFilePath,WorkingDirectory = Path.GetDirectoryName(batFilePath),UseShellExecute = false,CreateNoWindow = true,RedirectStandardOutput = true,RedirectStandardError = true};// 啟動進程try{using (Process process = Process.Start(psi)){// 讀取輸出(可選)string output = process.StandardOutput.ReadToEnd();string errors = process.StandardError.ReadToEnd();process.WaitForExit();ViewBag.Message = "批處理執行完成。輸出: " + output;if (!string.IsNullOrEmpty(errors)){ViewBag.Error = "錯誤: " + errors;}else{return true;}}}catch (Exception ex){ViewBag.Error = "執行批處理時出錯: " + ex.Message;}return false;}
1.2? 以下代碼為build_keil.bat代碼,通過該代碼調用了程序編譯器keil,編譯指定工程。
@echo off
chcp 65001 > nul
cd /d "%~dp0"set UV_PATH="C:\Keil_v5\UV4\UV4.exe"
set PROJECT="C:\Users\Administrator\Desktop\CompileSys\CompileSys\File\Prj\Bldc_Hall\Project\keil\project.uvprojx"
set LOG_FILE="build_log.txt"echo 正在編譯 Keil 工程...
%UV_PATH% -b %PROJECT% -j0 -o %LOG_FILE%if %errorlevel% equ 0 (echo 編譯成功!
) else (echo 編譯失敗,請檢查 %LOG_FILE%
)timeout /t 2
二、定時處理代碼,在服務器中通常是客戶提交,才會觸發服務器返回。但是經常服務器需要進行周期性的任務。
2.1? 定義了一個名為?AutoTaskAttribute
?的自定義屬性類,用于實現基于反射的定時任務調度系統。
2.2? AutoTaskAttribute.cs的具體代碼
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Web;namespace SaleSystem_20221225.MyClass
{/// <summary>/// Author:BigLiang(lmw)/// Date:2016-12-29/// </summary>[AttributeUsage(AttributeTargets.Class)]//表示此Attribute僅可以施加到類元素上public class AutoTaskAttribute : Attribute{/// <summary>/// 入口程序/// </summary>public string EnterMethod { get; set; }/// <summary>/// 執行間隔秒數(未設置或0 則只執行一次)/// </summary>public int IntervalSeconds { get; set; }/// <summary>/// 開始執行日期/// </summary>public string StartTime { get; set; }//保留對Timer 的引用,避免回收private static Dictionary<AutoTaskAttribute, System.Threading.Timer> timers = new Dictionary<AutoTaskAttribute, System.Threading.Timer>();/// <summary>/// Global.asax.cs 中調用/// </summary>public static void RegisterTask(){//異步執行該方法new Task(() => StartAutoTask()).Start();}/// <summary>/// 啟動定時任務/// </summary>private static void StartAutoTask(){var types = Assembly.GetExecutingAssembly().ExportedTypes.Where(t => Attribute.IsDefined(t, typeof(AutoTaskAttribute))).ToList();foreach (var t in types){try{var att = (AutoTaskAttribute)Attribute.GetCustomAttribute(t, typeof(AutoTaskAttribute));if (att != null){if (string.IsNullOrWhiteSpace(att.EnterMethod)){throw new Exception("未指定任務入口!EnterMethod");}var ins = Activator.CreateInstance(t);var method = t.GetMethod(att.EnterMethod);if (att.IntervalSeconds > 0){int duetime = 0; //計算延時時間if (string.IsNullOrWhiteSpace(att.StartTime)){duetime = 1000;}else{var datetime = DateTime.Parse(att.StartTime);if (DateTime.Now <= datetime){duetime = (int)(datetime - DateTime.Now).TotalSeconds * 1000;}else{duetime = att.IntervalSeconds * 1000 - ((int)(DateTime.Now - datetime).TotalMilliseconds) % (att.IntervalSeconds * 1000);}}timers.Add(att, new System.Threading.Timer((o) =>{method.Invoke(ins, null);}, ins, duetime, att.IntervalSeconds * 1000));}else{method.Invoke(ins, null);}}}catch (Exception ex){//LogHelper.Error(t.FullName + " 任務啟動失敗", ex);Debug.WriteLine(t.FullName + " 任務啟動失敗", ex);}}}}
}
2.3??AutoTaskAttribute的使用辦法,工程中的控制器代碼都是針對頁面提交的處理,只有在Global.asax是從服務器啟動以后一直運行,所以應該在Global.asax進行使用。
定義"StartTask"函數,定時3600s,1小時
定義StartTask函數處理程序
三、服務器中使用搜狐SMTP郵箱發送郵件的辦法。
public string sendEmail(string StrDate){/*try{*///發送者郵箱賬戶string sendEmail = "XXX@sohu.com";//發送者郵箱賬戶授權碼string code = "XXXX";//獨立密碼//發件人地址MailAddress from = new MailAddress(sendEmail);MailMessage message = new MailMessage();//收件人地址message.To.Add("XXX@163.com");message.To.Add("XXX@163.com");message.To.Add("XXX@s163.com");//標題message.Subject = DateTime.Now.ToString("yyyy-MM-dd") + "送貨單";message.SubjectEncoding = Encoding.UTF8;message.From = from;//郵件內容message.Body = "附件為當天送貨單";message.IsBodyHtml = true;message.BodyEncoding = Encoding.UTF8;string strFile = StrDate + ".xlsx";message.Attachments.Add(new Attachment(@"G:\SaleS\" + strFile ));//獲取或設置此電子郵件的發送通知。message.DeliveryNotificationOptions = DeliveryNotificationOptions.OnSuccess;SmtpClient client = new SmtpClient();client.EnableSsl = true;client.Host = "smtp.sohu.com";//smtp服務器client.Port = 25;//smtp端口//發送者郵箱賬戶和授權碼client.Credentials = new NetworkCredential(sendEmail, code);client.Send(message);return "發送成功";/* }catch (Exception e){return e.ToString();}*/}