ASP. NET CORE Linux Publishing tool (file compare only upload diff file, auto start and stop webserver command, upload complete automatic preheating webserver)

Source: Internet
Author: User
Tags local time

In recent days, I've been doing a little website: teach you.; (Interested friends can come to cheer, any spending on this site I can be refunded) due to frequent updates, manual update is particularly troublesome, so the development of this gadget for a period of time, or quite handy, at the same time. NET coreqq Group (225982985) group Friends @ Dead My heart not die Also recommend me to share this to the code published here, there is any problem can contact me:

First look at the configuration file, app. Config:
<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<appSettings>
<add key= "serveripaddress" value= "***.***.***.***"/>
<add key= "Sshusername" value= "* * *"/>
<add key= "Sshpassword" value= "*********"/>
<add key= "Serverpath" value= "/***/***/"/>
<add key= "Clientpath" value= "D:\p\JiaoNiA\code\JNA\JNA. Web\bin\release\netcoreapp2.0\centos.7-x64\publish\ "/>
<add key= "Ignorfilepatten" value= "system\. +; Microsoft\. +;. +\.so "/>
<add key= "Httpserverstartcommand" value= "systemctl start Jna.service"/>
<add key= "Httpserverstopcommand" value= "Systemctl stop Jna.service"/>
<add key= "Websiteurl" value= "http://www.jiaonia.com"/>
<add key= "websiteassertstring" value= "teach you-knowledge compounding manufacturing platform"/>
</appSettings>
<startup>
<supportedruntime version= "v4.0" sku= ". netframework,version=v4.5 "/>
</startup>
</configuration>
Serveripaddress: Server address, The server environment only supports Linuxsshusername: Server SSH username (also known as SFTP username) Sshpassword: server ssh password (also for sftp password) Serverpath: Deployment path for Server Web program Clientpath: You Development environment, VS compiled after the path, I use the compile command is:
dotnet publish -c release -r centos.7-x64   
Ignorfilepatten: Because the VS compiled files are very many, some files upload once, life also no longer upload, then you can set some regular expression here, filter these files, Reduce the workload (regular expressions are semicolon-delimited) Httpserverstopcommand: Most of the time the update requires a downtime update. This command is the command to stop webserver Httpserverstartcommand: This command is the command to start webserver after the upgrade is complete Websiteurl: After the upgrade is complete, and webserver has been restarted successfully, This program will request the URL of your Web application, to warm up the program, or the first time the visit is very slow, this URL is set here Websiteassertstring: The program Access URL, will get the server response to the HTML, Then determine whether the response HTML contains the assertion set here, there is proof that the upgrade was successful;
OK, look at the code:
Let's look at a couple of private variables: (note after the variable user)
        static List<FileInfo> clientFileInfos = new List<FileInfo>();//用于存储本地待对比的文件
