Browse Source

Merge repos.ubtob.net:usoft/mes-client

callm 1 week ago
parent
commit
43f3a9b326

+ 110 - 47
UAS_MES_YTDZ/FunctionCode/Make/Make_FirstInspect.cs

@@ -44,7 +44,7 @@ namespace UAS_MES_NEW.Make
         {
             dh = SystemInf.dh;
 
-            fileList.Add("E:\\4_奥维精密\\首件检测仪");
+            fileList.Add("D:\\FAIReport");
             txtPath.Text = fileList[0];
 
             currFileType = "txt";
@@ -286,8 +286,13 @@ namespace UAS_MES_NEW.Make
                 }
 
                 string isCheck = dh.getFieldDataByCondition("make", "nvl(ma_firstitemcheck, 0)", $"ma_code = '{workOrder}'").ToString();
-                string sr_code = dh.getFieldDataByCondition("spotcheckrecord", "sr_code",$"sr_type = '首件检验' AND sr_linecode = '{line}' AND sr_makecode = '{workOrder}'").ToString();
+                if (string.IsNullOrEmpty(isCheck))
+                {
+                    LogMessage(0, $"NG,工单号:{workOrder}不存在,请检查报告中{currFileType}文件");
+                    return;
+                }
 
+                string sr_code = dh.getFieldDataByCondition("spotcheckrecord", "sr_code",$"sr_type = '首件检验' AND sr_linecode = '{line}' AND sr_makecode = '{workOrder}'").ToString();
                 if (string.IsNullOrEmpty(sr_code))
                 {
                     if (generateRadio.Checked && isCheck == "-1")
@@ -319,54 +324,39 @@ namespace UAS_MES_NEW.Make
                 }
                 string sr_id = dh.getFieldDataByCondition("spotcheckrecord", "sr_id", $"sr_makecode = '{workOrder}' and sr_linecode = '{line}' and sr_type='首件检验'").ToString();
 
-                string cookie = "JSESSIONID=9A2D8BD2156087D2BB96CC2F6B6230D7; ";
 
-                string uploadFileApi = "http://192.168.41.232:8098/mes//common/uploadFiles.action";
-                var uploadFileParams = new Dictionary<string, string>
+                string uploadFileApi = "http://192.168.41.232:8098/mes/MEScommon/uploadFiles.action?_noc=1";
+                Dictionary<string, object> uploadFileParams = new Dictionary<string, object>()
                 {
-                    { "em_code", $"{User.UserCode}" },
-                    { "caller", "checkFirst" }
+                    {"em_name", "管理员" },
+                    {"em_code", "ADMIN" },
+                    {"caller", "FirstInspect" }
                 };
-                string uploadFileRes = await HttpHelper.PostMultipartWithFileAsync(uploadFileApi, uploadFileParams, itemFileList[1], cookie);
-                //LogMessage(1, $"{uploadFileRes}");
-
-                JObject root = JObject.Parse(uploadFileRes);
-                if (root["success"]?.ToString() == "True")
+                string fp_id = await HttpHelper.UploadFilesToRemoteUrl(uploadFileApi, itemFileList[1], uploadFileParams);
+                if (!string.IsNullOrEmpty(fp_id))
                 {
                     LogMessage(1, $"文件上传成功{itemFileList[1].Replace(txtPath.Text, "")}");
 
-                    JArray dataArr = (JArray)root["data"];
-                    foreach (JToken item in dataArr)
-                    {
-                        dh.ExecuteSql($@"UPDATE spotcheckrecord SET sr_prodtype = '{item["filepath"].ToString()};' WHERE sr_id = '{sr_id}'", "update");
-                        LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功");
-                    }
+                    dh.ExecuteSql($@"UPDATE spotcheckrecord SET sr_prodtype = '{fp_id};' WHERE sr_id = '{sr_id}'", "update");
+                    LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功");
 
+                    using (StreamReader SR = new StreamReader(itemFileList[0], Encoding.GetEncoding("GBK")))
+                    {
+                        string Content = SR.ReadToEnd();
+                        SR.Close();
+                        SR.Dispose();
 
-                    #region
-                    /*JArray dataArr = (JArray)root["data"];
-                    string updateApi = "http://192.168.41.232:8098/mes/common/attach/update.action";
+                        ConsoleLog(Content, itemFileList[0], $"C{workOrder.ToUpper()}");
+                    }
 
-                    foreach (JToken item in dataArr)
+                    using (StreamReader SR = new StreamReader(itemFileList[1], Encoding.GetEncoding("GBK")))
                     {
-                        var Params = new Dictionary<string, string>
-                        {
-                            { "caller", "checkFirst" },
-                            { "table", "SPOTCHECKRECORD" },
-                            { "update", $"sr_prodtype='{item["filepath"].ToString()};'" },
-                            { "condition", $"sr_id='{sr_id}'" },
-                            { "type", "添加附件" }
-                        };
-                        string updateRes = await HttpHelper.PostMultipartAsync(uploadFileApi, Params, cookie);
-                        LogMessage(1, $"{updateRes}");
-
-                        JObject root1 = JObject.Parse(updateRes);
-                        if (root["success"]?.ToString() == "True")
-                        {
-                            LogMessage(1, $"首件检验单:C{workOrder.ToUpper()} ,附件上传成功");
-                        }
-                    }*/
-                    #endregion
+                        string Content = SR.ReadToEnd();
+                        SR.Close();
+                        SR.Dispose();
+
+                        ConsoleLog(Content, itemFileList[1], $"C{workOrder.ToUpper()}");
+                    }
                 }
 
             }
