예제 #1
0
        private void PublishFile(ConnectorRelation connector, string fileUrl, string fileName)
        {
            switch ((FtpTypeEnum)connector.FtpType.Value)
            {
            case FtpTypeEnum.Customer:
                var ftp = new FtpManager(connector.FtpAddress, string.Empty, connector.Username, connector.FtpPass,
                                         false, connector.FtpType.HasValue ? (FtpConnectionTypeEnum)connector.FtpType.Value == FtpConnectionTypeEnum.Passive : false, log);

                fileName = String.Format("{0}_{1}", DateTime.Now.ToString("yyyyMMddhhmmss"), fileName);

                using (var wc = new System.Net.WebClient())
                {
                    using (var stream = new MemoryStream(wc.DownloadData(fileUrl)))
                    {
                        ftp.Upload(stream, fileName);
                    }
                }
                break;

            case FtpTypeEnum.Xtract:
                var xtractPath = Path.Combine(_config.AppSettings.Settings["XtractFtpPath"].Value, connector.CustomerID);
                DownloadFile(fileUrl, xtractPath, fileName);
                break;
            }
        }
예제 #2
0
        /// <summary>
        /// 获得下游信息
        /// </summary>
        /// <param name="fk_id"></param>
        /// <param name="db_id"></param>
        /// <returns></returns>
        public ConnectorRelation GetDownConnector(int fk_id, int upBuyerId, int db_id)
        {
            DataTable         dt     = DbAccess.GetDataTable(string.Format(CommandConstant.GetDownConnectorBySellerId, fk_id, db_id, upBuyerId));
            ConnectorRelation entity = new ConnectorRelation();

            if (dt != null && dt.Rows.Count > 0)
            {
                entity.SetValues(dt.Rows[0]);
            }
            return(entity);
        }
예제 #3
0
        /// <summary>
        /// 获取上游信息
        /// </summary>
        /// <param name="connectId"></param>
        /// <returns></returns>
        public ConnectorRelation GetUpConnector(int connectId)
        {
            DataTable         dt     = DbAccess.GetDataTable(string.Format(CommandConstant.GetUpConnectorById, connectId));
            ConnectorRelation entity = new ConnectorRelation();

            if (dt != null && dt.Rows.Count > 0)
            {
                entity.SetValues(dt.Rows[0]);
            }
            return(entity);
        }
