private OrderGraphicObject(Order order)
            : base(order)
        {
            _order = order;
            _order.PropertyChanged += new PropertyChangedEventHandler(_order_PropertyChanged);

            Geometry = _CreatePoint(order);
        }
        protected override List<Guid> GetOrderSpecIds(Order order)
        {
            List<Guid> specs = base.GetOrderSpecIds(order);

            if (_setAssignmentSpec && _unlockedOrdersToAssign.Contains(order))
                specs.Add(ASSIGNMENT_SPEC_ID);

            return specs;
        }
        public void Execute(params object[] args)
        {
            m_application.Messenger.AddInfo("Executing import from QuickBooks.");

            int countOrdersAdded     = 0;
            QBSessionManager session = null;

            try
            {
                // Start session with QuickBooks
                session = new QBSessionManager();

                session.OpenConnection("123", "ArcLogistics PlugIn: QuickBooksPlugIns.ImportOrdersFromInvoicesCmd");
                session.BeginSession("", ENOpenMode.omDontCare);

                IInvoiceRetList invoiceList  = QueryInvoices(session);
                int             invoiceCount = invoiceList.Count;

                for (int i = 0; i < invoiceCount; i++)
                {
                    IInvoiceRet invoiceRet = invoiceList.GetAt(i);

                    ESRI.ArcLogistics.DomainObjects.Order newOrder = MakeOrderFromInvoice(invoiceRet, session);

                    m_application.Project.Orders.Add(newOrder);

                    countOrdersAdded++;
                }
            }

            catch (Exception e)
            {
                m_application.Messenger.AddError("Error executing QuickBooksPlugIns.ImportOrdersFromInvoicesCmd: " + e.Message);
            }

            finally
            {
                // Close connection because we don't need it anymore
                if (session != null)
                {
                    session.EndSession();
                    session.CloseConnection();
                }

                m_application.Project.Save();

                m_application.Messenger.AddInfo(countOrdersAdded.ToString() + " orders added.");
            }
        }
        /// <summary>
        /// Create graphic object for order
        /// </summary>
        /// <param name="order">Source order</param>
        /// <returns>Graphic object for order</returns>
        public static OrderGraphicObject Create(Order order)
        {
            OrderGraphicObject graphic = null;

            graphic = new OrderGraphicObject(order);

            Color color = Color.FromRgb(0, 0, 0);
            graphic.Attributes.Add(SymbologyContext.FILL_ATTRIBUTE_NAME, new SolidColorBrush(color));
            graphic.Attributes.Add(SymbologyContext.OFFSETX_ATTRIBUTE_NAME,
                -(SymbologyManager.DEFAULT_SIZE - SymbologyManager.DEFAULT_INDENT / 2));
            graphic.Attributes.Add(SymbologyContext.OFFSETY_ATTRIBUTE_NAME,
                -(SymbologyManager.DEFAULT_SIZE - SymbologyManager.DEFAULT_INDENT / 2));
            graphic.Attributes.Add(SymbologyContext.SIZE_ATTRIBUTE_NAME, SymbologyManager.DEFAULT_SIZE);
            graphic.Attributes.Add(SymbologyContext.FULLSIZE_ATTRIBUTE_NAME,
                SymbologyManager.DEFAULT_SIZE + SymbologyManager.DEFAULT_INDENT);

            SymbologyManager.InitGraphic(graphic);

            return graphic;
        }
        /// <summary>
        /// Create map point for order
        /// </summary>
        /// <param name="order">Order to get geometry</param>
        /// <returns>Map point of order position</returns>
        private ESRI.ArcGIS.Client.Geometry.MapPoint _CreatePoint(Order order)
        {
            ESRI.ArcGIS.Client.Geometry.MapPoint point = null;

            // if order geocoded - create point
            if (order.GeoLocation.HasValue)
            {
                ESRI.ArcLogistics.Geometry.Point geoLocation = order.GeoLocation.Value;

                // Project point from WGS84 to Web Mercator if spatial reference of map is Web Mercator
                if (ParentLayer != null && ParentLayer.SpatialReferenceID != null)
                {
                    geoLocation = WebMercatorUtil.ProjectPointToWebMercator(geoLocation, ParentLayer.SpatialReferenceID.Value);
                }

                point = new ESRI.ArcGIS.Client.Geometry.MapPoint(geoLocation.X, geoLocation.Y);
            }
            else
            {
                point = null;
            }

            return point;
        }
Пример #6
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Checks is order locked.
        /// </summary>
        /// <param name="order">Order to check.</param>
        /// <param name="schedule">Schedule to check.</param>
        /// <returns>TRUE if order has stops belong schedule and this route or stop is locked.</returns>
        public static bool IsOrderLocked(Order order, Schedule schedule)
        {
            Debug.Assert(order != null);
            Debug.Assert(schedule != null);

            bool isLocked = order.Stops.Any(stop =>
                                                (null != stop.Route) &&
                                                stop.Route.Schedule.Equals(schedule) &&
                                                (stop.Route.IsLocked || stop.IsLocked));
            return isLocked;
        }