@@ -378,6 +368,75 @@ namespace UAS_MES_NEW.Make
 
         public class HttpHelper
         {
+            public static async Task<string> UploadFilesToRemoteUrl(string url1, string filepath, Dictionary<string, object> dic)
+            {
+                try
+                {
+                    ServicePointManager.DefaultConnectionLimit = 50;
+                    string boundary = DateTime.Now.Ticks.ToString("x");
+                    byte[] boundarybytes = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "\r\n");
+                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url1);
+                    request.Method = "POST";
+                    request.Timeout = 10 * 10000;
+                    request.ContentType = "multipart/form-data; boundary=" + boundary;
+                    Stream rs = request.GetRequestStream();
+                    var endBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "--\r\n");
+                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n" + "\r\n" + "{1}" + "\r\n";
+                    if (dic != null)
+                    {
+                        foreach (string key in dic.Keys)
+                        {
+                            rs.Write(boundarybytes, 0, boundarybytes.Length);
+                            string formitem = string.Format(formdataTemplate, key, dic[key]);
+                            byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
+                            rs.Write(formitembytes, 0, formitembytes.Length);
+                        }
+                    }
+
+                    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n\r\n";
+                    {
+                        rs.Write(boundarybytes, 0, boundarybytes.Length);
+                        var header = string.Format(headerTemplate, "file", Path.GetFileName(filepath));
+                        var headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
+                        rs.Write(headerbytes, 0, headerbytes.Length);
+                        using (var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read))
+                        {
+                            var buffer = new byte[1024];
+                            var bytesRead = 0;
+                            while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
+                            {
+                                rs.Write(buffer, 0, bytesRead);
+                            }
+                        }
+                        var cr = Encoding.UTF8.GetBytes("\r\n");
+                        rs.Write(cr, 0, cr.Length);
+                    }
+                    rs.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
+                    var response = request.GetResponse() as HttpWebResponse;
+                    StreamReader newReader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
+                    string Content = newReader.ReadToEnd();
+                    Dictionary<string, object> dic1 = new Dictionary<string, object>();
+                    List<Dictionary<string, object>> dic2 = null;
+                    dic1 = BaseUtil.ToDictionary(Content);
+                    dic2 = dic1["data"] as List<Dictionary<string, object>>;
+                    string fp_id = "";
+                    if (dic2[0]["filepath"] != null)
+                    {
+                        fp_id = dic2[0]["filepath"].ToString();
+                    }
+                    if (response.StatusCode == HttpStatusCode.OK)
+                    {
+                        return fp_id;
+                    }
+                }
+                catch (Exception e)
+                {
+                    LogicHandler.DoCommandLog("FirstInspect", User.UserCode, "", "", User.UserSourceCode, "上传首件报告", "上传失败", "", "");
+                    Console.WriteLine(e.Message + e.StackTrace);
+                }
+                return "";
+            }
+
             public static async Task<string> PostMultipartAsync(string url, Dictionary<string, string> parameters, string cookie = null)
             {
                 try
@@ -531,25 +590,29 @@ namespace UAS_MES_NEW.Make
             }
         }
 
