Example #1
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Initialize capacities from default values.
        /// </summary>
        /// <param name="capacitiesInfo">Capacity information.</param>
        private void _InitCapacitiesFromDefaults(CapacitiesInfo capacitiesInfo)
        {
            if (null == Defaults.Instance.VehiclesDefaults.CapacitiesDefaultValues)
            {
                return; // defaults is empty
            }
            var capacitiesDefaultValues = Defaults.Instance.VehiclesDefaults.CapacitiesDefaultValues.Capacity;

            for (int index = 0; index < capacitiesDefaultValues.Length; ++index)
            {
                try
                {   // init it as much as possible
                    var description = capacitiesDefaultValues[index];
                    for (int capacityIndex = 0; capacityIndex < capacitiesInfo.Count; ++capacityIndex)
                    {   // find capacity index by name
                        var capacityInfo = capacitiesInfo[capacityIndex];
                        if (capacityInfo.Name.Equals(description.Name, StringComparison.OrdinalIgnoreCase))
                        {          // set value by index
                            _capacities[capacityIndex] = description.Value;
                            break; // work done
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Warning(ex);
                }
            }

            _UpdateCapacitiesEntityData();
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Explicit initialization. Must be called on creating new project.
        /// </summary>
        public void PostInit(CapacitiesInfo capacitiesInfo,
                             OrderCustomPropertiesInfo orderCustomPropertiesInfo)
        {
            Debug.Assert(!_isInited); // init once

            // add scheme objects
            DataModel.ConfigSchemes scheme = DataModel.ConfigSchemes.CreateConfigSchemes(SCHEME_ID_CAPACITIES);
            scheme.Name  = SCHEME_NAME_CAPACITIES;
            scheme.Value = ConfigDataSerializer.SerializeCapacitiesInfo(capacitiesInfo);
            AddObject(SCHEMES_ENTITY_SET, scheme);

            scheme       = DataModel.ConfigSchemes.CreateConfigSchemes(SCHEME_ID_ORDERPROPERTIES);
            scheme.Name  = SCHEME_NAME_ORDERPROPERTIES;
            scheme.Value = ConfigDataSerializer.SerializeOrderCustomPropertiesInfo(orderCustomPropertiesInfo);
            AddObject(SCHEMES_ENTITY_SET, scheme);

            base.SaveChanges();

            // create object factory
            ObjectInitData initData = new ObjectInitData();

            initData.CapacitiesInfo            = capacitiesInfo;
            initData.OrderCustomPropertiesInfo = orderCustomPropertiesInfo;

            _fact        = new DataObjectFactory(initData);
            _objInitData = initData;

            // Attach handler for SavingChanges event.
            this.SavingChanges += new EventHandler(DataObjectContext_SavingChanges);
            _isInited           = true;
        }
Example #3
0
        /// <summary>
        /// Add Capacities properties
        /// </summary>
        private void _AddCapacityProperties(string prePath, IList <object> mapProperties,
                                            IList <object> selectedMapProperties, StringCollection selectedConfig)
        {
            // specials type: capacities
            if (App.Current.Project != null)
            {
                CapacitiesInfo info = App.Current.Project.CapacitiesInfo;
                for (int i = 0; i < info.Count; ++i)
                {
                    CapacityInfo capacityInfo = info[i];

                    Unit units;
                    if (RegionInfo.CurrentRegion.IsMetric)
                    {
                        units = capacityInfo.DisplayUnitMetric;
                    }
                    else
                    {
                        units = capacityInfo.DisplayUnitUS;
                    }

                    _AddPropertyTip(prePath, "Capacities.[" + i.ToString() + "]", info[i].Name,
                                    mapProperties, selectedMapProperties, selectedConfig, units, units);
                }
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Parses CapacitiesInfo.
        /// </summary>
        public static CapacitiesInfo ParseCapacitiesInfo(string xml)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);

            CapacitiesInfo info = null;
            XmlNode root = xmlDoc.SelectSingleNode(NODE_CAPACITIES);
            if (root != null)
            {
                info = new CapacitiesInfo();
                foreach (XmlNode node in root.ChildNodes)
                {
                    if (node.NodeType != XmlNodeType.Element)
                        continue; // skip comments and other non element nodes

                    if (node.Name.Equals(NODE_CAPACITY, StringComparison.OrdinalIgnoreCase))
                    {
                        XmlAttributeCollection attributes = node.Attributes;
                        string name = attributes[ATTR_NAME].Value;
                        Unit unitUS = (Unit)Enum.Parse(typeof(Unit), attributes[ATTR_DISPLAYUNITUS].Value);
                        Unit unitMetric = (Unit)Enum.Parse(typeof(Unit), attributes[ATTR_DISPLAYUNITMETRIC].Value);
                        info.Add(new CapacityInfo(name, unitUS, unitMetric));
                    }
                    else
                        throw new FormatException();
                }
            }
            else
                throw new FormatException();

            return info;
        }
        /// <summary>
        /// Creates collection of custom order properties to be exported.
        /// </summary>
        /// <param name="capacitiesInfo">The reference to capacities info object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="orderCustomPropertiesInfo">The reference custom order properties info
        /// object.</param>
        /// <param name="addressFields">The reference to address fields object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="orderPropertiesFilter">Function returning true for custom order
        /// property names which should not be exported.</param>
        /// <returns>A reference to the collection of custom order properties to be exported.
        /// </returns>
        private static IEnumerable <OrderPropertyInfo> _CreateExportOrderProperties(
            CapacitiesInfo capacitiesInfo,
            OrderCustomPropertiesInfo orderCustomPropertiesInfo,
            AddressField[] addressFields,
            Func <string, bool> orderPropertiesFilter)
        {
            Debug.Assert(capacitiesInfo != null);
            Debug.Assert(orderCustomPropertiesInfo != null);
            Debug.Assert(addressFields != null);

            if (orderPropertiesFilter == null)
            {
                orderPropertiesFilter = _ => false;
            }

            var names = new List <string>(Order.GetPropertyNames(
                                              capacitiesInfo,
                                              orderCustomPropertiesInfo,
                                              addressFields));
            var titles = new List <string>(Order.GetPropertyTitles(
                                               capacitiesInfo,
                                               orderCustomPropertiesInfo,
                                               addressFields));
            var orderPropertiesToExport = names
                                          .Zip(titles, OrderPropertyInfo.Create)
                                          .Where(info => !orderPropertiesFilter(info.Name))
                                          .ToArray();

            return(orderPropertiesToExport);
        }
        /// <summary>
        /// Serializes CapacitiesInfo object.
        /// </summary>
        public static string SerializeCapacitiesInfo(CapacitiesInfo capacitiesInfo)
        {
            string    xml    = null;
            XmlWriter writer = null;

            try
            {
                StringBuilder sb = new StringBuilder();
                writer = XmlWriter.Create(sb);

                writer.WriteStartElement(NODE_CAPACITIES);
                for (int index = 0; index < capacitiesInfo.Count; index++)
                {
                    writer.WriteStartElement(NODE_CAPACITY);
                    writer.WriteAttributeString(ATTR_NAME, capacitiesInfo[index].Name);
                    writer.WriteAttributeString(ATTR_DISPLAYUNITUS, capacitiesInfo[index].DisplayUnitUS.ToString());
                    writer.WriteAttributeString(ATTR_DISPLAYUNITMETRIC, capacitiesInfo[index].DisplayUnitMetric.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.Flush();

                xml = sb.ToString();
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }

            return(xml);
        }
Example #7
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Creates a new instance of the <c>Exporter</c> class.
        /// </summary>
        /// <param name="capacitiesInfo">Capacities information.</param>
        /// <param name="orderCustomPropertiesInfo">Order custom properties infromation.</param>
        /// <param name="addressFields">Geocoder address fields.</param>
        public Exporter(CapacitiesInfo capacitiesInfo,
                        OrderCustomPropertiesInfo orderCustomPropertiesInfo,
                        AddressField[] addressFields)
        {
            _structureKeeper = GetReader(capacitiesInfo, orderCustomPropertiesInfo, addressFields);

            _InitExtendedFields();
        }
Example #8
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Initializes a new instance of the <c>Vehicle</c> class.
        /// </summary>
        /// <param name="capacitiesInfo">Information about capacities. Get it from the project.</param>
        public Vehicle(CapacitiesInfo capacitiesInfo)
            : base(DataModel.Vehicles.CreateVehicles(Guid.NewGuid()))
        {
            _Entity.FuelConsumption = Defaults.Instance.VehiclesDefaults.FuelEconomy;
            _CreateCapacities(capacitiesInfo);
            _SpecialtiesWrap.DataObjects.CollectionChanged += new NotifyCollectionChangedEventHandler(_Specialties_CollectionChanged);
            base.SetCreationTime();
        }
Example #9
0
        private void _CreateCapacities(CapacitiesInfo capacitiesInfo)
        {
            _capacitiesInfo = capacitiesInfo;
            _capacities     = new Capacities(capacitiesInfo);
            _InitCapacitiesFromDefaults(capacitiesInfo);

            _capacities.PropertyChanged += new PropertyChangedEventHandler(Capacities_PropertyChanged);
        }
        public void Initialize(App app)
        {
            m_application = app;
            CapacitiesInfo capInfo = App.Current.Project.CapacitiesInfo;

            foreach (CapacityInfo c in capInfo)
            {
                itemList.Add(c.Name);
            }
        }
Example #11
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 #12
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);
         }
     }
 }
        /// <summary>
        /// Exports specified stops to serializable stop information.
        /// </summary>
        /// <param name="stops">The reference to the collection of stops to be exported.</param>
        /// <param name="capacitiesInfo">The reference to capacities info object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="orderCustomPropertiesInfo">The reference custom order properties info
        /// object.</param>
        /// <param name="addressFields">The reference to address fields object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="solver">The reference to VRPSolver to be used for retrieving
        /// curb approach policies for stops.</param>
        /// <param name="orderPropertiesFilter">Function returning true for custom order
        /// property names which should not be exported.</param>
        /// <returns>A reference to the collection of serializable stop information objects.
        /// </returns>
        public static IEnumerable <StopInfo> ExportStops(
            IEnumerable <Stop> stops,
            CapacitiesInfo capacitiesInfo,
            OrderCustomPropertiesInfo orderCustomPropertiesInfo,
            AddressField[] addressFields,
            IVrpSolver solver,
            Func <string, bool> orderPropertiesFilter = null)
        {
            Debug.Assert(stops != null);
            Debug.Assert(stops.All(stop => stop != null));
            Debug.Assert(stops.All(stop => stop.Route != null));
            Debug.Assert(capacitiesInfo != null);
            Debug.Assert(orderCustomPropertiesInfo != null);
            Debug.Assert(addressFields != null);

            if (!stops.Any())
            {
                return(Enumerable.Empty <StopInfo>());
            }

            var capacityProperties = Order.GetPropertiesInfo(capacitiesInfo);
            var addressProperties  = Order.GetPropertiesInfo(addressFields);
            var customProperties   = Order.GetPropertiesInfo(orderCustomPropertiesInfo);

            var exportOrderProperties = _CreateExportOrderProperties(
                capacitiesInfo,
                orderCustomPropertiesInfo,
                addressFields,
                orderPropertiesFilter);

            // Make a dictionary for mapping routes to collection of sorted route stops.
            var routesSortedStops = stops
                                    .Select(stop => stop.Route)
                                    .Distinct()
                                    .ToDictionary(route => route, route => CommonHelpers.GetSortedStops(route));

            // Prepare result by exporting each stop individually.
            var settings = CommonHelpers.GetSolverSettings(solver);
            var result   = stops
                           .Select(stop => _ExportStop(
                                       stop,
                                       routesSortedStops[stop.Route],
                                       exportOrderProperties,
                                       addressProperties,
                                       capacityProperties,
                                       customProperties,
                                       settings))
                           .ToList();

            return(result);
        }
        /// <summary>
        /// Exports specified stops to serializable stop information.
        /// </summary>
        /// <param name="stops">The reference to the collection of stops to be exported.</param>
        /// <param name="capacitiesInfo">The reference to capacities info object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="orderCustomPropertiesInfo">The reference custom order properties info
        /// object.</param>
        /// <param name="addressFields">The reference to address fields object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="solver">The reference to VRPSolver to be used for retrieving
        /// curb approach policies for stops.</param>
        /// <param name="orderPropertiesFilter">Function returning true for custom order
        /// property names which should not be exported.</param>
        /// <returns>A reference to the collection of serializable stop information objects.
        /// </returns>
        public static IEnumerable<StopInfo> ExportStops(
            IEnumerable<Stop> stops,
            CapacitiesInfo capacitiesInfo,
            OrderCustomPropertiesInfo orderCustomPropertiesInfo,
            AddressField[] addressFields,
            IVrpSolver solver,
            Func<string, bool> orderPropertiesFilter = null)
        {
            Debug.Assert(stops != null);
            Debug.Assert(stops.All(stop => stop != null));
            Debug.Assert(stops.All(stop => stop.Route != null));
            Debug.Assert(capacitiesInfo != null);
            Debug.Assert(orderCustomPropertiesInfo != null);
            Debug.Assert(addressFields != null);

            if (!stops.Any())
            {
                return Enumerable.Empty<StopInfo>();
            }

            var capacityProperties = Order.GetPropertiesInfo(capacitiesInfo);
            var addressProperties = Order.GetPropertiesInfo(addressFields);
            var customProperties = Order.GetPropertiesInfo(orderCustomPropertiesInfo);

            var exportOrderProperties = _CreateExportOrderProperties(
                capacitiesInfo,
                orderCustomPropertiesInfo,
                addressFields,
                orderPropertiesFilter);

            // Make a dictionary for mapping routes to collection of sorted route stops.
            var routesSortedStops = stops
                .Select(stop => stop.Route)
                .Distinct()
                .ToDictionary(route => route, route => CommonHelpers.GetSortedStops(route));

            // Prepare result by exporting each stop individually.
            var settings = CommonHelpers.GetSolverSettings(solver);
            var result = stops
                .Select(stop => _ExportStop(
                    stop,
                    routesSortedStops[stop.Route],
                    exportOrderProperties,
                    addressProperties,
                    capacityProperties,
                    customProperties,
                    settings))
                .ToList();

            return result;
        }
        private CapacitiesInfo _LoadCapacitiesInfo()
        {
            CapacitiesInfo info = null;

            try
            {
                string xml = _GetConfigScheme(SCHEME_ID_CAPACITIES);
                info = ConfigDataSerializer.ParseCapacitiesInfo(xml);
            }
            catch (Exception e)
            {
                throw new DataException(String.Format(
                                            Properties.Messages.Error_ConfigSchemeLoadFailed, SCHEME_ID_CAPACITIES), e);
            }

            return(info);
        }
Example #16
0
        public void Initialize(App app)
        {
            m_application = app;
            CapacitiesInfo            capInfo  = App.Current.Project.CapacitiesInfo;
            OrderCustomPropertiesInfo propInfo = App.Current.Project.OrderCustomPropertiesInfo;

            foreach (CapacityInfo c in capInfo)
            {
                itemList.Add(c.Name);
            }

            foreach (OrderCustomProperty c in propInfo)
            {
                itemList.Add(c.Name);
            }

            App.Current.ApplicationInitialized += new EventHandler(Current_ApplicationInitialized);
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Initializes a new instance of ExportValidator.
        /// </summary>
        /// <param name="capacitiesInfo">Current capacities info.</param>
        /// <param name="addressFields">Current address fields.</param>
        public ExportValidator(CapacitiesInfo capacitiesInfo,
                               AddressField[] addressFields)
        {
            if (null == capacitiesInfo)
                throw new ArgumentNullException("capacitiesInfo"); // exception

            if (null == addressFields)
                throw new ArgumentNullException("addressFields"); // exception

            // load export structure
            ExportStructureReader reader = Exporter.GetReader(capacitiesInfo,
                                                              new OrderCustomPropertiesInfo(),
                                                              addressFields);

            _readedNames = new List<string>();
            _GetFieldNames(reader, ExportType.Access, _readedNames);
            _GetFieldNames(reader, ExportType.TextOrders, _readedNames);
            _GetFieldNames(reader, ExportType.TextStops, _readedNames);

            _description = reader.GetTableDescription(TableType.Stops);
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Parses CapacitiesInfo.
        /// </summary>
        public static CapacitiesInfo ParseCapacitiesInfo(string xml)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xml);

            CapacitiesInfo info = null;
            XmlNode        root = xmlDoc.SelectSingleNode(NODE_CAPACITIES);

            if (root != null)
            {
                info = new CapacitiesInfo();
                foreach (XmlNode node in root.ChildNodes)
                {
                    if (node.NodeType != XmlNodeType.Element)
                    {
                        continue; // skip comments and other non element nodes
                    }
                    if (node.Name.Equals(NODE_CAPACITY, StringComparison.OrdinalIgnoreCase))
                    {
                        XmlAttributeCollection attributes = node.Attributes;
                        string name       = attributes[ATTR_NAME].Value;
                        Unit   unitUS     = (Unit)Enum.Parse(typeof(Unit), attributes[ATTR_DISPLAYUNITUS].Value);
                        Unit   unitMetric = (Unit)Enum.Parse(typeof(Unit), attributes[ATTR_DISPLAYUNITMETRIC].Value);
                        info.Add(new CapacityInfo(name, unitUS, unitMetric));
                    }
                    else
                    {
                        throw new FormatException();
                    }
                }
            }
            else
            {
                throw new FormatException();
            }

            return(info);
        }
Example #19
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Creates and inits a new instance of the <c>ExportStructureReader</c> class.
        /// </summary>
        /// <param name="capacitiesInfo">Capacities information.</param>
        /// <param name="orderCustomPropertiesInfo">Order custom properties infromation.</param>
        /// <param name="addressFields">Geocoder address fields.</param>
        /// <returns>Created and inited Export Structure Reader.</returns>
        internal static ExportStructureReader GetReader(CapacitiesInfo capacitiesInfo,
                                                        OrderCustomPropertiesInfo orderCustomPropertiesInfo,
                                                        AddressField[] addressFields)
        {
            Debug.Assert(null != capacitiesInfo);
            Debug.Assert(null != orderCustomPropertiesInfo);
            Debug.Assert(null != addressFields);

            // load export structure
            var structure          = ResourceLoader.ReadFileAsString(EXPORT_STRUCTURE_FILE_NAME);
            var exportStructureDoc = new System.Xml.XmlDocument();

            exportStructureDoc.LoadXml(structure);

            ExportStructureReader reader = new ExportStructureReader();

            reader.Load(exportStructureDoc,
                        capacitiesInfo,
                        orderCustomPropertiesInfo,
                        addressFields);

            return(reader);
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Initializes a new instance of ExportValidator.
        /// </summary>
        /// <param name="capacitiesInfo">Current capacities info.</param>
        /// <param name="addressFields">Current address fields.</param>
        public ExportValidator(CapacitiesInfo capacitiesInfo,
                               AddressField[] addressFields)
        {
            if (null == capacitiesInfo)
            {
                throw new ArgumentNullException("capacitiesInfo"); // exception
            }
            if (null == addressFields)
            {
                throw new ArgumentNullException("addressFields"); // exception
            }
            // load export structure
            ExportStructureReader reader = Exporter.GetReader(capacitiesInfo,
                                                              new OrderCustomPropertiesInfo(),
                                                              addressFields);

            _readedNames = new List <string>();
            _GetFieldNames(reader, ExportType.Access, _readedNames);
            _GetFieldNames(reader, ExportType.TextOrders, _readedNames);
            _GetFieldNames(reader, ExportType.TextStops, _readedNames);

            _description = reader.GetTableDescription(TableType.Stops);
        }
Example #21
0
        /// <summary>
        /// Parse string and split it to capacities values
        /// </summary>
        /// <param name="value">Capacities string</param>
        /// <param name="capacitiesInfo">Project capacities info</param>
        /// <returns>Parsed capacities</returns>
        internal static Capacities CreateFromDBString(string value, CapacitiesInfo capacitiesInfo)
        {
            Capacities capacities = new Capacities(capacitiesInfo);

            if (null != value)
            {
                value = value.Replace(CommonHelpers.SEPARATOR_OLD, CommonHelpers.SEPARATOR); // NOTE: for support old projects

                char[] valuesSeparator = new char[1] {
                    CommonHelpers.SEPARATOR
                };
                string[] capacitiesValues = value.Split(valuesSeparator, StringSplitOptions.None);

                System.Diagnostics.Debug.Assert(capacitiesValues.Length == capacitiesInfo.Count);

                for (int index = 0; index < capacitiesValues.Length; index++)
                {
                    double capacityValue = double.Parse(capacitiesValues[index], CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE));
                    capacities[index] = capacityValue;
                }
            }

            return(capacities);
        }
        /// <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 #23
0
        /// <summary>
        /// Gets list of object data field for application types.
        /// </summary>
        /// <param name="type">Propery type.</param>
        /// <param name="title">Property title.</param>
        /// <param name="isSourceShape">Flag is source shape file.</param>
        /// <param name="list">Output list object data field.</param>
        static private bool _GetAppTypeFieldInfos(Type type,
                                                  string title,
                                                  bool isSourceShape,
                                                  ref List <ObjectDataFieldInfo> list)
        {
            bool result = true;

            if (typeof(OrderCustomProperties) == type)
            {   // specials type: related object OrderCustomProperty
                OrderCustomPropertiesInfo infos = App.Current.Project.OrderCustomPropertiesInfo;
                for (int index = 0; index < infos.Count; ++index)
                {
                    Type propType = (infos[index].Type == OrderCustomPropertyType.Text) ?
                                    typeof(string) : typeof(double);
                    var info = new DataFieldInfo(infos[index].Name, propType);
                    list.Add(new ObjectDataFieldInfo(info, false));
                }
            }

            else if (typeof(Capacities) == type)
            {   // specials type: related object Capacities
                CapacitiesInfo infos = App.Current.Project.CapacitiesInfo;
                for (int index = 0; index < infos.Count; ++index)
                {
                    var info = new DataFieldInfo(infos[index].Name, typeof(double));
                    list.Add(new ObjectDataFieldInfo(info, false));
                }
            }

            else if (typeof(Address) == type)
            {   // specials type: related object Address
                AddressField[] fields = App.Current.Geocoder.AddressFields;
                for (int index = 0; index < fields.Length; ++index)
                {
                    var info = new DataFieldInfo(fields[index].Title, typeof(string));
                    list.Add(new ObjectDataFieldInfo(info, false));
                }
            }

            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
                var info      = new DataFieldInfo(title, typeof(string));
                var fieldInfo = new ObjectDataFieldInfo(info, false);
                list.Add(fieldInfo);
            }

            else
            {
                result = false;
            }

            return(result);
        }
