Пример #1
0
        public Stream GET()
        {
            IncomingWebRequestContext request = WebOperationContext.Current.IncomingRequest;

            FormatServerResponse.AsyncDisplayMessage("GET request served to User agent " + request.UserAgent);

            string output =
                "<HTML>" +
                "<HEAD>" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\" />" +
                "<TITLE>" +
                "AS2 EDI Trading Partner Simulator" +
                "</TITLE>" +
                "</HEAD>" +
                "<BODY>" +

                "<H1>AS2 EDI Trading Partner Simulator</H1>" +
                "<P>" +
                "This tool simulates TP commuincation over AS2 Protocol and generates Sync and Async MDNs as response." +
                "</P> " +
                "<H3>Copyright © 2012 Intel Corporation. All rights reserved</H3>" +
                "<H4>Internal Use Only - Do Not Distribute</H4>" +
                "</BODY>" +
                "</HTML>";

            MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(output));
            OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;

            response.ContentType = "text/html";
            return(stream);
        }
Пример #2
0
        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);
            }
        }
Пример #3
0
        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);
            }
        }
Пример #4
0
        private void button2_Click(object sender, EventArgs e)
        {
            errorProvider1.Clear();

            if (checkDefault.Checked)
            {
                ThreadPool.SetMinThreads(Settings.DefaultMinWorkerThreads, Settings.DefaultMinCompletionPortThread);
                ThreadPool.SetMaxThreads(Settings.DefaultMaxWorkerThreads, Settings.DefaultMaxCompletionPortThread);
            }
            else
            {
                ThreadPool.SetMinThreads((int)numerericThreads.Value, Settings.DefaultMinCompletionPortThread);
                ThreadPool.SetMaxThreads((int)numerericThreads.Value, Settings.DefaultMaxCompletionPortThread);
            }

            if (String.IsNullOrEmpty(TxtPubThumbprint.Text))
            {
                errorProvider1.SetError(TxtPubThumbprint, "Cannot be null");
                return;
            }
            if (String.IsNullOrEmpty(TxtPvtThumbprint.Text))
            {
                errorProvider1.SetError(TxtPvtThumbprint, "Cannot be null");
                return;
            }
            if (checkSSL.Checked && String.IsNullOrEmpty(TxtSSL.Text))
            {
                errorProvider1.SetError(TxtSSL, "Cannot be null");
                return;
            }
            if (!checkAS2Default.Checked && String.IsNullOrEmpty(TxtFileName.Text))
            {
                errorProvider1.SetError(TxtFileName, "Cannot be null if Default is unchecked");
                return;
            }



            Certificates.PrivateKeyThumbprint = TxtPvtThumbprint.Text;
            Certificates.PublicKeyThumbprint  = TxtPubThumbprint.Text;
            Certificates.SSLThumbprint        = TxtSSL.Text;
            Settings.AS2From               = TxtAS2From.Text;
            Settings.AS2To                 = TxtAS2To.Text;
            Settings.Email                 = TxtEmail.Text;
            Settings.AvgFolder             = TxtAvgFolder.Text;
            Settings.MaxFolder             = TxtMaxFolder.Text;
            Settings.MinFolder             = TxtMinFolder.Text;
            Settings.URL                   = TxtUrl.Text;
            Settings.IsAsync               = checkMDN.Checked;
            Settings.AvgMessagePerMin      = Convert.ToInt32(numericAvg.Value);
            Settings.MaxMessagePerMin      = Convert.ToInt32(numericMax.Value);
            Settings.MinMessagePerMin      = Convert.ToInt32(numericMin.Value);
            Settings.Timeout               = Convert.ToInt32(numericTimeout.Value) * 1000;
            Settings.Duration              = Convert.ToInt32(numericDuration.Value) * 1000 * 60;
            Settings.Log                   = CheckLog.Checked;
            Settings.EncryptionCertificate = Certificates.GetPublicCertificateFromStore();
            Settings.SigningCertificate    = Certificates.GetPrivateCertificateFromStore();
            Settings.NoSQL                 = checkSQLLog.Checked;
            Settings.LogToFile             = checkLogToFile.Checked;
            Settings.Mins                  = Convert.ToInt32(numericMins.Value);

            label1.Text  = (Settings.Mins > 1) ? "/" + Settings.Mins + "Mins" : "/Min";
            label8.Text  = (Settings.Mins > 1) ? "/" + Settings.Mins + "Mins" : "/Min";
            label12.Text = (Settings.Mins > 1) ? "/" + Settings.Mins + "Mins" : "/Min";


            if (checkSSL.Checked)
            {
                Certificates.OpenSSL();
                Settings.ReceiptDeliveryOption = Settings.SslURL;
            }
            else
            {
                if (Certificates.CheckSSL())
                {
                    Certificates.DeleteSSL();
                }
                Settings.ReceiptDeliveryOption = Settings.HttpURL;
            }

            Settings.IsAS2Default = checkAS2Default.Checked;

            if (checkAS2Default.Checked)
            {
                Settings.Subject  = "AS2 message";
                Settings.FileName = "EDI.txt";
            }
            else
            {
                Settings.Subject  = TxtSubject.Text;
                Settings.FileName = TxtFileName.Text;
            }

            FormatServerResponse.DisplayMessage("Updated settings");
            FormatServerResponse.DisplayMessage("From - " + Settings.AS2From);
            FormatServerResponse.DisplayMessage("To - " + Settings.AS2To);
            FormatServerResponse.DisplayMessage("Email - " + Settings.Email);
            FormatServerResponse.DisplayMessage("Selected Files Folder for Avg messages - " + Settings.AvgFolder);
            FormatServerResponse.DisplayMessage("Selected Files Folder for Min messages - " + Settings.MinFolder);
            FormatServerResponse.DisplayMessage("Selected Files Folder for Max messages - " + Settings.MaxFolder);
            FormatServerResponse.DisplayMessage("URL - " + Settings.URL);
            FormatServerResponse.DisplayMessage("Signing Cert Thumbprint - " + Certificates.PrivateKeyThumbprint);
            FormatServerResponse.DisplayMessage("Encryption Cert Thumbprint - " + Certificates.PublicKeyThumbprint);
            FormatServerResponse.DisplayMessage("SSL Cert Thumbprint - " + Certificates.SSLThumbprint);
            FormatServerResponse.DisplayMessage("Is Async MDN - " + checkMDN.Checked.ToString());
            FormatServerResponse.DisplayMessage("Is SSL enabled - " + checkSSL.Checked.ToString());
            FormatServerResponse.DisplayMessage("Is Subject enabled - " + checkAS2Default.Checked.ToString());
            FormatServerResponse.DisplayMessage("Subject - " + Settings.Subject);
            FormatServerResponse.DisplayMessage("Number of Averge sized message per minute - " + Settings.AvgMessagePerMin);
            FormatServerResponse.DisplayMessage("Number of Min sized message per minute - " + Settings.MinMessagePerMin);
            FormatServerResponse.DisplayMessage("Number of Max sized message per minute - " + Settings.MaxMessagePerMin);
            FormatServerResponse.DisplayMessage("Response URL - " + Settings.ReceiptDeliveryOption);
            FormatServerResponse.DisplayMessage("Duration of the run in milliseconds - " + Settings.Duration);
            FormatServerResponse.DisplayMessage("Timeout in sec - " + Settings.Timeout / 1000);
            FormatServerResponse.DisplayMessage("Log files - " + Settings.Log.ToString());
            FormatServerResponse.DisplayMessage("Log to SQL-" + Settings.NoSQL);
            FormatServerResponse.AsyncDisplayMessage("Log to File -" + Settings.LogToFile);
            FormatServerResponse.AsyncDisplayMessage("Assembly Path -" + Settings.AssemblyPath);
            button3.Visible = true;
        }