Пример #7
0
        private void processOrders(string path)
        {
            DataTable table = new DataTable();
            table = ReadCSV(path);

            foreach (DataRow row in table.Rows)
            {
                // Create New empty Order
                CapacitiesInfo capInfo = m_application.Project.CapacitiesInfo;
                OrderCustomPropertiesInfo propInfo = m_application.Project.OrderCustomPropertiesInfo;
                ESRI.ArcLogistics.DomainObjects.Order resultOrder = new ESRI.ArcLogistics.DomainObjects.Order(capInfo, propInfo);

                OrderCustomPropertiesInfo orderPropertiesInfo = resultOrder.CustomPropertiesInfo;
                OrderCustomProperties orderProperties = resultOrder.CustomProperties;
                CapacitiesInfo orderCapacitiesInfo = resultOrder.CapacitiesInfo;
                Capacities orderCapacities = resultOrder.Capacities;
                bool geocodeProvided = false;
                bool geocodeCorrect = false;
                double tempD;
                DateTime TWdateTime;
                Double tempX = 0.0;
                Double tempY = 0.0;

                // Insert Order Information
                resultOrder.PlannedDate = m_application.CurrentDate;

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    try
                    {
                        switch (table.Columns[i].ColumnName)
                        {
                            #region Case Statements
                            case "Name": resultOrder.Name = row["Name"].ToString(); break;
                            case "Address": resultOrder.Address.AddressLine = row["Address"].ToString(); break;
                            case "City": resultOrder.Address.Locality3 = row["City"].ToString(); break;
                            case "State": resultOrder.Address.StateProvince = row["State"].ToString(); break;
                            case "Zip": resultOrder.Address.PostalCode1 = row["Zip"].ToString(); break;
                            case "Zip4": resultOrder.Address.PostalCode2 = row["Zip4"].ToString(); break;
                            case "Country": resultOrder.Address.Country = row["Country"].ToString(); break;

                            case "PlannedDate":
                                DateTime tempDT = new DateTime();
                                if (System.DateTime.TryParse(row["PlannedDate"].ToString(), out tempDT))
                                    resultOrder.PlannedDate = tempDT;
                                break;

                            case "Priority":
                                if (row["Priority"].ToString() == "High") resultOrder.Priority = OrderPriority.High;
                                else if (row["Priority"].ToString() == "Normal") resultOrder.Priority = OrderPriority.Normal;
                                break;

                            case "OrderType":
                                if (row["OrderType"].ToString() == "Pickup") resultOrder.Type = OrderType.Pickup;
                                else if (row["OrderType"].ToString() == "Delivery") resultOrder.Type = OrderType.Delivery;
                                break;

                            case "ServiceTime":
                                if (Double.TryParse(row["ServiceTime"].ToString(), out tempD))
                                    resultOrder.ServiceTime = tempD;
                                break;

                            case "TimeWindowStart":
                                string tempS = row["TimeWindowStart"].ToString();
                                if (DateTime.TryParse(tempS, out TWdateTime))
                                {
                                    if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                                    {
                                        resultOrder.TimeWindow.From = TWdateTime.TimeOfDay;
                                        resultOrder.TimeWindow.IsWideOpen = false;
                                    }
                                }
                                break;

                            case "TimeWindowFinish":
                                if (DateTime.TryParse(row["TimeWindowFinish"].ToString(), out TWdateTime))
                                {
                                    if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                                    {
                                        resultOrder.TimeWindow.To = TWdateTime.TimeOfDay;
                                        resultOrder.TimeWindow.IsWideOpen = false;
                                    }
                                }
                                break;

                            case "TimeWindow2Start":

                                if (DateTime.TryParse(row["TimeWindow2Start"].ToString(), out TWdateTime))
                                {
                                    if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                                    {
                                        resultOrder.TimeWindow2.From = TWdateTime.TimeOfDay;
                                        resultOrder.TimeWindow2.IsWideOpen = false;
                                    }
                                }
                                break;

                            case "TimeWindow2Finish":

                                if (DateTime.TryParse(row["TimeWindow2Finish"].ToString(), out TWdateTime))
                                {
                                    if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                                    {
                                        resultOrder.TimeWindow2.To = TWdateTime.TimeOfDay;
                                        resultOrder.TimeWindow2.IsWideOpen = false;
                                    }
                                }
                                break;

                            case "MaxViolationTime":
                                if (Double.TryParse(row["MaxViolationTime"].ToString(), out tempD))
                                    resultOrder.MaxViolationTime = tempD;
                                break;

                            case "VehicleSpecialties":
                                if (row["VehicleSpecialties"].ToString() != "")
                                {
                                    string[] stringSeparators = new string[] { ";", "," };
                                    string[] specialties = row["VehicleSpecialties"].ToString().Split(stringSeparators, StringSplitOptions.None);
                                    foreach (string s in specialties)
                                    {
                                        VehicleSpecialty vs = new VehicleSpecialty();
                                        vs.Name = s;
                                        foreach (VehicleSpecialty V in m_application.Project.VehicleSpecialties)
                                        {
                                            if (String.Compare(V.Name, vs.Name, true) == 0)
                                            {
                                                V.CopyTo(vs);
                                                m_application.Project.VehicleSpecialties.Remove(V);
                                                break;
                                            }
                                        }
                                        m_application.Project.VehicleSpecialties.Add(vs);
                                        resultOrder.VehicleSpecialties.Add(vs);
                                    }
                                }
                                break;

                            case "DriverSpecialties":
                                if (row["DriverSpecialties"].ToString() != "")
                                {
                                    string[] stringSeparators2 = new string[] { ";", "," };
                                    string[] specialties2 = row["DriverSpecialties"].ToString().Split(stringSeparators2, StringSplitOptions.None);
                                    foreach (string s in specialties2)
                                    {
                                        DriverSpecialty ds = new DriverSpecialty();
                                        ds.Name = s;

                                        foreach (DriverSpecialty D in m_application.Project.DriverSpecialties)
                                        {
                                            if (String.Compare(D.Name, ds.Name, true) == 0)
                                            {
                                                D.CopyTo(ds);
                                                m_application.Project.DriverSpecialties.Remove(D);
                                                break;
                                            }
                                        }
                                        m_application.Project.DriverSpecialties.Add(ds);
                                        resultOrder.DriverSpecialties.Add(ds);
                                    }
                                }
                                break;

                            case "X":
                                string x = row["X"].ToString();
                                if (x != "" && x != null)
                                    if (Double.TryParse(row["X"].ToString(), out tempX))
                                    {
                                        if (tempX >= -180.0 && tempX <= 180.0 && tempX != 0.0)
                                        {
                                            geocodeProvided = true;
                                            geocodeCorrect = true;
                                        }
                                        else if (tempX == 0.0)
                                            geocodeCorrect = true;
                                    }

                                break;

                            case "Y":
                                string y = row["Y"].ToString();
                                if (y != "" && y != null)
                                    if (Double.TryParse(row["Y"].ToString(), out tempY))
                                    {
                                        if (tempY >= -90.0 && tempY <= 90.0 && tempY != 0)
                                        {
                                            geocodeProvided = true;
                                            geocodeCorrect = true;
                                        }
                                        else if (tempY == 0.0)
                                            geocodeCorrect = true;
                                    }

                                break;
                            #endregion
                        }// End Switch

                        if (orderProperties.Count > 0 )
                        {
                            OrderCustomProperty orderPropertyInfoItem = null;
                            for (int j = 0; j < orderPropertiesInfo.Count; j++)
                            {
                                orderPropertyInfoItem = orderPropertiesInfo.ElementAt(j) as OrderCustomProperty;
                                string tempName = orderPropertyInfoItem.Name.Replace(" ", "");
                                if (tempName == table.Columns[i].ColumnName)
                                {
                                    orderProperties[j] = (row[table.Columns[i].ToString()].ToString());
                                    break;
                                }
                            }
                        }

                        if( orderCapacities.Count > 0)
                        {
                            CapacityInfo orderCapacityInfoItem = null;
                            for (int k = 0; k < orderCapacitiesInfo.Count; k++)
                            {
                                orderCapacityInfoItem = orderCapacitiesInfo.ElementAt(k);
                                string tempName = orderCapacityInfoItem.Name.Replace(" ", "");
                                if (tempName == table.Columns[i].ColumnName)
                                {
                                    if(Double.TryParse(row[table.Columns[i].ToString()].ToString(), out tempD))
                                        orderCapacities[k] = tempD;

                                    break;
                                }
                            }

                        }
                    }
                    catch (Exception e)
                    {
                        string statusMessage = " Import from " + Params.Instance.importName + " encountered a problem: " + e.Message;
                        m_application.Messenger.AddError(statusMessage);
                    }
                }

                    resultOrder.CustomProperties = orderProperties;
                    resultOrder.Capacities = orderCapacities;

                if (geocodeProvided && geocodeCorrect)
                {
                    AddressCandidate candidate1 = new AddressCandidate();
                    ESRI.ArcLogistics.Geometry.Point p = new ESRI.ArcLogistics.Geometry.Point(tempX, tempY);
                    candidate1.GeoLocation = p;
                    candidate1.Score = 100;
                    candidate1.Address = resultOrder.Address;

                    resultOrder.GeoLocation = candidate1.GeoLocation;

                }
                else
                {
                    AddressCandidate candidate = m_application.Geocoder.Geocode(resultOrder.Address);
                    if (candidate != null)
                        resultOrder.GeoLocation = candidate.GeoLocation;
                    else
                    {
                        //TODO: Handle orders which were not geocoded!!
                    }
                }

                // Add Order
                m_application.Project.Orders.Add(resultOrder);
            }
        }
        /// <summary>
        /// Returns text that has to be shown in time windows section.
        /// </summary>
        /// <param name="order"></param>
        /// <returns></returns>
        private string _GetTimeWindowsText(Order order)
        {
            string twText;
            if (order.TimeWindow.IsWideOpen && order.TimeWindow2.IsWideOpen)
                twText = order.TimeWindow.ToString();

            else if (!order.TimeWindow.IsWideOpen && order.TimeWindow2.IsWideOpen)
                twText = order.TimeWindow.ToString();

            else if (order.TimeWindow.IsWideOpen && !order.TimeWindow2.IsWideOpen)
                twText = order.TimeWindow2.ToString();

            else
            {
                StringBuilder strBuilder = new StringBuilder();
                strBuilder.Append(order.TimeWindow.ToString());
                strBuilder.Append(TIME_WINDOWS_SEPARATOR);
                strBuilder.Append(order.TimeWindow2.ToString());

                twText = strBuilder.ToString();
            }

            return twText;
        }
        private ESRI.ArcLogistics.DomainObjects.Order MakeOrderFromInvoice(IInvoiceRet invoiceRet, QBSessionManager session)
        {
            ESRI.ArcLogistics.DomainObjects.Order resultOrder = null;

            ICustomerRet customerRet = QueryCustomer(session, invoiceRet.CustomerRef.FullName.GetValue());

            CapacitiesInfo            capInfo  = m_application.Project.CapacitiesInfo;
            OrderCustomPropertiesInfo propInfo = m_application.Project.OrderCustomPropertiesInfo;

            resultOrder = new ESRI.ArcLogistics.DomainObjects.Order(capInfo, propInfo);

            resultOrder.PlannedDate = m_application.CurrentDate;
            if (customerRet.ParentRef != null)
            {
                resultOrder.Name = customerRet.ParentRef.FullName.GetValue();
            }
            else
            {
                resultOrder.Name = customerRet.FullName.GetValue();
            }

            IAddress useAddress = null;

            if (customerRet.ShipAddress != null)
            {
                useAddress = customerRet.ShipAddress;
            }
            else if (customerRet.BillAddress != null)
            {
                useAddress = customerRet.BillAddress;
            }
            else
            {
                m_application.Messenger.AddWarning("No address for: " + resultOrder.Name);
            }

            if (useAddress != null)
            {
                if (useAddress.Addr2 != null)
                {
                    resultOrder.Address.AddressLine = useAddress.Addr2.GetValue();
                }
                else
                {
                    resultOrder.Address.AddressLine = useAddress.Addr1.GetValue();
                }

                resultOrder.Address.Locality3     = useAddress.City.GetValue();
                resultOrder.Address.StateProvince = useAddress.State.GetValue();
                resultOrder.Address.PostalCode1   = useAddress.PostalCode.GetValue();

                AddressCandidate candidate = m_application.Geocoder.Geocode(resultOrder.Address);

                resultOrder.GeoLocation = candidate.GeoLocation;
            }

            // Look in the order custom properties for matching invoice detail items (by item description).
            // Look in the order capacities for matching item type custom fields.

            OrderCustomPropertiesInfo orderPropertiesInfo = resultOrder.CustomPropertiesInfo;
            OrderCustomProperties     orderProperties     = resultOrder.CustomProperties;

            CapacitiesInfo orderCapacitiesInfo = resultOrder.CapacitiesInfo;
            Capacities     orderCapacities     = resultOrder.Capacities;

            // Retrieve invoice line list
            // Each line can be either InvoiceLineRet OR InvoiceLineGroupRet

            IORInvoiceLineRetList orInvoiceLineRetList = invoiceRet.ORInvoiceLineRetList;

            if (orInvoiceLineRetList != null && (orderProperties.Count > 0 || orderCapacities.Count > 0))
            {
                int lineCount = orInvoiceLineRetList.Count;
                for (int i = 0; i < lineCount; i++)
                {
                    IORInvoiceLineRet orInvoiceLineRet = orInvoiceLineRetList.GetAt(i);

                    // Check what to retrieve from the orInvoiceLineRet object
                    // based on the "ortype" property.  Skip summary lines.

                    if (orInvoiceLineRet.ortype != ENORInvoiceLineRet.orilrInvoiceLineRet)
                    {
                        continue;
                    }

                    if (orInvoiceLineRet.InvoiceLineRet.ItemRef.FullName != null)
                    {
                        string itemName     = orInvoiceLineRet.InvoiceLineRet.ItemRef.FullName.GetValue();
                        double itemQuantity = 0;
                        if (orInvoiceLineRet.InvoiceLineRet.ItemRef != null)
                        {
                            itemQuantity = System.Convert.ToDouble(orInvoiceLineRet.InvoiceLineRet.Quantity.GetValue());
                        }

                        // look for matching custom order property

                        OrderCustomProperty orderPropertyInfoItem = null;
                        for (int j = 0; j < orderPropertiesInfo.Count; j++)
                        {
                            orderPropertyInfoItem = orderPropertiesInfo.ElementAt(j) as OrderCustomProperty;
                            if (orderPropertyInfoItem.Name == itemName)
                            {
                                if (orderPropertyInfoItem.Type == OrderCustomPropertyType.Numeric)
                                {
                                    orderProperties[j] = itemQuantity;
                                }
                                else
                                {
                                    orderProperties[j] = itemQuantity.ToString();
                                }

                                break;
                            }
                        }

                        // look for matching capacity

                        // need to lookup item record so we get the extra field(s)
                        // TODO: It might be a good idea to cache these locally to avoid
                        // excess QB queries.

                        IORItemRet      orItemRet             = QueryItem(session, itemName);
                        IDataExtRetList custItemFieldsRetList = null;

                        switch (orItemRet.ortype)
                        {
                        case ENORItemRet.orirItemServiceRet:
                        {
                            // orir prefix comes from OR + Item + Ret
                            IItemServiceRet ItemServiceRet = orItemRet.ItemServiceRet;
                            custItemFieldsRetList = ItemServiceRet.DataExtRetList;
                        }
                        break;

                        case ENORItemRet.orirItemInventoryRet:
                        {
                            IItemInventoryRet ItemInventoryRet = orItemRet.ItemInventoryRet;
                            custItemFieldsRetList = ItemInventoryRet.DataExtRetList;
                        }
                        break;

                        case ENORItemRet.orirItemNonInventoryRet:
                        {
                            IItemNonInventoryRet ItemNonInventoryRet = orItemRet.ItemNonInventoryRet;
                            custItemFieldsRetList = ItemNonInventoryRet.DataExtRetList;
                        }
                        break;
                        }

                        int custItemFieldCount = 0;
                        if (custItemFieldsRetList != null)
                        {
                            custItemFieldCount = custItemFieldsRetList.Count;
                        }

                        for (int j = 0; j < custItemFieldCount; j++)
                        {
                            IDataExtRet custItemField     = custItemFieldsRetList.GetAt(j);
                            string      custItemFieldName = custItemField.DataExtName.GetValue();

                            CapacityInfo orderCapacityInfoItem = null;
                            for (int k = 0; k < orderCapacitiesInfo.Count; k++)
                            {
                                orderCapacityInfoItem = orderCapacitiesInfo.ElementAt(k);
                                if (orderCapacityInfoItem.Name == custItemFieldName)
                                {
                                    orderCapacities[k] += System.Convert.ToDouble(custItemField.DataExtValue.GetValue()) * itemQuantity;

                                    break;
                                }
                            }
                        }
                    }
                }
            }

            resultOrder.CustomProperties = orderProperties;
            resultOrder.Capacities       = orderCapacities;

            return(resultOrder);
        }