Example #24
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();
        }
        /// <summary>
        /// Serializes CapacitiesInfo object.
        /// </summary>
        public static string SerializeCapacitiesInfo(CapacitiesInfo capacitiesInfo)
        {
            string xml = null;
            XmlWriter writer = null;
            try
            {
                StringBuilder sb = new StringBuilder();
                writer = XmlWriter.Create(sb);

                writer.WriteStartElement(NODE_CAPACITIES);
                for (int index = 0; index < capacitiesInfo.Count; index++)
                {
                    writer.WriteStartElement(NODE_CAPACITY);
                    writer.WriteAttributeString(ATTR_NAME, capacitiesInfo[index].Name);
                    writer.WriteAttributeString(ATTR_DISPLAYUNITUS, capacitiesInfo[index].DisplayUnitUS.ToString());
                    writer.WriteAttributeString(ATTR_DISPLAYUNITMETRIC, capacitiesInfo[index].DisplayUnitMetric.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.Flush();

                xml = sb.ToString();
            }
            finally
            {
                if (writer != null)
                    writer.Close();
            }

            return xml;
        }
        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);
        }
Example #27
0
 private void _InitCapacities(DataModel.Vehicles entity, CapacitiesInfo capacitiesInfo)
 {
     _capacities = Capacities.CreateFromDBString(entity.Capacities, capacitiesInfo);
     _capacities.PropertyChanged += new PropertyChangedEventHandler(Capacities_PropertyChanged);
 }
