Blame view

web/WebMvc/Program.cs 11.1 KB
赖素文 authored
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using Hh.Mes.Common;
using Hh.Mes.Common.config;
using Hh.Mes.Common.log;
using Hh.Mes.Pojo.System;
using log4net;
using log4net.Config;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using WebMvc.Common;

namespace WebMvc
{
    /// <summary>
    /// 启动类 没有特殊情况请不要随便修改 lsw
    /// 路径 https://www.cnblogs.com/cang12138/p/5845122.html
    /// </summary>
    public class Program
    {
        #region 全局变量

        public static int httpsPort { get; set; }
        public static int httpPort { get; set; }
        public static int reportPort { get; set; }

        public static string cerPath { get; set; }

        public static string cerPwd { get; set; }

        public static readonly string service = "Hh.Mes.Service";
        public static readonly string serviceSuffix = "Service";

        private static string cmdPath { get; set; }

        /// <summary>
        /// 定时器job 定时器命名空间【Quartz.Job】保持一致,不然反射失败
        /// </summary>
        public static readonly string quartzJobNameSpaceTypeName = "Quartz.Job";

        private static IConfiguration config { get; set; }
        public static X509Certificate2 certificate { get; set; }
赖素文 authored
48
49
50
        #endregion
赖素文 authored
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
        /// <summary>
        /// 运用程序key
        /// </summary>
        public static string AppKey { get; set; }
        public static string AppSecret { get; set; }
        public static int PingTimeout { get; set; }
        public static void Main(string[] args)
        {
            ExceptionsHelp.Instance.ExecuteVoidFunc(() =>
            {
                InitLog4Net();

                InitSysValue();

                #region 端口是否占用

                var isHttpPort = ComputerHelp.PortInUse(httpPort);
                if (isHttpPort)
                {
赖素文 authored
70
                    Console.ForegroundColor = ConsoleColor.Red;
赖素文 authored
71
                    Console.WriteLine("httpPort端口已被占用:" + httpPort);
赖素文 authored
72
                    Console.ReadLine();
赖素文 authored
73
74
75
76
77
78
                    return;
                }

                var isHttpsPort = ComputerHelp.PortInUse(httpsPort);
                if (isHttpsPort)
                {
赖素文 authored
79
                    Console.ForegroundColor = ConsoleColor.Red;
赖素文 authored
80
                    Console.WriteLine("httpsPort端口已被占用:" + httpsPort);
赖素文 authored
81
                    Console.ReadLine();
赖素文 authored
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
                    return;
                }

                #endregion

                InitIConfiguration();

                #region 本地封装日接口日志

                Logging.GetInstance.InitWriteInterLog();

                #endregion

                //证书 根据实际情况开启
                //if (httpsPort != 0) InitCer();

                //启动java积木报表服务 根据实际情况开启
                //Task.Factory.StartNew(InitJavaJiMuReport);

                CreateWebHostBuilder(args).Build().Run();
            });
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args)
        {
赖素文 authored
107
            Console.ResetColor();
赖素文 authored
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
            InitIConfiguration();

            return WebHost.CreateDefaultBuilder(args).UseKestrel(options =>
                {
                    options.AddServerHeader = false;

                    //https://www.cnblogs.com/lxhbky/p/11969478.html
                    //https://www.cnblogs.com/wucy/p/14824585.html
                    //设置Body大小限制256MB
                    options.Limits.MaxRequestBodySize = 268435456;


                    if (certificate != null)
                    {
                        options.Listen(IPAddress.Any, httpsPort,
                            listenOptions => { listenOptions.UseHttps(certificate); });
                    }

                    //http  根据实际情况开启
                    options.Listen(IPAddress.Any, httpPort);

                    Console.WriteLine();
                    Console.WriteLine("WebHostBuilder Init  Started successfully!");
                    Console.WriteLine();
                })
                .UseConfiguration(config)
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>();
        }

        private static void InitIConfiguration()
        {
            config = new ConfigurationBuilder()
                .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                .AddEnvironmentVariables()
                .AddJsonFile("certificate.json", optional: true, reloadOnChange: true)
                .AddJsonFile($"certificate.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")}.json",
                    optional: true, reloadOnChange: true)
                .Build();
        }

        #region 证书

        public static void InitCer()
        {
            ConfigRead.GetInstance.GetAppsetConnection().HttpOrHttps = "https";
            var certificateSettings = config.GetSection("certificateSettings");
            var certificateFileName = certificateSettings.GetValue<string>("filename");
            var certificatePassword = certificateSettings.GetValue<string>("password");
            var filePath = Path.Combine(AppContext.BaseDirectory, certificateFileName);
            if (!File.Exists(filePath))
            {
赖素文 authored
160
                Console.ForegroundColor = ConsoleColor.Red;
赖素文 authored
161
162
                Console.WriteLine("证书文件路径不存在,请确认发布属性是【始终复制】:" + filePath);
                Log4NetHelper.Instance.Info("Certificate path:" + filePath);
赖素文 authored
163
                Console.ReadLine();
赖素文 authored
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
            }

            certificate = new X509Certificate2(certificateFileName, certificatePassword);
            cerPwd = certificatePassword;

            //内存缓存设置 路径和密码 定时器启动使用
            ConfigRead.GetInstance.GetAppsetConnection().CerPwd = cerPwd;
            ConfigRead.GetInstance.GetAppsetConnection().CerPath = cerPath;
            Console.WriteLine("InitCer Init  Started successfully!");
        }

        #endregion

        #region Log4Net
        private static void InitLog4Net()
        {
            Log4NetHelper.Instance.Repository = LogManager.CreateRepository("NETCoreRepository");
181
            var log4ConfigFilePath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "config",
赖素文 authored
182
                "log4net.config");