static List<string> IgnorFilePattens = new List<string>();//用于存储过滤器,过滤器命中的文件不用参与对比
static Dictionary<FileInfo,string> prepareFileInfo = new Dictionary<FileInfo, string>();//用于存储对比后待上传的文件
static NameValueCollection setting = ConfigurationManager.AppSettings;
Let's look at the main function: (I've written notes on a few key points)
static void Main (string[] args)
{
Console.WriteLine ("Start the file (based on the modified time of the file)?" Y: Start. Other keys to exit the program: ");
if (Console.ReadLine ()! = "Y")
{
Return
}
Console.WriteLine ("Start than File ...");
Ignorfilepattens.addrange (setting["Ignorfilepatten"). Split (';')); /cache the filter first.
Getclientfileinfos (setting["Clientpath"]);//recursive fetching of local files, filter hit files skipped
Sftpcomparefile (sftpclient =//local file vs. server file)
{
if (Preparefileinfo.count < 1)
{
Console.WriteLine ("No files need to be updated, press any key to quit the program!");
Console.readkey ();
Return
}
Console.WriteLine ("Start the shutdown upload file?") Y: Start. Other keys to exit the program: ");
if (Console.ReadLine ()! = "Y")
{
Return
}
Sshstartandstopwebserver (() =//Start-Stop Web server
{
foreach (Var fileInfo in Preparefileinfo.keys)
{
using (var FileStream = Fileinfo.openread ())
{
Sftpclient.buffersize = 6 * 1024;
Sftpclient.uploadfile (FileStream, preparefileinfo[fileinfo],true); Uploading files
}
Console.WriteLine ("Upload complete:" + preparefileinfo[fileinfo]);
}
});
Thread.Sleep (918); Leave the server breathing time
Console.WriteLine ("Start request target site ...");
var html = gethtml (setting["Websiteurl"]); URL of the request Web
if (HTML. Contains (setting["websiteassertstring"))//Determine if the assertion is hit
{
Console.WriteLine ("Upgrade successfully, press any key to exit the program");
}
Else
{
Console.WriteLine ("Upgrade failed, please contact the Administrator!") Press any key to exit the program! ");
}
Console.readkey ();
});
}

Next, we look at 1.1 points in the main function of a few key points: first look at recursion to take local files, filter hit file skipped
static void Getclientfileinfos (string path)
{
var directorypaths = directory.getdirectories (path);
foreach (Var directorypath in directorypaths)
{
Getclientfileinfos (DirectoryPath); Recursion, self-tune yourself
}
var filepaths = directory.getfiles (path);
foreach (Var filePath in filepaths)
{
var fi = new FileInfo (FilePath);
var flag = false;
foreach (Var patten in Ignorfilepattens)
{
Flag = Regex.IsMatch (FI. Name, Patten);
if (flag)
{
Break There is a filter hit, then no other filter
}
}
if (flag)
{
Continue Hit the file, then skip
}
Clientfileinfos.add (FI);
}
}
Local file vs. server file: (By last modification time comparison)
static void Sftpcomparefile (action<sftpclient> actor)
{
using (var client = new Sftpclient (setting["serveripaddress"], setting["Sshusername"], setting["Sshpassword"]))
{
Client. Connect ();
foreach (Var fileInfo in Clientfileinfos)
{
var subname = fileInfo.FullName.Remove (0, setting["Clientpath"]. Length);
if (subname.startswith ("\ \"))
{
SubName = Subname.remove (0, 1);
}
SubName = subname.replace (' \ \ ', '/');
var Serverpath = setting["Serverpath"] + subname;//The first few lines of code are to get the file on the service side of the absolute path, the configuration of the Serverpath must be/end, here do not check;
var flag = client. Exists (Serverpath);
if (!flag)
{
Preparefileinfo.add (FileInfo, Serverpath); If the server does not exist this file, then this file is definitely to upload it, note: There is no control directory exists
Console.WriteLine ("Pending File:" + subname);
}
Else
{
var dt = client. GetLastWriteTime (Serverpath);
if (dt < fileinfo.lastwritetime)//File Last update time comparison, local time is newer than server time, you need to upload
{
Preparefileinfo.add (FileInfo, Serverpath);
Console.WriteLine ("Pending File:" + subname);
}
}
}
Actor (client);
}
}
Then look at the code to start and stop the Web server: (just execute the command directly in the configuration file, nothing special)
static void sshStartAndStopWebServer(Action actor)
{
using (var sshclient = new SshClient(setting["ServerIPAddress"], setting["SSHUserName"], setting["SSHPassWord"]))
{
sshclient.Connect();
using (var cmd = sshclient.CreateCommand(setting["HttpServerStopCommand"]))
{
cmd.Execute();
Console.WriteLine("停用HttpServer");
}
actor();
using (var cmd = sshclient.CreateCommand(setting["HttpServerStartCommand"]))
{
cmd.Execute();
Console.WriteLine("启用HttpServer");
}
sshclient.Disconnect();
}
}
Code to request HTML
static string GetHtml(string url)
{
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Timeout = 16 * 1000;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
string html = reader.ReadToEnd();
stream.Close();
return html;
}

This project uses a key library: Ssh.net is here to pay tribute to the author!
Interested friends, also can add my QQ group communication: 51021155

ASP. NET CORE Linux Publishing tool (file compare only upload diff file, auto start and stop webserver command, upload complete automatic preheating webserver)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.