Example #1
0
        public async Task <IActionResult> PutCapacities(int id, Capacities capacities)
        {
            if (id != capacities.Id)
            {
                return(BadRequest());
            }

            _context.Entry(capacities).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CapacitiesExists(id))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(NoContent());
        }
Example #2
0
        public async Task <ActionResult <Capacities> > PostCapacities(Capacities capacities)
        {
            _context.Capacities.Add(capacities);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetCapacities", new { id = capacities.Id }, capacities));
        }
        private static List <MessageDetail> _CheckCapacities(Capacities routesAvailableCapacities,
                                                             Capacities ordersCapacities,
                                                             ICollection <Route> routes)
        {
            List <MessageDetail> details = new List <MessageDetail>();

            bool  checkOneRoute = (1 == routes.Count);
            Route route         = routes.First();

            Debug.Assert(routesAvailableCapacities.Count == ordersCapacities.Count);
            for (int cap = 0; cap < routesAvailableCapacities.Count; ++cap)
            {
                if (routesAvailableCapacities[cap] < ordersCapacities[cap])
                {
                    if (checkOneRoute)
                    {
                        string format = App.Current.FindString("ConstraintsCheckerCapacitiesRouteMessageFmt");
                        format = string.Format(format, route.CapacitiesInfo[cap].Name, ordersCapacities[cap].ToString(), "{0}", routesAvailableCapacities[cap].ToString(), (ordersCapacities[cap] - routesAvailableCapacities[cap]).ToString());
                        details.Add(new MessageDetail(MessageType.Warning, format, route.Vehicle));
                    }
                    else
                    {
                        string format = App.Current.FindString("ConstraintsCheckerCapacitiesRoutesMessageFmt");
                        string text   = string.Format(format, route.CapacitiesInfo[cap].Name, ordersCapacities[cap], routesAvailableCapacities[cap], ordersCapacities[cap] - routesAvailableCapacities[cap]);
                        details.Add(new MessageDetail(MessageType.Warning, text));
                    }
                }
            }

            return(details);
        }
Example #4
0
        static void Main(string[] args)
        {
            var      capacities = Capacities.Instance();
            Building building   = new Building();

            building.Main();
        }
Example #5
0
        public void RemoveCapacity(CapacityType capacityType)
        {
            Capacity capacity = new Capacity(capacityType);

            Capacities.Remove(capacity);

            if (capacityType == CapacityType.WeaponMastery)
            {
                this.WeaponMastery = WeaponTypes.None;
            }
        }
Example #6
0
        /// <summary>
        /// Gets dictonary title to name for application type.
        /// </summary>
        /// <param name="type">Propery type.</param>
        /// <param name="title">Property title.</param>
        /// <param name="name">Property name.</param>
        /// <param name="map">Dictonary title to name.</param>
        /// <returns>TRUE if processed successly.</returns>
        static private bool _GetAppTypeTitle2NameMap(Type type,
                                                     string title,
                                                     string name,
                                                     ref StringDictionary map)
        {
            bool result = true;

            if (typeof(OrderCustomProperties) == type)
            {   // specials type: related object OrderCustomProperty
                OrderCustomPropertiesInfo info = App.Current.Project.OrderCustomPropertiesInfo;
                for (int index = 0; index < info.Count; ++index)
                {
                    map.Add(info[index].Name, OrderCustomProperties.GetCustomPropertyName(index));
                }
            }

            else if (typeof(Capacities) == type)
            {   // specials type: related object Capacities
                CapacitiesInfo info = App.Current.Project.CapacitiesInfo;
                for (int index = 0; index < info.Count; ++index)
                {
                    map.Add(info[index].Name, Capacities.GetCapacityPropertyName(index));
                }
            }

            else if (typeof(Address) == type)
            {   // specials type: related object Address
                AddressField[] fields = App.Current.Geocoder.AddressFields;
                for (int index = 0; index < fields.Length; ++index)
                {
                    map.Add(fields[index].Title, fields[index].Type.ToString());
                }
            }

            else if ((typeof(IDataObjectCollection <VehicleSpecialty>) == type) ||
                     (typeof(IDataObjectCollection <DriverSpecialty>) == type) ||
                     (typeof(IDataObjectCollection <Location>) == type) ||
                     (typeof(IDataObjectCollection <Zone>) == type) ||
                     (typeof(FuelType) == type) ||
                     (!string.IsNullOrEmpty(title) &&
                      ((typeof(Location) == type) || (typeof(MobileDevice) == type) ||
                       (typeof(Vehicle) == type) || (typeof(Driver) == type))))
            {   // specials types: related objects and objects collection
                map.Add(title, name);
            }

            else
            {
                result = false;
            }

            return(result);
        }