예제 #4
0
        public bool SaveAccountSettings(XtractConnectorRelation btAccountSettings, int connectorID)
        {
            try
            {
                using (var unit = GetUnitOfWork())
                {
                    var _relationRepo = unit.Scope.Repository <ConnectorRelation>();

                    var user = unit.Scope.Repository <User>().GetSingle(x => x.Username == "SYSTEM");
                    ConcentratorPrincipal.Login("SYSTEM", user.Password);
                    ConnectorRelation exConnectorRelation = _relationRepo.GetSingle(x => x.CustomerID == btAccountSettings.CustomerID);

                    if (exConnectorRelation == null)
                    {
                        exConnectorRelation             = new ConnectorRelation();
                        exConnectorRelation.ConnectorID = connectorID;
                        exConnectorRelation.CustomerID  = btAccountSettings.CustomerID;
                        _relationRepo.Add(exConnectorRelation);
                    }

                    exConnectorRelation.AccountPrivileges      = btAccountSettings.AccountPrivileges;
                    exConnectorRelation.AuthorisationAddresses = btAccountSettings.AuthorisationAddresses;
                    exConnectorRelation.ConnectorType          = btAccountSettings.ConnectorType;
                    exConnectorRelation.FtpAddress             = btAccountSettings.FtpAddress;
                    exConnectorRelation.FtpConnectionType      = btAccountSettings.FtpConnectionType;
                    exConnectorRelation.FtpFrequency           = btAccountSettings.FtpFrequency;
                    exConnectorRelation.FtpPass                      = btAccountSettings.FtpPass;
                    exConnectorRelation.FtpPort                      = btAccountSettings.FtpPort;
                    exConnectorRelation.FtpType                      = btAccountSettings.FtpType;
                    exConnectorRelation.InvoiceConfirmation          = btAccountSettings.InvoiceConfirmation;
                    exConnectorRelation.OutboundInvoiceConfirmation  = btAccountSettings.OutboundInvoiceConfirmation;
                    exConnectorRelation.LanguageID                   = btAccountSettings.LanguageID;
                    exConnectorRelation.OrderConfirmation            = btAccountSettings.OrderConfirmation;
                    exConnectorRelation.OutboundOrderConfirmation    = btAccountSettings.OutboundOrderConfirmation;
                    exConnectorRelation.OutboundMessageType          = btAccountSettings.OutboundMessageType;
                    exConnectorRelation.OutboundPassword             = btAccountSettings.OutboundPassword;
                    exConnectorRelation.OutboundTo                   = btAccountSettings.OutboundTo;
                    exConnectorRelation.OutboundUsername             = btAccountSettings.OutboundUsername;
                    exConnectorRelation.ProviderType                 = btAccountSettings.ProviderType;
                    exConnectorRelation.ShipmentConfirmation         = btAccountSettings.ShipmentConfirmation;
                    exConnectorRelation.OutboundShipmentConfirmation = btAccountSettings.OutboundShipmentConfirmation;
                    exConnectorRelation.UseFtp     = btAccountSettings.UseFtp;
                    exConnectorRelation.XtractType = btAccountSettings.XtractType;

                    unit.Save();
                    return(true);
                }
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
예제 #5
0
        /// <summary>
        /// 修改上游订单
        /// </summary>
        /// <param name="ConnectorEntity"></param>
        /// <param name="orderDic"></param>
        /// <returns></returns>
        public int UpdateUpOrder(ConnectorRelation ConnectorEntity, Dictionary <string, object> orderDic)
        {
            int     upOrderId  = orderDic.ToInt("OrderId", 0);
            decimal upPayables = Utils.ToDecimal(orderDic.ToValue("Payables"));

            if (upOrderId == 0)
            {
                throw new Exception("代下单失败");
            }
            OrderRelationEntity orderRelationEntity = new OrderRelationEntity()
            {
                UpConnectorId   = ConnectorEntity.ThirdConnectorId,
                UpOrderId       = upOrderId,
                UpPayables      = upPayables,
                DownConnectorId = ConnectorEntity.Id,
            };

            return(DbAccess.ExecuteUpdate(TableName, orderRelationEntity, new string[] { "UpConnectorId", "UpOrderId", "DownConnectorId" }));
        }
예제 #6
0
        /// <summary>
        /// 插入订单关联信息
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="oddNumber"></param>
        /// <param name="ConnectorEntity"></param>
        /// <param name="orderDic"></param>
        /// <returns></returns>
        public int Insert(int orderId, string oddNumber, ConnectorRelation ConnectorEntity, Dictionary <string, object> orderDic)
        {
            int    upOrderId   = orderDic.ToInt("OrderId", 0);
            string upOddNumber = orderDic.ToValue("OddNumber");

            if (upOrderId == 0)
            {
                throw new Exception("代下单失败");
            }
            OrderRelationEntity orderRelationEntity = new OrderRelationEntity()
            {
                UpConnectorId   = ConnectorEntity.Id,
                UpOrderId       = upOrderId,
                UpOddNumber     = upOddNumber,
                DownConnectorId = ConnectorEntity.ThirdConnectorId,
                DownOrderId     = orderId,
                DownOddNumber   = oddNumber
            };

            return(DbAccess.ExecuteUpsert(TableName, orderRelationEntity, new string[] { "UpConnectorId", "UpOrderId", "DownConnectorId", "DownOrderId" }));
        }
        protected override void Process()
        {
            using (var unit = GetUnitOfWork())
            {
                var orders = (from o in unit.Scope.Repository <EdiOrder>().GetAll()
                              where o.Status == (int)EdiOrderStatus.Validate
                              select o).ToList();

                int edivendorID    = ediVendor.EdiVendorID;
                var ediValidations = unit.Scope.Repository <EdiValidate>().GetAll(v => v.EdiVendorID == edivendorID).ToList();


                foreach (var order in orders)
                {
                    try
                    {
                        List <string> errorMessages = new List <string>();
                        var           orderResult   = ValidateOrder <EdiOrder>(order, ediValidations, order.EdiOrderID);

                        foreach (var line in orderResult.Keys)
                        {
                            string error = string.Format("Validation failed for order {0}: {1}", line, orderResult[line]);
                            log.AuditError(error, "Validation EDI orders");
                            errorMessages.Add(error);
                        }

                        foreach (var orderLine in order.EdiOrderLines.Where(x => !x.EdiOrderLedgers.Any(y => y.Status == (int)EdiOrderStatus.Validate)))
                        {
                            var orderLineResult = ValidateOrder <EdiOrderLine>(orderLine, ediValidations, orderLine.EdiOrderLineID);

                            foreach (var line in orderLineResult.Keys)
                            {
                                string error = string.Format("Validation failed for orderline {0}: {1}", line, orderLineResult[line]);
                                log.AuditError(error, "Validation EDI orders");
                                errorMessages.Add(error);
                            }

                            orderLine.SetStatus(EdiOrderStatus.Validate, unit);
                        }

                        if (order.ShipToCustomerID.HasValue)
                        {
                            var shipToCustomerResult = ValidateOrder <Customer>(order.ShippedToCustomer, ediValidations, order.ShipToCustomerID.Value);

                            foreach (var line in shipToCustomerResult.Keys)
                            {
                                string error = string.Format("Validation failed for customer {0}: {1}", line, shipToCustomerResult[line]);
                                log.AuditError(error, "Validation EDI orders");
                                errorMessages.Add(error);
                            }
                        }

                        if (order.SoldToCustomerID.HasValue)
                        {
                            var soldToCustomerResult = ValidateOrder <Customer>(order.SoldToCustomer, ediValidations, order.SoldToCustomerID.Value);

                            foreach (var line in soldToCustomerResult.Keys)
                            {
                                string error = string.Format("Validation failed for customer {0}: {1}", line, soldToCustomerResult[line]);
                                log.AuditError(error, "Validation EDI orders");
                                errorMessages.Add(error);
                            }
                        }

                        ConnectorRelation ediRelation = null;
                        if (order.ConnectorRelationID.HasValue)
                        {
                            ediRelation = unit.Scope.Repository <ConnectorRelation>().GetSingle(x => x.ConnectorRelationID == order.ConnectorRelationID.Value);
                        }
                        else
                        {
                            ediRelation = unit.Scope.Repository <ConnectorRelation>().GetSingle(x => x.CustomerID == order.ShippedToCustomer.EANIdentifier);
                        }

                        if (ediRelation == null)
                        {
                            throw new Exception(string.Format("No Edi Customer availible for {0}", order.ShippedToCustomer.EANIdentifier));
                        }
                        order.ConnectorRelationID = ediRelation.ConnectorRelationID;

                        var response = ediProcessor.ValidateOrder(order, ediVendor, ediRelation, Config, unit);
                        unit.Save();

                        if (response.ResponseErrors != null)
                        {
                            errorMessages.AddRange(response.ResponseErrors.Select(x => x.ErrorMessage));
                        }

                        bool skipOrder = false;
                        foreach (var rLine in response.EdiOrderResponseLines.Where(x => x.ResponseErrors.Count > 0))
                        {
                            errorMessages.AddRange(rLine.ResponseErrors.Select(x => x.ErrorMessage + "," + x.ErrorCode));
                            rLine.ResponseErrors.ForEach(error =>
                            {
                                if (error.SkipOrder)
                                {
                                    skipOrder = error.SkipOrder;
                                }
                            });
                        }

                        if (errorMessages.Count > 0)
                        {
                            var listener = unit.Scope.Repository <EdiOrderListener>().GetSingle(x => x.EdiRequestID == order.EdiRequestID);
                            listener.ErrorMessage = string.Join(";", errorMessages);
                            if (skipOrder)
                            {
                                order.Status = (int)EdiOrderStatus.Error;
                            }
                            else
                            {
                                order.Status = (int)EdiOrderStatus.ProcessOrder;
                            }
                        }
                        else
                        {
                            order.Status = (int)EdiOrderStatus.ProcessOrder;
                        }

                        unit.Save();
                    }
                    catch (Exception ex)
                    {
                        order.EdiOrderListener.ErrorMessage = string.Format("Validation failed: {0}", ex.Message);
                        log.AuditError(string.Format("Validation failed for order {0}", order.EdiOrderID), ex, "Validation EDI orders");
                    }
                }
            }
        }
예제 #8
0
        public int ProcessOrderToVendor(EdiOrder order, ConnectorRelation ediRelation, Configuration config)
        {
            string company      = ediRelation.EdiVendor.CompanyCode;
            string businessUnit = string.Empty;

            if (company.Contains("-"))
            {
                businessUnit = company.Split('-')[1];
                company      = company.Split('-')[0];
            }
            string dcto = ediRelation.EdiVendor.DefaultDocumentType;

            #region CreateOrder
            using (JDEDataContext context = new JDEDataContext(ConfigurationManager.ConnectionStrings["JDE"].ConnectionString))
            {
                if (order.isDropShipment.HasValue && order.isDropShipment.Value)
                {
                    #region DropShipment
                    Addresses address = new Addresses();
                    address.AdressType   = '2';
                    address.MailingName  = order.ShippedToCustomer.CustomerName;
                    address.AddressLine1 = order.ShippedToCustomer.CustomerAddressLine1;
                    address.AddressLine2 = order.ShippedToCustomer.CustomerAddressLine2;
                    address.AddressLine3 = order.ShippedToCustomer.CustomerAddressLine3;;
                    if (!string.IsNullOrEmpty(order.ShippedToCustomer.CustomerEmail))
                    {
                        address.AddressLine4 = order.ShippedToCustomer.CustomerEmail;
                    }

                    address.ZIPCode = order.ShippedToCustomer.PostCode;
                    address.City    = order.ShippedToCustomer.City;
                    if (!string.IsNullOrEmpty(order.ShippedToCustomer.Country))
                    {
                        switch (order.ShippedToCustomer.Country)
                        {
                        case "Nederland":
                        case "Nederlands":
                            address.Country = "NL";
                            break;

                        case "United Kingdom":
                            address.Country = "UK";
                            break;

                        default:
                            address.Country = order.ShippedToCustomer.Country;
                            break;
                        }
                    }
                    //else
                    // address.Country = shipToCustomer.Country;

                    address.EDICompany        = company;
                    address.EDIDocumentType   = dcto;
                    address.EDIDocumentNumber = order.EdiRequestID;
                    address.DocumentCompany   = company;
                    address.DocumentType      = dcto;
                    address.FileName          = "F47011";

                    address.TransactionOriginator = ediRelation.EdiVendor.Name;
                    address.UserID    = ediRelation.EdiVendor.Name;
                    address.ProgramID = "EDI";
                    address.Date      = JulianDate.FromDate(System.DateTime.Now).Value;
                    address.Time      = double.Parse(System.DateTime.Now.ToString("HHmmss"));

                    context.Addresses.InsertOnSubmit(address);
                    #endregion
                }

                OrderHeader header = new OrderHeader();

                header.EDICompany        = company;
                header.EDIDocumentType   = dcto;
                header.EDIDocumentNumber = order.EdiRequestID;

                header.DocumentCompany = company;
                header.DocumentType    = dcto;
                header.BusinessUnit    = businessUnit.PadLeft(12);
                header.IsProcessed     = ' ';

                header.EDIMessageType = "850";

                header.EDIOrderReference = order.EdiRequestID.ToString();

                header.CustomerReference    = JdeUtility.FilterValue(order.CustomerOrderReference, 25);
                header.EndCustomerReference = JdeUtility.FilterValue(order.WebSiteOrderNumber, 25);

                //header.SoldToNumber = (double)soldToCustomer.AddressBookNumber.Value;
                header.ShipToNumber = double.Parse(order.ShippedToCustomer.EANIdentifier);
                header.ParentNumber = 0;
                header.IsProcessed  = ' ';

                if (order.RequestDate.HasValue)
                {
                    header.RequestedDate = JulianDate.FromDate(order.RequestDate.Value).Value;
                }
                else
                {
                    header.RequestedDate = JulianDate.FromDate(DateTime.Now.AddDays(1)).Value;
                }

                header.OrderedBy    = ediRelation.EdiVendor.Name;
                header.OrderTakenBy = ediRelation.EdiVendor.OrderBy;

                header.TransactionOriginator = ediRelation.EdiVendor.Name;
                header.UserID    = ediRelation.EdiVendor.Name;
                header.ProgramID = "EDI";
                header.Date      = JulianDate.FromDate(System.DateTime.Now).Value;
                header.Time      = double.Parse(System.DateTime.Now.ToString("HHmmss"));

                if (!string.IsNullOrEmpty(order.HoldCode))
                {
                    header.EDIHoldCode = order.HoldCode;
                }

                if (order.BackOrdersAllowed.HasValue)
                {
                    if (order.BackOrdersAllowed.Value)
                    {
                        header.BackordersAllowed = 'Y';
                    }
                }

                //if (order.OrderExpireDate != null)
                //{
                //  header.EDIExpireDate = JulianDate.FromDate(ediDocument.OrderHeader.OrderExpireDate).Value;
                //}

                #region Details

                double lineNumber = 1000;

                if (!string.IsNullOrEmpty(ediRelation.FreightProduct))
                {
                    OrderRequestDetail freightdetail = new OrderRequestDetail();
                    freightdetail.ProductIdentifier = new ProductIdentifier();
                    freightdetail.ProductIdentifier.ProductNumber = ediRelation.FreightProduct;
                    freightdetail.Quantity = 1;
                    header.OrderDetails.Add(AddOrderDetail(freightdetail, header, lineNumber, context));
                    lineNumber += 1000;
                }

                if (!string.IsNullOrEmpty(ediRelation.FinChargesProduct))
                {
                    OrderRequestDetail finChargesdetail = new OrderRequestDetail();
                    finChargesdetail.ProductIdentifier = new ProductIdentifier();
                    finChargesdetail.ProductIdentifier.ProductNumber = ediRelation.FinChargesProduct;
                    finChargesdetail.Quantity = 1;
                    header.OrderDetails.Add(AddOrderDetail(finChargesdetail, header, lineNumber, context));
                    lineNumber += 1000;
                }

                foreach (EdiOrderLine detail in order.EdiOrderLines)
                {
                    OrderDetail orderDetail = AddOrderDetail(null, detail, header, lineNumber, order.PartialDelivery, context);

                    if (orderDetail != null)
                    {
                        header.OrderDetails.Add(orderDetail);
                        lineNumber += 1000;
                    }
                }

                #endregion
                context.OrderHeaders.InsertOnSubmit(header);
                context.SubmitChanges();

                return(-1);
            }
            #endregion
        }
예제 #9
0
        public List <Objects.Models.EDI.Order.EdiOrder> ProcessOrder(string type, string document, int?connectorID)
        {
            XDocument xdocument = XDocument.Parse(document);

            using (var unit = ServiceLocator.Current.GetInstance <IUnitOfWork>())
            {
                #region ParseXML
                var header   = xdocument.Element("WebOrderRequest").Element("WebOrderHeader");
                var details  = xdocument.Element("WebOrderRequest").Element("WebOrderDetails").Elements("WebOrderDetail");
                var customer = xdocument.Element("WebOrderRequest").Element("WebCustomer");
                var ord      = new
                {
                    OrderHeader = new
                    {
                        isDropShipment =
                            header.Element("CustomerOverride").Element("Dropshipment").Try(
                                c => bool.Parse(c.Value), false),
                        CustomerOrderReference = header.Element("CustomerOrderReference").Value,
                        EdiVersion             = header.Element("EdiVersion").Value,
                        BSKIdentifier          = header.Element("BSKIdentifier").Value,
                        WebSiteOrderNumber     = header.Element("WebSiteOrderNumber").Value,
                        PaymentTermsCode       = header.Element("PaymentTermsCode").Value,
                        PaymentInstrument      = header.Element("PaymentInstrument").Value,
                        BackOrdersAllowed      = header.Try(c => bool.Parse(c.Element("BackOrdersAllowed").Value), false),
                        RouteCode     = header.Try(c => c.Element("RouteCode").Value, string.Empty),
                        EANIdentifier =
                            header.Element("ShipToCustomer").Try(
                                c => c.Element("EanIdentifier").Value, string.Empty).Trim(),
                        HoldCode       = header.Try(c => c.Element("HoldCode").Value, string.Empty),
                        NonDropDetails = new
                        {
                            ShipToShopID =
                                header.Try(c => c.Element("ShipToShopID").Value,
                                           string.Empty)
                        }
                    },
                    Customer = new
                    {
                        Name         = header.Try(dc => dc.Element("CustomerOverride").Element("OrderAddress").Element("Name").Value, string.Empty),
                        AddressLine1 = header.Try(dc => dc.Element("CustomerOverride").Element("OrderAddress").Element("AddressLine1").Value, string.Empty),
                        AddressLine2 = header.Try(dc => dc.Element("CustomerOverride").Element("OrderAddress").Element("AddressLine2").Value, string.Empty),
                        AddressLine3 = header.Try(dc => dc.Element("CustomerOverride").Element("OrderAddress").Element("AddressLine3").Value, string.Empty),
                        HouseNumber  = header.Try(dc => dc.Element("CustomerOverride").Element("OrderAddress").Element("HouseNumber").Value, string.Empty),
                        PostCode     = header.Try(dc => dc.Element("CustomerOverride").Element("OrderAddress").Element("ZipCode").Value, string.Empty),
                        City         = header.Try(dc => dc.Element("CustomerOverride").Element("OrderAddress").Element("City").Value, string.Empty),
                        Country      = header.Try(dc => dc.Element("CustomerOverride").Element("OrderAddress").Element("Country").Value, string.Empty),
                        Email        = header.Try(dc => dc.Element("CustomerOverride").Element("CustomerContact").Element("Email").Value, string.Empty)
                    },
                    OrderLines = (from o in details
                                  let custReference = o.Element("CustomerReference")
                                                      let product = o.Element("ProductIdentifier")
                                                                    select new
                    {
                        CustomerReference = custReference == null ? null : new
                        {
                            CustomerOrder = custReference.Try(c => c.Element("CustomerOrder").Value, string.Empty),
                            CustomerOrderLine = custReference.Try(c => c.Element("CustomerOrderLine").Value, string.Empty),
                            CustomerItemNumber = custReference.Try(c => c.Element("CustomerItemNumber").Value, string.Empty)
                        },
                        Product = product == null ? null : new
                        {
                            ID = product.Element("ProductNumber").Value,
                            EAN = product.Try(c => c.Element("EANIdentifier").Value, string.Empty),
                            ManufacturerItemID = product.Try(c => c.Element("ManufacturerItemID").Value, string.Empty),
                            Qty = o.Try(c => int.Parse(c.Element("Quantity").Value), 1),
                            VendorItemNumber = o.Try(c => c.Element("VendorItemNumber").Value, string.Empty),
                            WarehouseCode = o.Try(c => c.Element("WareHouseCode").Value, string.Empty),
                            UnitPrice = o.Try(c => double.Parse(c.Element("UnitPrice").Value) / 10000, 0),
                            PriceOverride = o.Try(c => bool.Parse(c.Element("PriceOverride").Value), false)
                        }
                    }).ToList(),
                    CustomerContactInfo = customer == null ? null : new
                    {
                        Name         = customer.Try(c => c.Element("CustomerAddress").Element("Name").Value, string.Empty),
                        AddressLine1 = customer.Try(c => c.Element("CustomerAddress").Element("AddressLine1").Value, string.Empty),
                        AddressLine2 = customer.Try(c => c.Element("CustomerAddress").Element("AddressLine2").Value, string.Empty),
                        AddressLine3 = customer.Try(c => c.Element("CustomerAddress").Element("AddressLine3").Value, string.Empty),
                        Number       = customer.Try(c => c.Element("CustomerAddress").Element("Number").Value, string.Empty),
                        ZipCode      = customer.Try(c => c.Element("CustomerAddress").Element("ZipCode").Value, string.Empty),
                        City         = customer.Try(c => c.Element("CustomerAddress").Element("City").Value, string.Empty),
                        Country      = customer.Try(c => c.Element("CustomerAddress").Element("Country").Value, string.Empty),
                        Email        = customer.Try(c => c.Element("CustomerContact").Element("Email").Value, string.Empty),
                        CompanyName  = customer.Try(c => c.Element("CustomerContact").Element("Name").Value, string.Empty),
                        CoCNumber    = customer.Try(c => c.Element("CustomerContact").Element("CoCNumber").Value, string.Empty)
                    }
                };
                #endregion

                #region Dropshipment/Non-Drop

                //Customer customerE = (from c in context.Customers
                //                      where c.EANIdentifier == ord.OrderHeader.EANIdentifier
                //                      select c).FirstOrDefault();

                //if (customerE == null ||  ord.OrderHeader.EANIdentifier == "0")
                //{
                Concentrator.Objects.Models.Orders.Customer customerE = new Concentrator.Objects.Models.Orders.Customer
                {
                    EANIdentifier = ord.OrderHeader.EANIdentifier
                };
                unit.Scope.Repository <Concentrator.Objects.Models.Orders.Customer>().Add(customerE);
                //}
                if (ord.Customer != null)
                {
                    customerE.CustomerAddressLine1 = ord.Customer.AddressLine1;
                    customerE.CustomerAddressLine2 = ord.Customer.AddressLine2;
                    customerE.CustomerAddressLine3 = ord.Customer.AddressLine3;
                    customerE.HouseNumber          = ord.Customer.HouseNumber;
                    customerE.City          = ord.Customer.City;
                    customerE.Country       = ord.Customer.Country;
                    customerE.PostCode      = ord.Customer.PostCode;
                    customerE.CustomerName  = ord.Customer.Name;
                    customerE.CustomerEmail = ord.Customer.Email;//ord.Try(c => c.CustomerContactInfo.Email, string.Empty);
                }

                Concentrator.Objects.Models.Orders.Customer customerS = null;
                if (ord.CustomerContactInfo != null)
                {
                    customerS = new Concentrator.Objects.Models.Orders.Customer
                    {
                        EANIdentifier = null
                    };
                    customerS.CustomerAddressLine1 = ord.CustomerContactInfo.AddressLine1;
                    customerS.CustomerAddressLine2 = ord.CustomerContactInfo.AddressLine2;
                    customerS.CustomerAddressLine3 = ord.CustomerContactInfo.AddressLine3;
                    customerS.HouseNumber          = ord.CustomerContactInfo.Number;
                    customerS.City          = ord.CustomerContactInfo.City;
                    customerS.Country       = ord.CustomerContactInfo.Country;
                    customerS.PostCode      = ord.CustomerContactInfo.ZipCode;
                    customerS.CustomerName  = ord.CustomerContactInfo.Name;
                    customerS.CustomerEmail = ord.CustomerContactInfo.Email;
                    customerS.CoCNumber     = ord.CustomerContactInfo.CoCNumber;

                    unit.Scope.Repository <Concentrator.Objects.Models.Orders.Customer>().Add(customerS);
                }

                if (!connectorID.HasValue)
                {
                    ConnectorRelation rel = unit.Scope.Repository <ConnectorRelation>().GetSingle(x => x.CustomerID == customerE.EANIdentifier);

                    if (rel == null || !rel.ConnectorID.HasValue)
                    {
                        throw new Exception("No Connector Relation found for numer" + customerE.EANIdentifier);
                    }
                    else
                    {
                        connectorID = rel.ConnectorID.Value;
                    }
                }

                EdiOrder newOrd = new EdiOrder()
                {
                    ShippedToCustomer      = customerE,
                    SoldToCustomer         = customerS,
                    Document               = document,
                    ConnectorID            = connectorID.Value,
                    isDropShipment         = ord.OrderHeader.isDropShipment,
                    ReceivedDate           = DateTime.Now,
                    BackOrdersAllowed      = ord.OrderHeader.BackOrdersAllowed,
                    CustomerOrderReference = ord.OrderHeader.CustomerOrderReference,
                    EdiVersion             = ord.OrderHeader.EdiVersion,
                    BSKIdentifier          = int.Parse(ord.OrderHeader.BSKIdentifier),
                    WebSiteOrderNumber     = ord.OrderHeader.WebSiteOrderNumber,
                    PaymentInstrument      = ord.OrderHeader.PaymentInstrument,
                    PaymentTermsCode       = ord.OrderHeader.PaymentTermsCode,
                    RouteCode              = ord.OrderHeader.RouteCode,
                    HoldCode               = ord.OrderHeader.HoldCode
                };
                #endregion
                var orderRepo      = unit.Scope.Repository <EdiOrder>();
                var duplicateOrder = orderRepo.GetSingle(d => d.ConnectorID == newOrd.ConnectorID &&
                                                         d.WebSiteOrderNumber == newOrd.WebSiteOrderNumber);


                if (duplicateOrder != null)
                {
                    newOrd.HoldOrder = true;
                }
                else
                {
                    newOrd.HoldOrder = false;
                }

                orderRepo.Add(newOrd);

                #region Order Lines
                foreach (var line in ord.OrderLines)
                {
                    int?productid = null;
                    var product   = unit.Scope.Repository <Concentrator.Objects.Models.Products.Product>().GetSingle(p => p.ProductID == int.Parse(line.Product.ID));

                    if (product != null)
                    {
                        productid = product.ProductID;
                    }

                    EdiOrderLine ol = new EdiOrderLine
                    {
                        CustomerEdiOrderLineNr = line.CustomerReference.CustomerOrderLine,
                        CustomerOrderNr        = line.CustomerReference.CustomerOrder,
                        CustomerItemNumber     = line.CustomerReference.CustomerItemNumber,
                        EdiOrder      = newOrd,
                        Quantity      = line.Product.Qty,
                        ProductID     = productid,
                        Price         = line.Product.UnitPrice,
                        WareHouseCode = line.Product.WarehouseCode,
                        PriceOverride = line.Product.PriceOverride,
                        EdiProductID  = line.Product.ID
                    };

                    unit.Scope.Repository <EdiOrderLine>().Add(ol);
                }
                #endregion

                unit.Save();

                return(new List <EdiOrder>()
                {
                    newOrd
                });
            }
        }
예제 #10
0
        protected override void Process()
        {
            using (var unit = GetUnitOfWork())
            {
                using (Concentrator.Web.ServiceClient.EDI.CommunicationServiceSoapClient client = new Concentrator.Web.ServiceClient.EDI.CommunicationServiceSoapClient())
                {
                    var ediSettings = client.GetRelationSettings();
                    using (TextReader reader = new StringReader(ediSettings))
                    {
                        XmlSerializer x = new XmlSerializer(typeof(List <RelationCommunicationProperty>));
                        List <RelationCommunicationProperty> ediRelationSettings = (List <RelationCommunicationProperty>)x.Deserialize(reader);
                        var relationRepository = unit.Scope.Repository <ConnectorRelation>();
                        var connectorRelations = relationRepository.GetAll().ToList();

                        foreach (var ediRelation in ediRelationSettings)
                        {
                            var connectorRelation = connectorRelations.FirstOrDefault(y => y.CustomerID == ediRelation.RelationNumber.ToString());

                            if (connectorRelation == null)
                            {
                                connectorRelation = new ConnectorRelation()
                                {
                                    CustomerID                   = ediRelation.RelationNumber.ToString(),
                                    OrderConfirmation            = ediRelation.OrderConfirmation,
                                    OutboundOrderConfirmation    = ediRelation.OrderConfirmationEmail,
                                    ShipmentConfirmation         = ediRelation.ShipmentConfirmation,
                                    OutboundShipmentConfirmation = ediRelation.ShipmentConfirmationEmail,
                                    InvoiceConfirmation          = ediRelation.InvoiceConfirmation,
                                    OutboundInvoiceConfirmation  = ediRelation.InvoiceConfirmationEmail,
                                    OutboundTo                   = ediRelation.OutboundTo,
                                    OutboundPassword             = ediRelation.OutboundPassword,
                                    OutboundUsername             = ediRelation.OutboundUsername,
                                    ConnectorType                = ediRelation.ConnectorType.Try <string, int?>(c => int.Parse(c), null),
                                    OutboundMessageType          = ediRelation.OutboundMessageType.Try <string, int?>(c => int.Parse(c), null),
                                    LanguageID                   = 1,
                                    AccountPrivileges            = (int)AccountPrivilegesEnum.XtractS,
                                    XtractType                   = (int)XractTypeEnum.WebshopPriceList
                                };

                                relationRepository.Add(connectorRelation);
                                connectorRelations.Add(connectorRelation);
                                unit.Save();
                            }
                        }

                        foreach (var relationCommunication in connectorRelations)
                        {
                            var ediRelation = ediRelationSettings.FirstOrDefault(y => y.RelationNumber == int.Parse(relationCommunication.CustomerID));

                            if (ediRelation != null)
                            {
                                if (relationCommunication.OrderConfirmation != ediRelation.OrderConfirmation ||
                                    relationCommunication.OutboundOrderConfirmation != ediRelation.OrderConfirmationEmail ||
                                    relationCommunication.ShipmentConfirmation != ediRelation.ShipmentConfirmation ||
                                    relationCommunication.OutboundShipmentConfirmation != ediRelation.ShipmentConfirmationEmail ||
                                    relationCommunication.InvoiceConfirmation != ediRelation.InvoiceConfirmation ||
                                    relationCommunication.OutboundInvoiceConfirmation != ediRelation.InvoiceConfirmationEmail ||
                                    relationCommunication.OutboundTo != ediRelation.OutboundTo ||
                                    relationCommunication.OutboundPassword != ediRelation.OutboundPassword ||
                                    relationCommunication.OutboundUsername != ediRelation.OutboundUsername ||
                                    relationCommunication.ConnectorType.ToString() != ediRelation.ConnectorType ||
                                    relationCommunication.OutboundMessageType.ToString() != ediRelation.OutboundMessageType)
                                {
                                    RelationCommunicationProperty property = new RelationCommunicationProperty()
                                    {
                                        RelationNumber            = int.Parse(relationCommunication.CustomerID),
                                        OrderConfirmation         = relationCommunication.OrderConfirmation,
                                        OrderConfirmationEmail    = relationCommunication.OutboundOrderConfirmation,
                                        ShipmentConfirmation      = relationCommunication.ShipmentConfirmation,
                                        ShipmentConfirmationEmail = relationCommunication.OutboundShipmentConfirmation,
                                        InvoiceConfirmation       = relationCommunication.InvoiceConfirmation,
                                        InvoiceConfirmationEmail  = relationCommunication.OutboundInvoiceConfirmation,
                                        OutboundTo          = relationCommunication.OutboundTo,
                                        OutboundPassword    = relationCommunication.OutboundPassword,
                                        OutboundUsername    = relationCommunication.OutboundUsername,
                                        ConnectorType       = relationCommunication.ConnectorType.ToString(),
                                        OutboundMessageType = relationCommunication.OutboundMessageType.ToString()
                                    };

                                    client.UpdateRelationSettings(property);
                                }
                            }
                            else if (string.IsNullOrEmpty(relationCommunication.OutboundTo))
                            {
                                relationRepository.Delete(relationCommunication);
                            }
                            unit.Save();
                        }
                    }
                }
            }
        }
예제 #11
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");
        }