close
工作上有遇到需要跟ERP串接更新員工資料的需求,
故筆記一下用法。
Sample code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
try { String url = String.Empty; String nb = String.Empty; String response = String.Empty; DataTable dt = new DataTable(); StringBuilder post = new StringBuilder(); String empNo = String.Empty;//職工編號 String deptNo = String.Empty;//部門 String postName = String.Empty;//職稱 String chiName = String.Empty;//中文姓名 String checkCode = String.Empty;//員工卡內碼 StringBuilder sql = new StringBuilder(); //先刪除舊資料 sql.Append("SELECT COUNT(*) FROM 員工資料"); dt = DB.SelectData(sql.ToString()); if (int.Parse(dt.Rows[0][0].ToString()) != 0) { sql.Clear(); sql.Append("DELETE FROM 員工資料"); DB.DBInsertUpdateDelete(sql.ToString()); } url = ConfigurationManager.AppSettings["ApiUrl"]; nb = ConfigurationManager.AppSettings["NBName"]; //開始執行更新員工資料作業 if (!String.IsNullOrEmpty(url) && !String.IsNullOrEmpty(nb)) { post.Append("<SOAP-ENV:Envelope xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'>"); post.Append("<SOAP-ENV:Body>"); post.Append("<getCheckUser>"); post.AppendFormat("<Hostname>{0}</Hostname>", nb); post.Append("</getCheckUser>"); post.Append("</SOAP-ENV:Body>"); post.Append("</SOAP-ENV:Envelope>"); using (WebClient wc = new WebClient()) { wc.Encoding = Encoding.UTF8; wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); //這行要加才是標準格式 response = wc.UploadString(url, "POST", post.ToString()); //取得response的String XmlDocument doc = new XmlDocument(); doc.LoadXml(response);//讀取回傳的String XmlNamespaceManager mgr = new XmlNamespaceManager(doc.NameTable); mgr.AddNamespace("soap", "http://schemas.xmlsoap.org/soap/envelope/"); //這是SOAP 1.1 var xmlNode = doc.SelectSingleNode("//soap:Body/*", mgr); XmlDocument XmlDoc = new XmlDocument(); XmlDoc.LoadXml(xmlNode.FirstChild.InnerText); XmlNodeList NodeLists = XmlDoc.SelectNodes("DSS/empInfo"); foreach (XmlElement element in NodeLists) { empNo = element.GetElementsByTagName("empNo")[0].InnerText; deptNo = element.GetElementsByTagName("deptNo")[0].InnerText; postName = element.GetElementsByTagName("postName")[0].InnerText; chiName = element.GetElementsByTagName("chiName")[0].InnerText; checkCode = element.GetElementsByTagName("checkCode")[0].InnerText; sql.Clear(); sql.AppendFormat("INSERT INTO 員工資料(內碼,職工編號,姓名,單位,職稱) VALUES (N'{0}',N'{1}',N'{2}',N'{3}',N'{4}')", checkCode, empNo, chiName, deptNo, postName); DB.DBInsertUpdateDelete(sql.ToString()); } } MessageBox.Show("員工資料同步完成!"); } else { MessageBox.Show("同步API URL抓取出現問題!"); } } catch (Exception ex) { MessageBox.Show("同步時出現非預期錯誤,請重新再試:"+ex.Message); } |
全站熱搜
留言列表