コード例 #1
0
        protected override void Process()
        {
            using (var unit = GetUnitOfWork())
            {
                try
                {
                    if (Config.AppSettings.Settings["EdiOrderDir"] != null)
                    {
                        var importpath = Config.AppSettings.Settings["EdiOrderDir"].Value;

                        foreach (var file in Directory.GetFiles(importpath))
                        {
                            FileInfo inf = new FileInfo(file);
                            log.InfoFormat("Found file with extension", inf.Extension);
                            if (inf.Extension == ".xls" || inf.Extension == ".xlsx")
                            {
                                log.Info("Found excel order");
                                ExcelReader excel = new ExcelReader(importpath, log, unit);
                                excel.ProcessFile(file, "OrderDir");
                            }
                            else
                            {
                                using (StreamReader reader = new StreamReader(file))
                                {
                                    EdiOrderListener ediListener = new EdiOrderListener()
                                    {
                                        CustomerName     = "new",
                                        CustomerIP       = "Unknown",
                                        CustomerHostName = "Directory order",
                                        RequestDocument  = reader.ReadToEnd(),
                                        Processed        = false,
                                        ReceivedDate     = DateTime.Now,
                                        ConnectorID      = int.Parse(Config.AppSettings.Settings["DefaultConnectorID"].Value)
                                    };
                                    unit.Scope.Repository <EdiOrderListener>().Add(ediListener);

                                    unit.Save();
                                }
                            }
                            var archivePath = Path.Combine(importpath, "Processed");

                            if (!Directory.Exists(archivePath))
                            {
                                Directory.CreateDirectory(archivePath);
                            }

                            FileInfo fInf = new FileInfo(file);

                            if (File.Exists(Path.Combine(archivePath, fInf.Name)))
                            {
                                File.Delete(Path.Combine(archivePath, fInf.Name));
                            }

                            File.Move(file, Path.Combine(archivePath, fInf.Name));
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.AuditError("Failed to load files from directory");
                }

                var orders = (from o in unit.Scope.Repository <EdiOrderListener>().GetAll()
                              where o.Processed == false &&
                              o.ErrorMessage == null
                              select o).ToList();

                foreach (var order in orders)
                {
                    try
                    {
                        string type = ediProcessor.DocumentType(order.RequestDocument);

                        if (!string.IsNullOrEmpty(type))
                        {
                            var messageType = ediOrderTypes.FirstOrDefault(x => x.Name == type);

                            if (messageType != null)
                            {
                                order.Processed = true;

                                var ediOrders = ediProcessor.ProcessOrder(type, order.RequestDocument, order.ConnectorID, order.EdiRequestID, unit);
                                foreach (var ediOrder in ediOrders)
                                {
                                    var o = unit.Scope.Repository <EdiOrder>().GetSingle(x => x.EdiOrderID == ediOrder.EdiOrderID);
                                    o.Status = (int)EdiOrderStatus.Validate;
                                }
                            }
                            else
                            {
                                string error = string.Format("Messagetype {0} does not exists in Database", type);
                                log.AuditError(error, "EDI New Messages");
                                order.ErrorMessage = error;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        log.AuditError(string.Format("Failed to process order {0}", order.EdiRequestID), ex, "Process New EDI orders");
                        order.ErrorMessage = ex.Message;
                    }
                    finally
                    {
                        unit.Save();
                    }
                }
            }
        }
コード例 #2
0
        void ListenerCallback(IAsyncResult result)
        {
            XmlDocument         doc     = new XmlDocument();
            HttpListenerContext context = null;

            try
            {
                //Get listener instance from async result
                HttpListener listener = (HttpListener)result.AsyncState;
                if (!listener.IsListening)
                {
                    return;
                }

                context = listener.EndGetContext(result);
                log.Info("Response received");

                string responseString;
                using (StreamReader reader = new StreamReader(context.Request.InputStream))
                {
                    responseString = reader.ReadToEnd();
                }

                try
                {
                    if (!string.IsNullOrEmpty(responseString))
                    {
                        using (var unit = GetUnitOfWork())
                        {
                            ConnectorRelation relation = null;
                            #region Authentication
                            if (_authentication)
                            {
                                HttpListenerBasicIdentity identity = (HttpListenerBasicIdentity)context.User.Identity;
                                relation = unit.Scope.Repository <ConnectorRelation>().GetSingle(x => x.Username == identity.Name && x.Password == identity.Password && x.IsActive);
                                if (relation == null)
                                {
                                    #region Forward
                                    if (GetConfiguration().AppSettings.Settings["ForwardPostUrl"] != null && !string.IsNullOrEmpty(GetConfiguration().AppSettings.Settings["ForwardPostUrl"].Value))
                                    {
                                        try
                                        {
                                            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(GetConfiguration().AppSettings.Settings["ForwardPostUrl"].Value);
                                            request.Method      = "POST";
                                            request.Credentials = new NetworkCredential(identity.Name, identity.Password);

                                            byte[] byteData = UTF8Encoding.UTF8.GetBytes(responseString);

                                            using (Stream postStream = request.GetRequestStream())
                                            {
                                                postStream.Write(byteData, 0, byteData.Length);
                                            }

                                            HttpWebResponse objResponse = (HttpWebResponse)request.GetResponse();
                                            using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
                                            {
                                                context.Response.StatusCode        = (int)objResponse.StatusCode;
                                                context.Response.StatusDescription = objResponse.StatusDescription;
                                                using (StreamWriter writer = new StreamWriter(objResponse.GetResponseStream()))
                                                {
                                                    writer.WriteLine(sr.ReadToEnd());
                                                }
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            log.AuditError("Forward EDI message failed", ex);
                                        }
                                        #endregion
                                    }
                                    else
                                    {
                                        context.Response.StatusCode = 401;
                                        log.AuditInfo(string.Format("Login failed for username: {0} and password: {1}", identity.Name, identity.Password), "EDI listener");
                                    }
                                }
                            }

                            if (context.Response.StatusCode == 401)
                            {
                                context.Response.AddHeader("WWW-Authenticate",
                                                           "Basic Realm=\"EDI Service\""); // show login dialog
                                byte[] message = new UTF8Encoding().GetBytes("Access denied");
                                context.Response.ContentLength64 = message.Length;
                                context.Response.OutputStream.Write(message, 0, message.Length);
                            }
                            else
                            {
                                #endregion

                                string logPath = Path.Combine(GetConfiguration().AppSettings.Settings["XMLlogReceive"].Value, DateTime.Now.ToString("dd-MM-yyyy"));

                                if (!Directory.Exists(logPath))
                                {
                                    Directory.CreateDirectory(logPath);
                                }

                                string fileName = LogFile(logPath, responseString);



                                EdiOrderListener ediListener = new EdiOrderListener()
                                {
                                    CustomerName     = relation == null ? "new" : relation.Name,
                                    CustomerIP       = context.Request.UserHostAddress,
                                    CustomerHostName = context.Request.UserHostName,
                                    RequestDocument  = responseString,
                                    ReceivedDate     = DateTime.Now,
                                    Processed        = false,
                                    ConnectorID      = int.Parse(GetConfiguration().AppSettings.Settings["DefaultConnectorID"].Value)
                                };

                                if (relation != null && relation.ConnectorID.HasValue)
                                {
                                    ediListener.ConnectorID = relation.ConnectorID.Value;
                                }

                                unit.Scope.Repository <EdiOrderListener>().Add(ediListener);
                                unit.Save();

                                context.Response.StatusCode = 200;
                                using (StreamWriter writer = new StreamWriter(context.Response.OutputStream))
                                {
                                    writer.WriteLine("Response received succesfully");
                                }
                            }
                        }
                    }
                    else
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.NoContent;
                        using (StreamWriter writer = new StreamWriter(context.Response.OutputStream))
                        {
                            writer.WriteLine("No content found in request");
                        }
                    }
                }
                catch (Exception ex)
                {
                    log.Error("Error processing response", ex);
                }

                context.Response.Close();
            }
            catch (Exception ex)
            {
                log.Error("Writing of response to xml failed", ex);
            }
            finally
            {
                if (_httpListener != null && _httpListener.IsListening)
                {
                    _httpListener.BeginGetContext(ListenerCallback, _httpListener);
                }
            }
            log.Info("Response processing ended");
        }