-        private bool ConsoleLog(string Content, string PathName,string SN)
+        private bool ConsoleLog(string Content, string PathName, string SN)
         {
             try
             {
-                string sourcePaht = Path.GetDirectoryName(PathName);
-                string changeName = Path.Combine(sourcePaht, $"{SN}.{currFileType}");
+                string sourcePath = Path.GetDirectoryName(PathName);
 
-                string newFolderName = "Logs";
-                string newFolderPath = Path.Combine(sourcePaht, newFolderName);
+                string newFolderName = "Meslog";
+                string newFolderPath = Path.Combine(sourcePath, newFolderName, SN);
 
                 if (!Directory.Exists(newFolderPath))
                 {
                     Directory.CreateDirectory(newFolderPath);
                 }
 
-                string newFileName = "Log_" + Path.GetFileName(changeName);
+                string newFileName = Path.GetFileName(PathName);
                 string newFilePath = Path.Combine(newFolderPath, newFileName);
 
-                File.AppendAllText(newFilePath, Content + Environment.NewLine);
+                if (File.Exists(newFilePath))
+                {
+                    File.Delete(newFilePath);
+                }
+
+                File.Move(PathName, newFilePath);
                 return true;
             }
             catch (Exception ex)

+ 46 - 0
UAS_MES_YTDZ/PublicMethod/BaseUtil.cs

@@ -12,6 +12,7 @@ using System.Net;
 using System.Net.Sockets;
 using System.Reflection;
 using System.Text;
+using System.Text.RegularExpressions;
 using System.Threading;
 using System.Windows.Forms;
 using System.Windows.Forms.DataVisualization.Charting;
@@ -90,6 +91,51 @@ namespace UAS_MES_NEW.PublicMethod
                 return "";
             }
         }
+        public static Dictionary<string, object> ToDictionary(string JsonData)
+        {
+            object Data = null;
+            Dictionary<string, object> Dic = new Dictionary<string, object>();
+            if (JsonData.StartsWith("["))
+            {
+                //如果目标直接就为数组类型,则将会直接输出一个Key为List的List<Dictionary<string, object>>集合 
+                //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["List"]; 
+                List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
+                MatchCollection ListMatch = Regex.Matches(JsonData, @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组 
+                foreach (Match ListItem in ListMatch)
+                {
+                    List.Add(ToDictionary(ListItem.ToString()));//递归调用 
+                }
+                Data = List;
+                Dic.Add("List", Data);
+            }
+            else
+            {
+                MatchCollection Match = Regex.Matches(JsonData, @"""(.+?)"": {0,1}(\[[\s\S]+?\]|null|"".+?""|-{0,1}\d*)");//使用正则表达式匹配出JSON数据中的键与值 
+                foreach (Match item in Match)
+                {
+                    try
+                    {
+                        if (item.Groups[2].ToString().StartsWith("["))
+                        {
+                            //如果目标是数组,将会输出一个Key为当前Json的List<Dictionary<string, object>>集合 
+                            //使用示例List<Dictionary<string, object>> ListDic = (List<Dictionary<string, object>>)Dic["Json中的Key"]; 
+                            List<Dictionary<string, object>> List = new List<Dictionary<string, object>>();
+                            MatchCollection ListMatch = Regex.Matches(item.Groups[2].ToString(), @"{[\s\S]+?}");//使用正则表达式匹配出JSON数组 
+                            foreach (Match ListItem in ListMatch)
+                            {
+                                List.Add(ToDictionary(ListItem.ToString()));//递归调用 
+                            }
+                            Data = List;
+                        }
+                        else if (item.Groups[2].ToString().ToLower() == "null") Data = null;//如果数据为null(字符串类型),直接转换成null
+                        else Data = item.Groups[2].ToString(); //数据为数字、字符串中的一类,直接写入 
+                        Dic.Add(item.Groups[1].ToString(), Data);
+                    }
+                    catch { }
+                }
+            }
+            return Dic;
+        }
 
         /// <summary>
         /// 通过字段和其展示的中文值获取查询的内容