Example #28
0
 ///////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////
 private void _CreateCapacities(CapacitiesInfo capacitiesInfo)
 {
     _capacitiesInfo = capacitiesInfo;
     _capacities = new Capacities(capacitiesInfo);
     _capacities.PropertyChanged += new PropertyChangedEventHandler(Capacities_PropertyChanged);
 }
        /// <summary>
        /// Loads table description.
        /// </summary>
        /// <param name="nodeTable">Table's node.</param>
        /// <param name="capacityInfos">Capacity informations.</param>
        /// <param name="orderCustomPropertyInfos">Order custom property informations.</param>
        /// <param name="addressFields">Address fields.</param>
        /// <returns>Readed table description.</returns>
        private TableDescription _LoadTableDescription(XmlNode nodeTable,
                                                       CapacitiesInfo capacityInfos,
                                                       OrderCustomPropertiesInfo orderCustomPropertyInfos,
                                                       AddressField[] addressFields)
        {
            TableType type =
                (TableType)Enum.Parse(typeof(TableType),
                                      nodeTable.Attributes[ATTRIBUTE_NAME_TYPE].Value);

            string name = nodeTable.Attributes[ATTRIBUTE_NAME_NAME].Value;

            List<FieldInfo> fields = null;
            foreach (XmlNode node in nodeTable.ChildNodes)
            {
                if (node.NodeType != XmlNodeType.Element)
                    continue; // skip comments and other non element nodes

                if (node.Name.Equals(NODE_NAME_FIELDS, StringComparison.OrdinalIgnoreCase))
                    fields = _LoadFields(node);
            }

            return new TableDescription(name,
                                        type,
                                        fields,
                                        capacityInfos,
                                        orderCustomPropertyInfos,
                                        addressFields);
        }