Пример #10
0
 /// <summary>
 /// Add priority if it High
 /// </summary>
 /// <param name="order">Source order</param>
 /// <param name="inlines">Inlines to fill</param>
 private static void _AddPriorityIfNeeded(Order order, InlineCollection inlines)
 {
     if (order.Priority == OrderPriority.High)
     {
         string priority = order.Priority.ToString();
         _AddLine(_priorityCaption, priority, inlines, false);
     }
 }
        /// <summary>
        /// Method converts pickup and delivery orders into GPFeature.
        /// </summary>
        /// <param name="pickupOrder">Order.</param>
        /// <param name="deliveryOrder">Order.</param>
        /// <returns>OrderPair GPFeature.</returns>
        private GPFeature _ConvertOrderPair(Order pickupOrder, Order deliveryOrder)
        {
            Debug.Assert(pickupOrder != null && deliveryOrder != null);

            GPFeature feature = new GPFeature();

            // Attributes.
            AttrDictionary attrs = new AttrDictionary();

            // Pickup Name.
            attrs.Add(NAAttribute.FIRST_ORDER_NAME, pickupOrder.Id.ToString());

            // Delivery Name.
            attrs.Add(NAAttribute.SECOND_ORDER_NAME, deliveryOrder.Id.ToString());

            // not using MaxTransitTime

            feature.Attributes = attrs;

            return feature;
        }