183
            if (!File.Exists(log4ConfigFilePath))
赖素文 authored
184
            {
赖素文 authored
185
                Console.ForegroundColor = ConsoleColor.Red;
186
187
                Console.WriteLine("log4net.config文件路径不存在,请确认发布属性是【始终复制】:" + log4ConfigFilePath);
                Log4NetHelper.Instance.Info("InitLog4Net path:" + log4ConfigFilePath);
赖素文 authored
188
                Console.ReadLine();
赖素文 authored
189
            }
190
            XmlConfigurator.Configure(Log4NetHelper.Instance.Repository, new FileInfo(log4ConfigFilePath));
赖素文 authored
191
192
193
194
195
196
197
            Console.WriteLine("InitLog4Net Init  Started successfully!");
        }
        #endregion

        #region 获取配置信息
        private static void InitSysValue()
        {
赖素文 authored
198
            Console.Title = "IOT WebServer 网关服务"; 
赖素文 authored
199
200
201
202
203
204
205
            httpPort = ConfigRead.GetInstance.GetAppsetConnection().HttpPort;
            httpsPort = ConfigRead.GetInstance.GetAppsetConnection().HttpsPort;
            reportPort = ConfigRead.GetInstance.GetAppsetConnection().ReportPort;
            cmdPath = @"C:\Windows\System32\cmd.exe";
            cerPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "huaheng.pfx");
            if (!File.Exists(cerPath))
            {
赖素文 authored
206
                Console.ForegroundColor = ConsoleColor.Red;
赖素文 authored
207
208
                Console.WriteLine("cerPath文件路径不存在,请确认发布属性是【始终复制】:" + cerPath);
                Log4NetHelper.Instance.Info("Certificate path:" + cerPath);
赖素文 authored
209
                Console.ReadLine();
赖素文 authored
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
            }
            SystemVariable.StartTime = DateTime.Now;
            ConfigRead.GetInstance.GetAppsetConnection().HttpOrHttps = "http";
            Console.WriteLine("InitSysValue Init  Started successfully!");
        }
        #endregion

        #region InitJavaJiMuReport
        private static void InitJavaJiMuReport()
        {
            Console.WriteLine();
            var isReportPort = ComputerHelp.PortInUse(reportPort);
            if (isReportPort)
            {
                Console.WriteLine($"ReportPort端口{reportPort}已占用,或者服务报表已经启动成功!Url【http://localhost:{reportPort}/jmreport/list】");
                Console.WriteLine();
赖素文 authored
226
                Console.ReadLine();
赖素文 authored
227
228
229
230
231
232
233
234
235
236
237
238
239
240
                return;
            }
            var reportPath = Path.Combine(Path.GetDirectoryName(typeof(Program).Assembly.Location), "report");
            if (Directory.Exists(reportPath))
            {
                Console.WriteLine($"Init JavaJiMuReport Initing......Url【http://localhost:{reportPort}/jmreport/list】No exception is success!");
                var cmd = $"cd {reportPath}&javaServiceStart.bat";
                var output = "";
                RunCmd(cmd, out output);
                Console.WriteLine(output);
            }
            else
            {
                Console.WriteLine("javaServiceStart.bat path is not existence!");
赖素文 authored
241
                Console.ReadLine();
赖素文 authored
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
            }
        }

        /// <summary>
        /// 执行cmd命令 https://www.cnblogs.com/njl041x/p/3881550.html
        /// 多命令请使用批处理命令连接符:
        /// <![CDATA[
        /// &:同时执行两个命令
        /// |:将上一个命令的输出,作为下一个命令的输入
        /// &&:当&&前的命令成功时,才执行&&后的命令
        /// ||:当||前的命令失败时,才执行||后的命令]]>
        /// 其他请百度
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="output"></param>
        private static void RunCmd(string cmd, out string output)
        {
            cmd = cmd.Trim().TrimEnd('&') + "&exit";//说明:不管命令是否成功均执行exit命令,否则当调用ReadToEnd()方法时,会处于假死状态
            using (var p = new Process())
            {
                p.StartInfo.FileName = cmdPath;
                p.StartInfo.UseShellExecute = false;        //是否使用操作系统shell启动
                p.StartInfo.RedirectStandardInput = true;   //接受来自调用程序的输入信息
                p.StartInfo.RedirectStandardOutput = true;  //由调用程序获取输出信息
                p.StartInfo.RedirectStandardError = true;   //重定向标准错误输出
                p.StartInfo.CreateNoWindow = true;          //不显示程序窗口
                p.Start();//启动程序

                //cmd窗口写入命令
                p.StandardInput.WriteLine(cmd);
                p.StandardInput.AutoFlush = true;
                //获取cmd窗口的输出信息
                output = p.StandardOutput.ReadToEnd();
                p.WaitForExit();//等待程序执行完退出进程
                p.Close();
            }
赖素文 authored
278
        }
赖素文 authored
279
        #endregion
赖素文 authored
280
281
赖素文 authored
282
283
    }
}