Example #30
0
 ///////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////
 /// <summary>
 /// Initializes a new instance of the <c>Vehicle</c> class.
 /// </summary>
 /// <param name="capacitiesInfo">Information about capacities. Get it from the project.</param>
 public Vehicle(CapacitiesInfo capacitiesInfo)
     : base(DataModel.Vehicles.CreateVehicles(Guid.NewGuid()))
 {
     _Entity.FuelConsumption = Defaults.Instance.VehiclesDefaults.FuelEconomy;
     _CreateCapacities(capacitiesInfo);
     _SpecialtiesWrap.DataObjects.CollectionChanged += new NotifyCollectionChangedEventHandler(_Specialties_CollectionChanged);
     base.SetCreationTime();
 }
        /// <summary>
        /// Creates project.
        /// </summary>
        /// <param name="name">Project's name.</param>
        /// <param name="folderPath">Project's folder path.</param>
        /// <param name="description">Proejct's description.</param>
        /// <returns>Created project</returns>
        public static Project CreateProject(string name, string folderPath, string description, CapacitiesInfo capacitiesInfo,
            OrderCustomPropertiesInfo orderCustomPropertiesInfo, FuelTypesInfo fuelTypesInfo /*serivces*/,
                                     IProjectSaveExceptionHandler logHandler)
        {
            WorkspaceHandler workspaceHandler = new WorkspaceHandler(logHandler);

            if (name == null)
                throw new ArgumentNullException("name");
            if (folderPath == null)
                throw new ArgumentNullException("folderPath");
            if (description == null)
                throw new ArgumentNullException("description");

            if (!CheckMaximumLengthConstraint(orderCustomPropertiesInfo))
                throw new ApplicationException(Properties.Messages.Error_OrderCustomPropTooLong);

            bool isDBCreated = false;
            string dbPath = "";

            try
            {
                name = name.Trim();

                // make project configuration path
                string projCfgPath = System.IO.Path.Combine(folderPath, name);
                projCfgPath += ProjectConfiguration.FILE_EXTENSION;

                string databasePath = ProjectConfiguration.GetDatabaseFileName(name);
                // create project configuration
                ProjectConfiguration projConfig = new ProjectConfiguration(name, folderPath, description,
                    databasePath, null, DateTime.Now);

                projConfig.Validate();

                projConfig.Save();

                dbPath = projConfig.DatabasePath;

                DatabaseEngine.DeleteDatabase(dbPath);

                // create database
                DatabaseEngine.CreateDatabase(dbPath, SchemeVersion.CreationScript);
                isDBCreated = true;

                Project project = new Project(projCfgPath, capacitiesInfo,
                    orderCustomPropertiesInfo, workspaceHandler);

                foreach (FuelTypeInfo fuelTypeInfo in fuelTypesInfo)
                {
                    FuelType projectFuelType = new FuelType();
                    projectFuelType.Name = fuelTypeInfo.Name;
                    projectFuelType.Price = fuelTypeInfo.Price;
                    projectFuelType.Co2Emission = fuelTypeInfo.Co2Emission;
                    project.FuelTypes.Add(projectFuelType);
                }

                project.Save();

                workspaceHandler.Handled = true;

                return project;
            }
            catch(Exception ex)
            {
                Logger.Info(ex);
                if (isDBCreated)
                    DatabaseEngine.DeleteDatabase(dbPath);

                throw;
            }
        }
        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();
        }
        /// <summary>
        /// Adds capacity relative fields.
        /// </summary>
        /// <param name="capacityInfos">Capacities informations.</param>
        /// <param name="info">Field information with data settings.</param>
        private void _AddCapacityRelativeFields(CapacitiesInfo capacityInfos, FieldInfo info)
        {
            for (int index = 0; index < capacityInfos.Count; ++index)
            {
                FieldInfo infoRealtion = (FieldInfo)info.Clone();

                CapacityInfo capacityInfo = capacityInfos[index];
                _UpdateInfoWithInfoName(capacityInfo.Name, info, ref infoRealtion);

                // format description
                if (!string.IsNullOrEmpty(infoRealtion.Description))
                {
                    if ((infoRealtion.Description == Properties.Resources.ExportFieldDescriptionCapacity) ||
                        (infoRealtion.Description == Properties.Resources.ExportFieldDescriptionRelativeCapacity))
                    {
                        infoRealtion.Description =
                            _FormatCapacityDescription(capacityInfo, infoRealtion.Description);
                    }

                    else if (infoRealtion.Description == Properties.Resources.ExportFieldDescriptionTotal)
                    {
                        infoRealtion.Description =
                            _FormatCapacityDescriptionTotal(capacityInfo, infoRealtion.Description);
                    }

                    else if (infoRealtion.Description == Properties.Resources.ExportFieldDescriptionUtilization)
                    {
                        infoRealtion.Description =
                            _FormatCapacityDescriptionUtilization(capacityInfo, infoRealtion.Description);
                    }

                    // else Do nothing - use without modification
                }

                Debug.Assert(!string.IsNullOrEmpty(infoRealtion.Name));
                _fieldsMap.Add(infoRealtion.Name, infoRealtion);
            }
        }
