public Stream POST(Stream as2Message) { try { IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest; WebHeaderCollection collection = request.Headers; if (collection["Subject"].Contains("Signed Message Disposition Notification")) { FormatServerResponse.AsyncDisplaySuccessMessage("Received Async MDN - " + MessageCounter.IncrementAsyncMessageRcv()); var mdn = new StreamReader(as2Message); string lookfor = "Original-Message-ID:"; string line = string.Empty; while (!mdn.EndOfStream) { if ((line = mdn.ReadLine()).StartsWith(lookfor)) { line = line.Substring(lookfor.Length).Trim(); FormatServerResponse.AsyncDisplaySuccessMessage(line); break; } } if (MessageCounter.collection.ContainsKey(line)) { var data = MessageCounter.collection[line]; data.EndTime = DateTime.Now; MessageCounter.collection.AddOrUpdate(line, data, (key, oldvalue) => data); } return(null); } FormatServerResponse.AsyncDisplayMessage("Received EDI message"); DateTime dt = DateTime.Now; try { byte[] buffer = new byte[16 * 1024]; using (MemoryStream ms = new MemoryStream()) { int read; while ((read = as2Message.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } buffer = ms.ToArray(); } string content = DecryptMessage(buffer); StringReader stringReader = new StringReader(content); stringReader.ReadLine(); string divider = stringReader.ReadLine().Split('"')[2]; stringReader.ReadLine(); stringReader.ReadLine(); StringBuilder builder = new StringBuilder(); string line = string.Empty; builder.Append(line = stringReader.ReadLine()); while ((line = stringReader.ReadLine()) != null) { if (line.Contains("--" + divider)) { break; } else { builder.Append("\r\n" + line); } } string data = builder.ToString(); var response = WebOperationContext.Current.OutgoingResponse; PropogationContext context = new PropogationContext(); context.MIC = MDNSend.GenerateMIC(data); context.OrginalMessageID = collection["Message-ID"] as string; MDNSend generateMDN = new MDNSend(); if (collection.AllKeys.Contains("Receipt-Delivery-Option")) { context.URL = collection.Get("Receipt-Delivery-Option"); response.StatusDescription = "EDI Message was received"; SendAsyncMDN.AsyncSend(context); if (!Settings.IsAS2Default) { Helper.GetInboundLogger().LogEndTime(data, DateTime.Now); } return(null); } else { FormatServerResponse.AsyncDisplaySuccessMessage("Sending Sync MDN"); if (!Settings.IsAS2Default) { Helper.GetInboundLogger().LogEndTime(data, DateTime.Now); } return(generateMDN.SyncMDNSend(ref response, context)); } } catch (Exception ex) { FormatServerResponse.AsyncDisplayErrorMessage(ex.Message); } return(null); } catch (Exception ex) { FormatServerResponse.DisplayErrorMessage(ex.Message); return(null); } }
public void ASyncMDNSend(PropogationContext context) { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); FormatServerResponse.AsyncDisplaySuccessMessage("Begin Async send for ID-" + context.OrginalMessageID); X509Certificate2 cert = Settings.SigningCertificate; DateTime dt = DateTime.Now; String divider1 = "=Part" + dt.ToString("_dd_HHmmss.ffffff"); String divider2 = "=Part" + dt.ToString("_HH_ddmmss.ffffff"); HttpWebRequest request = WebRequest.Create(context.URL) as HttpWebRequest; request.Method = "POST"; request.ContentType = "multipart/signed;protocol=\"application/pkcs7-signature\";micalg=sha1;boundary=\"" + divider1 + "\""; request.Headers.Add("Message-Id", "<" + Guid.NewGuid().ToString() + "@" + Settings.AS2From + ">"); request.Headers.Add("Subject", "Signed Message Disposition Notification"); request.Headers.Add("Mime-Version", "1.0"); request.Headers.Add("AS2-Version", "1.2"); request.Headers.Add("AS2-From", Settings.AS2From); request.Headers.Add("AS2-To", Settings.AS2To); StringBuilder part1 = new StringBuilder(); StringBuilder part5 = new StringBuilder(); part1.Append("Content-Type: multipart/report;Report-Type=disposition-notification;boundary=\"" + divider2 + "\""); part1.Append("\r\n"); part1.Append("\r\n"); part1.Append("--" + divider2 + "\r\n"); part1.Append("\r\n"); part1.Append("Your message was successfully received and processed."); part1.Append("\r\n"); part1.Append("\r\n"); part1.Append("--" + divider2 + "\r\n"); part1.Append("Content-Type: message/disposition-notification"); part1.Append("\r\n"); part1.Append("\r\n"); part1.Append("Original-Recipient: rfc822;" + Settings.AS2From); part1.Append("\r\n"); part1.Append("Final-Recipient: rfc822;" + Settings.AS2From); part1.Append("\r\n"); part1.Append(String.Format("Original-Message-ID: {0}", context.OrginalMessageID)); part1.Append("\r\n"); part1.Append(String.Format("Received-Content-MIC: {0},sha1", context.MIC)); part1.Append("\r\n"); part1.Append("Disposition: Automatic-action/mdn-sent-automatically;processed"); part1.Append("\r\n"); part1.Append("\r\n"); part1.Append("--" + divider2 + "--\r\n"); part1.Append("\r\n"); part5.Append("--" + divider1 + "\r\n" + part1.ToString() + "\r\n" + "--" + divider1 + "\r\n" + "Content-Type: application/pkcs7-signature; name= smime.p7s; smime-type=signed-data" + "\r\n" + "Content-Disposition: attachment; filename=\"smime.p7s\"" + "\r\n" + "Content-Transfer-Encoding: base64\r\n" + "\r\n" + Certificates.SignDetached(Encoding.Default.GetBytes(part1.ToString()), cert) + "\r\n" + "--" + divider1 + "--"); byte[] byteData = Encoding.Default.GetBytes(part5.ToString()); Stream sw = request.GetRequestStream(); sw.Write(byteData, 0, byteData.Length); sw.Close(); using (HttpWebResponse resp = (HttpWebResponse)request.GetResponse()) { StringBuilder response = new StringBuilder(); foreach (string key in resp.Headers.Keys) { response.AppendLine(String.Format("{0}:{1}", key, resp.Headers[key])); } StreamReader sr = new StreamReader(resp.GetResponseStream()); string _responseText = sr.ReadToEnd(); response.Append(Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(_responseText))); if (Settings.Log) { File.WriteAllText(@"C:\Users\rmd\Documents\Sterling Documents\Sample\log\Asyncmdn" + dt.ToString("_dd_HHmmss.ffffff") + ".txt", _responseText, Encoding.UTF8); } sr.Close(); resp.Close(); } FormatServerResponse.AsyncDisplaySuccessMessage("Completed Async send for ID-" + context.OrginalMessageID); }
public void SendEDI(PropogationContext context) { try { ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); HttpWebRequest req = WebRequest.Create(context.URL) as HttpWebRequest; DataStruct data = new DataStruct(); var logger = Helper.GetInboundLogger(); if (Settings.Timeout > 0) { req.Timeout = Settings.Timeout; } DateTime dt = DateTime.Now; X509Certificate2 encryptioncert = Settings.EncryptionCertificate; X509Certificate2 signingcert = Settings.SigningCertificate; string GUID = Guid.NewGuid().ToString("N"); string messageID = "<" + GUID + "@" + Settings.AS2From + ">"; req.Method = "POST"; req.ContentType = "application/pkcs7-mime; smime-type=enveloped-data; name=\"smime.p7m\""; req.UserAgent = "Sampler.EDI.AS2"; req.Headers.Add("Message-Id", messageID); req.Headers.Add("From", Settings.Email); if (!Settings.IsAS2Default && Settings.Subject.Contains("{0}")) { req.Headers.Add("Subject", String.Format(Settings.Subject, GUID)); } else { req.Headers.Add("Subject", Settings.Subject); } // req.Headers.Add("Date", DateTime.Now.ToUniversalTime().ToString("ddd, dd MMM yyyy hh:mm:ss ") + "GMT"); req.Date = DateTime.Now.ToUniversalTime(); req.Headers.Add("Mime-Version", "1.0"); req.Headers.Add("AS2-Version", "1.2"); req.Headers.Add("AS2-From", Settings.AS2From); req.Headers.Add("AS2-To", Settings.AS2To); if (Settings.IsAsync) { req.Headers.Add("Receipt-Delivery-Option", Settings.ReceiptDeliveryOption); } req.Headers.Add("Content-Disposition", "attachment; filename=\"smime.p7m\""); req.Headers.Add("Disposition-notification-To", Settings.ReceiptDeliveryOption); req.Headers.Add("Disposition-notification-options", "signed-receipt-protocol=optional,pkcs7-signature;signed-receipt-micalg=optional,sha1"); String divider = "=Part" + dt.ToString("_dd_HHmmss.ffffff"); StringBuilder sendData = new StringBuilder(); sendData.Append("MIME-Version: 1.0\r\n"); sendData.Append("Content-Type: multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha1; boundary=\"" + divider + "\"\r\n"); sendData.Append("\r\n"); StringBuilder strHeader = new StringBuilder(); FormatServerResponse.AsyncDisplayMessage("Create MIME Content"); strHeader.Append(String.Format( "Content-Type: {0}; name=\"{1}\"\r\n" + "Content-Transfer-Encoding: binary\r\n" + "Content-Disposition: attachment; filename=\"{2}\"\r\n" + "\r\n", "application/EDI-Consent", Settings.FileName, Settings.FileName)); try { foreach (string file in Directory.GetFiles(context.Folder)) { /* FileInfo fileInfo = new FileInfo(file); * strHeader.Append(String.Format("{0}" + "\r\n", + File.ReadAllText(file) + ));*/ strHeader.Append(String.Format("{0}" + "\r\n", (Settings.IsAS2Default) ? logger.generateStringFromEDIFile(file):logger.generateMiddlewareMessage(GUID, file) )); } } catch (Exception ex) { FormatServerResponse.AsyncDisplayErrorMessage(ex.Message); return; } string strData = "--" + divider + "\r\n" + strHeader + "\r\n" + "--" + divider + "\r\n" + "Content-Type: application/pkcs7-signature; name= smime.p7s; smime-type=signed-data" + "\r\n" + "Content-Disposition: attachment; filename=\"smime.p7s\"" + "\r\n" + "Content-Transfer-Encoding: base64\r\n" + "\r\n" + Certificates.SignDetached(Encoding.Default.GetBytes(strHeader.ToString()), signingcert) + "\r\n"; sendData.Append(strData); sendData.Append("--" + divider + "--"); StringBuilder request = new StringBuilder(); foreach (string key in req.Headers.Keys) { request.AppendLine(String.Format("{0}:{1}", key, req.Headers[key])); } request.Append(sendData); if (Settings.Log) { File.WriteAllBytes(@"C:\Users\rmd\Documents\Sterling Documents\Sample\log\request" + dt.ToString("_dd_HHmmss.ffffff") + ".txt", Encoding.Default.GetBytes(request.ToString())); FormatServerResponse.DisplayMessage("Log Payload before Encryption"); FormatServerResponse.DisplayMessage("Begin Payload Encryption"); } byte[] byteData = Certificates.Encrypt(Encoding.Default.GetBytes(sendData.ToString()), encryptioncert); try { data.StartTime = DateTime.Now; data.Type = 'S'; MessageCounter.collection.AddOrUpdate(messageID, data, (key, oldValue) => data); FormatServerResponse.AsyncDisplayMessage("Fetch stream"); MessageCounter.IncrementConnection(); Stream sw = req.GetRequestStream(); FormatServerResponse.AsyncDisplayMessage("Write to stream"); sw.Write(byteData, 0, byteData.Length); sw.Close(); StringBuilder response = new StringBuilder(); FormatServerResponse.AsyncDisplayMessage("Waiting for response"); using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse()) { foreach (string key in resp.Headers.Keys) { response.AppendLine(String.Format("{0}:{1}", key, resp.Headers[key])); } StreamReader sr = new StreamReader(resp.GetResponseStream()); MessageCounter.DecrementConnection(); string _responseText = sr.ReadToEnd(); response.Append(Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(_responseText))); if (Settings.Log) { File.WriteAllText(@"C:\Users\rmd\Documents\Sterling Documents\Sample\log\mdn_actually" + dt.ToString("_dd_HHmmss.ffffff") + ".txt", _responseText, Encoding.UTF8); } sr.Close(); if (!Settings.IsAsync) { data.EndTime = DateTime.Now; MessageCounter.collection.AddOrUpdate(messageID, data, (key, oldValue) => data); if (_responseText.Contains("Your message was successfully received and processed.")) { FormatServerResponse.AsyncDisplaySuccessMessage("State:Success"); } else { FormatServerResponse.AsyncDisplayErrorMessage("State:Error CHECK mdn" + dt.ToString("_dd_HHmmss.ffffff")); } } resp.Close(); } if (Settings.Log) { File.WriteAllText(@"C:\Users\rmd\Documents\Sterling Documents\Sample\log\mdn" + dt.ToString("_dd_HHmmss.ffffff") + ".txt", response.ToString()); } try { if (Settings.NoSQL) { logger.LogStartTime(data.StartTime); } } catch (Exception ex) { FormatServerResponse.AsyncDisplayErrorMessage(ex.Message); } } catch (Exception ex) { MessageCounter.DecrementConnection(); FormatServerResponse.AsyncDisplayErrorMessage(ex.Message); if (Settings.LogToFile) { Logger.Log(String.Format("{0},{1},{2}", messageID, ex.Message, DateTime.Now.ToString("o"))); } } } catch (Exception ex) { FormatServerResponse.AsyncDisplayErrorMessage(ex.Message); } }