Example #7
0
        private void NewRoom(object sender, AddingNewEventArgs e)
        {
            var room = new Room
            {
                FloorNumber  = (Floor)Floors.GetValue(Randomizer.Next(Floors.Length)),
                HostelNumber = (Hostel)Hostels.GetValue(Randomizer.Next(Hostels.Length)),
                Capacity     = (Capacity)Capacities.GetValue(Randomizer.Next(Capacities.Length)),
                RoomNumber   = Randomizer.Next(100, 500)
            };

            e.NewObject = room;
        }
Example #8
0
 private static void _AddCapacitiesInfos(PropertyInfo property)
 {
     if (App.Current.Project != null)
     {
         CapacitiesInfo info = App.Current.Project.CapacitiesInfo;
         for (int i = 0; i < info.Count; ++i)
         {
             _quantityFieldTitles.Add(info[i].Name);
             _quantityFieldNames.Add(Capacities.GetCapacityPropertyName(i));
             _quantityFieldProperties.Add(property);
         }
     }
 }
Example #9
0
        /// <summary>
        /// Builds collection of dynamic capacities
        /// </summary>
        /// <returns></returns>
        private Collection <DataGridItemProperty> _GetDynamicCapacitiesProperties(string baseValuePath, bool isReadonly)
        {
            Collection <DataGridItemProperty> dynamicProperties = new Collection <DataGridItemProperty>();

            for (int i = 0; i < App.Current.Project.CapacitiesInfo.Count; i++)
            {
                string valuePath = baseValuePath + string.Format("Capacities[{0}]", i);
                string valueName = Capacities.GetCapacityPropertyName(i);

                DataGridItemProperty newProperty = new DataGridItemProperty(valueName, valuePath, typeof(double));
                newProperty.IsReadOnly = isReadonly;
                dynamicProperties.Add(newProperty);
            }
            return(dynamicProperties);
        }
Example #10
0
 private bool CanAddItemToAllSacks(int k, int j)
 {
     if (k > Capacities.Min())
     {
         return(false);
     }
     for (int i = 0; i < NumOfknapsacks; i++)
     {
         if (Items[j - 1].Constrains[i] > k)
         {
             return(false);
         }
     }
     return(true);
 }
Example #11
0
        /// <summary>
        /// Gets collection of dynamic capacities columns
        /// </summary>
        /// <returns></returns>
        private Collection <Column> _GetDynamicCapacitiesColumns(bool isReadOnly)
        {
            Collection <Column> dynamicColumns = new Collection <Column>();

            for (int i = 0; i < App.Current.Project.CapacitiesInfo.Count; i++)
            {
                Column col = new Column();
                col.FieldName           = Capacities.GetCapacityPropertyName(i);
                col.Title               = App.Current.Project.CapacitiesInfo[i].Name;
                col.ReadOnly            = isReadOnly;
                col.CellContentTemplate = (DataTemplate)App.Current.FindResource("UnitCellContentTemplate");
                col.CellEditor          = (CellEditor)App.Current.FindResource("UnitEditorTemplate");
                dynamicColumns.Add(col);
            }
            return(dynamicColumns);
        }
Example #12
0
        private void Awake()
        {
            _serialController = FindObjectOfType <SerialControllerCinta>();
            _serialController.OnSerialMessageReceived += OnSerialMessageReceived;
            _tmpCapacities     = new Capacities();
            _flowWatch         = new Stopwatch();
            _timerWatch        = new Stopwatch();
            _capturedSamples   = new Dictionary <float, float>();
            _calibrationLogger = new CalibrationLoggerCinta();

            _dudeObject.transform.Translate(-Camera.main.orthographicSize * Camera.main.aspect + (_dudeObject.transform.localScale.x / 2f), 0f, 0f);

            if (CalibrationToLoad > 0)
            {
                _currentExercise = CalibrationToLoad;
            }
        }
