public void ShowConfig() { FrmConfig frm = new FrmConfig(); frm.ShowDialog(); }
public FunctionResult <InvoiceInfo> PublishAndSignInvoice(string stt_rec, string ma_ct, System.Collections.Hashtable htOverrireDmct) { FunctionResult <InvoiceInfo> result = new FunctionResult <InvoiceInfo>(); result.Status = ResultCode.Error; result.Data = new InvoiceInfo(); Guid logId = Guid.Empty; Stopwatch sw = new Stopwatch(); Stopwatch sw2 = new Stopwatch(); string log_content = ""; try { sw.Start(); logId = CreateLog(ma_ct, stt_rec, (int)PublishType.Publish); SqlCommand cmd = new SqlCommand("Select * from dmct where ma_ct='" + ma_ct + "'"); DataSet dsDmct = StartupBase.SysObj.ExcuteReader(cmd); if (dsDmct.Tables[0].Rows.Count > 0) { string ph = dsDmct.Tables[0].Rows[0]["v_phdbf"].ToString(); string ct = dsDmct.Tables[0].Rows[0]["v_ctdbf"].ToString(); string mph = dsDmct.Tables[0].Rows[0]["m_phdbf"].ToString(); string mct = dsDmct.Tables[0].Rows[0]["m_ctdbf"].ToString(); cmd = new SqlCommand("Select * FROM " + ph + " Where stt_rec=@stt_rec"); cmd.Parameters.Add(new SqlParameter("@stt_rec", stt_rec)); DataSet dsPH = StartupBase.SysObj.ExcuteReader(cmd); cmd = new SqlCommand("Select * FROM " + ct + " Where stt_rec=@stt_rec"); cmd.Parameters.Add(new SqlParameter("@stt_rec", stt_rec)); DataSet dsCt = StartupBase.SysObj.ExcuteReader(cmd); string ma_qs0 = dsPH.Tables[0].Rows[0]["ma_qs"].ToString(); DataTable tblDmqs = Utils.GetQuyenHddtInfo(ma_qs0, 0); if (tblDmqs.Rows.Count == 0) { throw new Exception("Không tìm thấy quyển khai báo sử dụng hóa đơn điện tử cho quyển chứng từ " + ma_qs0); } if (tblDmqs.Rows[0]["ma_qs_ax"].ToString().Trim() == "") { throw new Exception(string.Format("Quyển chứng từ [{0}] chưa được gán mã quyển HĐĐT", tblDmqs.Rows[0]["ma_qs"])); } DataTable tblQHddt = Utils.GetQuyenHddtInfo(tblDmqs.Rows[0]["ma_qs_ax"].ToString(), 1); if (tblQHddt.Rows.Count == 0) { throw new Exception("Không tìm thấy khai báo quyển chứng từ có mã " + tblDmqs.Rows[0]["ma_qs_ax"].ToString()); } DataRow dmKhRow = Utils.SelectDmkhInfo(dsPH.Tables[0].Rows[0]["ma_kh"].ToString()); if (dmKhRow["e_mail"].ToString().Trim() == "") { throw new Exception("Khách hàng mã " + dsPH.Tables[0].Rows[0]["ma_kh"].ToString() + " chưa được khai báo email để sử dụng hóa đơn điện tử"); } string email_cus = dmKhRow["e_mail"].ToString().Trim(); string ma_qs = tblQHddt.Rows[0]["ma_qs"].ToString(); string pattern = tblQHddt.Rows[0]["kh_mau_hd"].ToString().Trim(); string serial = tblQHddt.Rows[0]["so_seri"].ToString().Trim(); string transform = tblQHddt.Rows[0]["transform"].ToString().Trim(); result.Data.MaQs_Luu = ma_qs0; result.Data.MaQs_Hddt = ma_qs; result.Data.Transform = transform; //Kiểm tra xem hóa đơn đã được post trước đó chưa ResponeBaseGenneric <CheckInvoiceStateData> rsCheck = checkInvoiceState(stt_rec); InvoiceState state = rsCheck.Data.GetInvState(stt_rec); if (state == InvoiceState.NotExist) { Hashtable htJson = new Hashtable(); string xmlContent = ConvertDataToXMLInvoice(dsPH.Tables[0], dsCt.Tables[0], ma_ct, (int)PublishType.Publish); htJson.Add("XmlData", xmlContent); htJson.Add("Pattern", pattern); htJson.Add("Serial", serial); htJson.Add("IkeyEmail", new KeyValuePair <string, string>(stt_rec, email_cus)); string json = Newtonsoft.Json.JsonConvert.SerializeObject(htJson); string use_client_cert = FrmConfig.GetConfig(FrmConfig.KEY_USE_CLIENT_CERT); string respone = ""; if (use_client_cert != "true") { sw2.Start(); log_content += Environment.NewLine + "Phát hành trực tiếp hóa đơn điện tử"; UpdateLogField(logId, new string[] { "request", "end_point" }, new object[] { json, "api/publish/importAndPublishInvoice" }); respone = Post2Server("api/publish/importAndPublishInvoice", SMethod.POST, json); sw2.Stop(); UpdateLogField(logId, new string[] { "respone" }, new object[] { respone }); Hashtable htResult = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(respone); string status = htResult["Status"].ToString(); string message = htResult["Message"].ToString(); if (status == "2") { result.Status = ResultCode.Success; result.Message = message; result.ResponeData = Encoding.UTF8.GetBytes(respone); Hashtable htInvoiceInfo = htResult["Data"] as Hashtable; result.Data.Pattern = htInvoiceInfo["Pattern"].ToString(); result.Data.Serial = htInvoiceInfo["Serial"].ToString(); Hashtable htKeyInvoiceNo = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htInvoiceInfo["KeyInvoiceNo"].ToString()); if (result.Data.Transform != "") { result.Data.InvoiceNo = string.Format(result.Data.Transform, int.Parse(htKeyInvoiceNo[stt_rec].ToString())); } else { result.Data.InvoiceNo = htKeyInvoiceNo[stt_rec].ToString(); } } else { result.Status = ResultCode.Error; result.Message = message; } } else { sw2.Start(); log_content += Environment.NewLine + "Phát hành 2 bước hóa đơn điện tử"; //Ký số 2 bước //Bước 1. //Tạo hóa đơn tạm api/publish/externalGetDigestForImportation //Chọn CKS X509Certificate2 signCert = null; string certString = GetCertString(out signCert); htJson.Add("CertString", certString); json = Newtonsoft.Json.JsonConvert.SerializeObject(htJson); log_content += Environment.NewLine + "1. Tạo hóa đơn tạm"; log_content += Environment.NewLine + "==>JSon:" + json; respone = Post2Server("api/publish/externalGetDigestForImportation", SMethod.POST, json); log_content += Environment.NewLine + "==>Respone:" + respone; //Xử lý kết quả trả về Hashtable htResult = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(respone); if (htResult.ContainsKey("Status") && htResult["Status"].ToString() == "2") { //Tạo hóa đơn thành công //Bước 2. Ký số hóa đơn và phát hành Hashtable htData = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htResult["Data"].ToString()); //Lấy digest value Hashtable hDigestData = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htData["DigestData"].ToString()); Hashtable htData2Post2 = new Hashtable(); IDictionaryEnumerator ie = hDigestData.GetEnumerator(); while (ie.MoveNext()) { string sDigestData = hDigestData[ie.Key].ToString(); string signHash = SignHash(signCert, sDigestData); htData2Post2.Add(ie.Key, signHash); } Hashtable htData2Post = new Hashtable(); htData2Post.Add("Pattern", htData["Pattern"]); htData2Post.Add("Serial", htData["Serial"]); htData2Post.Add("Signature", htData2Post2); log_content += Environment.NewLine + "2. Phát hành hóa đơn tạm"; json = Newtonsoft.Json.JsonConvert.SerializeObject(htData2Post); log_content += Environment.NewLine + "==>JSon:" + json; respone = Post2Server("api/publish/externalWrapAndLaunchImportation", SMethod.POST, json); log_content += Environment.NewLine + "==>Respone:" + respone; htResult = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(respone); if (htResult.ContainsKey("Status") && htResult["Status"].ToString() == "2") { result.Status = ResultCode.Success; result.Message = ""; result.ResponeData = Encoding.UTF8.GetBytes(respone); Hashtable htInvoiceInfo = htInvoiceInfo = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htResult["Data"].ToString()); result.Data.Pattern = htInvoiceInfo["Pattern"].ToString(); result.Data.Serial = htInvoiceInfo["Serial"].ToString(); result.Data.InvoiceDate = (DateTime)dsPH.Tables[0].Rows[0]["ngay_ct"]; Hashtable htKeyInvoiceNo = Newtonsoft.Json.JsonConvert.DeserializeObject <Hashtable>(htInvoiceInfo["KeyInvoiceNo"].ToString()); if (result.Data.Transform != "") { result.Data.InvoiceNo = string.Format(result.Data.Transform, int.Parse(htKeyInvoiceNo[stt_rec].ToString())); } else { result.Data.InvoiceNo = htKeyInvoiceNo[stt_rec].ToString(); } } else { //Lỗi result.Status = ResultCode.Error; result.Message = htResult["Message"].ToString(); } } else { result.Status = ResultCode.Error; result.Message = htResult["Message"].ToString(); } sw2.Stop(); } UpdateLogField(logId, new string[] { "status_code" }, new object[] { result.Status.ToString() }); } else { switch (state) { case InvoiceState.NaN: throw new Exception("Lỗi khi tra cứu trạng thái hóa đơn"); case InvoiceState.Published: if (MessageBox.Show("Hóa đơn hiện tại đã được phát hành. Bạn có muốn cập nhật lại trạng thái hóa đơn?", "Cảnh báo", MessageBoxButtons.YesNo) == DialogResult.Yes) { result.Status = ResultCode.Success; ResponeBaseGenneric <ViewInvoiceData> rsViewInv = GetViewInvoice(stt_rec, rsCheck.Data.Pattern); // result.Data = new InvoiceInfo(); result.Data.InvState = rsViewInv.Data.InvState; if (result.Data.Transform != "") { result.Data.InvoiceNo = string.Format(result.Data.Transform, int.Parse(rsViewInv.Data.No)); } else { result.Data.InvoiceNo = rsViewInv.Data.No; } result.Data.InvoiceDate = DateTime.ParseExact(rsViewInv.Data.ArisingDate, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture); result.Data.Serial = rsViewInv.Data.Serial; } break; default: throw new Exception("Trạng thái hóa đơn hiện tại không cho phép cập nhật:" + InvStateDescription[state]); } } } else { throw new Exception("Không tìm thấy mã chứng từ " + ma_ct); } } catch (Exception ex) { result.Status = ResultCode.Exception; result.Message = ex.ToString(); log_content += ex.ToString(); } finally { sw.Stop(); sw2.Stop(); try { UpdateLogField(logId, new string[] { "duration", "duration_publish", "log_content", "status_code" }, new object[] { sw.Elapsed.Seconds, sw2.Elapsed.Seconds, log_content, result.Status.ToString() }); } catch { } } return(result); }
public string Post2Server(string apiName, string sMethod, string sData) { string apiUrl = FrmConfig.GetConfig(FrmConfig.KEY_URL); string _urlAPI = apiUrl + apiName; string _strReturn = ""; string uid = FrmConfig.GetConfig(FrmConfig.KEY_LOGIN_NAME); string pwd = FrmConfig.GetConfig(FrmConfig.KEY_PASSWORD); try { ServicePointManager.ServerCertificateValidationCallback -= new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate); } catch { } if (apiUrl.Contains("https:")) { ServicePointManager.ServerCertificateValidationCallback += new System.Net.Security.RemoteCertificateValidationCallback(ValidateServerCertificate); } //using (WebClient wc = new WebClient()) //{ // wc.Headers[HttpRequestHeader.UserAgent] = "538c8b5f-2fb8-42be-a4ab-63fbee68e6af"; // wc.Headers[HttpRequestHeader.Accept] = "application/json"; //; // wc.Headers[HttpRequestHeader.ContentType] = "application/json";//;charset=UTF-8 // string authen_token = GenerateToken(uid, pwd, sMethod); // // wc.Headers[HttpRequestHeader.Authorization] = authen_token; // wc.Headers.Add("Authentication", authen_token); // wc.Encoding = UTF8Encoding.UTF8; // try // { // lock (_KeyToPost) // { // if (sMethod == SMethod.GET) // _strReturn = System.Text.Encoding.UTF8.GetString(wc.DownloadData(_urlAPI + "?" + sData)); // else // _strReturn = wc.UploadString(_urlAPI, sMethod, sData); // } // } // catch(WebException we) // { // if (we.Response is HttpWebResponse) // { // HttpWebResponse r = we.Response as HttpWebResponse; // using (StreamReader sr = new StreamReader(r.GetResponseStream())) // { // _strReturn = sr.ReadToEnd(); // } // } // } // catch(Exception ex) // { // throw; // } //} //string authen_token = EasyRequest.GenAuthentication(uid, pwd, sMethod);// GenerateToken(uid, pwd, sMethod); ////HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_urlAPI); ////request.UserAgent = "EasyInvoice-Client/1.0.0.0"; ////request.Accept = "application/json, text/json"; ////request.ContentType = "application/json"; ////request.Method = sMethod; ////request.Headers.Add("Authentication", authen_token); ////request.ServicePoint.Expect100Continue = false; ////request.KeepAlive = true; ////request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip | DecompressionMethods.None; ////using (Stream sw = request.GetRequestStream()) ////{ //// byte[] d=Encoding.UTF8.GetBytes(sData); //// sw.Write(d,0,d.Length); //// sw.Flush(); ////} ////HttpWebResponse response = request.GetResponse() as HttpWebResponse; ////using (StreamReader sr = new StreamReader(response.GetResponseStream())) ////{ //// _strReturn = sr.ReadToEnd(); ////} EasyClient CLIENT = new EasyClient(apiUrl, uid, pwd); EasyResponse respone = CLIENT.PostJsonObject(apiName, sData); _strReturn = respone.Content; return(_strReturn); }