calpuff-server-Form1.cs

来源:互联网 发布:mac分区失败 发生错误 编辑:程序博客网 时间:2024/05/22 21:18
using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;using System.IO;using System.Diagnostics;using System.Net;using System.Threading;namespace ServerV1._1{    public partial class Form1 : Form    {                   public static string exeDir = "C:\\calpuff\\exe"; // exe文件的路径        public static string inpDir = "C:\\calpuff\\inp";        public static string wrfoutDir = "C:\\calpuff\\wrfout";              // Server  Database         public static string dbIp = "127.0.0.1";        public static string dbName = "mysql";        public static string dbUser = "root";        public static string dbPasswd = "1234";        public static string outputDir = "C:\\calpuff\\output";        //  ftp 相关操作         public static string ftpIp="120.25.206.223";               public static string ftpUser="finalformat";                public static string ftpPasswd="finalformat";                   // 与头文件相关           public static double[] maxLstValue = new double [1000];//  #MaxLimit#   就当最多有1000种类污染物         public static int calpuffDaySpan = 0;        public static string finalFormatDir = "C:\\calpuff\\finalFormat";        //  头文件        public static string[] headFile = new string[1000];        // 与calpuff 相关        public static string srcDir = "C:\\calpuff\\src";             // public static string logs = "";        public static string taskRecords = "";              // 取出来的数据用来更新        public static int id;        public static string modelname = "";        public static string startdate = "";        public static string enddate = "";        public static string xrefkm = "";        public static string yrefkm = "";        public static string nx = "";        public static string ny = "";        public static string dgridkm = "";        public static string identifier = "";        public static string gtopo30 = "";        public static string glazas = "";        public static byte[] srcfile;        // 重新定义每一个exePath...  又刷新一遍逻辑        public static string terrelExePath = "C:\\calpuff\\exe\\terrel.exe";        public static string ctgprocExePath = "C:\\calpuff\\exe\\ctgproc.exe";        public static string makegeoExePath = "C:\\calpuff\\exe\\makegeo.exe";        public static string calwrfExePath = "C:\\calpuff\\exe\\calwrf.exe";        public static string calmetExePath = "C:\\calpuff\\exe\\calmet.exe";        public static string calpuffExePath = "C:\\calpuff\\exe\\calpuff.exe";        public static string terrelInpPath = "C:\\calpuff\\output\\terrel.inp";        public static string ctgprocInpPath = "C:\\calpuff\\output\\ctgproc.inp";        public static string makegeoInpPath = "C:\\calpuff\\output\\makegeo.inp";        public static string calwrfInpPath = "C:\\calpuff\\output\\calwrf.inp";        public static string calmetInpPath = "C:\\calpuff\\output\\calmet.inp";        public static string calpuffInpPath = "C:\\calpuff\\output\\calpuff.inp";        //  两个函数保证static的参数和本地的ini文件始终保持一致        public static void loadIni()        {             string iniPath="C:\\calpuff\\ini\\calpuff.ini";           if(!File.Exists(iniPath))           {               MessageBox.Show("calpuf.ini is missing ,please place it as 'C:\\calpuff\\ini\\calpuff.ini'");               return;           }            // 先获取最大行~            int lineCnt = 0;            FileStream fs = new FileStream(iniPath, FileMode.Open, FileAccess.Read);            StreamReader sr = new StreamReader(fs);            string tempStr="";            while (tempStr != null)            {                tempStr = sr.ReadLine();                lineCnt++;            }            lineCnt--;  // 有一位位移            string [] ini = new string[lineCnt + 100];            fs = new FileStream(iniPath, FileMode.Open, FileAccess.Read);            sr = new StreamReader(fs);            int index = 0;            tempStr = "";            while (tempStr != null)            {                tempStr = sr.ReadLine();                ini[index++] = tempStr;               }            index--; // 此时index就是行数                        // 这样做其实很麻烦的  完全可以一次性就申请多一点  但是既然现成的代码也有 就这样写吧            string [] key =new string [index];            string [] value = new string [index];                        string [] keyAndValue=new string [100];// 2就够了                        for(int i=0;i<index;i++)            {                string curStr=ini[i];                int wordsCnt = 0;                infoExtract(keyAndValue, ref wordsCnt, curStr);                key[i] = keyAndValue[0];                value[i] = keyAndValue[1];            }                         // 有点枚举  但是数据规模比较小             for(int i=0;i<index;i++)            {                  string curKey=key[i];                string curValue=value[i];                if (curKey == "dbIp") dbIp = curValue;                else if (curKey == "dbName") dbName = curValue;                else if (curKey == "dbUser") dbUser = curValue;                else if (curKey == "dbPasswd") dbPasswd = curValue;                else if (curKey == "ftpIp") ftpIp = curValue;                else if (curKey == "ftpUser") ftpUser = curValue;                else if (curKey == "ftpPasswd") ftpPasswd = curValue;                else if (curKey == "inpDir") inpDir = curValue;                else if (curKey == "exeDir") exeDir = curValue;                else if (curKey == "wrfoutDir") wrfoutDir = curValue;                else if (curKey == "outputDir") outputDir = curValue;                else if (curKey == "srcDir") srcDir = curValue;            }            sr.Close();            fs.Close();            //  V1.2.1   labelTxt也要更新啊                    }        public static void saveIni()        {            // 写文件           string iniPath="C:\\calpuff\\ini\\calpuff.ini";           if (!File.Exists(iniPath))           {               MessageBox.Show("calpuf.ini is missing ,please place it as 'C:\\calpuff\\ini\\calpuff.ini'");               return;           }           FileStream fs = new FileStream(iniPath, FileMode.Open, FileAccess.Write);           StreamWriter sw = new StreamWriter(fs);           sw.WriteLine("dbIp" + " " + dbIp);           sw.WriteLine("dbName" + " " + dbName);           sw.WriteLine("dbUser" + " " + dbUser);           sw.WriteLine("dbPasswd" + " " + dbPasswd);           sw.WriteLine("ftpIp" + " " + ftpIp);           sw.WriteLine("ftpUser" + " " + ftpUser);           sw.WriteLine("ftpPasswd" + " " + ftpPasswd);           sw.WriteLine("inpDir" + " " + inpDir);           sw.WriteLine("exeDir" + " " + exeDir);           sw.WriteLine("wrfoutDir" + " " + wrfoutDir);           sw.WriteLine("outputDir" + " " + outputDir);           sw.WriteLine("srcDir" + " " + srcDir);           sw.Close();           fs.Close();        }        // 构造函数         public Form1()        {            InitializeComponent();            Point point = new Point(Screen.PrimaryScreen.WorkingArea.Width / 2 - this.Size.Width / 2, Screen.PrimaryScreen.WorkingArea.Height / 2 - this.Size.Height / 2);//窗体位置            this.StartPosition = FormStartPosition.Manual;            this.Location = point;            //  这个时候就要loadIni            //  本地配置文件            loadIni();              // load以后  注意更新labelTxt            label5.Text = exeDir;            label6.Text = inpDir;            label7.Text = wrfoutDir;            label8.Text = outputDir;            label9.Text = srcDir;            //  等待标示            pictureBox1.Visible = false;        }         private void button1_Click(object sender, EventArgs e)        {            Form form = new GeoFile();            Point point = new Point(Screen.PrimaryScreen.WorkingArea.Width / 2 - form.Size.Width / 2, Screen.PrimaryScreen.WorkingArea.Height / 2 - form.Size.Height / 2);//窗体位置            form.StartPosition = FormStartPosition.Manual;            form.Location = point;            form.ShowDialog();                 }        // File Test  检查所有文件是否存在        private void button2_Click(object sender, EventArgs e)        {                      //  -------------------------------------------------- test only----------------            string terrelInpPath = inpDir + "\\terrel.inp";            string ctgprocInpPath = inpDir + "\\ctgproc.inp";            string makegeoInpPath = inpDir + "\\makegeo.inp";            string calwrfInpPath = inpDir + "\\calwrf.inp";            string calmetInpPath = inpDir + "\\calmet.inp";            string calpuffInpPath = inpDir + "\\calpuff.inp";            string terrelExePath = exeDir + "\\terrel.exe";            string ctgprocExePath = exeDir + "\\ctgproc.exe";            string makegeoExePath = exeDir + "\\makegeo.exe";            string calwrfExePath = exeDir + "\\calwrf.exe";            string calmetExePath = exeDir + "\\calmet.exe";            string calpuffExePath = exeDir + "\\calpuffl.exe";  // note 'l'            if (!File.Exists(terrelInpPath))            {                MessageBox.Show("Error:terrel.inp does not exist in current directory");                return;            }            if (!File.Exists(ctgprocInpPath))            {                MessageBox.Show("Error:ctgproc.inp does not exist in current directory");                return;            }            if (!File.Exists(makegeoInpPath))            {                MessageBox.Show("Error:makegeo.inp does not exist in current directory");                return;            }            if (!File.Exists(calwrfInpPath))            {                MessageBox.Show("Error:calwrf.inp does not exist in current directory");                return;            }            if (!File.Exists(calmetInpPath))            {                MessageBox.Show("Error:calmet.inp does not exist in current directory");                return;            }            if (!File.Exists(calpuffInpPath))            {                MessageBox.Show("Error:calpuff.inp does not exist in current directory");                return;            }            // exe            if (!File.Exists(terrelExePath))            {                MessageBox.Show("Error:terrel.exe does not exist in current directory");                return;            }            if (!File.Exists(ctgprocExePath))            {                MessageBox.Show("Error:ctgproc.exe does not exist in current directory");                return;            }            if (!File.Exists(makegeoExePath))            {                MessageBox.Show("Error:makegeo.exe does not exist in current directory");                return;            }            if (!File.Exists(calwrfExePath))            {                MessageBox.Show("Error:calwrf.exe does not exist in current directory");                return;            }            if (!File.Exists(calmetExePath))            {                MessageBox.Show("Error:calmet.exe does not exist in current directory");                 return;            }            if (!File.Exists(calpuffExePath))            {                MessageBox.Show("Error:calpuffl.exe does not exist in current directory");                return;            }            // dll 文件检查             string dllPath1=exeDir+"\\libgcc_s_dw2-1.dll";             string dllPath2=exeDir+"\\libgfortran-3.dll";             string dllPath3=exeDir+"\\libnetcdf-0.dll";             string dllPath4=exeDir+"\\libquadmath-0.dll";             if (!File.Exists(dllPath1))            {                MessageBox.Show("Error:libgcc_s_dw2-1.dll should exist in exe directory");                return;            }             if (!File.Exists(dllPath2))            {                MessageBox.Show("Error:libgfortran-3.dll should exist in current directory");                return;            }             if (!File.Exists(dllPath3))            {                MessageBox.Show("Error:libnetcdf-0.dll does not exist in current directory");                return;            }             if (!File.Exists(dllPath4))            {                MessageBox.Show("Error:libquadmath-0.dll should exist in exe directory");                return;            }             MessageBox.Show("All The Necessary Files Are Available");        }        //  Server Conf        private void button7_Click(object sender, EventArgs e)        {            Form form = new ServerConf();            Point point = new Point(Screen.PrimaryScreen.WorkingArea.Width / 2 - form.Size.Width / 2, Screen.PrimaryScreen.WorkingArea.Height / 2 - form.Size.Height / 2);//窗体位置            form.StartPosition = FormStartPosition.Manual;            form.Location = point;            form.ShowDialog();        }         //设置exe目录        private void button3_Click(object sender, EventArgs e)        {            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();            folderBrowser.ShowDialog();            if (folderBrowser.SelectedPath != "")            {                exeDir = folderBrowser.SelectedPath;                label5.Text = exeDir;                // 存储到本地配置                saveIni();            }        }        //设置inpDir         private void button4_Click(object sender, EventArgs e)        {            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();            folderBrowser.ShowDialog();            if (folderBrowser.SelectedPath != "")            {                inpDir = folderBrowser.SelectedPath;                label6.Text = inpDir;                // 存储到本地配置                saveIni();            }        }       //  设置wrfout 目录        private void button5_Click(object sender, EventArgs e)        {            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();            folderBrowser.ShowDialog();            if (folderBrowser.SelectedPath != "")            {                wrfoutDir = folderBrowser.SelectedPath;                label7.Text = wrfoutDir;                // 存储到本地配置                saveIni();            }        }        // output 目录选择        private void button6_Click(object sender, EventArgs e)        {            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();            folderBrowser.ShowDialog();            if (folderBrowser.SelectedPath != "")            {                outputDir = folderBrowser.SelectedPath;                label8.Text = outputDir;                // 存储到本地配置                saveIni();            }        }        // Load Tasks            private void button8_Click(object sender, EventArgs e)        {            this.loadTasks();        }        // Start Running---------mannual          private void button9_Click(object sender, EventArgs e)        {            // 六个模型一起Run                         MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection();            // 到时候换成一个公网IP              string connStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";            conn.ConnectionString = connStr;            try            {                conn.Open();  // conn Open();            }            catch            {                MessageBox.Show("Database Connection Error");            }            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();            cmd.Connection = conn;            cmd.CommandText = "select id,modelname,startdate,enddate,xrefkm,yrefkm,nx,ny,dgridkm,gtopo30,glazas,identifier,srcfile from t_calpuf_conf where done=0";                       System.Data.Common.DbDataReader reader = cmd.ExecuteReader();            if(!reader.HasRows)            {                MessageBox.Show("No Tasks To Be Dealt With");                return;            }            // 一个个的取出应用            while (reader.Read())  //  想一次处理完  Read() 也是个修改调用者的函数啊            {                              id = reader.GetInt32(reader.GetOrdinal("id"));                identifier = reader.GetString(reader.GetOrdinal("identifier"));                modelname = reader.GetString(reader.GetOrdinal("modelname"));                 if (modelname == "terrel")                {                      // 需要再从数据库取出来                    nx = reader.GetString(reader.GetOrdinal("nx"));                    ny = reader.GetString(reader.GetOrdinal("ny"));                    xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                    yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                    dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                    gtopo30 = reader.GetString(reader.GetOrdinal("gtopo30"));                    runTerrel();                }                else if (modelname == "ctgproc")                {                    nx = reader.GetString(reader.GetOrdinal("nx"));                    ny = reader.GetString(reader.GetOrdinal("ny"));                    xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                    yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                    dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                    glazas = reader.GetString(reader.GetOrdinal("glazas"));                    runCtgproc();                }                else if(modelname=="makegeo")                {                    nx = reader.GetString(reader.GetOrdinal("nx"));                    ny = reader.GetString(reader.GetOrdinal("ny"));                    xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                    yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                    dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                    gtopo30 = reader.GetString(reader.GetOrdinal("gtopo30"));                    glazas = reader.GetString(reader.GetOrdinal("glazas"));                                        runMakegeo();                }                else if (modelname == "calwrf")   // 依赖于wrfout 只需要起始日期即可                {                    startdate = reader.GetString(reader.GetOrdinal("startdate"));                    enddate = reader.GetString(reader.GetOrdinal("enddate"));                    runCalwrf();                   }                else if (modelname == "calmet")                {                    nx = reader.GetString(reader.GetOrdinal("nx"));                    ny = reader.GetString(reader.GetOrdinal("ny"));                    xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                    yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                    dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                    // for calwrf                    startdate = reader.GetString(reader.GetOrdinal("startdate"));                    enddate = reader.GetString(reader.GetOrdinal("enddate"));                    // for makegeo                    gtopo30 = reader.GetString(reader.GetOrdinal("gtopo30"));                    glazas = reader.GetString(reader.GetOrdinal("glazas"));                    runCalmet();                }                else if (modelname == "calpuff")                {                    nx = reader.GetString(reader.GetOrdinal("nx"));                    ny = reader.GetString(reader.GetOrdinal("ny"));                    xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                    yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                    dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                    // for calwrf                    startdate = reader.GetString(reader.GetOrdinal("startdate"));                    enddate = reader.GetString(reader.GetOrdinal("enddate"));                    // for makegeo                    gtopo30 = reader.GetString(reader.GetOrdinal("gtopo30"));                    glazas = reader.GetString(reader.GetOrdinal("glazas"));                    // then we have calmet                     // in the function we get src file                    runCalpuff();                }                // 用完了 reader 绑定的reader了                conn.Clone();  // conn Close()    SO! Crucial!                // 确保只有运行完毕了才会更新数据                MySql.Data.MySqlClient.MySqlConnection updateConn = new MySql.Data.MySqlClient.MySqlConnection();                // 到时候换成一个公网IP                  string updateConnStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";                updateConn.ConnectionString = updateConnStr;               updateConn.Open();  // update  Conn Open()               cmd = new MySql.Data.MySqlClient.MySqlCommand();               cmd.Connection = updateConn;               cmd.CommandText = "update t_calpuf_conf set done=1 where identifier="+"\""+identifier+"\"";               cmd.ExecuteNonQuery();               updateConn.Close(); // update Conn Close()                // 日志更新              // textBox2.Text = logs;                          }                        MessageBox.Show("All Tasks Completed");                    }       public   void runTerrel()        {             terrelExePath = exeDir + "\\terrel.exe";                if (!File.Exists(terrelExePath))            {                MessageBox.Show("Warning:terrel.exe does not exist in current exe path");                return;            }                     terrelInpMaking();                       ProcessStartInfo info = new ProcessStartInfo();            info.FileName = terrelExePath;            info.Arguments = terrelInpPath;            info.WindowStyle = ProcessWindowStyle.Minimized;            Process p = new Process();            p.StartInfo = info;            p.Start();            textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[Status: Terrel-StartRunning]-[Time: " + DateTime.Now.ToString() + "]\r\n";                        //  开始等待            pictureBox1.Visible = true;            while(true)            {                if(p.HasExited)                {                    pictureBox1.Visible = false;                    break;                }            }            textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[Status: Terrel-Done]-[Time: " + DateTime.Now.ToString() + "]\r\n";        }       public  void runCtgproc()       {           ctgprocExePath = exeDir + "\\ctgproc.exe";           //  再检查校验一下是否存在   以防点了FileTest 以后还是修改了           if (!File.Exists(ctgprocExePath))           {               MessageBox.Show("Warning:ctgproc.exe does not exist in current exe path");               return;           }                      ctgprocInpMaking();                      ProcessStartInfo info = new ProcessStartInfo();           info.FileName = ctgprocExePath;           info.Arguments = ctgprocInpPath;           info.WindowStyle = ProcessWindowStyle.Minimized;          // Process.Start(info);  // 这种方式不用kill           Process p = new Process();           p.StartInfo = info;           p.Start();           // indicator           pictureBox1.Visible = true;           textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[Status: Ctgproc-StartRunning]-[Time: " + DateTime.Now.ToString() + "]\r\n";           while(true)           {               if(p.HasExited)               {                   pictureBox1.Visible = false;                   break;               }           }           textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[Status: Ctgproc-Done]-[Time: " + DateTime.Now.ToString() + "]\r\n";       }       public  void runMakegeo()       {           // makegeo 依赖于前两个模型的结果            makegeoExePath= exeDir + "\\makegeo.exe";           //  再检查校验一下是否存在   以防点了FileTest 以后还是修改了            if (!File.Exists(makegeoExePath))           {               MessageBox.Show("Warning:makegeo.exe does not exist in current exe path");               return;           }                     terrelInpMaking();           runTerrel();           // 然后是ctgproc           ctgprocInpMaking();           runCtgproc();           //  最后是makegeo           makegeoInpMaking();           Process process = new Process();           ProcessStartInfo info = new ProcessStartInfo();           info.FileName = makegeoExePath;           info.Arguments = makegeoInpPath;           info.WindowStyle = ProcessWindowStyle.Minimized;           process = new Process();           process.StartInfo = info;           process.Start();           pictureBox1.Visible = true;           textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[Status: Makegeo-StartRunning]-[Time: " + DateTime.Now.ToString() + "]\r\n";           while (true)           {               if (process.HasExited)               {                   pictureBox1.Visible = false;                   break;               }           }           textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[Status: Makegeo-Done]-[Time: " + DateTime.Now.ToString() + "]\r\n";                  }       public  void runCalwrf()       {           // 基本上只需要一个日期+ 日期循环即可           DateTime curDate = new DateTime();           string curDateStr = "";           DateTime startdateDtt=Convert.ToDateTime(startdate);           DateTime enddateDtt=Convert.ToDateTime(enddate);           TimeSpan span = enddateDtt.Subtract(startdateDtt);           int days = span.Days;           for(int i=0;i<=days;i++)   // 注意是<=days           {               curDate = startdateDtt.AddDays(i);               curDateStr = dateStr(curDate);               calwrfInpMaking(curDateStr);               // 把wrfout文件的检查放在run的里面吧~               ProcessStartInfo info = new ProcessStartInfo();               info.FileName = calwrfExePath;               info.Arguments = calwrfInpPath;               // 没个日期是不一样的..               info.WindowStyle = ProcessWindowStyle.Minimized;               // Process.Start(info);  // 这种方式不用kill               Process p = new Process();               p.StartInfo = info;               p.Start();               pictureBox1.Visible = true;               textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[ForDate: " + curDate + "]-[Status: Calwrf-StartRunning]-[Time: " + DateTime.Now.ToString() + "]\r\n";                               while (true)               {                   if (p.HasExited)                   {                       pictureBox1.Visible = false;                       break;                   }               }               textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[ForDate: " + curDate + "]-[Status: Calwrf-Done]-[Time: " + DateTime.Now.ToString() + "]\r\n";           }              }                public  void runCalmet()       {           runMakegeo();   //  terrel 和ctgproc 已经run过了                     runCalwrf();  // calwrf 结果            calmetExePath = exeDir + "\\calmet.exe";           //  再检查校验一下是否存在   以防点了FileTest 以后还是修改了           if (!File.Exists(calmetExePath))           {               MessageBox.Show("Warning:calmet.exe does not exist in current exe path");               return;           }           DateTime curDate = new DateTime();           string curDateStr = "";           DateTime startdateDtt = Convert.ToDateTime(startdate);           DateTime enddateDtt = Convert.ToDateTime(enddate);           TimeSpan span = enddateDtt.Subtract(startdateDtt);           int days = span.Days;           for (int i = 0; i <= days; i++)   // 注意是<=days           {               curDate = startdateDtt.AddDays(i);               curDateStr = dateStr(curDate);               calmetInpMaking(curDateStr);               // 把wrfout文件的检查放在run的里面吧~               ProcessStartInfo info = new ProcessStartInfo();               info.FileName = calmetExePath;               info.Arguments = calmetInpPath;               // 没个日期是不一样的..               info.WindowStyle = ProcessWindowStyle.Minimized;                             Process p = new Process();               p.StartInfo = info;               p.Start();               pictureBox1.Visible = true;               textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[ForDate: " + curDate + "]-[Status: Calmet-StartRunning]-[Time: " + DateTime.Now.ToString() + "]\r\n";               while (true)               {                   if (p.HasExited)                   {                       pictureBox1.Visible = false;                       break;                   }               }               textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[ForDate: " + curDate + "]-[Status: Calmet-Done]-[Time: " + DateTime.Now.ToString() + "]\r\n";           }       }               public  void runCalpuff()       {           runCalmet();           calpuffExePath = exeDir + "\\calpuffl.exe";           if (!File.Exists(calpuffExePath))           {               MessageBox.Show("Warning:calpuffl.exe does not exist in current exe path");               return;           }           DateTime curDate = new DateTime();           string curDateStr = "";           DateTime startdateDtt = Convert.ToDateTime(startdate);           DateTime enddateDtt = Convert.ToDateTime(enddate);           TimeSpan span = enddateDtt.Subtract(startdateDtt);           int days = span.Days;           // 更新calpuffDaySpan            calpuffDaySpan=days+1;           // 每次对所有的污染物种类 最大值清零           // 一定要在processLstFile之前            for (int i = 0; i < 1000; i++)       // #MaxLimit#   // 在自己假定的最大值附近标注           {               maxLstValue[i] = 0;           }           // ftp目录创建  即使已经创建过  也会catch 不会引发程序中断           // 先创建好目录   然后上传           FtpWebRequest dirMakeRequest = (FtpWebRequest)FtpWebRequest.Create("ftp://" + ftpIp + "/" + identifier);           dirMakeRequest.Credentials = new NetworkCredential(ftpUser, ftpPasswd);           dirMakeRequest.Method = WebRequestMethods.Ftp.MakeDirectory;           try           {               FtpWebResponse ftpWebResponse = (FtpWebResponse)dirMakeRequest.GetResponse();               ftpWebResponse.Close();           }           catch (Exception e)           {               // MessageBox.Show("目录创建失败");               textBox2.Text += e.ToString();               textBox2.Text += "\r\n";           }           for (int i = 0; i <= days; i++)   // 注意是<=days           {               curDate = startdateDtt.AddDays(i);               curDateStr = dateStr(curDate);               calpuffInpMaking(curDateStr);   // 这里面有输出路径 inpMaking               // 把wrfout文件的检查放在run的里面吧~               ProcessStartInfo info = new ProcessStartInfo();               info.FileName = calpuffExePath;               info.Arguments = calpuffInpPath;    // modified in InpMaking               // 没个日期是不一样的..               info.WindowStyle = ProcessWindowStyle.Minimized;               Process p = new Process();               p.StartInfo = info;               p.Start();               pictureBox1.Visible = true;               textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[ForDate: " + curDate + "]-[Status: Calpuff-StartRunning]-[Time: " + DateTime.Now.ToString() + "]\r\n";                 while (true)               {                   if (p.HasExited)                   {                       pictureBox1.Visible = false;                       break;                   }               }               textBox2.Text += "[Id: " + id.ToString() + "]-[Identifier: " + identifier + "]-[Model: " + modelname + "]-[ForDate: " + curDate + "]-[Status: Calpuff-Done]-[Time: " + DateTime.Now.ToString() + "]\r\n";                                                      // 处理LstFile               //#processLstFile#               // taskId=identifier               // 修改  因为要把创建ftp目录放在外面  在这个代码之前就要创建好               processLstFile(outputDir + "\\" + identifier + "\\CALPUFF_" + curDateStr + ".LST", identifier, i); // 第i天的lst数据;           }          //  准备头文件                     // 暂时定位1000吧  后期再修改 或者写入ini文件           double latitude1 = 0, longitude1 = 0, latitude2 = 0, longitude2 = 0;           utm2LatLon(double.Parse(xrefkm)*1000, double.Parse(yrefkm)*1000, ref latitude1, ref longitude1);           utm2LatLon((double.Parse(xrefkm) + double.Parse(nx) * double.Parse(dgridkm))*1000, (double.Parse(yrefkm) + double.Parse(ny) * double.Parse(dgridkm))*1000, ref latitude2, ref longitude2);           headFile[0] = "*************This file is for separated files' information ****";           headFile[1] = "The min point (Longitude, Latitude):";           headFile[2] = longitude1.ToString()+" "+latitude1.ToString();           headFile[3] = "The max point (Longitude, Latitude):";           headFile[4] = longitude2.ToString() + " " + latitude2.ToString();           headFile[5] = "The cell number (X, Y), and resolution (X[m], Y[m]):";           headFile[6] = nx.ToString() + " " + ny.ToString() + " " + (double.Parse(dgridkm) * 1000).ToString();           headFile[7] = "The number of layer:";           headFile[8] = "1";           headFile[9] = "The start datetime:";           string startdateYear = startdateDtt.Year.ToString();           string enddateYear = enddateDtt.Year.ToString();            string startdateMonth = startdateDtt.Month.ToString();           string enddateMonth = enddateDtt.Month.ToString();           string startdateDay = startdateDtt.Day.ToString();           string enddateDay = enddateDtt.Day.ToString();           headFile[10] = "00_01_"+startdateDay+"_"+startdateMonth+"_"+startdateYear;           headFile[11] = "The end datetime:";           headFile[12] = "00_24_"+enddateDay+"_"+enddateMonth+"_"+enddateYear;           headFile[13] = "The time interval[s]:";           headFile[14] = "3600";                     headFile[15] = "The time layer:";           headFile[16] = (calpuffDaySpan * 24).ToString();           headFile[17] = "The value types:";           headFile[18] = cNum.ToString();           // processLstFile 都处理完毕了  最大值已经get()           for (int i = 0; i < cNum; i++)           {               headFile[18 + i * 3 + 1] = CSPECs[i];               headFile[18 + i * 3 + 2] = "Unit:ug/m3";               headFile[18 + i * 3 + 3] = "0" + " " + maxLstValue[i].ToString();           }           headFile[19 + 3 * cNum] = "The sigma height:";           headFile[20 + 3 * cNum] = "10";                     // 开始将头文件保存成txt           DirectoryInfo di = new DirectoryInfo(finalFormatDir + "\\" + identifier);           di.Create();           FileStream fs = new FileStream(finalFormatDir + "\\" + identifier + "\\" + "metadata.txt", FileMode.Create, FileAccess.ReadWrite);           StreamWriter sw = new StreamWriter(fs);           for (int i = 0; i <= 20 + 3 * cNum; i++)           {               sw.WriteLine(headFile[i]);           }           //----------------------------------new---------------------------------------------------           // string terrPath = "C:\\Users\\jingqiMB\\Desktop\\metadata_pre1.txt";           string terrPath = outputDir + "\\" + identifier+"\\terr.dat";           //  打开一个LST文件           if (!File.Exists(terrPath))           {               textBox2.Text+="[error]terr  File does not exist in current lst path."+"\r\n";                          }           // 定义最大行数  calpuff.inp 有1800 行  定成3000 比较合理           // 先获取最大行~           int lineCnt = 0;           FileStream terrFs = new FileStream(terrPath, FileMode.Open, FileAccess.Read);           StreamReader terrSr = new StreamReader(terrFs);           string tempStr = "";           while (tempStr != null)           {               tempStr = terrSr.ReadLine();               lineCnt++;           }           lineCnt--;  // 有一位位移           // 然后开辟一个空间存放 这个数组           //           string[] terrLine = new string[lineCnt + 100];           terrFs = new FileStream(terrPath, FileMode.Open, FileAccess.Read);           terrSr = new StreamReader(terrFs);           int index = 0;           tempStr = "";           while (tempStr != null)           {               tempStr = terrSr.ReadLine();               terrLine[index++] = tempStr;           }           index--; // 此时index就是行数                      terrSr.Close();           terrFs.Close();           // 现在lst数组里面就是所有数据           //  Debug            // -------------------------new program--------------------           int blockRelativeRow = 0;                      int blockRows = int.Parse(nx)/ 10;           if (int.Parse(nx) % 10 != 0) blockRows++;           int[] maxColumn = new int[blockRows + 100];           int startIndex = 0;           for (int i = 0; i < index; i++)           {               if (terrLine[i].Contains("W_E N_S"))               {                   startIndex = i;                   break;               }           }           startIndex++;           // MessageBox.Show(startIndex.ToString());           string[] terrDataLine = new string[index + 100]; // 开大一点不受影响           for (int i = startIndex; i < startIndex + int.Parse(ny) * blockRows; i++)           {               terrDataLine[i - startIndex] = terrLine[i];           }           string[, ,] blockData = new string[int.Parse(ny), blockRows, 10];           int blockCnt = 0;           for (int i = 0; i < int.Parse(ny) * blockRows; i++)   // 第i行           {               if (blockRelativeRow == blockRows - 1)               {                   maxColumn[blockRelativeRow] = int.Parse(nx) % 10;               }               else maxColumn[blockRelativeRow] = 10;               // 切换Block机制搭建好               string temp = terrDataLine[i];               string[] eachData = new string[100]; // 肯定用不到这么多               int tokenCnt = 0;               infoExtract(eachData, ref tokenCnt, temp);               //  突然发现辛苦获得的maxColumn 没有用了.,,在这个例子下               for (int j = 0; j < tokenCnt; j++)               {                   blockData[blockCnt, blockRelativeRow, j] = eachData[j];               }               // 一定要放在最后一行才行               if (blockRelativeRow == blockRows - 1)               {                   blockCnt++;               }               blockRelativeRow = (blockRelativeRow + 1) % blockRows;           }           double[] terrelDoubleData = new double[int.Parse(nx) * int.Parse(ny) + 100];           int terrelDoubleCnt = 0;           for (int block = int.Parse(ny) - 1; block >= 0; block--)               for (int i = 0; i < blockRows; i++)                   for (int j = 0; j < maxColumn[i]; j++)                   {                       double temp = double.Parse(blockData[block, i, j]);                       if (temp < 0) temp = 0;                       terrelDoubleData[terrelDoubleCnt++] = temp;                   }           //MessageBox.Show(terrelDoubleCnt.ToString());           // beginning            sw.WriteLine("The gridded elevation:");           for (int i = 0; i < terrelDoubleCnt; i++)               sw.WriteLine(terrelDoubleData[i].ToString()+" ,");  // 继续写入头文件              //------------------------------------------------------------------------           sw.Close();           fs.Close();          //#upload#          // 上传头文件           uploadWithFilePath(finalFormatDir + "\\" + identifier + "\\" + "metadata.txt", identifier);       }       //=====================================================================================================       // 把inp文件的创建分离出来  程序看起来简单一点       public static void terrelInpMaking()       {           string originalInpPath = inpDir + "\\terrel.inp";           if (!File.Exists(originalInpPath))           {               MessageBox.Show("Warning:terrel.inp does not exist in current inp path");               return;           }           // 定义最大行数  calpuff.inp 有1800 行  定成3000 比较合理           int maxLines = 3000;           string[] inpLines = new string[maxLines];           FileStream fs = new FileStream(originalInpPath, FileMode.Open, FileAccess.Read);           StreamReader sr = new StreamReader(fs);           string inpLine = sr.ReadLine();           int index = 0;           while (inpLine != null)           {               inpLines[index++] = inpLine;               inpLine = sr.ReadLine();           }           sr.Close();           fs.Close();           // 输出路径           string replace_line37 = " TERREL.DAT       output    ! OUTFIL = " + outputDir + "\\" + identifier.ToString() + "\\TERR.DAT !";           string replace_line38 = " TERREL.LST       output    ! LSTFIL = " + outputDir + "\\" + identifier.ToString() + "\\TERR.LST !";           string replace_line39 = " TERREL.GRD       output    ! PLTFIL = " + outputDir + "\\" + identifier.ToString() + "\\TERR.GRD !";           // 指定 E100N40.DEM            //string replace_line100 = " 1 !GTOPO30 = C:\\calpuff\\E100N40.DEM!     !END!";           string replace_line91 = " 1 !GTOPO30 =" + gtopo30 + "!     !END!";           string replace_line395 = " (XREFKM)                   No Default      ! XREFKM =" + xrefkm + " !";           string replace_line396 = " (YREFKM)                   No Default      ! YREFKM =" + yrefkm + " !";           string replace_line400 = " No. X grid cells (NX)      No default      ! NX = " + nx + " !";           string replace_line401 = " No. Y grid cells (NY)      No default      ! NY = " + ny + " !";           string replace_line402 = " Grid Spacing (km)(DGRIDKM) No default      ! DGRIDKM =  " + dgridkm + "!";           inpLines[37 - 1] = replace_line37;           inpLines[38 - 1] = replace_line38;           inpLines[39 - 1] = replace_line39;           inpLines[91 - 1] = replace_line91;           inpLines[395 - 1] = replace_line395;           inpLines[396 - 1] = replace_line396;           inpLines[400 - 1] = replace_line400;           inpLines[401 - 1] = replace_line401;           inpLines[402 - 1] = replace_line402;           // 开始创建文件之前  需要将输出目录创建好           string terrelInpDir = outputDir + "\\" + identifier.ToString();           System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(terrelInpDir);           di.Create();           terrelInpPath = outputDir + "\\" + identifier.ToString() + "\\terrel.inp";           //开始写文件 创建文件了           //System.IO.File.Create(newInpPath);           fs = new FileStream(terrelInpPath, FileMode.Create, FileAccess.ReadWrite);           StreamWriter sw = new StreamWriter(fs);           for (int i = 0; i < index; i++)           {               sw.WriteLine(inpLines[i]);           }           sw.Close();           fs.Close();       }       public static void ctgprocInpMaking()       {           string originalInpPath = inpDir + "\\ctgproc.inp";           if (!File.Exists(originalInpPath))           {               MessageBox.Show("Warning:ctgproc.inp does not exist in current inp path");               return;           }           // 定义最大行数  calpuff.inp 有1800 行  定成3000 比较合理           int maxLines = 3000;           string[] inpLines = new string[maxLines];           FileStream fs = new FileStream(originalInpPath, FileMode.Open, FileAccess.Read);           StreamReader sr = new StreamReader(fs);           string inpLine = sr.ReadLine();           int index = 0;           while (inpLine != null)           {               inpLines[index++] = inpLine;               inpLine = sr.ReadLine();           }           sr.Close();           fs.Close();           // 输出路径           string replace_line34 = "LU.DAT         output   ! LUDAT =" + outputDir + "\\" + identifier.ToString() + "\\LU.DAT !";           string replace_line35 = " CTGPROC.LST    output   ! RUNLST =" + outputDir + "\\" + identifier.ToString() + "\\CTGPROC.LST    !";           string replace_line77 = "1 !GLAZAS =" + glazas + "!     !END!";           string replace_line266 = " (XREFKM)                   No Default      ! XREFKM =" + xrefkm + " !";           string replace_line267 = " (YREFKM)                   No Default      ! YREFKM =" + yrefkm + " !";           string replace_line270 = " No. X grid cells (NX)      No default      ! NX = " + nx + " !";           string replace_line271 = " No. Y grid cells (NY)      No default      ! NY = " + ny + " !";           string replace_line272 = " Grid Spacing (km)(DGRIDKM) No default      ! DGRIDKM =  " + dgridkm + "!";           inpLines[34 - 1] = replace_line34;           inpLines[35 - 1] = replace_line35;           inpLines[77 - 1] = replace_line77;           inpLines[266 - 1] = replace_line266;           inpLines[267 - 1] = replace_line267;           inpLines[270 - 1] = replace_line270;           inpLines[271 - 1] = replace_line271;           inpLines[272 - 1] = replace_line272;           // 开始创建文件之前  需要将输出目录创建好           string newInpDir = outputDir + "\\" + identifier.ToString();           System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(newInpDir);           di.Create();           ctgprocInpPath = outputDir + "\\" + identifier + "\\ctgproc.inp";           //开始写文件 创建文件了           //System.IO.File.Create(newInpPath);           fs = new FileStream(ctgprocInpPath, FileMode.Create, FileAccess.ReadWrite);           StreamWriter sw = new StreamWriter(fs);           for (int i = 0; i < index; i++)           {               sw.WriteLine(inpLines[i]);           }           sw.Close();           fs.Close();       }       public static void makegeoInpMaking()       {           string originalInpPath = inpDir + "\\makegeo.inp";           if (!File.Exists(originalInpPath))           {               MessageBox.Show("Warning:makegeo.inp does not exist in current inp path");               return;           }           int maxLines = 3000;           string[] inpLines = new string[maxLines];           FileStream fs = new FileStream(originalInpPath, FileMode.Open, FileAccess.Read);           StreamReader sr = new StreamReader(fs);           string inpLine = sr.ReadLine();           int index = 0;           while (inpLine != null)           {               inpLines[index++] = inpLine;               inpLine = sr.ReadLine();           }           sr.Close();           fs.Close();           // 输出路径           string replace_line21 = "LU.DAT       input   ! LUDAT =" + outputDir + "\\" + identifier + "\\LU.DAT !";           string replace_line23 = "TERR.DAT     input    ! TERRDAT =" + outputDir + "\\" + identifier + "\\TERR.DAT!";           string replace_line24 = "GEO.DAT      output   ! GEODAT =" + outputDir + "\\" + identifier + "\\GEO.DAT!";           string replace_line25 = " MAKEGEO.LST  output   ! RUNLST = " + outputDir + "\\" + identifier + "\\MAKEGEO.LST!";           string replace_line26 = " QALUSE.GRD   output   ! LUGRD  = " + outputDir + "\\" + identifier + "\\QALUSE.GRD!";           string replace_line27 = " QATERR.GRD   output   ! TEGRD = " + outputDir + "\\" + identifier + "\\QATERR.GRD !";           string replace_line155 = " (XREFKM)                   No Default      ! XREFKM =" + xrefkm + " !";           string replace_line156 = " (YREFKM)                   No Default      ! YREFKM =" + yrefkm + " !";           string replace_line159 = " No. X grid cells (NX)      No default      ! NX = " + nx + " !";           string replace_line160 = " No. Y grid cells (NY)      No default      ! NY = " + ny + " !";           string replace_line161 = " Grid Spacing (km)(DGRIDKM) No default      ! DGRIDKM =  " + dgridkm + "!";           // 经典替换           inpLines[21 - 1] = replace_line21;           inpLines[23 - 1] = replace_line23;           inpLines[24 - 1] = replace_line24;           inpLines[25 - 1] = replace_line25;           inpLines[26 - 1] = replace_line26;           inpLines[27 - 1] = replace_line27;           inpLines[155 - 1] = replace_line155;           inpLines[156 - 1] = replace_line156;           inpLines[159 - 1] = replace_line159;           inpLines[160 - 1] = replace_line160;           inpLines[161 - 1] = replace_line161;           // 开始创建文件之前  需要将输出目录创建好           string newInpDir = outputDir + "\\" + identifier;           System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(newInpDir);           di.Create();           makegeoInpPath = outputDir + "\\" + identifier + "\\makegeo.inp";           //开始写文件 创建文件了           //System.IO.File.Create(newInpPath);          fs = new FileStream(makegeoInpPath, FileMode.Create, FileAccess.ReadWrite);           StreamWriter sw = new StreamWriter(fs);           for (int i = 0; i < index; i++)           {               sw.WriteLine(inpLines[i]);           }           sw.Close();           fs.Close();       }       public  void calwrfInpMaking(string curDate)       {           // 这个inp文件生成很easy                       string [] inpLines=new string[100];  // 100 is enough           inpLines[0]="Create cx3D.DAT file for WRF output";           inpLines[1]=outputDir+"\\"+identifier+"\\calwrf"+curDate+".lst";           inpLines[2]=outputDir+"\\"+identifier+"\\calwrf"+curDate+".m3d";           inpLines[3]="-1,-1,-1,-1,-1,-1    ! Beg/End I/J/K (\"-\" for all)";           inpLines[4]="-1                   ! Start date (UTC yyyymmddhh, \"-\" for all)";           inpLines[5]="-1                   ! End   date (UTC yyyymmddhh), \"-\" for all";           inpLines[6]="1                    ! Number of WRF output files ( 1 only now)";           inpLines[7]=wrfoutDir+"\\wrfout_d03_"+curDate;           if (!File.Exists(wrfoutDir + "\\wrfout_d03_" + curDate))           {               //MessageBox.Show("Warning:wrfout_d03_" + curDate + " does not exist");               textBox2.Text += "Warning:wrfout_d03_" + curDate + " does not exist\r\n";           }           string newInpDir = outputDir + "\\" + identifier;           System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(newInpDir);           di.Create();           calwrfInpPath = outputDir + "\\" + identifier + "\\calwrf"+curDate+".inp";           FileStream fs = new FileStream(calwrfInpPath, FileMode.Create, FileAccess.ReadWrite);           StreamWriter sw = new StreamWriter(fs);           for (int i = 0; i <8; i++)           {               sw.WriteLine(inpLines[i]);           }           sw.Close();           fs.Close();       }       public static void calmetInpMaking(string curDate)       {           string originalInpPath = inpDir + "\\calmet.inp";           if (!File.Exists(originalInpPath))           {               MessageBox.Show("Warning:calmet.inp does not exist in current inp path");               return;           }           // 定义最大行数  calpuff.inp 有1800 行  定成3000 比较合理           int maxLines = 3000;           string[] inpLines = new string[maxLines];           FileStream fs = new FileStream(originalInpPath, FileMode.Open, FileAccess.Read);           StreamReader sr = new StreamReader(fs);           string inpLine = sr.ReadLine();           int index = 0;           while (inpLine != null)           {               inpLines[index++] = inpLine;               inpLine = sr.ReadLine();           }           sr.Close();           fs.Close();           // 输出路径                   string replace_line19 = "GEO.DAT       input    ! GEODAT=" + outputDir + "\\" + identifier + "\\GEO.DAT!";           string replace_line25 = "CALMET.LST    output   ! METLST=" + outputDir + "\\" + identifier + "\\CALMET_" +curDate+ ".LST  !";           string replace_line26 = "CALMET.DAT    output   ! METDAT=" + outputDir + "\\" + identifier + "\\CALMET_" + curDate + ".DAT  !";           string replace_line73 = "WRF01.DAT       input     1  ! M3DDAT=" + outputDir + "\\" + identifier + "\\calwrf" + curDate + ".m3d !  !END!";           string replace_line93 = "DIAG.DAT      input      ! DIADAT="+ outputDir + "\\" + identifier + "\\calwrf" + curDate + ".m3d!";                       string replace_line121 = "Starting date:   Year (IBYR) -- No default       ! IBYR=" + curDate.Substring(0, 4) + "!";           string replace_line122 = "Month (IBMO) -- No default       ! IBMO= " + curDate.Substring(5, 2) + "!";           string replace_line123 = "Day (IBDY) -- No default       ! IBDY= " + curDate.Substring(8, 2) + "!";                         string replace_line268 = " No. X grid cells (NX)      No default      ! NX = " + nx + " !";           string replace_line269 = " No. Y grid cells (NY)      No default      ! NY = " + ny + " !";           string replace_line271 = " Grid spacing (DGRIDKM)            No default     ! DGRIDKM =  " + dgridkm + "!";           string replace_line277 = "X coordinate (XORIGKM)         No default     ! XORIGKM =" + xrefkm + " !";           string replace_line278 = "Y coordinate (YORIGKM)         No default     ! YORIGKM =" + yrefkm + " !";           inpLines[19 - 1] = replace_line19;           inpLines[25 - 1] = replace_line25;           inpLines[26 - 1] = replace_line26;           inpLines[73 - 1] = replace_line73;           inpLines[93 - 1] = replace_line93;           inpLines[121 - 1] = replace_line121;           inpLines[122 - 1] = replace_line122;           inpLines[123 - 1] = replace_line123;           inpLines[268 - 1] = replace_line268;           inpLines[269 - 1] = replace_line269;           inpLines[271 - 1] = replace_line271;           inpLines[277 - 1] = replace_line277;           inpLines[278 - 1] = replace_line278;           // 开始创建文件之前  需要将输出目录创建好           string newInpDir = outputDir + "\\" + identifier;           System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(newInpDir);           di.Create();           calmetInpPath = outputDir + "\\" + identifier + "\\calmet"+curDate+".inp";                               fs = new FileStream(calmetInpPath, FileMode.Create, FileAccess.ReadWrite);           StreamWriter sw = new StreamWriter(fs);           for (int i = 0; i < index; i++)           {               sw.WriteLine(inpLines[i]);           }           sw.Close();           fs.Close();       }       public  void calpuffInpMaking(string curDate)       {           string originalInpPath = inpDir + "\\calpuff.inp";           if (!File.Exists(originalInpPath))           {               MessageBox.Show("Warning:calpuff.inp does not exist in current inp path");               return;           }           // 定义最大行数  calpuff.inp 有1800 行  定成3000 比较合理           int maxLines = 3000;           string[] inpLines = new string[maxLines];           FileStream fs = new FileStream(originalInpPath, FileMode.Open, FileAccess.Read);           StreamReader sr = new StreamReader(fs);           string inpLine = sr.ReadLine();           int index = 0;           while (inpLine != null)           {               inpLines[index++] = inpLine;               inpLine = sr.ReadLine();           }           sr.Close();           fs.Close();           // 读完了原始文件先把srcFile 读出来           //先从数据库保存文件   using byte []           saveSrc(curDate);           // 然后 从文件中读出有效信息           readSrc(curDate);             //  改写了  NSPEC  NSE NPT2           //            // 分治   Part1           string replace_line16 ="CALMET.DAT    input    ! METDAT ="+outputDir + "\\" + identifier + "\\CALMET_" + curDate + ".DAT  !";           string replace_line26 = "CALPUFF.LST   output   ! PUFLST =" + outputDir + "\\" + identifier + "\\CALPUFF_"+curDate+".LST !";           string replace_line27 = "CONC.DAT      output   ! CONDAT =" + outputDir + "\\" + identifier + "\\CALPUFF_" + curDate + ".CON !";           //src file           string replace_line103 = "none input  ! PTDAT  ="+srcDir+"\\"+identifier+"\\"+"src"+curDate+".src"+"  ! ! END ! ";           string replace_line127 = "Default: 5       ! NSPEC =" + NSPEC+" !";           string replace_line130 = "to be emitted  (NSE)            Default: 3       ! NSE ="+NSE+" !";           //            string replace_line588 = " No. X grid cells (NX)      No default      ! NX = " + nx + " !";           string replace_line589 = " No. Y grid cells (NY)      No default      ! NY = " + ny + " !";           string replace_line592 = " Grid spacing (DGRIDKM)            No default     ! DGRIDKM =  " + dgridkm + "!";                              string replace_line604 = "X coordinate (XORIGKM)         No default     ! XORIGKM =" + xrefkm + " !";           string replace_line605 = "Y coordinate (YORIGKM)         No default     ! YORIGKM =" + yrefkm + " !";           string replace_line624 = "X index of UR corner (IECOMP)      No default     ! IECOMP =" + nx + "  !";           string replace_line627 = "Y index of UR corner (JECOMP)      No default     ! JECOMP =" + ny + "  !";           //            string replace_line652 = "X index of UR corner (IESAMP)      No default     ! IESAMP ="+nx+"  !";           string replace_line655 = "Y index of UR corner (JESAMP)      No default     ! JESAMP ="+ny+"  !";           // 和污染物有关的           string replace_line461 = "! CSPEC =" + CSPECs[0] + " ! !END!";           string replace_line471 = "! " + CSPECs[0] + "= 1,1,0,0 !";           string replace_line755 = "! " + CSPECs[0] + "= 1,1,0,1,0,0,0  !";           string replace_line1333 = " provided in external file      (NPT2)  No default  !  NPT2 =" + NPT2 + " !";           // 下面创建插入之前的文件           inpLines[16-1] = replace_line16;           inpLines[26-1] = replace_line26;           inpLines[27-1] = replace_line27;           inpLines[103-1] = replace_line103;           inpLines[127-1] = replace_line127;           inpLines[130-1] = replace_line130;           inpLines[588-1] = replace_line588;           inpLines[589-1] = replace_line589;           inpLines[592-1] = replace_line592;           inpLines[604-1] = replace_line604;           inpLines[605-1] = replace_line605;           inpLines[624-1] = replace_line624;           inpLines[627-1] = replace_line627;           inpLines[652-1] = replace_line652;           inpLines[655-1] = replace_line655;           inpLines[461-1] = replace_line461;           inpLines[471-1] = replace_line471;           inpLines[755-1] = replace_line755;           inpLines[1333-1] = replace_line1333;           int inpLength = index;                     if(cNum>1)   // 插入更多           {               string[] CSPECtoInsert1 = new string[cNum];               string[] CSPECtoInsert2 = new string[cNum];               string[] CSPECtoInsert3 = new string[cNum];               for(int i=0;i<cNum-1;i++)               {                   CSPECtoInsert1[i] = "! CSPEC =" + CSPECs[i + 1] + " ! !END!";    // 从下标为1开始取                   CSPECtoInsert2[i] = "! " + CSPECs[i+1] + "= 1,1,0,0 !";                   CSPECtoInsert3[i] = "! " + CSPECs[i+1] + "= 1,1,0,1,0,0,0  !";               }               // 开始插入               insertToLines(inpLines, inpLength, CSPECtoInsert1, cNum - 1, 461);                 inpLength += cNum - 1;               insertToLines(inpLines, inpLength, CSPECtoInsert2, cNum - 1, 471+cNum-1);                inpLength += cNum - 1;               insertToLines(inpLines, inpLength, CSPECtoInsert3, cNum - 1, 755 + 2*(cNum - 1));                 inpLength += cNum - 1;           }                      // 开始创建文件之前  需要将输出目录创建好                      string newInpDir = outputDir + "\\" + identifier.ToString();           System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(newInpDir);           di.Create();           calpuffInpPath = outputDir + "\\" + identifier.ToString() + "\\calpuff" + curDate + ".inp";           fs = new FileStream(calpuffInpPath, FileMode.Create, FileAccess.ReadWrite);           StreamWriter sw = new StreamWriter(fs);           for (int i = 0; i < inpLength; i++)           {               sw.WriteLine(inpLines[i]);           }           sw.Close();           fs.Close();       }                // Tasks Record       private void button11_Click(object sender, EventArgs e)       {           string recordDir = "C:\\calpuff\\records";           System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(recordDir);           di.Create();           string recordPath = "C:\\calpuff\\records\\" + "TaskRecords" + DateTime.Now.ToString("yyyy_MM_dd-hh_mm_ss") + ".txt";           FileStream fs = new FileStream(recordPath, FileMode.Create, FileAccess.ReadWrite);           StreamWriter sw = new StreamWriter(fs);           sw.WriteLine(taskRecords);           sw.Close();           fs.Close();           MessageBox.Show("Saved To " + recordPath);       }               public void saveLogs()       {           string logDir = "C:\\calpuff\\logs";           System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(logDir);           di.Create();           string logPath = "C:\\calpuff\\logs\\" + "log" + DateTime.Now.ToString("yyyy_MM_dd-hh_mm_ss") + ".txt";           FileStream fs = new FileStream(logPath, FileMode.Create, FileAccess.ReadWrite);           StreamWriter sw = new StreamWriter(fs);           sw.WriteLine(textBox2.Text);                      sw.Close();           fs.Close();         //  MessageBox.Show("Saved To " + logPath);       }       private void button10_Click(object sender, EventArgs e)       {           saveLogs();           string logDir = "C:\\calpuff\\logs";           MessageBox.Show("Saved To " + logDir);       }       // 日期转化       public static string dateStr(DateTime dtt)       {           string year = dtt.Year.ToString();           if (dtt.Year < 10)               year = "0" + year;           string month = dtt.Month.ToString();           if (dtt.Month < 10)               month = "0" + month;           string day = dtt.Day.ToString();           if (dtt.Day < 10)               day = "0" + day;           return year+"-"+ month+"-" +day;       }       private void button12_Click(object sender, EventArgs e)       {           FolderBrowserDialog folderBrowser = new FolderBrowserDialog();           folderBrowser.ShowDialog();           if (folderBrowser.SelectedPath != "")           {               srcDir = folderBrowser.SelectedPath;               label9.Text = srcDir;               // 存储到本地配置               saveIni();           }       }        // 保存srcFile 到本地        public static void saveSrc(string curDate)       {           MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection();           string connStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";           conn.ConnectionString = connStr;           try           {               conn.Open();  //src conn Open()            }           catch           {               MessageBox.Show("Database Connection Error");               return;           }           MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();           cmd.Connection = conn;           cmd.CommandText = "select srcfile from t_calpuf_conf where identifier=\""+identifier+"\"";           System.Data.Common.DbDataReader reader = cmd.ExecuteReader();           byte[] buffer = null;           if (reader.HasRows)           {                             reader.Read();               long len = reader.GetBytes(0, 0, null, 0, 0);//0是 因为只选出一个字段  第一个0                buffer = new byte[len];               // 字节数               len = reader.GetBytes(0, 0, buffer, 0, (int)len);               // 先得创建保存文件的目录               System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(srcDir + "\\" + identifier);               di.Create();               // 再保存               string savePath = srcDir + "\\"+identifier+"\\src" + curDate + ".src";               BinaryWriter bw = new BinaryWriter(File.Open(savePath, FileMode.OpenOrCreate));               bw.Write(buffer);               bw.Close();             }                      conn.Close();   // src conn Close()       }         public static string getFirstNum(string str)        {            int length = 0;             str = str.Trim();            for(int i=0;i<str.Length;i++)            {                   if(str[i]>'9'||str[i]<'0')                {                    length=i;                    break;                }            }            return str.Substring(0, length);        }        public static string getSecondNum(string str)        {            int startIndex = 0;            bool enter = false;            str = str.Trim();            for(int i=0;i<str.Length;i++)            {                   if(enter&&str[i]>='0'&&str[i]<='9')                {                    startIndex = i;                    break;                }                if(str[i]>'9'||str[i]<'0')                {                    enter = true;                }            }            return str.Substring(startIndex, str.Length - startIndex);        }        public  void splitStr(string str)        {            int cnt = 0;            str = str.Trim();            str=str+" ";  // 加一个空格 用来取出来最后一个字符            while(str!=" ")            {               for(int i=0;i<str.Length;i++)               {                   if(str[i]==' ')                   {                         string temp=str.Substring(0, i);                       if (temp.Length < 2)                       {                           textBox2.Text += "something wrong with src file \r\n";                           break;  // 首先保证污染源文件合法                        }                       CSPECs[cnt++] = temp.Substring(1,temp.Length-2);                       str = str.Substring(i);                       break;  // go to next finding ' ';                   }               }               str = str.Trim();               str = str + " ";            }            cNum = cnt;        }        // 全面解读srcFile        public static string NSPEC = "";        public static string NSE = "";    //  same as above         public static string NPT2 = "";   // src 文件决定        public static string CSPEC = "";        public static int maxCSPECs = 1000; // #MaxLimit#        public static string[] CSPECs = new string[maxCSPECs];        public static int cNum = 0;        public  void readSrc(string curDate)        {           //  srcFile 已经用 saveSrc() 保存到目录了~           string srcPath = srcDir + "\\" + identifier + "\\src" + curDate + ".src";                     //  这里可以改成日志信息            //  如果不存在  写一行到日志里           if (!File.Exists(srcPath))           {              //  MessageBox.Show("Warning:src file  is missing ");               textBox2.Text += "Warning:src" + curDate + ".src file  is missing \r\n";               return;           }                                  // 定义最大行数   假设src 最多10000 行           int srcMaxLines = 10000;           string[] srcLines = new string[srcMaxLines];           FileStream fs = new FileStream(srcPath, FileMode.Open, FileAccess.Read);           StreamReader sr = new StreamReader(fs);           string inpLine = sr.ReadLine();           int index = 0;           while (inpLine != null)           {               srcLines[index++] = inpLine;               inpLine = sr.ReadLine();           }           sr.Close();           fs.Close();                      NSPEC = getSecondNum(srcLines[9]);           NSE = NSPEC;           NPT2 = getFirstNum(srcLines[9]);           CSPEC = srcLines[10];           splitStr(CSPEC);           //  数组就位置                   }        // Delete Identifier         private void button13_Click(object sender, EventArgs e)        {                        string identifierToDelete = textBox3.Text;            if(identifierToDelete=="")            {                MessageBox.Show("No Identifier is Specified");                return;            }            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection();            string connStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";            conn.ConnectionString = connStr;            try            {                 conn.Open();  // delete identifier conn Open()            }              catch            {                MessageBox.Show("Database Connection Error");                return;            }            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();            cmd.Connection = conn;            // 关联新的cmd conn需要重启            cmd.CommandText = "delete from t_calpuf_conf where identifier=" + "\"" + identifierToDelete + "\"";            // 已经确认过可以连接了            cmd.ExecuteNonQuery();                        conn.Close();   // delete identifier conn Close()            textBox3.Text = "";            MessageBox.Show("If "+identifierToDelete+" Exists ,Delete  Successful");                      // 重新loadTasks            this.loadTasks();                    }        // 要求lines 申请空间本身足够长        public static void insertToLines(string[] lines, int length, string[] toInsert,int insertLength, int fromIndex)        {                 string [] newLines =new string [length+insertLength+100]; // +100 保险             for (int i = 0; i < length + insertLength; i++)             {                 if (i < fromIndex)  newLines[i]=lines[i];                 else  if(i>=fromIndex&&i<fromIndex+insertLength)                 {                     newLines[i] = toInsert[i - fromIndex];                 }                 else  // i>                 {                     newLines[i] = lines[i - insertLength];                 }             }                          // 然后再还给lines             for(int i=0;i<length+insertLength;i++)            {                lines[i] = newLines[i];            }        }        public  void loadTasks()        {            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection();            string connStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";            conn.ConnectionString = connStr;            try            {                conn.Open(); // load Tasks             }            catch            {                MessageBox.Show("Database Connection Error");                return;            }            textBox1.Text = "";            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();            cmd.Connection = conn;            cmd.CommandText = "select id,modelname,identifier from t_calpuf_conf where done=0";            System.Data.Common.DbDataReader reader = cmd.ExecuteReader();            if (!reader.HasRows)            {                MessageBox.Show("No Tasks To Be Dealt With");                return;            }            taskRecords = "";                        // 每个task            while (reader.Read())            {                int id = reader.GetInt32(reader.GetOrdinal("id"));                // 生成inp 文件                string modelname = reader.GetString(reader.GetOrdinal("modelname"));                string identifier = reader.GetString(reader.GetOrdinal("identifier"));                // 更新tasks 列表                taskRecords += "[Id: " + id + "]  [Model: " + modelname + "]  [Identifier:" + identifier + "]\r\n";                textBox1.AppendText("[Id: " + id + "]  [Model: " + modelname + "]  [Identifier:" + identifier + "]\r\n");                             }           conn.Close(); // load conn Close                    }        // clear logs        private void button14_Click(object sender, EventArgs e)        {                        textBox2.Text = "";        }        // 用于数据拆分        public static void infoExtract(string [] param,ref int tokenNum,string str)        {            str = str.Trim();            str += " ";            int cnt=0;            while(str!=" ")            {                for (int i = 0; i < str.Length; i++)                {                    if(str[i]==' ')                    {                        param[cnt++] = str.Substring(0, i);                        str = str.Substring(i, str.Length - i);                        str = str.Trim();                        str += " "; // 为了最后一次推出循环                        break;   //  这个break 很关键  因为找到了就应该进入下一次循环了                    }                }            }            tokenNum = cnt;        }              // 处理一个lst文件        //  处理某个lst文件 ,上传到对应的Identifier 目录  并且区分是第几天的(24*i+curHr)        public  void processLstFile(string lstPath,string taskId,int day)        {            if (!File.Exists(lstPath))            {                textBox2.Text += "Lst File does not exist in "+lstPath+"\r\n";                return;            }            //  indicator            pictureBox1.Visible = true;            // 先获取最大行~            int lineCnt = 0;            FileStream fs = new FileStream(lstPath, FileMode.Open, FileAccess.Read);            StreamReader sr = new StreamReader(fs);            string tempStr = "";            while (tempStr != null)            {                tempStr = sr.ReadLine();                lineCnt++;            }            lineCnt--;  // 有一位位移            // 然后开辟一个空间存放 这个数组            string[] lst = new string[lineCnt + 100];            fs = new FileStream(lstPath, FileMode.Open, FileAccess.Read);            sr = new StreamReader(fs);            int index = 0;            tempStr = "";            while (tempStr != null)            {                tempStr = sr.ReadLine();                lst[index++] = tempStr;            }            index--; // 此时index就是行数            sr.Close();            fs.Close();            // 现在lst数组里面就是所有数据            //  Debug             // MessageBox.Show(index.ToString());  行数            int[] splitIndex = new int[index]; // 肯定不需要这么多  但是没关系            int splitIndexCnt = 0;            for (int i = 0; i < index; i++)            {                if (lst[i].Contains("CONCENTRATIONS (ug/m**3)"))                {                    splitIndex[splitIndexCnt++] = i;                }            }            // 现在有splitIndexCnt 这么多块~            // +100 内存保护            // 取出分割str  并且提取信息            string[] splictStr = new string[splitIndexCnt + 100];            string[] species = new string[splitIndexCnt + 100];  // 拆分以后的第三个            int[] hr = new int[splitIndexCnt + 100];            int[] exp = new int[splitIndexCnt + 100];            string[] columnStr = new string[splitIndexCnt + 100];                       int nx = 199;            int ny = 197;            int parts = nx / 20;       // 一种污染物的一个时间段被分成多少段  循环节            if (nx % 20 != 0) parts++;            int speciesNum = splitIndexCnt / 24 / parts;            string[] allSpeciesName = new string[speciesNum]; // 所有污染物种类名   这个应该            // 求指数            for (int i = 0; i < splitIndexCnt; i++)            {                splictStr[i] = lst[splitIndex[i]];                columnStr[i] = lst[splitIndex[i] + 5 + 2 * ny - 2 + 3];                string temp = lst[splitIndex[i] + 3];                string[] para = new string[100]; // 6 就足够了                int cnt = 0;                infoExtract(para, ref cnt, temp);                exp[i] = int.Parse(para[6]);     // 取出指数            }            // 480 个分隔符 and know why it is 480  24*10*2            // MessageBox.Show(splitIndexCnt.ToString());            //  获取hr 还有种类            for (int i = 0; i < splitIndexCnt; i++)            {                // 100 绝对足够不会数组越界                string[] param = new string[100];                int paramCnt = 0;                infoExtract(param, ref paramCnt, splictStr[i]);                species[i] = param[3];                hr[i] = int.Parse(param[14]);  // 第15个信息就是小时            }            // 获取 i  k 对应的 real column            // 还是先取出纯data吧  感觉这样比较方便后面的处理            double[, ,] data = new double[splitIndexCnt, ny, 20];   // 列只会访问到这里            int[,] column = new int[splitIndexCnt, 20];            //  先把columnStr信息拆解             // columnStr 到底有多少列  有时候是没有20列的            int iCnt = 0;  //  处于第几个块中            int columnMax = 0;            // 时间复杂度分析: index*20 左右   这次是380w            int speciesTempCnt = 0; // 用来统计allSpeceis的            double[, , ,] sourceData = new double[24, speciesNum, ny, nx];  // enough to hold all the data            for (int i = 0; i < splitIndexCnt; i++)   // 第i块儿            {                int beginIndex = splitIndex[i] + 5;  // 第i个数据块从+5行这里开始                if (iCnt == parts - 1) columnMax = nx % 20;  //  采用余数控制来判断到底是不是到了最后                else columnMax = 20;                if (iCnt == 0)                {                    //  这个是换污染物的标志  也同时是maxColomn应该取多少的判断方法                    allSpeciesName[(speciesTempCnt++) % speciesNum] = species[i];   // 虽然反复修改 但是无所谓 不会错误                }                iCnt = (iCnt + 1) % parts;  //  这行代码在columnMax之后                // 获取第i块,第k列的实际列数                string[] param = new string[100]; // 其实20就够了                int paramCnt = 0;                infoExtract(param, ref paramCnt, columnStr[i]);                for (int k = 0; k < columnMax; k++)                {                    column[i, k] = int.Parse(param[k]);                    //MessageBox.Show(column[i, k].ToString());                }                int curExp = exp[i];  // 这一块的指数                // 开始获取每一个data[i,j,k];                for (int j = 0; j < ny; j++)                {                    // 取出这个 string 进行转化                    string info20 = lst[beginIndex + 2 * ny - 2 - 2 * j];  // tested  真正的数据源                    //  MessageBox.Show(info20);                    // MessageBox.Show((beginIndex+2 * ny - 2 - 2 * j).ToString());    // 注意notepad++的行号                    string[] eachData = new string[100]; // 22  就足够了                     int eachDataCnt = 0;                    infoExtract(eachData, ref eachDataCnt, info20);                    // MessageBox.Show(eachData[21]);                    for (int k = 0; k < columnMax; k++)                    {                        // MessageBox.Show(eachData[k]+" "+k.ToString());                        data[i, j, k] = double.Parse(eachData[k + 2]) * Math.Pow(10, curExp);  // 至于为什么是k+2                         // 开始写入核心数据sourceData[h,s,i,j] 了                        // 注意column[i, k] 是写在notepad++ 里的列数  -1  才是对应的数组编号                         sourceData[hr[i], (speciesTempCnt - 1 + speciesNum) % speciesNum, j, column[i, k] - 1] = data[i, j, k];     //  第一次这样使用  因为speciesTempCnt-1的值恰好就是++之前的值                    }                }            }            //  MessageBox.Show(data[390,59-1,7-1].ToString());   //测试完毕  Pow(10,exp) 也测试完毕            // 好了 现在data[i,j,k] 都储备好了  更方便的是还把倒序纠正了过来            // 好了 现在column[i,k] 的信息也储备好了            // 好了 开始往txt里面写数据了            // finalFormatDir = "c:\\calpuff\\finalFormat\\"+taskId;  // 本地生成路径  不应修改 //#ini#            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(finalFormatDir + "\\" + taskId);            di.Create();    // 已经创建过 不会出现问题            for (int h = 0; h < 24; h++)  // 小时            {                for (int s = 0; s < speciesNum; s++)   // 污染物种类                {                    //  这层循环将对应一个独立文件                    string curSpeciesName = allSpeciesName[s];                    string curHr = (h + 1+day*24).ToString();  // 考虑到了第几天 所以会出现CO_36.txt                    string finalFormatPath = finalFormatDir + "\\" + taskId + "\\" + curSpeciesName + "_" + curHr + ".txt";                    FileStream finalFormatFs = new FileStream(finalFormatPath, FileMode.Create, FileAccess.ReadWrite);                    StreamWriter finalFormatSW = new StreamWriter(finalFormatFs);                    //  finalFormatSW.WriteLine("{");                    finalFormatSW.WriteLine("Timestep " + curHr);                    finalFormatSW.WriteLine("CurLayer1");                    for (int i = 0; i < ny; i++)                        for (int j = 0; j < nx; j++)                        {                            // 取出当前taskId任务最大值                            maxLstValue[s] = Math.Max(maxLstValue[s], sourceData[h, s, i, j]);                            finalFormatSW.WriteLine(sourceData[h, s, i, j].ToString() + " ,");                        }                    // finalFormatSW.WriteLine("}");                    finalFormatSW.Close();                    finalFormatFs.Close();                                                          // 数据上传                      //  针对一个taskId 的  一天的  一个时间点 一个污染物 具体的txt                      this.uploadWithFilePath(finalFormatPath,taskId);                  }            }            pictureBox1.Visible = false;        }  // end of processLstFile        // 知道文件名 and taskid   上传到指定目录上去        // 更新的时候加上等待动画         public  void uploadWithFilePath(string filePath,string taskId)        {            pictureBox1.Visible = true;            FileInfo fileInfo = new FileInfo(filePath);            string uri = "ftp://" + ftpIp + "/"+taskId+"/" + fileInfo.Name;      //  fileInfo.Name 仅仅是这个文件名 好东西啊            //  Connecting Fhase            FtpWebRequest ftpWebRequest;            // 根据uri创建FtpWebRequest对象            ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));            // 指定数据传输类型            ftpWebRequest.UseBinary = true;            // ftp用户名和密码            ftpWebRequest.Credentials = new NetworkCredential(ftpUser, ftpPasswd);            // 默认为true,连接不会被关闭            // 在一个命令之后被执行            ftpWebRequest.KeepAlive = false;            ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;            // 上传文件时通知服务器文件的大小            ftpWebRequest.ContentLength = fileInfo.Length;            // 缓冲大小设置为kb            int buffLength = 2048;            byte[] buff = new byte[buffLength];            int contentLen;            // 打开一个文件流(System.IO.FileStream) 去读上传的文件            FileStream fs = fileInfo.OpenRead();            try            {                // 把上传的文件写入流                 Stream ftpUploadStream = ftpWebRequest.GetRequestStream();  // 流就是通道                // 每次读文件流的kb                contentLen = fs.Read(buff, 0, buffLength);   // 然后文件的二进制流就在buff数组中                // 返回0 表示读完了                // 流内容没有结束                while (contentLen != 0)                {                    // 把内容从file stream 写入upload stream                    ftpUploadStream.Write(buff, 0, contentLen);                    contentLen = fs.Read(buff, 0, buffLength);  // Read 文件会记住上次读的进度,从上次结束的地方开始                }                ftpUploadStream.Close();                fs.Close();            }            catch (Exception e)            {                // 记录在日志里                textBox2.Text += e.ToString();                textBox2.Text += "\r\n";            }            pictureBox1.Visible = false;        }  // end of upload        public static void utm2LatLon(double utmX, double utmY, ref double latitude,ref double longitude)        {                       string utmZone="49N";            bool isNorthHemisphere = utmZone.Last() >= 'N';         //   var diflat = -0.00066286966871111111111111111111111111;         //   var diflon = -0.0003868060578;            var zone = int.Parse(utmZone.Remove(utmZone.Length - 1));            var c_sa = 6378137.000000;            var c_sb = 6356752.314245;            var e2 = Math.Pow((Math.Pow(c_sa, 2) - Math.Pow(c_sb, 2)), 0.5) / c_sb;            var e2cuadrada = Math.Pow(e2, 2);            var c = Math.Pow(c_sa, 2) / c_sb;            var x = utmX - 500000;            var y = isNorthHemisphere ? utmY : utmY - 10000000;            var s = ((zone * 6.0) - 183.0);            var lat = y / (6366197.724 * 0.9996); // Change c_sa for 6366197.724            var v = (c / Math.Pow(1 + (e2cuadrada * Math.Pow(Math.Cos(lat), 2)), 0.5)) * 0.9996;            var a = x / v;            var a1 = Math.Sin(2 * lat);            var a2 = a1 * Math.Pow((Math.Cos(lat)), 2);            var j2 = lat + (a1 / 2.0);            var j4 = ((3 * j2) + a2) / 4.0;            var j6 = (5 * j4 + a2 * Math.Pow((Math.Cos(lat)), 2)) / 3.0; // saque a2 de multiplicar por el coseno de lat y elevar al cuadrado            var alfa = (3.0 / 4.0) * e2cuadrada;            var beta = (5.0 / 3.0) * Math.Pow(alfa, 2);            var gama = (35.0 / 27.0) * Math.Pow(alfa, 3);            var bm = 0.9996 * c * (lat - alfa * j2 + beta * j4 - gama * j6);            var b = (y - bm) / v;            var epsi = ((e2cuadrada * Math.Pow(a, 2)) / 2.0) * Math.Pow((Math.Cos(lat)), 2);            var eps = a * (1 - (epsi / 3.0));            var nab = (b * (1 - epsi)) + lat;            var senoheps = (Math.Exp(eps) - Math.Exp(-eps)) / 2.0;            var delt = Math.Atan(senoheps / (Math.Cos(nab)));            var tao = Math.Atan(Math.Cos(delt) * Math.Tan(nab));            longitude = (delt / Math.PI) * 180 + s;            latitude = (((lat + (1 + e2cuadrada * Math.Pow(Math.Cos(lat), 2) - (3.0 / 2.0) * e2cuadrada * Math.Sin(lat) * Math.Cos(lat) * (tao - lat)) * (tao - lat))) / Math.PI) * 180; // era incorrecto el calculo                    }        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)        {            System.Diagnostics.Process.Start("http://calpuff.sinaapp.com");            }               public  void loadAndRun()        {            Thread.Sleep(1000);  // 减小资源浪费            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection();            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();            // 到时候换成一个公网IP              string connStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";            conn.ConnectionString = connStr;            try            {                conn.Open(); //Load And Run conn Open()                           }            catch            {                MessageBox.Show("Database Connection Error");  // 应该不会有问题 已经测试过                              return;            }            cmd.Connection = conn;            cmd.CommandText = "select id,modelname,startdate,enddate,xrefkm,yrefkm,nx,ny,dgridkm,gtopo30,glazas,identifier,srcfile from t_calpuf_conf where done = 0"; // 只取一条记录            System.Data.Common.DbDataReader reader = cmd.ExecuteReader();            if (!reader.HasRows)            {                 return;            }            // 一个个的取出应用            else  // HasRows            {     // 有真实的任务                    reader.Read();  // 只读了一次                                  id = reader.GetInt32(reader.GetOrdinal("id"));                    identifier = reader.GetString(reader.GetOrdinal("identifier"));                    modelname = reader.GetString(reader.GetOrdinal("modelname"));                    if (modelname == "terrel")                    {                        // 需要再从数据库取出来                        nx = reader.GetString(reader.GetOrdinal("nx"));                        ny = reader.GetString(reader.GetOrdinal("ny"));                        xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                        yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                        dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                        gtopo30 = reader.GetString(reader.GetOrdinal("gtopo30"));                        runTerrel();                                   } // end of  if (modelname == "terrel")                    else if (modelname == "ctgproc")                    {                        nx = reader.GetString(reader.GetOrdinal("nx"));                        ny = reader.GetString(reader.GetOrdinal("ny"));                        xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                        yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                        dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                        glazas = reader.GetString(reader.GetOrdinal("glazas"));                        runCtgproc();                    } // end of  else if (modelname == "ctgproc")                    else if (modelname == "makegeo")                    {                        nx = reader.GetString(reader.GetOrdinal("nx"));                        ny = reader.GetString(reader.GetOrdinal("ny"));                        xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                        yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                        dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                        gtopo30 = reader.GetString(reader.GetOrdinal("gtopo30"));                        glazas = reader.GetString(reader.GetOrdinal("glazas"));                        //runTerrel();                        //runCtgproc();                        runMakegeo();                    } // end of  else if (modelname == "makegeo")                    else if (modelname == "calwrf")                    {                        startdate = reader.GetString(reader.GetOrdinal("startdate"));                        enddate = reader.GetString(reader.GetOrdinal("enddate"));                        runCalwrf();                    } // end of  else if (modelname == "calwrf")                    else if (modelname == "calmet")                    {                        nx = reader.GetString(reader.GetOrdinal("nx"));                        ny = reader.GetString(reader.GetOrdinal("ny"));                        xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                        yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                        dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                        startdate = reader.GetString(reader.GetOrdinal("startdate"));                        enddate = reader.GetString(reader.GetOrdinal("enddate"));                        gtopo30 = reader.GetString(reader.GetOrdinal("gtopo30"));                        glazas = reader.GetString(reader.GetOrdinal("glazas"));                        runCalmet();                    } //  else if (modelname == "calmet")                    else if (modelname == "calpuff")                    {                        nx = reader.GetString(reader.GetOrdinal("nx"));                        ny = reader.GetString(reader.GetOrdinal("ny"));                        xrefkm = reader.GetString(reader.GetOrdinal("xrefkm"));                        yrefkm = reader.GetString(reader.GetOrdinal("yrefkm"));                        dgridkm = reader.GetString(reader.GetOrdinal("dgridkm"));                        startdate = reader.GetString(reader.GetOrdinal("startdate"));                        enddate = reader.GetString(reader.GetOrdinal("enddate"));                        gtopo30 = reader.GetString(reader.GetOrdinal("gtopo30"));                        glazas = reader.GetString(reader.GetOrdinal("glazas"));                        runCalpuff();                    } // else if (modelname == "calpuff")                    updateDone();                 // 任务执行完毕 保存日志                    saveLogs();            } // end of  else HasRows            // hasRows over            conn.Close();    //也许一直差的就是这行代码        }  //  end of the fun               //  Start Listening And Processing        private void button15_Click(object sender, EventArgs e)        {            // 全自动监听            updateFlag();  // flag=1            bool inListening = true;             label13.Text = "Runing";            MessageBox.Show("Start Listening Successful");            while (inListening)            {                             // ---------------------------------------run  program-------------------------------------                loadAndRun();                //----------------------------------------end run program----------------------------------                // 如果正在run的过程中被叫停  不会受影响 但后面的不会 run  也就是等当前运行的run完~                int flag = getListenStatus();  // 尽量封装在函数里                if (flag == 0)  // 被叫停了                {                    inListening = false;                    label13.Text = "Stopped";                }            } // end of while(inListening)        }  //  end of click function              public static void updateFlag()        {            MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection();            string connStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";            conn.ConnectionString = connStr;            conn.Open();  //updateFlag  conn Open()            MySql.Data.MySqlClient.MySqlCommand cmd = new MySql.Data.MySqlClient.MySqlCommand();            cmd.Connection = conn;            // 关联新的cmd conn需要重启            cmd.CommandText = "update t_calpuf_listen set flag=1"; // 这个id 一定取不到            // 已经确认过可以连接了            cmd.ExecuteNonQuery();             conn.Close();   //update Flag conn Close        }              public static int getListenStatus()       {           MySql.Data.MySqlClient.MySqlConnection checkConn = new MySql.Data.MySqlClient.MySqlConnection();           string checkConnStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";           checkConn.ConnectionString = checkConnStr;           try           {               checkConn.Open(); // checkConn Open           }           catch           {               //MessageBox.Show("Database Connection Error");  // 应该不会有问题 已经测试过               return 1;  // //统一不破坏           }           MySql.Data.MySqlClient.MySqlCommand checkCmd = new MySql.Data.MySqlClient.MySqlCommand();           checkCmd.Connection = checkConn;           checkCmd.CommandText = "select flag from t_calpuf_listen "; // 只取一条记录           System.Data.Common.DbDataReader checkReader = checkCmd.ExecuteReader();           if(!checkReader.HasRows)           {               return 1;  //统一不破坏            }           checkReader.Read();// 只会有一行数据           int flag = checkReader.GetInt32(checkReader.GetOrdinal("flag"));           checkConn.Close();   //// checkConn Close()           return flag;       }        public static void updateDone()  // make done =1       {           MySql.Data.MySqlClient.MySqlConnection updateConn = new MySql.Data.MySqlClient.MySqlConnection();           // 到时候换成一个公网IP             string updateConnStr = "server=" + Form1.dbIp + ";user id=" + Form1.dbUser + ";password=" + Form1.dbPasswd + ";database=" + Form1.dbName + ";pooling=false;charset=utf8";           updateConn.ConnectionString = updateConnStr;           updateConn.Open();   // upDateDone conn Open()           MySql.Data.MySqlClient.MySqlCommand updateCmd = new MySql.Data.MySqlClient.MySqlCommand();           updateCmd.Connection = updateConn;           updateCmd.CommandText = "update t_calpuf_conf set done=1 where identifier=" + "\"" + identifier + "\"";           updateCmd.ExecuteNonQuery();           updateConn.Close();  // upDateDone conn CLose();                         }       private void label14_Click(object sender, EventArgs e)       {       }    }  //  Class -Form1}  // namespace 

0 0
原创粉丝点击