Example #13
0
        public void run_algorithm(string path)
        {
            Stopwatch stopWatch = new Stopwatch();

            _chosenItems = "";
            ReadDataFromFile(path);
            Console.WriteLine("Probelm: " + path);
            _counter = 0;
            switch (_neglectedConstrain)
            {
            case NeglectedConstrain.Capacity:
                _estimationBound = (uint)Weights.Sum(num => num); break;

            case NeglectedConstrain.Integrality:
                BuildItemsList(true);
                _estimationBound = calc_estimate_neglecting_integrality(); break;
            }
            _bestLeaf = new Node(0, NumOfknapsacks, Capacities.ToArray(), 0, 0);
            short[] rooms = new short[NumOfknapsacks];
            Array.Copy(Capacities.ToArray(), rooms, NumOfknapsacks);
            Node root = new Node(0, NumOfknapsacks, rooms, _estimationBound, 0);

            //solving while iterating between Branch and Bound
            switch (_searchAlgorithm)
            {
            case SearchAlgorithm.BestFirstSearch:
                stopWatch.Start();
                BestFirstSearch(root);
                break;

            case SearchAlgorithm.DepthFirstSearch:
                stopWatch.Start();
                DepthFirstSearch(root);
                break;
            }
            stopWatch.Stop();
            double totalTicks = (stopWatch.ElapsedTicks / (double)Stopwatch.Frequency) * 1000;

            stopWatch.Restart();
            print_result_details();
            Console.WriteLine("Total Ticks " + (long)totalTicks + "\n");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="GraphBalancerAlgorithm{TVertex,TEdge}"/> class.
        /// </summary>
        /// <param name="visitedGraph">Graph to visit.</param>
        /// <param name="source">Flow source vertex.</param>
        /// <param name="sink">Flow sink vertex.</param>
        /// <param name="vertexFactory">Vertex factory method.</param>
        /// <param name="edgeFactory">Edge factory method.</param>
        public GraphBalancerAlgorithm(
            [NotNull] IMutableBidirectionalGraph <TVertex, TEdge> visitedGraph,
            [NotNull] TVertex source,
            [NotNull] TVertex sink,
            [NotNull] VertexFactory <TVertex> vertexFactory,
            [NotNull] EdgeFactory <TVertex, TEdge> edgeFactory)
        {
            if (source == null)
            {
                throw new ArgumentNullException(nameof(source));
            }
            if (sink == null)
            {
                throw new ArgumentNullException(nameof(sink));
            }

            VisitedGraph  = visitedGraph ?? throw new ArgumentNullException(nameof(visitedGraph));
            VertexFactory = vertexFactory ?? throw new ArgumentNullException(nameof(vertexFactory));
            EdgeFactory   = edgeFactory ?? throw new ArgumentNullException(nameof(edgeFactory));

            if (!VisitedGraph.ContainsVertex(source))
            {
                throw new ArgumentException("Source must be in the graph", nameof(source));
            }
            if (!VisitedGraph.ContainsVertex(sink))
            {
                throw new ArgumentException("Sink must be in the graph", nameof(sink));
            }
            Source = source;
            Sink   = sink;

            foreach (TEdge edge in VisitedGraph.Edges)
            {
                // Setting capacities = u(e) = +infinity
                Capacities.Add(edge, double.MaxValue);

                // Setting preflow = l(e) = 1
                _preFlow.Add(edge, 1);
            }
        }
Example #15
0
        private void Awake()
        {
            _serialController = FindObjectOfType <SerialControllerMano>();
            _serialController.OnSerialMessageReceived += OnSerialMessageReceived;
            _tmpCapacities = new Capacities();
            _calibrationOverviewSendDto = new CalibrationOverviewSendDto
            {
                GameDevice = GameDevice.Mano.GetDescription(),
                PacientId  = Pacient.Loaded.IdApi
            };
            _flowWatch         = new Stopwatch();
            _timerWatch        = new Stopwatch();
            _capturedSamples   = new Dictionary <float, float>();
            _calibrationLogger = new CalibrationLoggerMano();

            _dudeObject.transform.Translate(-Camera.main.orthographicSize * Camera.main.aspect + (_dudeObject.transform.localScale.x / 2f), 0f, 0f);

            if (CalibrationToLoad > 0)
            {
                _currentExercise = CalibrationToLoad;
            }
        }
Example #16
0
        public void AddCapacity(CapacityType capacityType)
        {
            if (this.MaxNumberOfCapacities > this.Capacities.Count)
            {
                if (!PossesCapacity(capacityType))
                {
                    Capacity capacity = new Capacity(capacityType);
                    Capacities.Add(capacity);

                    if (capacityType == CapacityType.WeaponMastery)
                    {
                        while (this.WeaponMastery == WeaponTypes.None)
                        {
                            this.WeaponMastery = GlobalFunction.RandomEnumValue <WeaponTypes>();
                        }
                    }
                }
            }
            else
            {
                throw new MaxNumberOfCapacitiesReached(GlobalTranslator.Instance.Translator.ProvideValue("TooManyCapacities") + " (" + MaxNumberOfCapacities + ")");
            }
        }
        /// <summary>
        /// Creates violation message for route's capacities.
        /// </summary>
        /// <param name="obj">Violation's object (can be any DataObject: Vehicle, Driver and etc).</param>
        /// <returns>Created violation messages for route's capacities.</returns>
        private static ICollection <MessageDetail> _GetCapacitiesRouteViolationMessages(DataObject obj)
        {
            Debug.Assert(obj is Route);

            Route route = obj as Route;

            CapacitiesInfo info            = App.Current.Project.CapacitiesInfo;
            Capacities     stopsCapacities = new Capacities(info);

            foreach (Stop stop in route.Stops)
            {
                if (StopType.Order == stop.StopType)
                {
                    Debug.Assert(null != stop.AssociatedObject);

                    Order order = stop.AssociatedObject as Order;
                    for (int cap = 0; cap < info.Count; ++cap)
                    {
                        stopsCapacities[cap] += order.Capacities[cap];
                    }
                }
            }

            Collection <MessageDetail> details = new Collection <MessageDetail>();

            for (int cap = 0; cap < App.Current.Project.CapacitiesInfo.Count; ++cap)
            {
                if (route.Vehicle.Capacities[cap] < stopsCapacities[cap])
                {
                    string format = App.Current.GetString("CapacityRouteViolationMessage", "{0}", route.CapacitiesInfo[cap].Name);
                    details.Add(new MessageDetail(MessageType.Error, format, route));
                }
            }

            return(details);
        }
Example #18
0
 private void _ClearCapacities()
 {
     _capacities = new Capacities(_capacitiesInfo);
 }
Example #19
0
        public void run_algorithm(string problem)
        {
            ReadDataFromFile(problem);
            BuildItemsList(false);
            Stopwatch stopWatch = new Stopwatch();

            stopWatch.Start();
            var max      = Capacities.Min();
            int indexMax = -1;

            for (int i = 0; i < Capacities.Count; i++)
            {
                if (max <= Capacities[i])
                {
                    max      = Capacities[i];
                    indexMax = i;
                }
            }
            int[,] table = new int[Capacities[indexMax] + 1, NumOfItems + 1];
            for (int j = 1; j <= NumOfItems; j++)
            {
                for (int k = 0; k <= Capacities[indexMax]; k++)
                {
                    bool result = CanAddItemToAllSacks(k, j);
                    if (result == true)
                    {
                        var previousResult = table[k, j - 1];
                        var plusItem       = Items[j - 1].Weight + table[k - Items[j - 1].Constrains[indexMax], j - 1];
                        table[k, j] = (int)Math.Max(previousResult, plusItem);
                    }
                    else
                    {
                        table[k, j] = table[k, j - 1];
                    }
                }
            }
            stopWatch.Stop();
            double totalTicks = (stopWatch.ElapsedTicks / (double)Stopwatch.Frequency) * 1000;
            var    best       = table.Cast <int>().Max();

            for (int j = 0; j <= Capacities[indexMax]; j++)
            {
                for (int i = 0; i <= NumOfItems; i++)
                {
                    Console.Write(table[j, i] + " ");
                }
                Console.WriteLine(" ");
            }
            Console.WriteLine("Best Value:" + best);
            print_result_details();
            int row = Capacities[indexMax];

            if (table[row, Items.Count] == 0)
            {
                for (int i = Capacities[indexMax] - 1; i > 0; i--)
                {
                    if (table[i, Items.Count] != 0)
                    {
                        row = i;
                        break;
                    }
                }
            }
            print_chosen_items(table, indexMax, row);
            Console.WriteLine("Total Ticks " + (long)totalTicks);
        }
        private static ICollection <MessageDetail> _Check(Schedule schedule, ICollection <Route> routes, ICollection <Order> orders)
        {
            List <MessageDetail> details = new List <MessageDetail>();

            string orderIsNotGeocodedFmt = App.Current.FindString("OrderIsNotGeocodedFormat");

            // get orders requirments
            string farFromRoadMatchMethod    = App.Current.FindString("ManuallyEditedXYFarFromNearestRoad");
            string farViolationMessageFormat = App.Current.FindString("OrderNotFoundOnNetworkViolationMessage");

            List <Order> processedOrders  = new List <Order>();
            Capacities   ordersCapacities = new Capacities(App.Current.Project.CapacitiesInfo);

            foreach (Order order in orders)
            {
                if (!order.IsGeocoded)
                {
                    details.Add(new MessageDetail(MessageType.Warning, orderIsNotGeocodedFmt, order));
                    continue; // NOTE: if orders is ungeocoded skip it
                }

                if ((null != order.Address.MatchMethod) &&
                    order.Address.MatchMethod.Equals(farFromRoadMatchMethod, StringComparison.OrdinalIgnoreCase))
                {
                    details.Add(new MessageDetail(MessageType.Warning, farViolationMessageFormat, order));
                    continue; // NOTE: if orders is far from nearest road skip it
                }

                if (IsOrderLocked(order, schedule))
                {
                    continue; // NOTE: if orders is locked skip it
                }
                // Order capapcities should not be accounted in case order is assigned to route of
                // the same solution and either new route to assign is the same or the best route.
                if (null != schedule.UnassignedOrders)
                {
                    if (schedule.UnassignedOrders.Contains(order))
                    {   // add these capacities to require capacities
                        // calculate total capacities
                        for (int cap = 0; cap < order.Capacities.Count; ++cap)
                        {
                            ordersCapacities[cap] += order.Capacities[cap];
                        }

                        processedOrders.Add(order);
                    }
                }
            }

            if (0 < processedOrders.Count)
            {
                OrderType orderType   = OrderType.Delivery;
                bool      isMixedCase = false;
                _GetOrdersDeliveryType(processedOrders, ref orderType, ref isMixedCase);

                // calculate totals of constraint properties
                bool       hasRenewal = false;
                Capacities routesAvailableCapacities = new Capacities(App.Current.Project.CapacitiesInfo);
                int        routesSupportedOrderCount = 0;
                foreach (Route route in routes)
                {
                    List <Order> routeOrders = new List <Order>();
                    if (null != route.Stops)
                    {
                        foreach (Stop stop in route.Stops)
                        {
                            if (StopType.Order == stop.StopType)
                            {
                                Debug.Assert(null != stop.AssociatedObject);
                                Debug.Assert(stop.AssociatedObject is Order);

                                routeOrders.Add((Order)stop.AssociatedObject);
                            }
                        }
                    }

                    if (0 < routeOrders.Count)
                    {
                        OrderType orderTypeRt   = OrderType.Delivery;
                        bool      isMixedCaseRt = false;
                        _GetOrdersDeliveryType(routeOrders, ref orderTypeRt, ref isMixedCaseRt);

                        if (isMixedCaseRt || (orderTypeRt != orderType))
                        {
                            isMixedCase = true;
                        }
                    }

                    if (route.IsLocked)
                    {
                        continue; // NOTE: if route is locked simply skip it
                    }
                    // calculate total orders count, subtract presently count
                    routesSupportedOrderCount += route.MaxOrders - route.OrderCount; // or route.OrderCount

                    // calculate total capacities
                    // NOTE: subtract busy capacities from available capacities
                    Debug.Assert(null != route.Vehicle);
                    Capacities vehicleCapacities = route.Vehicle.Capacities;
                    Debug.Assert(vehicleCapacities.Count == route.Capacities.Count);
                    for (int cap = 0; cap < vehicleCapacities.Count; ++cap)
                    {
                        routesAvailableCapacities[cap] += vehicleCapacities[cap] - route.Capacities[cap];
                    }

                    // check if route has renewal locations
                    hasRenewal |= (0 < route.RenewalLocations.Count);
                }

                // Max Order Count constraint violation
                details.AddRange(_CheckMaxOrderCount(routesSupportedOrderCount, processedOrders.Count, routes));

                // {Capacity} constraint violation
                if (!hasRenewal && !isMixedCase)
                {
                    details.AddRange(_CheckCapacities(routesAvailableCapacities, ordersCapacities, routes));
                }

                // Vehicle specialties violation
                details.AddRange(_CheckVehicleSpecialties(routes, processedOrders));

                // Driver specialties violation
                details.AddRange(_CheckDriverSpecialties(routes, processedOrders));

                // ToDo - Zones violation
            }

            return(details);
        }
Example #21
0
        public static void makeEdit(string field, string value)
        {
            field = field.Replace(" ", "");

            string message = "Changing " + field + " to " + value + " for all seleced orders.";

            App.Current.Messenger.AddInfo(message);

            ISupportSelection selector = (ISupportSelection)App.Current.MainWindow.CurrentPage;

            for (int i = 0; i < selector.SelectedItems.Count; i++)
            {
                // orderRef is a reference to the selected order [i]
                Order orderRef = (ESRI.ArcLogistics.DomainObjects.Order)selector.SelectedItems[i];

                OrderCustomPropertiesInfo orderPropertiesInfo = orderRef.CustomPropertiesInfo;
                OrderCustomProperties     orderProperties     = orderRef.CustomProperties;
                CapacitiesInfo            orderCapacitiesInfo = orderRef.CapacitiesInfo;
                Capacities orderCapacities = orderRef.Capacities;

                double   tempD;
                DateTime TWdateTime;

                try
                {
                    switch (field)
                    {
                        #region Case Statements
                    case "Name": orderRef.Name = value; break;

                    case "Address": orderRef.Address.AddressLine = value; break;

                    case "City": orderRef.Address.Locality3 = value; break;

                    case "State": orderRef.Address.StateProvince = value; break;

                    case "Zip": orderRef.Address.PostalCode1 = value; break;

                    case "Zip4": orderRef.Address.PostalCode2 = value; break;

                    case "Country": orderRef.Address.Country = value; break;

                    case "PlannedDate":
                        DateTime tempDT = new DateTime();
                        if (System.DateTime.TryParse(value, out tempDT))
                        {
                            orderRef.PlannedDate = tempDT;
                        }
                        break;

                    case "Priority":
                        if (value == "High")
                        {
                            orderRef.Priority = OrderPriority.High;
                        }
                        else if (value == "Normal")
                        {
                            orderRef.Priority = OrderPriority.Normal;
                        }
                        break;

                    case "OrderType":
                        if (value == "Pickup")
                        {
                            orderRef.Type = OrderType.Pickup;
                        }
                        else if (value == "Delivery")
                        {
                            orderRef.Type = OrderType.Delivery;
                        }
                        break;

                    case "ServiceTime":
                        if (Double.TryParse(value.ToString(), out tempD))
                        {
                            orderRef.ServiceTime = tempD;
                        }
                        break;

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

                    case "TimeWindowFinish":
                        if (DateTime.TryParse(value, out TWdateTime))
                        {
                            if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                            {
                                orderRef.TimeWindow.To         = TWdateTime.TimeOfDay;
                                orderRef.TimeWindow.IsWideOpen = false;
                            }
                        }
                        break;

                    case "TimeWindow2Start":

                        if (DateTime.TryParse(value, out TWdateTime))
                        {
                            if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                            {
                                orderRef.TimeWindow2.From       = TWdateTime.TimeOfDay;
                                orderRef.TimeWindow2.IsWideOpen = false;
                            }
                        }
                        break;

                    case "TimeWindow2Finish":

                        if (DateTime.TryParse(value, out TWdateTime))
                        {
                            if (TWdateTime.TimeOfDay != TimeSpan.Zero)
                            {
                                orderRef.TimeWindow2.To         = TWdateTime.TimeOfDay;
                                orderRef.TimeWindow2.IsWideOpen = false;
                            }
                        }
                        break;

                    case "MaxViolationTime":
                        if (Double.TryParse(value, out tempD))
                        {
                            orderRef.MaxViolationTime = tempD;
                        }
                        break;

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

                                foreach (VehicleSpecialty V in orderRef.VehicleSpecialties)
                                {
                                    if (String.Compare(V.Name, vs.Name, true) == 0)
                                    {
                                        V.CopyTo(vs);
                                        orderRef.VehicleSpecialties.Remove(V);
                                        break;
                                    }
                                }

                                App.Current.Project.VehicleSpecialties.Add(vs);
                                orderRef.VehicleSpecialties.Add(vs);
                            }
                        }
                        break;

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

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

                                App.Current.Project.DriverSpecialties.Add(ds);
                                orderRef.DriverSpecialties.Add(ds);
                            }
                        }
                        break;
                        //end of case statements
                        #endregion
                    }

                    #region Custom order properties and capacities

                    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 == field)
                            {
                                orderRef.CustomProperties[j] = value;
                                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 == field)
                            {
                                if (Double.TryParse(value, out tempD))
                                {
                                    orderRef.Capacities[k] = tempD;
                                }

                                break;
                            }
                        }
                    }
                    // End custom order properties and capacities
                    #endregion
                }
                catch (Exception e)
                {
                    message = "Error: " + e.Message;
                    App.Current.Messenger.AddError(message);
                }
            }
            App.Current.Project.Save();
        }
        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);
        }
        /// <summary>
        /// Method creates capacities for stop data collection.
        /// </summary>
        /// <param name="stops">Stop data collection.</param>
        /// <returns>Capacities.</returns>
        private Capacities _CreateCapacities(IList<StopData> stops)
        {
            var capacities = new Capacities(_project.CapacitiesInfo);
            foreach (StopData stop in stops)
            {
                if (stop.StopType == StopType.Order)
                {
                    Order order = stop.AssociatedObject as Order;
                    Debug.Assert(order != null);

                    if (order.Type == OrderType.Delivery ||
                        order.Type == OrderType.Pickup)
                    {
                        Debug.Assert(capacities.Count == order.Capacities.Count);
                        for (int cap = 0; cap < order.Capacities.Count; cap++)
                            capacities[cap] += order.Capacities[cap];
                    }
                }
            }

            return capacities;
        }
        /// <summary>
        /// Method returns formatted string of capacities collection.
        /// </summary>
        /// <param name="capacities">Collection of capacities.</param>
        /// <returns>Formatted string of capacities.</returns>
        private static string _FormatCapacities(Capacities capacities)
        {
            Debug.Assert(capacities != null);

            List<string> caps = new List<string>();
            for (int cap = 0; cap < capacities.Count; cap++)
            {
                var capacity = string.Format(
                    CultureInfo.InvariantCulture,
                    CAPACITY_FORMAT,
                    capacities[cap]);
                caps.Add(capacity);
            }

            return String.Join(ATTR_LIST_DELIMITER, caps.ToArray());
        }
