//Private, outside sendDocument.SoapResult Member private ServicesATSoapResult GetSoapResultDC() { ServicesATSoapResult result = new ServicesATSoapResult(); if (File.Exists(_pathSaveSoapResult)) { result.ReturnRaw = File.ReadAllText(_pathSaveSoapResult); XElement doc = XElement.Load(_pathSaveSoapResult); //Envelop Namespace S XNamespace xnS = "http://schemas.xmlsoap.org/soap/envelope/"; //RegisterInvoiceResponseElem Namespace XNamespace xnRI = "http://servicos.portaldasfinancas.gov.pt/faturas/"; foreach (var itm in doc.Descendants(xnS + "Body").Descendants(xnRI + "RegisterInvoiceResponseElem")) { //<ns2:RegisterInvoiceResponseElem> result.ReturnCode = itm.Element("ReturnCode").Value; result.ReturnMessage = itm.Element("ReturnMessage").Value; //</ns2:RegisterInvoiceResponseElem> } } return(result); }
//Private, outside sendDocument.SoapResult Member private ServicesATSoapResult GetSoapResultWB() { ServicesATSoapResult result = new ServicesATSoapResult(); if (File.Exists(_pathSaveSoapResult)) { result.ReturnRaw = File.ReadAllText(_pathSaveSoapResult); XElement doc = XElement.Load(_pathSaveSoapResult); //Envelop Namespace S XNamespace xnS = "http://schemas.xmlsoap.org/soap/envelope/"; //RegisterInvoiceResponseElem Namespace XNamespace xnRI = "https://servicos.portaldasfinancas.gov.pt/sgdtws/documentosTransporte/"; foreach (var itm in doc.Descendants(xnS + "Body").Descendants(xnRI + "envioDocumentoTransporteResponseElem")) { //<ns0:envioDocumentoTransporteResponseElem //<ResponseStatus> result.ReturnCode = itm.Element("ResponseStatus").Element("ReturnCode").Value; result.ReturnMessage = itm.Element("ResponseStatus").Element("ReturnMessage").Value; //<//ResponseStatus> if (result.ReturnCode == "0") { result.DocumentNumber = itm.Element("DocumentNumber").Value; result.ATDocCodeID = itm.Element("ATDocCodeID").Value; } //</ns0:envioDocumentoTransporteResponseElem } } return(result); }
/// <summary> /// Persist SOAP Result in DataBase /// </summary> /// <param name="SoapResult"></param> public bool PersistResult(ServicesATSoapResult pSoapResult) { bool result = false; try { //Always Add to sys_systemauditat Log SystemAuditATWSType systemAuditATWSType = (!_wayBillMode) ? SystemAuditATWSType.Document : SystemAuditATWSType.DocumentWayBill; var systemAuditATWS = new sys_systemauditat(GlobalFramework.SessionXpo) { Date = DateTime.Now, Type = systemAuditATWSType, PostData = _postData, ReturnCode = Convert.ToInt16(pSoapResult.ReturnCode), ReturnMessage = pSoapResult.ReturnMessage, ReturnRaw = pSoapResult.ReturnRaw, DocumentNumber = _documentMaster.DocumentNumber, ATDocCodeID = pSoapResult.ATDocCodeID, DocumentMaster = _documentMaster }; systemAuditATWS.Save(); //Always Add to fin_documentfinancemaster ATAudit _documentMaster.ATAudit.Add(systemAuditATWS); _documentMaster.Save(); //Assign OK Result if (pSoapResult.ReturnCode == "0") { //Assign to ATValidResult to Document Master _documentMaster.ATValidAuditResult = systemAuditATWS; //Assign ATDocCodeID if (_wayBillMode) { _documentMaster.ATDocCodeID = pSoapResult.ATDocCodeID; } //Disable Resend if Enabled (Used when document is Cancelled) if (_documentMaster.ATResendDocument) { _documentMaster.ATResendDocument = false; } //Override Default Document Date _documentMaster.MovementStartTime = _movementStartTime; _documentMaster.Save(); //Assign True to Result result = true; } } catch (Exception ex) { _log.Error(ex.Message, ex); } return(result); }
public string Send() { Utils.Log(string.Format("urlWebService: {0}", _urlWebService)); Utils.Log(string.Format("urlSoapAction: {0}", _urlSoapAction)); Utils.Log(string.Format("Send Document DocumentNumber: [{0}]/WayBillMode: [{1}]", _documentMaster.DocumentNumber, _wayBillMode)); //Check Certificates if (!_validCerificates) { string msg = string.Format("Invalid Certificates: [{0}], [{1}] in current Directory [{2}]", _pathPublicKey, _pathCertificate, Directory.GetCurrentDirectory()); Utils.Log(msg); return(string.Format(msg)); } //Fix for Error 99 //Neste momento o erro internal error ainda está a ocorrer? Fiquei sem perceber se o erro deriva de alguma atualização do windows ou problema da AT. //Pode ser resolvido, em c#, com: ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls; buildCredentials(); try { //Prepare Request HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_urlWebService); request.Headers.Add("SOAPAction", _urlSoapAction.ToString()); if (SettingsApp.ServicesATRequestTimeout > 0) { request.Timeout = SettingsApp.ServicesATRequestTimeout; } // Old Method : without Using VendorPlugin //X509Certificate2 cert = new X509Certificate2(); //From user installed Certificates //cert.Import(_pathCertificate, _passwordCertificate, X509KeyStorageFlags.DefaultKeySet); //From FileSystem "Resources\Certificates" //cert.Import(_pathCertificate, _atPasswordCertificate, X509KeyStorageFlags.Exportable); // New Method : Import Certificate From VendorPlugin X509Certificate2 cert = GlobalFramework.PluginSoftwareVendor.ImportCertificate(SettingsApp.ServiceATEnableTestMode, _pathCertificate); // Output Certificate Utils.Log(string.Format("Cert Subject: [{0}], NotBefore: [{1}], NotAfter: [{2}]", cert.Subject, cert.NotBefore, cert.NotAfter)); request.ClientCertificates.Add(cert); request.Method = "POST"; request.ContentType = "text/xml; charset=utf-8"; request.Accept = "text/xml"; string oRequest = (!_wayBillMode) ? (_useMockSampleData) ? GenerateXmlStringDCSample() : GenerateXmlStringDC() : (_useMockSampleData) ? GenerateXmlStringWBSample() : GenerateXmlStringWB() ; _postData = oRequest; byte[] byteArray = Encoding.UTF8.GetBytes(_postData); request.ContentLength = byteArray.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(byteArray, 0, byteArray.Length); dataStream.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); //Save Result to File System.IO.File.WriteAllText(_pathSaveSoapResult, responseFromServer); //GetSoapResult _soapResult = (!_wayBillMode) ? GetSoapResultDC() : GetSoapResultWB(); //Log Utils.Log(string.Format("Send Document ReturnCode: [{0}]", _soapResult.ReturnCode)); Utils.Log(string.Format("Send Document ReturnMessage: [{0}]", _soapResult.ReturnMessage), true); //Persist Result in Database PersistResult(_soapResult); return(responseFromServer); } catch (WebException ex) { _log.Error(ex.Message, ex); if (ex.Status == WebExceptionStatus.ProtocolError) { WebResponse response = ex.Response; StreamReader streamReader = new StreamReader(response.GetResponseStream()); //Store Result to use 2 times, else second time is string.Empty string streamResult = streamReader.ReadToEnd(); //Save Result Error to File System.IO.File.WriteAllText(_pathSaveSoapResultError, streamResult); //Log Utils.Log(string.Format("Send ProtocolError StreamResult: [{0}]", streamResult), true); return(streamResult); } else { //Log Utils.Log(string.Format("Exception: [{0}]", ex.Message), true); return(ex.Message); } } }