Example #34
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Initializes a new instance of the <c>Order</c> class.
        /// </summary>
        /// <param name="capacitiesInfo">Information about capacities.</param>
        /// <param name="customPropertiesInfo">Information about custom properties.</param>
        public Order(CapacitiesInfo capacitiesInfo, OrderCustomPropertiesInfo customPropertiesInfo)
            : base(DataModel.Orders.CreateOrders(Guid.NewGuid()))
        {
            // Enable address validation.
            IsAddressValidationEnabled = true;

            _Entity.OrderType = (int)Defaults.Instance.OrdersDefaults.OrderType;
            _Entity.OrderPriority = (int)Defaults.Instance.OrdersDefaults.Priority;
            _Entity.ServiceTime = Defaults.Instance.OrdersDefaults.ServiceTime;
            _Entity.CurbApproach = (int)Defaults.Instance.OrdersDefaults.CurbApproach;
            _Entity.MaxViolationTime = Defaults.Instance.OrdersDefaults.MaxViolationTime;

            _timeWindow1.IsWideOpen = Defaults.Instance.OrdersDefaults.TimeWindow.IsWideopen;
            if (!_timeWindow1.IsWideOpen)
            {
                _timeWindow1.From = Defaults.Instance.OrdersDefaults.TimeWindow.From;
                _timeWindow1.To = Defaults.Instance.OrdersDefaults.TimeWindow.To;
                _timeWindow1.Day = 0;
            }

            _timeWindow2.IsWideOpen = Defaults.Instance.OrdersDefaults.TimeWindow2.IsWideopen;
            if (!_timeWindow2.IsWideOpen)
            {
                _timeWindow2.From = Defaults.Instance.OrdersDefaults.TimeWindow2.From;
                _timeWindow2.To = Defaults.Instance.OrdersDefaults.TimeWindow2.To;
                _timeWindow2.Day = 0;
            }

            _SubscribeToAddressEvent();
            _CreateCapacities(capacitiesInfo);
            _CreateCustomProperties(customPropertiesInfo);

            _timeWindow1.PropertyChanged += new PropertyChangedEventHandler(TimeWindow_PropertyChanged1);
            _timeWindow2.PropertyChanged += new PropertyChangedEventHandler(TimeWindow_PropertyChanged2);
            _VehicleSpecialtiesWrap.DataObjects.CollectionChanged += new NotifyCollectionChangedEventHandler(VehicleSpecialties_CollectionChanged);
            _DriverSpecialtiesWrap.DataObjects.CollectionChanged += new NotifyCollectionChangedEventHandler(DriverSpecialties_CollectionChanged);

            base.SetCreationTime();
        }