Example #25
0
        private uint calc_estimate_neglecting_integrality(string chosenItems = "")
        {
            double estimateBound = 0;
            //avilableItems holds the current items according to the chosen items so far in the recursive search
            List <Item> avilableItems = new List <Item>();
            List <int>  numbers       = new List <int>();

            if (!chosenItems.Equals("")) //no items were selected yet. add all items.
            {
                var binaryNumbers = chosenItems.Replace(" ", "");
                foreach (var bin in binaryNumbers)
                {
                    numbers.Add(Int32.Parse(bin.ToString()));
                }
                for (int i = 0; i < numbers.Count; i++)
                {
                    if (numbers[i] == 1)
                    {
                        avilableItems.Add(Items[i]);
                    }
                }
            }
            for (int i = numbers.Count; i < NumOfItems; i++) // add the rest of the items
            {
                avilableItems.Add(Items[i]);
            }
            var itemsSorted = avilableItems.OrderByDescending(x => x.DensitiesAvg);

            short[] rooms = new short[NumOfknapsacks];
            Array.Copy(Capacities.ToArray(), rooms, NumOfknapsacks);
            foreach (var item in itemsSorted)
            {
                bool canBeAddedToAllSacks = true;
                //check if this item cab be added to all knapsacks
                for (int j = 0; j < NumOfknapsacks; j++)
                {
                    if (rooms[j] < item.Constrains[j])
                    {
                        canBeAddedToAllSacks = false;
                        break;
                    }
                }
                if (canBeAddedToAllSacks == true)
                {
                    for (int j = 0; j < NumOfknapsacks; j++)
                    {
                        rooms[j] = (short)(rooms[j] - item.Constrains[j]);
                    }
                    estimateBound += item.Weight;
                }
                else //add a fraction of this item to all knapsacks
                {
                    double fraction = Int16.MaxValue;
                    for (int j = 0; j < NumOfknapsacks; j++)
                    {
                        if (item.Constrains[j] != 0)
                        {
                            double temp = (rooms[j] / (double)item.Constrains[j]) * item.Weight;
                            if (fraction > temp)
                            {
                                fraction = temp;                  //take the smallest fraction
                            }
                        }
                    }
                    estimateBound += fraction;
                    break; //stop because we filled up at least one room
                }
            }
            return((uint)estimateBound);
        }