Пример #12
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Creates a new object that is a copy of the current instance.
        /// </summary>
        /// <returns></returns>
        public override object Clone()
        {
            Order obj = new Order(this._capacitiesInfo, this._customPropertiesInfo);
            this.CopyTo(obj);

            return obj;
        }
        private List <ESRI.ArcLogistics.DomainObjects.Order> processOrders(DataTable table)
        {
            List <ESRI.ArcLogistics.DomainObjects.Order> OrderList = new List <Order>();

            foreach (DataRow row in table.Rows)
            {
                // Create New empty Order
                CapacitiesInfo                        capInfo     = m_application.Project.CapacitiesInfo;
                OrderCustomPropertiesInfo             propInfo    = m_application.Project.OrderCustomPropertiesInfo;
                ESRI.ArcLogistics.DomainObjects.Order resultOrder = new ESRI.ArcLogistics.DomainObjects.Order(capInfo, propInfo);

                OrderCustomPropertiesInfo orderPropertiesInfo = resultOrder.CustomPropertiesInfo;
                OrderCustomProperties     orderProperties     = resultOrder.CustomProperties;
                CapacitiesInfo            orderCapacitiesInfo = resultOrder.CapacitiesInfo;
                Capacities orderCapacities   = resultOrder.Capacities;
                bool       geocodeProvided   = false;
                bool       geocodeCorrect    = false;
                bool       geocodedCorrectly = false;
                double     tempD;
                DateTime   TWdateTime;
                Double     tempX = 0.0;
                Double     tempY = 0.0;

                // Insert Order Information
                resultOrder.PlannedDate = m_application.CurrentDate;

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    try
                    {
                        switch (table.Columns[i].ColumnName)
                        {
                            #region Case Statements
                        case "Name": resultOrder.Name = row["Name"].ToString(); break;

                        case "Address": resultOrder.Address.AddressLine = row["Address"].ToString(); break;

                        case "City": resultOrder.Address.Locality3 = row["City"].ToString(); break;

                        case "State": resultOrder.Address.StateProvince = row["State"].ToString(); break;

                        case "Zip": resultOrder.Address.PostalCode1 = row["Zip"].ToString(); break;

                        case "Zip4": resultOrder.Address.PostalCode2 = row["Zip4"].ToString(); break;

                        case "Country": resultOrder.Address.Country = row["Country"].ToString(); break;

                        case "PlannedDate":
                            DateTime tempDT = new DateTime();
                            if (System.DateTime.TryParse(row["PlannedDate"].ToString(), out tempDT))
                            {
                                resultOrder.PlannedDate = tempDT;
                            }
                            break;

                        case "Priority":
                            if (row["Priority"].ToString() == "High")
                            {
                                resultOrder.Priority = OrderPriority.High;
                            }
                            else if (row["Priority"].ToString() == "Normal")
                            {
                                resultOrder.Priority = OrderPriority.Normal;
                            }
                            break;

                        case "OrderType":
                            if (row["OrderType"].ToString() == "Pickup")
                            {
                                resultOrder.Type = OrderType.Pickup;
                            }
                            else if (row["OrderType"].ToString() == "Delivery")
                            {
                                resultOrder.Type = OrderType.Delivery;
                            }
                            break;

                        case "ServiceTime":
                            if (Double.TryParse(row["ServiceTime"].ToString(), out tempD))
                            {
                                resultOrder.ServiceTime = tempD;
                            }
                            break;


                        case "TimeWindowStart":
                            string tempS = row["TimeWindowStart"].ToString();
                            if (DateTime.TryParse(tempS, out TWdateTime))
                            {
                                if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                                {
                                    resultOrder.TimeWindow.From       = TWdateTime.TimeOfDay;
                                    resultOrder.TimeWindow.IsWideOpen = false;
                                }
                            }
                            break;

                        case "TimeWindowFinish":
                            if (DateTime.TryParse(row["TimeWindowFinish"].ToString(), out TWdateTime))
                            {
                                if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                                {
                                    resultOrder.TimeWindow.To         = TWdateTime.TimeOfDay;
                                    resultOrder.TimeWindow.IsWideOpen = false;
                                }
                            }
                            break;

                        case "TimeWindow2Start":

                            if (DateTime.TryParse(row["TimeWindow2Start"].ToString(), out TWdateTime))
                            {
                                if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                                {
                                    resultOrder.TimeWindow2.From       = TWdateTime.TimeOfDay;
                                    resultOrder.TimeWindow2.IsWideOpen = false;
                                }
                            }
                            break;

                        case "TimeWindow2Finish":

                            if (DateTime.TryParse(row["TimeWindow2Finish"].ToString(), out TWdateTime))
                            {
                                if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                                {
                                    resultOrder.TimeWindow2.To         = TWdateTime.TimeOfDay;
                                    resultOrder.TimeWindow2.IsWideOpen = false;
                                }
                            }
                            break;

                        case "MaxViolationTime":
                            if (Double.TryParse(row["MaxViolationTime"].ToString(), out tempD))
                            {
                                resultOrder.MaxViolationTime = tempD;
                            }
                            break;

                        case "VehicleSpecialties":
                            if (row["VehicleSpecialties"].ToString() != "")
                            {
                                string[] stringSeparators = new string[] { ";", "," };
                                string[] specialties      = row["VehicleSpecialties"].ToString().Split(stringSeparators, StringSplitOptions.None);
                                foreach (string s in specialties)
                                {
                                    VehicleSpecialty vs = new VehicleSpecialty();
                                    vs.Name = s;
                                    foreach (VehicleSpecialty V in m_application.Project.VehicleSpecialties)
                                    {
                                        if (String.Compare(V.Name, vs.Name, true) == 0)
                                        {
                                            V.CopyTo(vs);
                                            m_application.Project.VehicleSpecialties.Remove(V);
                                            break;
                                        }
                                    }
                                    m_application.Project.VehicleSpecialties.Add(vs);
                                    resultOrder.VehicleSpecialties.Add(vs);
                                }
                            }
                            break;

                        case "DriverSpecialties":
                            if (row["DriverSpecialties"].ToString() != "")
                            {
                                string[] stringSeparators2 = new string[] { ";", "," };
                                string[] specialties2      = row["DriverSpecialties"].ToString().Split(stringSeparators2, StringSplitOptions.None);
                                foreach (string s in specialties2)
                                {
                                    DriverSpecialty ds = new DriverSpecialty();
                                    ds.Name = s;

                                    foreach (DriverSpecialty D in m_application.Project.DriverSpecialties)
                                    {
                                        if (String.Compare(D.Name, ds.Name, true) == 0)
                                        {
                                            D.CopyTo(ds);
                                            m_application.Project.DriverSpecialties.Remove(D);
                                            break;
                                        }
                                    }
                                    m_application.Project.DriverSpecialties.Add(ds);
                                    resultOrder.DriverSpecialties.Add(ds);
                                }
                            }
                            break;

                        case "X":
                            string x = row["X"].ToString();
                            if (x != "" && x != null)
                            {
                                if (Double.TryParse(row["X"].ToString(), out tempX))
                                {
                                    if (tempX >= -180.0 && tempX <= 180.0 && tempX != 0.0)
                                    {
                                        geocodeProvided = true;
                                        geocodeCorrect  = true;
                                    }
                                    else if (tempX == 0.0)
                                    {
                                        geocodeCorrect = true;
                                    }
                                }
                            }

                            break;

                        case "Y":
                            string y = row["Y"].ToString();
                            if (y != "" && y != null)
                            {
                                if (Double.TryParse(row["Y"].ToString(), out tempY))
                                {
                                    if (tempY >= -90.0 && tempY <= 90.0 && tempY != 0)
                                    {
                                        geocodeProvided = true;
                                        geocodeCorrect  = true;
                                    }
                                    else if (tempY == 0.0)
                                    {
                                        geocodeCorrect = true;
                                    }
                                }
                            }

                            break;
                            #endregion
                        }


                        if (orderProperties.Count > 0)
                        {
                            OrderCustomProperty orderPropertyInfoItem = null;
                            for (int j = 0; j < orderPropertiesInfo.Count; j++)
                            {
                                orderPropertyInfoItem = orderPropertiesInfo.ElementAt(j) as OrderCustomProperty;
                                string tempName = orderPropertyInfoItem.Name.Replace(" ", "");
                                if (tempName == table.Columns[i].ColumnName)
                                {
                                    orderProperties[j] = (row[table.Columns[i].ToString()].ToString());
                                    break;
                                }
                            }
                        }

                        if (orderCapacities.Count > 0)
                        {
                            CapacityInfo orderCapacityInfoItem = null;
                            for (int k = 0; k < orderCapacitiesInfo.Count; k++)
                            {
                                orderCapacityInfoItem = orderCapacitiesInfo.ElementAt(k);
                                string tempName = orderCapacityInfoItem.Name.Replace(" ", "");
                                if (tempName == table.Columns[i].ColumnName)
                                {
                                    if (Double.TryParse(row[table.Columns[i].ToString()].ToString(), out tempD))
                                    {
                                        orderCapacities[k] = tempD;
                                    }

                                    break;
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        string statusMessage = " Distribute Orders encountered a problem: " + e.Message;
                        m_application.Messenger.AddError(statusMessage);
                    }
                }

                resultOrder.CustomProperties = orderProperties;
                resultOrder.Capacities       = orderCapacities;

                if (geocodeProvided && geocodeCorrect)
                {
                    AddressCandidate candidate1        = new AddressCandidate();
                    ESRI.ArcLogistics.Geometry.Point p = new ESRI.ArcLogistics.Geometry.Point(tempX, tempY);
                    candidate1.GeoLocation = p;
                    candidate1.Score       = 100;
                    candidate1.Address     = resultOrder.Address;

                    resultOrder.GeoLocation = candidate1.GeoLocation;
                    geocodedCorrectly       = true;
                }
                else
                {
                    try
                    {
                        AddressCandidate candidate = new AddressCandidate();
                        candidate = m_application.Geocoder.Geocode(resultOrder.Address);
                        if (candidate != null)
                        {
                            resultOrder.GeoLocation = candidate.GeoLocation;
                            geocodedCorrectly       = true;
                        }
                        else
                        {
                            string statusMessage = "Could not geocode address for: " + resultOrder.Name;
                            m_application.Messenger.AddError(statusMessage);
                            //TODO: Handle orders which were not geocoded!!
                        }
                    }
                    catch (Exception e)
                    {
                        string statusMessage = "Distribute Orders encountered a problem while geocoding addresses: " + e.Message;
                        m_application.Messenger.AddError(statusMessage);
                    }
                }

                // Add Order
                if (geocodedCorrectly)
                {
                    OrderList.Add(resultOrder);
                }
                else
                {
                    string statusMessage = "Distribute Orders encountered a problem while adding order: " + resultOrder.Name;
                    m_application.Messenger.AddError(statusMessage);
                }
            }

            return(OrderList);
        }
Пример #14
0
        /// <summary>
        /// Fill order tip
        /// </summary>
        /// <param name="inlines">Inlines to fill</param>
        /// <param name="location">Source order</param>
        private static void _FillOrder(InlineCollection inlines, Order order)
        {
            string name = order.Name;
            _AddLine(_nameCaption, name, inlines, false);

            _AddPriorityIfNeeded(order, inlines);

            _AddTimeWindow(order.TimeWindow, false, inlines, false);
            if (!order.TimeWindow.IsWideOpen)
                _AddTimeWindow(order.TimeWindow2, true, inlines, false);

            foreach (TipProperty tipProperty in App.Current.MapDisplay.OrderTitlesSelected)
            {
                _AddBindableProperty(inlines, tipProperty, order);
            }
        }
        public void Execute(params object[] args)
        {
            string statusMessage = "Adding periodic orders between " + m_application.CurrentDate.ToShortDateString() + " and " + m_application.CurrentDate.AddDays(PeriodicOrdersPage.numDays -1).ToShortDateString();
            m_application.Messenger.AddInfo(statusMessage);
            m_application.MainWindow.StatusBar.WorkingStatus = statusMessage;
            Mouse.OverrideCursor = Cursors.Wait;

            List<ESRI.ArcLogistics.DomainObjects.Order> oList = processOrders2(PeriodicOrdersPage.dt);

            int checkBoxCount = 0;
            int comboBoxCount = 0;
            int periodicity = 0;

            foreach (Order o in oList)
            {
                periodicity = PeriodicOrdersPage.comboBoxList[comboBoxCount].SelectedIndex +1;

                for (int i = 0; i < PeriodicOrdersPage.numDays; i++)
                {
                    if ((i / 7) % (periodicity) == 0)
                    {
                        DayOfWeek d = m_application.CurrentDate.AddDays(i).DayOfWeek;
                        if (PeriodicOrdersPage.checkBoxList[checkBoxCount + (int)d].IsChecked == true)
                        {
                            Order tempO = new Order(o.CapacitiesInfo, o.CustomPropertiesInfo);
                            o.CopyTo(tempO);
                            tempO.PlannedDate = m_application.CurrentDate.AddDays(i);
                            m_application.Project.Orders.Add(tempO);
                        }
                    }
                }
                checkBoxCount = checkBoxCount + 7;
                comboBoxCount++;
            }

            m_application.Project.Save();
            m_application.MainWindow.StatusBar.WorkingStatus = null;
            Mouse.OverrideCursor = null;
            statusMessage = "Completed adding Periodic Orders.";
            m_application.Messenger.AddInfo(statusMessage);
        }
        /// <summary>
        /// Method converts order into GPFeature.
        /// </summary>
        /// <param name="unassignedOrder">Unassigned order to convert.</param>
        /// <param name="assignedOrder">Assigned order to convert.</param>
        /// <returns>Orders GPFeature.</returns>
        /// <exception cref="RouteException">If unassigned order is not geocoded.</exception>
        private GPFeature _ConvertOrder(Order unassignedOrder, AssignedOrder assignedOrder)
        {
            Debug.Assert(unassignedOrder != null);

            GPFeature feature = new GPFeature();

            // Geometry.
            IGeocodable gc = unassignedOrder as IGeocodable;
            Debug.Assert(gc != null);

            if (!gc.IsGeocoded)
            {
                throw new RouteException(String.Format(
                    Properties.Messages.Error_OrderIsUngeocoded, unassignedOrder.Id));
            }

            Debug.Assert(gc.GeoLocation != null);
            feature.Geometry = new GeometryHolder();
            feature.Geometry.Value = GPObjectHelper.PointToGPPoint((Point)gc.GeoLocation);

            // Attributes.
            AttrDictionary attrs = new AttrDictionary();

            // Name.
            attrs.Add(NAAttribute.NAME, unassignedOrder.Id.ToString());

            // Curb approach.
            attrs.Add(NAAttribute.CURB_APPROACH,
                (int)CurbApproachConverter.ToNACurbApproach(
                _context.SolverSettings.GetOrderCurbApproach()));

            // Service time.
            attrs.Add(NAAttribute.SERVICE_TIME, unassignedOrder.ServiceTime);

            // Time windows.
            TimeWindow timeWindow1 = unassignedOrder.TimeWindow;
            TimeWindow timeWindow2 = unassignedOrder.TimeWindow2;

            _SetTimeWindowsAttributes(attrs, ref timeWindow1, ref timeWindow2);

            // Max Violation Time 1.
            attrs.Add(NAAttribute.MAX_VIOLATION_TIME1,
                timeWindow1.IsWideOpen ? (double?)null : unassignedOrder.MaxViolationTime);

            // Max Violation Time 2.
            attrs.Add(NAAttribute.MAX_VIOLATION_TIME2,
                timeWindow2.IsWideOpen ? (double?)null : unassignedOrder.MaxViolationTime);

            // PickUp or DropOff quantities.
            string capacities = _FormatCapacities(unassignedOrder.Capacities);

            if (unassignedOrder.Type == OrderType.Delivery)
            {
                attrs.Add(NAAttribute.DELIVERY, capacities);
                attrs.Add(NAAttribute.PICKUP, null);
            }
            else
            {
                attrs.Add(NAAttribute.PICKUP, capacities);
                attrs.Add(NAAttribute.DELIVERY, null);
            }

            // Revenue.
            attrs.Add(NAAttribute.REVENUE,
                unassignedOrder.Priority == OrderPriority.Normal ? 0 : (long)_orderRevenue);

            // Specialties.
            List<Guid> specIds = GetOrderSpecIds(unassignedOrder);
            if (specIds.Count > 0)
                attrs.Add(NAAttribute.SPECIALTY_NAMES, _FormatSpecList(specIds));

            if (assignedOrder != null)
                SetOrderAssignment(attrs, assignedOrder);
            else
                SetOrderAssignment(attrs, unassignedOrder);

            // Status.
            attrs.Add(NAAttribute.STATUS, (int)NAObjectStatus.esriNAObjectStatusOK);

            feature.Attributes = attrs;

            return feature;
        }
        /// <summary>
        /// Method set unassigned order attributes.
        /// </summary>
        /// <param name="attrs">Attributes to set.</param>
        /// <param name="unassignedOrder">Unassigned order to get attribute values.</param>
        protected virtual void SetOrderAssignment(AttrDictionary attrs, Order unassignedOrder)
        {
            Debug.Assert(attrs != null);

            // Route name.
            attrs.Set(NAAttribute.ROUTE_NAME, "");
            // Sequence.
            attrs.Set(NAAttribute.SEQUENCE, null);
            // Assignment rule.
            attrs.Set(NAAttribute.ASSIGNMENT_RULE,
                (int)NAOrderAssignmentRule.esriNAOrderOverride);
        }
        /// <summary>
        /// Method gets specialties Ids from order.
        /// </summary>
        /// <param name="order">Order to get specialties.</param>
        /// <returns>Collection of specialties Ids from order.</returns>
        protected virtual List<Guid> GetOrderSpecIds(Order order)
        {
            Debug.Assert(order != null);

            List<Guid> specs = new List<Guid>();

            foreach (DriverSpecialty spec in order.DriverSpecialties)
                specs.Add(spec.Id);

            foreach (VehicleSpecialty spec in order.VehicleSpecialties)
                specs.Add(spec.Id);

            return specs;
        }
        /// <summary>
        /// Method determine if assigned order exists and returns it in output parameter.
        /// </summary>
        /// <param name="order">Order to find.</param>
        /// <param name="assignedOrders">Collection of assigned orders to search in.</param>
        /// <param name="assignedOrder">Output assigned order.</param>
        /// <returns>True - if assigned order found, otherwise - false.</returns>
        private bool _FindAssignedOrder(Order order, ICollection<AssignedOrder> assignedOrders,
            out AssignedOrder assignedOrder)
        {
            assignedOrder = null;

            bool found = false;
            foreach (AssignedOrder ao in assignedOrders)
            {
                if (ao.Order.Equals(order))
                {
                    assignedOrder = ao;
                    found = true;
                    break;
                }
            }

            return found;
        }
Пример #20
0
        /// <summary>
        /// Fill order-specific properties.
        /// </summary>
        /// <param name="order">Order.</param>
        /// <param name="settings">Current solver settings.</param>
        /// <param name="result">Stop information to fill in.</param>
        private static void _FillOrderProperties(Order order,
            SolverSettings settings, StopInfo result)
        {
            Debug.Assert(order != null);
            Debug.Assert(result != null);

            result.OrderType = order.Type;
            result.Priority = order.Priority;
            result.MaxViolationTime = (int)order.MaxViolationTime;

            // Fill curb approach policies.
            if (settings != null)
            {
                result.CurbApproach = settings.GetOrderCurbApproach();
            }
        }
Пример #21
0
        /// <summary>
        /// Gets order property value by property name.
        /// </summary>
        /// <param name="order">Order instance.</param>
        /// <param name="name">Property name.</param>
        /// <returns>Returns property value.</returns>
        public static object GetPropertyValue(Order order, string name)
        {
            object value = null;

            int orderPropertyIndex = OrderCustomProperties.GetCustomPropertyIndex(name);
            int capacityIndex = Capacities.GetCapacityPropertyIndex(name);

            AddressPart? addressPart = null;
            try
            {
                addressPart = (AddressPart)Enum.Parse(typeof(AddressPart), name);
            }
            catch { }

            if (orderPropertyIndex != -1)
            {   // specials type: order custom property
                if ((0 <= orderPropertyIndex) && (orderPropertyIndex < order.CustomProperties.Count))
                    value = order.CustomProperties[orderPropertyIndex];
                else
                {
                    string mes = string.Format(Properties.Resources.PropertyNameNotExists, name);
                    throw new ArgumentException(mes);
                }
            }
            else if (capacityIndex != -1)
            {   // specials type: capacities
                if ((0 <= capacityIndex) && (capacityIndex < order.Capacities.Count))
                    value = order.Capacities[capacityIndex];
                else
                {
                    string mes = string.Format(Properties.Resources.PropertyNameNotExists, name);
                    throw new ArgumentException(mes);
                }
            }
            else if (addressPart.HasValue)
            {   // specials type: address
                value = order.Address[addressPart.Value];
            }
            else if (name.Equals("X", StringComparison.OrdinalIgnoreCase) || name.Equals("Y", StringComparison.OrdinalIgnoreCase))
            {
                if (order.GeoLocation.HasValue)
                {
                    if (name.Equals("X", StringComparison.OrdinalIgnoreCase))
                        value = order.GeoLocation.Value.X;
                    if (name.Equals("Y", StringComparison.OrdinalIgnoreCase))
                        value = order.GeoLocation.Value.Y;
                }
            }
            else
            {
                PropertyInfo propInfo = _GetPropertyByName(name);
                value = propInfo.GetValue(order, null);
            }

            return value;
        }
        /// <summary>
        /// Method determines is order assigned to one of selected routes.
        /// </summary>
        /// </summary>
        /// <param name="order">Order.</param>
        /// <param name="routes">Collection of routes.</param>
        /// <param name="targetOrderSequence">Target orders sequence.</param>
        /// <returns>True - if order assigned to one of selected routes, otherwise - false.</returns>
        private static bool _IsOrderAssignedToRoute(Order order,
            ICollection<Route> routes, int? targetOrderSequence)
        {
            Debug.Assert(routes != null);
            Debug.Assert(order != null);

            var assignedStops =
                from route in routes
                where route.Stops != null
                from stop in route.Stops
                where
                    stop.AssociatedObject == order &&
                    (targetOrderSequence == null ||
                    stop.OrderSequenceNumber == targetOrderSequence)
                select stop;

            return assignedStops.Any();
        }
Пример #23
0
        /// <summary>
        /// Geocode order, using local geocoder.
        /// </summary>
        /// <param name="order">Order to geocode.</param>
        /// <param name="useLocalAsPrimary">If true and record exists in storage, than dont use server geocoder.</param>
        /// <param name="includeDisabledLocators">Is need to add candidates from disabled locators.</param>
        /// <returns>Candidates list.</returns>
        private static List<AddressCandidate> _DoLocalOrderGeocode(Order order, bool useLocalAsPrimary, bool includeDisabledLocators)
        {
            LocalGeocoder localGeocoder = new LocalGeocoder(App.Current.Geocoder, App.Current.NameAddressStorage);

            NameAddress nameAddress = new NameAddress();
            nameAddress.Name = order.Name;
            nameAddress.Address = (Address)order.Address.Clone();

            List<AddressCandidate> candidates = new List<AddressCandidate>();

            AddressCandidate candidateFromLocalGeocoder = localGeocoder.Geocode(nameAddress);

            if (useLocalAsPrimary && candidateFromLocalGeocoder != null)
            {
                candidates.Add(candidateFromLocalGeocoder);
            }
            else
            {
                AddressCandidate[] candidatesArray = localGeocoder.GeocodeCandidates(nameAddress, includeDisabledLocators);
                candidates.AddRange(candidatesArray);
            }

            return candidates;
        }
        /// <summary>
        /// Updates properties for all orders with the same name as the specified one.
        /// </summary>
        /// <param name="sourceOrder">The reference to an
        /// <see cref="ESRI.ArcLogistics.DomainObjects.Order"/> object to read property values
        /// from.</param>
        private void _UpdateOrdersProperties(Order sourceOrder)
        {
            Debug.Assert(sourceOrder != null);

            var orders = _orderGroups[sourceOrder].Where(order => order != sourceOrder);
            foreach (var order in orders)
            {
                sourceOrder.CopyTo(order);
            }
        }
        public void Execute(params object[] args)
        {
            string importPath    = DistributeOrdersPage.importpath;
            int    numDays       = DistributeOrdersPage.numDays;
            string statusMessage = "Started distributing orders.";
            int    numClusters   = 0;

            m_application.MainWindow.StatusBar.WorkingStatus = statusMessage;
            Mouse.OverrideCursor = Cursors.Wait;

            try
            {
                if (File.Exists(importPath))
                {
                    //Read orders info from file
                    DataTable table = new DataTable();
                    table = ReadCSV(importPath);

                    if (numDays > 0)
                    {
                        statusMessage = "Distributing " + table.Rows.Count + " orders over " + numDays + " days.";
                        m_application.Messenger.AddInfo(statusMessage);



                        /////////////////////////////////
                        // Count total number of routes
                        /////////////////////////////////
                        DateTime dt = new DateTime();
                        dt = m_application.CurrentDate;

                        for (int i = 0; i < numDays; i++)
                        {
                            if (m_application.Project.DefaultRoutes.Count > 0)
                            {
                                List <Schedule> S = m_application.Project.Schedules.Search(dt.AddDays(i)).ToList();

                                //If the Current Schedule has routes, use those, else use default routes
                                if (S.Count > 0 && S[0].Routes.Count > 0)
                                {
                                    numClusters = numClusters + S[0].Routes.Count;
                                }
                                else
                                {
                                    foreach (Route route in m_application.Project.DefaultRoutes)
                                    {
                                        if (route.Days.DoesDaySatisfy(dt.AddDays(i)))
                                        {
                                            numClusters++;
                                        }
                                    }
                                }
                            }
                        }

                        statusMessage = "Creating " + numClusters + " clusters.";
                        m_application.Messenger.AddInfo(statusMessage);


                        /////////////////////////////////
                        // Create Dataset
                        /////////////////////////////////

                        List <ESRI.ArcLogistics.DomainObjects.Order> oList = processOrders(table);
                        int     numOrders = oList.Count;
                        Point[] data      = new Point[numOrders];
                        Point[] centres   = new Point[numClusters];

                        for (int i = 0; i < numOrders; i++)
                        {
                            ESRI.ArcLogistics.DomainObjects.Order o = oList.ElementAt(i);
                            Point p = new Point(0, o.GeoLocation.Value.X, o.GeoLocation.Value.Y);
                            data[i] = p;
                        }

                        /////////////////////////////////
                        // Perform Clustering
                        /////////////////////////////////

                        int iterations = cluster(ref data, ref centres);

                        /////////////////////////////////
                        // Add clustered orders to days
                        /////////////////////////////////
                        int numRoutes     = 0;
                        int index         = 0;
                        int tempNumOrders = 0;
                        for (int k = 0; k < numDays; k++)
                        {
                            if (m_application.Project.DefaultRoutes.Count > 0)
                            {
                                List <Schedule> S = m_application.Project.Schedules.Search(dt.AddDays(k)).ToList();

                                if (S.Count > 0 && S[0].Routes.Count > 0)
                                {
                                    numRoutes = S[0].Routes.Count;
                                }
                                else
                                {
                                    foreach (Route route in m_application.Project.DefaultRoutes)
                                    {
                                        if (route.Days.DoesDaySatisfy(dt.AddDays(k)))
                                        {
                                            numRoutes++;
                                        }
                                    }
                                }

                                for (int i = 0; i < numOrders; i++)
                                {
                                    if (data[i].cluster >= index && data[i].cluster < (index + numRoutes))
                                    {
                                        ESRI.ArcLogistics.DomainObjects.Order o = oList.ElementAt(i);
                                        o.PlannedDate = dt.AddDays(k);
                                        m_application.Project.Orders.Add(o);
                                        tempNumOrders++;
                                    }
                                }
                                statusMessage = "Added " + numRoutes + " Clusters (" + tempNumOrders + " orders) to " + dt.AddDays(k);
                                m_application.Messenger.AddInfo(statusMessage);


                                index         = index + numRoutes;
                                numRoutes     = 0;
                                tempNumOrders = 0;
                            }
                        }

                        m_application.Project.Save();
                        statusMessage = "Finished Distributing Orders";
                        m_application.Messenger.AddInfo(statusMessage);
                    }
                    else
                    {
                        statusMessage = "Please specify number of days.";
                        m_application.Messenger.AddError(statusMessage);
                    }
                }
                else
                {
                    statusMessage = "Import from " + importPath + " failed! Specified file does not exist.";
                    m_application.Messenger.AddError(statusMessage);
                }
            }

            catch (Exception e)
            {
                statusMessage = "Distribute Orders encountered an error: " + e.Message;
                m_application.Messenger.AddError(statusMessage);
            }
            finally
            {
                m_application.MainWindow.StatusBar.WorkingStatus = null;
                Mouse.OverrideCursor = null;
            }

            if (Mouse.OverrideCursor != null)
            {
                m_application.MainWindow.StatusBar.WorkingStatus = null;
                Mouse.OverrideCursor = null;
            }
        }
        /// <summary>
        /// Method gets route name for assigned order.
        /// </summary>
        /// <param name="info">Operation info.</param>
        /// <param name="order">Assigned order.</param>
        /// <returns>Route name or empty string, in case order is unassigned.</returns>
        private static string _GetRouteNameForAssignedOrder(
            AsyncOperationInfo info, Order order)
        {
            Debug.Assert(info != null);
            Debug.Assert(order != null);

            var inputParameters = (AssignOrdersParams)info.InputParams;
            ICollection<Route> targetRoutes = inputParameters.TargetRoutes;

            // Search for stop associated with order, which was assigned to route.
            var assignedStops =
                from route in targetRoutes
                where route.Stops != null
                from stop in route.Stops
                where (stop.AssociatedObject == order)
                select stop;

            string routeName = string.Empty;

            if (assignedStops.Any())
            {
                Stop stop = assignedStops.First();
                routeName = stop.Route.Name;
            }

            return routeName;
        }