Example #35
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Initialize capacities from default values.
        /// </summary>
        /// <param name="capacitiesInfo">Capacity information.</param>
        private void _InitCapacitiesFromDefaults(CapacitiesInfo capacitiesInfo)
        {
            if (null == Defaults.Instance.VehiclesDefaults.CapacitiesDefaultValues)
                return; // defaults is empty

            var capacitiesDefaultValues = Defaults.Instance.VehiclesDefaults.CapacitiesDefaultValues.Capacity;
            for (int index = 0; index < capacitiesDefaultValues.Length; ++index)
            {
                try
                {   // init it as much as possible
                    var description = capacitiesDefaultValues[index];
                    for (int capacityIndex = 0; capacityIndex < capacitiesInfo.Count; ++capacityIndex)
                    {   // find capacity index by name
                        var capacityInfo = capacitiesInfo[capacityIndex];
                        if (capacityInfo.Name.Equals(description.Name, StringComparison.OrdinalIgnoreCase))
                        {   // set value by index
                            _capacities[capacityIndex] = description.Value;
                            break; // work done
                        }
                    }
                }
                catch (Exception ex)
                {
                    Logger.Warning(ex);
                }
            }

            _UpdateCapacitiesEntityData();
        }
Example #36
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Initializes a new instance of the <c>Capacities</c> class.
        /// </summary>
        public Capacities(CapacitiesInfo capacitiesInfo)
        {
            _capacitiesInfo = capacitiesInfo;
            _values         = new double[_capacitiesInfo.Count];
        }
        /// <summary>
        /// Creates collection of custom order properties to be exported.
        /// </summary>
        /// <param name="capacitiesInfo">The reference to capacities info object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="orderCustomPropertiesInfo">The reference custom order properties info
        /// object.</param>
        /// <param name="addressFields">The reference to address fields object to be used
        /// for retrieving custom order properties for stops.</param>
        /// <param name="orderPropertiesFilter">Function returning true for custom order
        /// property names which should not be exported.</param>
        /// <returns>A reference to the collection of custom order properties to be exported.
        /// </returns>
        private static IEnumerable<OrderPropertyInfo> _CreateExportOrderProperties(
            CapacitiesInfo capacitiesInfo,
            OrderCustomPropertiesInfo orderCustomPropertiesInfo,
            AddressField[] addressFields,
            Func<string, bool> orderPropertiesFilter)
        {
            Debug.Assert(capacitiesInfo != null);
            Debug.Assert(orderCustomPropertiesInfo != null);
            Debug.Assert(addressFields != null);

            if (orderPropertiesFilter == null)
            {
                orderPropertiesFilter = _ => false;
            }

            var names = new List<string>(Order.GetPropertyNames(
                capacitiesInfo,
                orderCustomPropertiesInfo,
                addressFields));
            var titles = new List<string>(Order.GetPropertyTitles(
                capacitiesInfo,
                orderCustomPropertiesInfo,
                addressFields));
            var orderPropertiesToExport = names
                .Zip(titles, OrderPropertyInfo.Create)
                .Where(info => !orderPropertiesFilter(info.Name))
                .ToArray();

            return orderPropertiesToExport;
        }
        /// <summary>
        /// Loads table descriptions.
        /// </summary>
        /// <param name="nodeTables">Tables node.</param>
        /// <param name="capacityInfos">Capacity informations.</param>
        /// <param name="orderCustomPropertyInfos">Order custom property informations.</param>
        /// <param name="addressFields">Address fields.</param>
        private void _LoadTableDescriptions(XmlNode nodeTables,
                                            CapacitiesInfo capacityInfos,
                                            OrderCustomPropertiesInfo orderCustomPropertyInfos,
                                            AddressField[] addressFields)
        {
            foreach (XmlNode node in nodeTables.ChildNodes)
            {
                if (node.NodeType != XmlNodeType.Element)
                    continue; // skip comments and other non element nodes

                if (node.Name.Equals(NODE_NAME_TABLEDEFINITION, StringComparison.OrdinalIgnoreCase))
                {
                    TableDescription table = _LoadTableDescription(node,
                                                                   capacityInfos,
                                                                   orderCustomPropertyInfos,
                                                                   addressFields);
                    if (null != table)
                    {
                        Debug.Assert(!_listTables.ContainsKey(table.Type));
                        _listTables.Add(table.Type, table);
                    }
                }
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Creates a new instance of the <c>TableDescription</c> class.
        /// </summary>
        /// <param name="name">Table name.</param>
        /// <param name="type">Table type.</param>
        /// <param name="fields">Table fields.</param>
        /// <param name="capacityInfos">Capacity infos.</param>
        /// <param name="orderCustomPropertyInfos">Order custom properties infos.</param>
        /// <param name="addressFields">Address fields.</param>
        public TableDescription(string name,
                                TableType type,
                                List<FieldInfo> fields,
                                CapacitiesInfo capacityInfos,
                                OrderCustomPropertiesInfo orderCustomPropertyInfos,
                                AddressField[] addressFields)
        {
            Debug.Assert(!string.IsNullOrEmpty(name));
            Debug.Assert(0 < fields.Count);
            Debug.Assert(null != capacityInfos);
            Debug.Assert(null != orderCustomPropertyInfos);
            Debug.Assert(null != addressFields);

            _capacityInfos = capacityInfos;
            _orderCustomPropertyInfos = orderCustomPropertyInfos;
            _addressFields = addressFields;

            _name = name;
            _type = type;

            foreach (FieldInfo info in fields)
            {
                Debug.Assert(!_fieldsMap.ContainsKey(info.Name));

                if (string.IsNullOrEmpty(info.RelationType))
                    _fieldsMap.Add(info.Name, info);
                else
                {   // special routine to relative fields
                    switch (info.RelationType)
                    {
                        case "Capacities":
                            _AddCapacityRelativeFields(capacityInfos, info);
                            break;

                        case "CustomOrderProperties":
                            _AddCustomOrderPropertyRelativeFields(orderCustomPropertyInfos, info);
                            break;

                        case "Address":
                            _AddAddressRelativeFields(addressFields, info);
                            break;

                        default:
                            Debug.Assert(false); // NOTE: not supported
                            break;
                    }
                }
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Loads export settings.
        /// </summary>
        /// <param name="doc">Export keeper document.</param>
        /// <param name="capacityInfos">Capacity informations.</param>
        /// <param name="orderCustomPropertiesInfo">Order custom property informations.</param>
        /// <param name="addressFields">Address fields.</param>
        public void Load(XmlDocument doc, CapacitiesInfo capacityInfos,
                         OrderCustomPropertiesInfo orderCustomPropertiesInfo,
                         AddressField[] addressFields)
        {
            Debug.Assert(null != doc);

            foreach (XmlNode node in doc.DocumentElement.ChildNodes)
            {
                if (node.NodeType != XmlNodeType.Element)
                    continue; // skip comments and other non element nodes

                if (node.Name.Equals(NODE_NAME_EXPORTPATTERNS, StringComparison.OrdinalIgnoreCase))
                    _LoadPatterns(node);
                else if (node.Name.Equals(NODE_NAME_TABLEDEFINITIONS, StringComparison.OrdinalIgnoreCase))
                    _LoadTableDescriptions(node, capacityInfos, orderCustomPropertiesInfo, addressFields);
                else if (node.Name.Equals(NODE_NAME_RESERVEDWORDS, StringComparison.OrdinalIgnoreCase))
                    _LoadReservedWords(node);
                else if (node.Name.Equals(NODE_NAME_HARDFIELDS, StringComparison.OrdinalIgnoreCase))
                    _LoadHardFields(node);
                else
                    throw new NotSupportedException();
            }

            _capacityInfos = capacityInfos;
            _orderCustomPropertyInfos = orderCustomPropertiesInfo;
        }
Example #41
0
        /// <summary>
        /// Get order property titles.
        /// </summary>
        /// <param name="capacitiesInfo">Information about capacities.</param>
        /// <param name="orderCustomPropertiesInfo">Information about custom order properties.</param>
        /// <param name="addressFields">Set of geocoder address fields.</param>
        /// <returns>Returns full collection of order property title to show in UI.</returns>
        public static string[] GetPropertyTitles(CapacitiesInfo capacitiesInfo,
                    OrderCustomPropertiesInfo orderCustomPropertiesInfo, AddressField[] addressFields)
        {
            Type type = typeof(Order);

            List<string> propertyTitles = new List<string>();

            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                if (Attribute.IsDefined(property, typeof(DomainPropertyAttribute)))
                {
                    DomainPropertyAttribute attribute = (DomainPropertyAttribute)Attribute.GetCustomAttribute(property, typeof(DomainPropertyAttribute));
                    Debug.Assert(null != attribute);
                    Type typeProperty = _GetEffectiveType(property.PropertyType);

                    if (typeof(OrderCustomProperties) == typeProperty)
                    {   // specials type: order custom property
                        OrderCustomPropertiesInfo info = orderCustomPropertiesInfo;
                        for (int i = 0; i < info.Count; ++i)
                            propertyTitles.Add(info[i].Name);
                    }
                    else if (typeof(Capacities) == typeProperty)
                    {   // specials type: capacities
                        CapacitiesInfo info = capacitiesInfo;
                        for (int i = 0; i < info.Count; ++i)
                            propertyTitles.Add(info[i].Name);
                    }
                    else if (typeof(Address) == typeProperty)
                    {   // specials type: address
                        ESRI.ArcLogistics.Geocoding.AddressField[] fields = addressFields;
                        for (int i = 0; i < fields.Length; ++i)
                            propertyTitles.Add(fields[i].Title);
                    }
                    else if (typeof(Point) == typeProperty)
                    {
                        propertyTitles.Add(Properties.Resources.DomainPropertyNameX);
                        propertyTitles.Add(Properties.Resources.DomainPropertyNameY);
                    }
                    else
                        propertyTitles.Add(attribute.Title);
                }
            }

            return propertyTitles.ToArray();
        }
Example #42
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;
 }
Example #43
0
 private void _InitCapacities(DataModel.Orders entity, CapacitiesInfo capacitiesInfo)
 {
     _capacities = Capacities.CreateFromDBString(entity.Capacities, capacitiesInfo);
     _capacities.PropertyChanged += new PropertyChangedEventHandler(Capacities_PropertyChanged);
 }
Example #44
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// Initializes a new instance of the <c>Route</c> class.
        /// </summary>
        /// <param name="capacitiesInfo">Information about capacities.</param>
        public Route(CapacitiesInfo capacitiesInfo)
            : base(DataModel.Routes.CreateRoutes(Guid.NewGuid()))
        {
            Color = Color.Empty;

            Defaults defaults = Defaults.Instance;

            _timeWindow.IsWideOpen = defaults.RoutesDefaults.StartTimeWindow.IsWideopen;
            if (!_timeWindow.IsWideOpen)
            {
                _timeWindow.From = defaults.RoutesDefaults.StartTimeWindow.From;
                _timeWindow.To = defaults.RoutesDefaults.StartTimeWindow.To;
                _timeWindow.Day = 0;
            }
            _UpdateTimeWindowEntityData();

            _Entity.TimeAtStart = defaults.RoutesDefaults.TimeAtStart;
            _Entity.TimeAtEnd = defaults.RoutesDefaults.TimeAtEnd;
            _Entity.TimeAtRenewal = defaults.RoutesDefaults.TimeAtRenewal;
            _Entity.MaxOrders = defaults.RoutesDefaults.MaxOrder;
            _Entity.MaxTravelDistance = defaults.RoutesDefaults.MaxTravelDistance;
            _Entity.MaxTravelDuration = defaults.RoutesDefaults.MaxTravelDuration;
            _Entity.MaxTotalDuration = defaults.RoutesDefaults.MaxTotalDuration;

            _UpdateBreaksEntityData();
            _UpdateDaysEntityData();

            _CreateCapacities(capacitiesInfo);
            _InitPropertiesEvents();

            base.SetCreationTime();
        }
        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);
        }
        /// <summary>
        /// Write schema.
        /// </summary>
        /// <param name="fields">Fields to export.</param>
        /// <param name="table">Table to data writing.</param>
        /// <param name="tracker">Cancel tracker (can be null).</param>
        private void _WriteSchema(ICollection <string> fields,
                                  DataTable table,
                                  ICancelTracker tracker)
        {
            TableDescription description = _structureKeeper.GetTableDescription(TableType.Schema);

            // Capacities
            var            capacitiesSpecFields = new List <string> ();
            CapacitiesInfo capacitiesInfo       = _structureKeeper.CapacitiesInfo;

            for (int index = 0; index < capacitiesInfo.Count; ++index)
            {
                string relativeName = description.ValidateRelativeName(capacitiesInfo[index].Name);
                capacitiesSpecFields.Add(relativeName);
            }

            _CheckCancelState(tracker);

            // add text Capacities
            if (0 < capacitiesSpecFields.Count)
            {
                _AddSchemaRow(fields, SCHEMA_TABLE_TYPE_CAPACITIES,
                              capacitiesSpecFields.AsReadOnly(), table);
            }

            // CustomOrderProperties
            var textCustomPropSpecFields    = new List <string>();
            var numericCustomPropSpecFields = new List <string>();
            OrderCustomPropertiesInfo customOrderPropsInfo =
                _structureKeeper.OrderCustomPropertiesInfo;

            for (int index = 0; index < customOrderPropsInfo.Count; ++index)
            {
                var name = description.ValidateRelativeName(customOrderPropsInfo[index].Name);
                if (customOrderPropsInfo[index].Type == OrderCustomPropertyType.Text)
                {
                    textCustomPropSpecFields.Add(name);
                }
                else
                {   // numeric
                    Debug.Assert(customOrderPropsInfo[index].Type == OrderCustomPropertyType.Numeric);
                    numericCustomPropSpecFields.Add(name);
                }
            }

            _CheckCancelState(tracker);

            // add text CustomOrderProperties
            if (0 < textCustomPropSpecFields.Count)
            {
                _AddSchemaRow(fields, SCHEMA_TABLE_TYPE_CUSTOMPROP_TEXT,
                              textCustomPropSpecFields.AsReadOnly(), table);
            }

            _CheckCancelState(tracker);

            // add numeric CustomOrderProperties
            if (0 < numericCustomPropSpecFields.Count)
            {
                _AddSchemaRow(fields, SCHEMA_TABLE_TYPE_CUSTOMPROP_NUMERIC,
                              numericCustomPropSpecFields.AsReadOnly(), table);
            }
        }