Example #26
0
 ///////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////
 private void _CreateCapacities(CapacitiesInfo capacitiesInfo)
 {
     _capacitiesInfo = capacitiesInfo;
     _capacities = new Capacities(capacitiesInfo);
     _capacities.PropertyChanged += new PropertyChangedEventHandler(Capacities_PropertyChanged);
 }
        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);
        }
Example #28
0
 private void _InitCapacities(DataModel.Orders entity, CapacitiesInfo capacitiesInfo)
 {
     _capacities = Capacities.CreateFromDBString(entity.Capacities, capacitiesInfo);
     _capacities.PropertyChanged += new PropertyChangedEventHandler(Capacities_PropertyChanged);
 }
Example #29
0
 ///////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////
 /// <summary>
 /// Creates capacities by capacities info.
 /// </summary>
 /// <param name="capacitiesInfo">Capacities info.</param>
 private void _CreateCapacities(CapacitiesInfo capacitiesInfo)
 {
     _capacities = new Capacities(capacitiesInfo);
     _capacitiesInfo = capacitiesInfo;
 }
        public static void makeEdit(string field, string value)
        {
            field = field.Replace(" ", "");

            string message = "Changing " + field + " to " + value + " for all seleced vehicles.";

            App.Current.Messenger.AddInfo(message);

            ISupportSelection selector = (ISupportSelection)App.Current.MainWindow.CurrentPage;

            for (int i = 0; i < selector.SelectedItems.Count; i++)
            {
                Vehicle vehicleRef = (Vehicle)selector.SelectedItems[i];

                CapacitiesInfo orderCapacitiesInfo = vehicleRef.CapacitiesInfo;
                Capacities     orderCapacities     = vehicleRef.Capacities;

                double tempD;


                try
                {
                    switch (field)
                    {
                        #region Case Statements

                    case "VehicleName": vehicleRef.Name = value; break;

                    case "FixedCost":
                        if (Double.TryParse(value.ToString(), out tempD))
                        {
                            vehicleRef.FixedCost = tempD;
                        }
                        break;

                    case "FuelEconomy":
                        if (Double.TryParse(value.ToString(), out tempD))
                        {
                            vehicleRef.FuelEconomy = tempD;
                        }
                        break;

                    case "FuelType":
                        foreach (FuelType f in App.Current.Project.FuelTypes)
                        {
                            if (f.Name == value)
                            {
                                vehicleRef.FuelType = f;
                            }
                        }
                        break;

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

                                foreach (VehicleSpecialty V in vehicleRef.Specialties)
                                {
                                    if (String.Compare(V.Name, vs.Name, true) == 0)
                                    {
                                        V.CopyTo(vs);
                                        vehicleRef.Specialties.Remove(V);
                                        break;
                                    }
                                }

                                App.Current.Project.VehicleSpecialties.Add(vs);
                                vehicleRef.Specialties.Add(vs);
                            }
                        }
                        break;

                    case "MobileDevice":
                        foreach (MobileDevice m in App.Current.Project.MobileDevices)
                        {
                            if (m.Name == value)
                            {
                                vehicleRef.MobileDevice = m;
                            }
                        }
                        break;

                    case "Comment": vehicleRef.Comment = value; break;

                        #endregion
                    }// End Switch

                    #region Custom order capacities


                    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 == field)
                            {
                                if (Double.TryParse(value, out tempD))
                                {
                                    vehicleRef.Capacities[k] = tempD;
                                }

                                break;
                            }
                        }
                    }

                    #endregion custom order capacities
                }
                catch (Exception e)
                {
                    message = "Error: " + e.Message;
                    App.Current.Messenger.AddError(message);
                }
            }
            App.Current.Project.Save();
        }
Example #31
0
        /// <summary>
        /// Initialize control.
        /// </summary>
        private void _Init()
        {
            Xceed.Wpf.DataGrid.CellContentPresenter cellContentPresenter = this.VisualParent as Xceed.Wpf.DataGrid.CellContentPresenter;
            if (cellContentPresenter == null)
            {
                return;
            }

            Xceed.Wpf.DataGrid.DataCell dataCell = cellContentPresenter.TemplatedParent as Xceed.Wpf.DataGrid.DataCell;
            string columnName = dataCell.ParentColumn.FieldName;

            ESRI.ArcLogistics.Data.DataObject dataObject = dataCell.ParentRow.DataContext as ESRI.ArcLogistics.Data.DataObject;

            if (dataObject != null)
            {
                int capacityPropertyIndex = Capacities.GetCapacityPropertyIndex(columnName);
                if (capacityPropertyIndex != -1)
                {
                    CapacityInfo capacityInfo = App.Current.Project.CapacitiesInfo[capacityPropertyIndex];
                    if (RegionInfo.CurrentRegion.IsMetric)
                    {
                        _displayUnits = capacityInfo.DisplayUnitMetric;
                    }
                    else
                    {
                        _displayUnits = capacityInfo.DisplayUnitUS;
                    }

                    _valueUnits = _displayUnits;
                }
                else
                {
                    Type         type     = dataObject.GetType();
                    PropertyInfo property = type.GetProperty(columnName);

                    UnitPropertyAttribute unitAttribute = (UnitPropertyAttribute)Attribute.GetCustomAttribute(property, typeof(UnitPropertyAttribute));

                    _displayUnits = (RegionInfo.CurrentRegion.IsMetric) ? unitAttribute.DisplayUnitMetric : unitAttribute.DisplayUnitUS;
                    _valueUnits   = unitAttribute.ValueUnits;
                }

                _TextBox.Text = UnitFormatter.Format(0.0, _displayUnits);

                _inited = true;

                _SetTextToInnerTextBox();
            }
            else
            {
                // If this is not DataObject
                Break breakObject = dataCell.ParentRow.DataContext as Break;
                if (breakObject != null)
                {
                    // If this is Break. Get it`s type and initiate control in a proper way.
                    Type type = breakObject.GetType();

                    PropertyInfo property = type.GetProperty(columnName);
                    if (property != null)
                    {
                        Attribute attr = Attribute.GetCustomAttribute(property, typeof(UnitPropertyAttribute));

                        UnitPropertyAttribute unitAttribute = (UnitPropertyAttribute)attr;

                        _displayUnits = (RegionInfo.CurrentRegion.IsMetric) ? unitAttribute.DisplayUnitMetric : unitAttribute.DisplayUnitUS;
                        _valueUnits   = unitAttribute.ValueUnits;
                    }

                    _TextBox.Text = UnitFormatter.Format(0.0, _displayUnits);

                    _inited = true;

                    _SetTextToInnerTextBox();
                }
            }
        }