예제 #1
0
        /// <summary>
        /// Gets collection of dynamic custom oreder properties columns
        /// </summary>
        /// <returns></returns>
        private Collection <Column> _GetDynamicCustomOrderColumns(bool isReadOnly)
        {
            Collection <Column> dynamicColumns = new Collection <Column>();

            OrderCustomPropertiesInfo infos = App.Current.Project.OrderCustomPropertiesInfo;

            for (int i = 0; i < infos.Count; i++)
            {
                OrderCustomProperty info = infos[i];

                Column col = new Column();
                col.FieldName = OrderCustomProperties.GetCustomPropertyName(i);
                col.Title     = info.Name;

                if (info.Type == OrderCustomPropertyType.Text)
                {
                    col.CellEditor = (CellEditor)App.Current.FindResource("CustomOrderPropertyTextEditor");
                }
                else if (info.Type == OrderCustomPropertyType.Numeric)
                {
                    col.CellEditor          = (CellEditor)App.Current.FindResource("CustomOrderPropertyNumericEditor");
                    col.CellContentTemplate = (DataTemplate)App.Current.FindResource("DefaultStringTemplate");
                }
                else
                {
                    Debug.Assert(false); // NOTE: not supported
                }

                col.ReadOnly = isReadOnly;
                dynamicColumns.Add(col);
            }
            return(dynamicColumns);
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <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;
        }
예제 #3
0
        /// <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>
        /// Parses OrderCustomPropertiesInfo.
        /// </summary>
        public static OrderCustomPropertiesInfo ParseOrderCustomPropertiesInfo(string xml)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(xml);

            OrderCustomPropertiesInfo info = null;
            XmlNode root = xmlDoc.SelectSingleNode(NODE_ORDERCUSTOMPROP);

            if (root != null)
            {
                info = new OrderCustomPropertiesInfo();
                foreach (XmlNode node in root.ChildNodes)
                {
                    if (node.NodeType != XmlNodeType.Element)
                    {
                        continue; // skip comments and other non element nodes
                    }
                    if (node.Name.Equals(NODE_PROPERTY, StringComparison.OrdinalIgnoreCase))
                    {
                        XmlAttributeCollection attributes = node.Attributes;

                        string name        = attributes[ATTR_NAME].Value;
                        string description = null;
                        if (null != attributes[ATTR_DESCRIPTION])
                        {
                            description = attributes[ATTR_DESCRIPTION].Value;
                        }
                        int length = int.Parse(attributes[ATTR_MAXLENGTH].Value);

                        OrderCustomPropertyType type          = OrderCustomPropertyType.Text; // NOTE: for default used text
                        XmlAttribute            typeAttribute = attributes[ATTR_TYPE];
                        if (null != typeAttribute)
                        {
                            type = (OrderCustomPropertyType)Enum.Parse(typeof(OrderCustomPropertyType), typeAttribute.Value);
                        }

                        bool         orderPairKey          = false; // default
                        XmlAttribute orderPairKeyAttribute = attributes[ATTR_ORDERPAIRKEY];
                        if (null != orderPairKeyAttribute)
                        {
                            orderPairKey = bool.Parse(orderPairKeyAttribute.Value);
                        }

                        info.Add(new OrderCustomProperty(name, type, length, description, orderPairKey));
                    }
                    else
                    {
                        throw new FormatException();
                    }
                }
            }
            else
            {
                throw new FormatException();
            }

            return(info);
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Put all properties to string.
        /// </summary>
        /// <param name="properties">Order custom properties values</param>
        internal static string AssemblyDBString(OrderCustomProperties properties, OrderCustomPropertiesInfo info)
        {
            Debug.Assert(properties.Count == info.Count);

            string strSeparator = new string(new char[1] {
                CommonHelpers.SEPARATOR
            });

            StringBuilder result = new StringBuilder();

            for (int index = 0; index < info.Count; ++index)
            {
                OrderCustomProperty propertyInfo = info[index];

                string value = null;
                if (OrderCustomPropertyType.Text == propertyInfo.Type)
                {
                    if (null != properties[index])
                    {
                        Debug.Assert(properties[index] is string);
                        value = (string)properties[index];
                    }
                }
                else if (OrderCustomPropertyType.Numeric == propertyInfo.Type)
                {
                    double tmp = 0.0;
                    if (null != properties[index])
                    {
                        if (properties[index] is double)
                        {
                            tmp = (double)properties[index];
                        }
                        else if (properties[index] is string)
                        {
                            tmp = double.Parse(properties[index].ToString());
                        }
                    }

                    value = tmp.ToString(CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE));
                }
                else
                {
                    Debug.Assert(false); // NOTE: not supported
                }

                if (!string.IsNullOrEmpty(value))
                {
                    string prop = value.Replace(strSeparator, CommonHelpers.SEPARATOR_ALIAS);
                    result.Append(prop);
                }

                if (index < properties.Count - 1)
                {
                    result.Append(CommonHelpers.SEPARATOR); // NOTE: after last not neded
                }
            }

            return(result.ToString());
        }
예제 #6
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();
        }
예제 #7
0
        private static void _AddCustomOrderProperties(PropertyInfo property)
        {
            OrderCustomPropertiesInfo info = App.Current.Project.OrderCustomPropertiesInfo;

            for (int i = 0; i < info.Count; ++i)
            {
                _quantityFieldTitles.Add(info[i].Name);
                _quantityFieldNames.Add(OrderCustomProperties.GetCustomPropertyName(i));
                _quantityFieldProperties.Add(property);
            }
        }
예제 #8
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);
        }
예제 #9
0
        /// <summary>
        /// Checks maximum length constraint for list of custom order properties.
        /// </summary>
        /// <returns></returns>
        private bool _CheckMaximumLengthConstraint()
        {
            bool checkMaxLengthConstraint = false;

            // Get order custom properties info.
            OrderCustomPropertiesInfo propertiesInfo = GetOrderCustomPropertiesInfo();

            // Check constraint.
            checkMaxLengthConstraint = ProjectFactory.CheckMaximumLengthConstraint(propertiesInfo);

            return(checkMaxLengthConstraint);
        }
예제 #10
0
        /// <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;
        }
예제 #11
0
        /// <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>
        /// Initializes a new instance of the <c>OrderCustomProperties</c> class.
        /// </summary>
        public OrderCustomProperties(OrderCustomPropertiesInfo info)
        {
            _propertiesInfo = info;
            _values         = new object[_propertiesInfo.Count];

            // post init all numeric must set
            for (int index = 0; index < info.Count; ++index)
            {
                if (OrderCustomPropertyType.Numeric == info[index].Type)
                {
                    _values[index] = 0.0;
                }
            }
        }
예제 #13
0
 /// <summary>
 /// Add custom order properties
 /// </summary>
 private void _AddCustomOrderProperties(string prePath, IList <object> mapProperties,
                                        IList <object> selectedMapProperties, StringCollection selectedConfig)
 {
     // specials type: order custom property
     if (App.Current.Project != null)
     {
         OrderCustomPropertiesInfo info = App.Current.Project.OrderCustomPropertiesInfo;
         for (int i = 0; i < info.Count; ++i)
         {
             _AddPropertyTip(prePath, "CustomProperties.[" + i.ToString() + "]", info[i].Name,
                             mapProperties, selectedMapProperties, selectedConfig, null, null);
         }
     }
 }
        private OrderCustomPropertiesInfo _LoadOrderPropertiesInfo()
        {
            OrderCustomPropertiesInfo info = null;

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

            return(info);
        }
        /// <summary>
        /// Updates order custom properties info in database.
        /// </summary>
        /// <param name="propertiesInfo">Order custom properrties info.</param>
        public void UpdateCustomOrderPropertiesInfo(OrderCustomPropertiesInfo propertiesInfo)
        {
            Debug.Assert(propertiesInfo != null);

            // Get custom order properties config scheme.
            DataModel.ConfigSchemes customOrderPropertiesScheme = _GetConfigSchemeObject(SCHEME_ID_ORDERPROPERTIES);

            // Update value of custom order properties database field.
            customOrderPropertiesScheme.Value =
                ConfigDataSerializer.SerializeOrderCustomPropertiesInfo(propertiesInfo);

            // Update init data.
            _objInitData.OrderCustomPropertiesInfo = propertiesInfo;

            // Save changes to the database.
            base.SaveChanges();
        }
예제 #16
0
        /// <summary>
        /// Builds collection of dynamic custom oreder properties fields
        /// </summary>
        /// <returns></returns>
        private Collection <DataGridItemProperty> _GetDynamicCustomOrderProperties(string baseValuePath, bool isReadOnly)
        {
            Collection <DataGridItemProperty> dynamicProperties = new Collection <DataGridItemProperty>();

            OrderCustomPropertiesInfo infos = App.Current.Project.OrderCustomPropertiesInfo;

            for (int i = 0; i < infos.Count; i++)
            {
                string valuePath = baseValuePath + string.Format("CustomProperties[{0}]", i);
                string valueName = OrderCustomProperties.GetCustomPropertyName(i);
                Type   type      = (infos[i].Type == OrderCustomPropertyType.Text)? typeof(string) : typeof(double);

                DataGridItemProperty newProperty = new DataGridItemProperty(valueName, valuePath, type);
                newProperty.IsReadOnly = isReadOnly;
                dynamicProperties.Add(newProperty);
            }
            return(dynamicProperties);
        }
예제 #17
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);
        }
예제 #18
0
        /// <summary>
        /// Converts collection of CustomOrderProperty objects to OrderCustomPropertiesInfo.
        /// </summary>
        /// <returns>OrderCustomPropertiesInfo object.</returns>
        public OrderCustomPropertiesInfo GetOrderCustomPropertiesInfo()
        {
            OrderCustomPropertiesInfo orderCustomPropertiesInfo = new OrderCustomPropertiesInfo();

            foreach (CustomOrderProperty customOrderProperty in _customOrderProperties)
            {
                // Create custom order property info using data of item in collection.
                OrderCustomProperty newOrderCustomProperty =
                    new OrderCustomProperty(customOrderProperty.Name,
                                            OrderCustomPropertyType.Text,
                                            customOrderProperty.MaximumLength,
                                            customOrderProperty.Description,
                                            customOrderProperty.OrderPairKey);

                // Add new custom order property to collection.
                orderCustomPropertiesInfo.Add(newOrderCustomProperty);
            }

            return(orderCustomPropertiesInfo);
        }
        /// <summary>
        /// Calculates maximum length of string needed to serialize values of custom order properties
        /// to string taking into account types of properties (numeric / text), delimiter
        /// characters used to separate values of properties are accounted too.
        /// </summary>
        /// <param name="orderCustomPropertiesInfo">Order custom properties info.</param>
        /// <returns>Maximum length of string with values of properties.</returns>
        internal static int CalculateMaximumLengthOfDBString(OrderCustomPropertiesInfo orderCustomPropertiesInfo)
        {
            Debug.Assert(orderCustomPropertiesInfo != null);

            // Maximum string length of numeric property value.
            int numericPropertyMaxStringLength = _GetNumericPropertyMaxStringLength();

            // Result max length.
            int maxLength = 0;

            // Iterate through custom order properties info and calculate maximum length
            // needed to serialize values of properties to string taking into account
            // type of properties (numeric / text).
            foreach (OrderCustomProperty orderCustomProperty in orderCustomPropertiesInfo)
            {
                // If property is numeric.
                if (orderCustomProperty.Type == OrderCustomPropertyType.Numeric)
                {
                    maxLength += numericPropertyMaxStringLength;
                }
                // If property is text.
                else if (orderCustomProperty.Type == OrderCustomPropertyType.Text)
                {
                    maxLength += orderCustomProperty.Length;
                }
                // Unknown property type.
                else
                {
                    // NOTE: not supported.
                    Debug.Assert(false);
                }
            }

            // Take into account that after each value (except the last) delimiter character is added.
            if (orderCustomPropertiesInfo.Count != 0)
            {
                maxLength += orderCustomPropertiesInfo.Count - 1;
            }

            return(maxLength);
        }
        /// <summary>
        /// Serializes OrderCustomPropertiesInfo object.
        /// </summary>
        public static string SerializeOrderCustomPropertiesInfo(OrderCustomPropertiesInfo orderCustomPropertiesInfo)
        {
            string    xml    = null;
            XmlWriter writer = null;

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

                writer.WriteStartElement(NODE_ORDERCUSTOMPROP);
                writer.WriteAttributeString(ATTR_VERSION, ORDER_CUST_PROP_CURRENT_VERSION.ToString(CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE)));
                for (int index = 0; index < orderCustomPropertiesInfo.Count; index++)
                {
                    OrderCustomProperty property = orderCustomPropertiesInfo[index];
                    writer.WriteStartElement(NODE_PROPERTY);
                    writer.WriteAttributeString(ATTR_NAME, property.Name);
                    writer.WriteAttributeString(ATTR_TYPE, property.Type.ToString());
                    writer.WriteAttributeString(ATTR_MAXLENGTH, property.Length.ToString());
                    writer.WriteAttributeString(ATTR_DESCRIPTION, property.Description);
                    writer.WriteAttributeString(ATTR_ORDERPAIRKEY, property.OrderPairKey.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.Flush();

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

            return(xml);
        }
예제 #21
0
        /// <summary>
        /// Initializes custom order properties control.
        /// </summary>
        private void _InitializeCustomOrderPropertiesControl()
        {
            // Get current project.
            Project currentProject = App.Current.Project;

            if (currentProject != null)
            {
                // Get order custom properties info.
                OrderCustomPropertiesInfo customPropertiesInfo = currentProject.OrderCustomPropertiesInfo;
                Debug.Assert(customPropertiesInfo != null);

                // Load custom order properties to the control's collection.
                _customOrderPropertiesControl.LoadCustomOrderProperties(customPropertiesInfo);

                // Enable custom order properties control.
                _customOrderPropertiesControl.IsEnabled = true;
            }
            else
            {
                // Disable custom order properties control.
                _customOrderPropertiesControl.IsEnabled = false;
            }
        }
예제 #22
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);
        }
예제 #23
0
        /// <summary>
        /// Loads custom order properties from collection OrderCustomPropertiesInfo.
        /// </summary>
        /// <param name="customPropertiesInfo">OrderCustomPropertiesInfo collection.</param>
        public void LoadCustomOrderProperties(OrderCustomPropertiesInfo customPropertiesInfo)
        {
            Debug.Assert(customPropertiesInfo != null);

            // Clear collection.
            _customOrderProperties.Clear();

            foreach (OrderCustomProperty orderCustomProperty in customPropertiesInfo)
            {
                // Create custom order property using data of item in collection.
                CustomOrderProperty newOrderProperty =
                    new CustomOrderProperty(orderCustomProperty.Name,
                                            orderCustomProperty.Description,
                                            orderCustomProperty.Length,
                                            orderCustomProperty.OrderPairKey);

                // Add new custom order property to collection.
                _customOrderProperties.Add(newOrderProperty);
            }

            // Backup collection of custom order properties.
            _BackupCustomOrderPropertiesCollection();
        }
        /// <summary>
        /// Serializes OrderCustomPropertiesInfo object.
        /// </summary>
        public static string SerializeOrderCustomPropertiesInfo(OrderCustomPropertiesInfo orderCustomPropertiesInfo)
        {
            string xml = null;
            XmlWriter writer = null;
            try
            {
                StringBuilder sb = new StringBuilder();
                writer = XmlWriter.Create(sb);

                writer.WriteStartElement(NODE_ORDERCUSTOMPROP);
                writer.WriteAttributeString(ATTR_VERSION, ORDER_CUST_PROP_CURRENT_VERSION.ToString(CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE)));
                for (int index = 0; index < orderCustomPropertiesInfo.Count; index++)
                {
                    OrderCustomProperty property = orderCustomPropertiesInfo[index];
                    writer.WriteStartElement(NODE_PROPERTY);
                    writer.WriteAttributeString(ATTR_NAME, property.Name);
                    writer.WriteAttributeString(ATTR_TYPE, property.Type.ToString());
                    writer.WriteAttributeString(ATTR_MAXLENGTH, property.Length.ToString());
                    writer.WriteAttributeString(ATTR_DESCRIPTION, property.Description);
                    writer.WriteAttributeString(ATTR_ORDERPAIRKEY, property.OrderPairKey.ToString());
                    writer.WriteEndElement();
                }
                writer.WriteEndElement();
                writer.Flush();

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

            return xml;
        }
        /// <summary>
        /// Parses OrderCustomPropertiesInfo.
        /// </summary>
        public static OrderCustomPropertiesInfo ParseOrderCustomPropertiesInfo(string xml)
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(xml);

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

                    if (node.Name.Equals(NODE_PROPERTY, StringComparison.OrdinalIgnoreCase))
                    {
                        XmlAttributeCollection attributes = node.Attributes;

                        string name = attributes[ATTR_NAME].Value;
                        string description = null;
                        if (null != attributes[ATTR_DESCRIPTION])
                            description = attributes[ATTR_DESCRIPTION].Value;
                        int length = int.Parse(attributes[ATTR_MAXLENGTH].Value);

                        OrderCustomPropertyType type = OrderCustomPropertyType.Text; // NOTE: for default used text
                        XmlAttribute typeAttribute = attributes[ATTR_TYPE];
                        if (null != typeAttribute)
                            type = (OrderCustomPropertyType)Enum.Parse(typeof(OrderCustomPropertyType), typeAttribute.Value);

                        bool orderPairKey = false;  // default
                        XmlAttribute orderPairKeyAttribute = attributes[ATTR_ORDERPAIRKEY];
                        if (null != orderPairKeyAttribute)
                            orderPairKey = bool.Parse(orderPairKeyAttribute.Value);

                        info.Add(new OrderCustomProperty(name, type, length, description, orderPairKey));
                    }
                    else
                        throw new FormatException();
                }
            }
            else
                throw new FormatException();

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

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

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

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

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

            IAddress useAddress = null;

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

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

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

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

                resultOrder.GeoLocation = candidate.GeoLocation;
            }

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

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

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

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

            IORInvoiceLineRetList orInvoiceLineRetList = invoiceRet.ORInvoiceLineRetList;

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

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

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

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

                        // look for matching custom order property

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

                                break;
                            }
                        }

                        // look for matching capacity

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

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

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

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

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

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

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

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

                                    break;
                                }
                            }
                        }
                    }
                }
            }

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

            return(resultOrder);
        }
        /// <summary>
        /// Loads custom order properties from collection OrderCustomPropertiesInfo.
        /// </summary>
        /// <param name="customPropertiesInfo">OrderCustomPropertiesInfo collection.</param>
        public void LoadCustomOrderProperties(OrderCustomPropertiesInfo customPropertiesInfo)
        {
            Debug.Assert(customPropertiesInfo != null);

            // Clear collection.
            _customOrderProperties.Clear();

            foreach (OrderCustomProperty orderCustomProperty in customPropertiesInfo)
            {
                // Create custom order property using data of item in collection.
                CustomOrderProperty newOrderProperty =
                    new CustomOrderProperty(orderCustomProperty.Name,
                                            orderCustomProperty.Description,
                                            orderCustomProperty.Length,
                                            orderCustomProperty.OrderPairKey);

                // Add new custom order property to collection.
                _customOrderProperties.Add(newOrderProperty);
            }

            // Backup collection of custom order properties.
            _BackupCustomOrderPropertiesCollection();
        }
예제 #28
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);
        }
예제 #29
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();
        }
예제 #30
0
        /// <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);
            }
        }
예제 #31
0
        /// <summary>
        /// Updates project's custom order properties info.
        /// </summary>
        /// <param name="projectConfig">Project configuration.</param>
        /// <param name="propertiesInfo">Order custom properties info.</param>
        /// <exception cref="DataException">Failed to update database.</exception>
        public static void UpdateProjectCustomOrderPropertiesInfo(ProjectConfiguration projectConfig,
                                                                  OrderCustomPropertiesInfo propertiesInfo)
        {
            Debug.Assert(projectConfig != null);
            Debug.Assert(propertiesInfo != null);

            DataObjectContext dataContext = null;

            try
            {
                // Open database.
                dataContext = DatabaseOpener.OpenDatabase(projectConfig.DatabasePath);

                // Update custom order properties info in database.
                dataContext.UpdateCustomOrderPropertiesInfo(propertiesInfo);
            }
            catch (Exception ex)
            {
                // Failed to update database.
                throw new DataException(Properties.Messages.Error_DatabaseUpdate, ex, DataError.DatabaseUpdateError);
            }
            finally
            {
                if (dataContext != null)
                    dataContext.Dispose();
            }
        }
예제 #32
0
        /// <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;
            }
        }
        /// <summary>
        /// Parse string and split it to properties values
        /// </summary>
        /// <param name="propertiesValuesString">DB order custom properties string</param>
        /// <param name="orderCustomPropertiesInfo">Project order custom properties info</param>
        /// <returns>Parsed order custom properties</returns>
        internal static OrderCustomProperties CreateFromDBString(string propertiesValuesString,
                                                                 OrderCustomPropertiesInfo orderCustomPropertiesInfo)
        {
            Debug.Assert(orderCustomPropertiesInfo != null);

            // Create order custom properties object using data of orderCustomPropertiesinfo.
            OrderCustomProperties orderCustomProperties = new OrderCustomProperties(orderCustomPropertiesInfo);

            if (null == propertiesValuesString)
            {   // special initialization - of numeric values
                for (int index = 0; index < orderCustomPropertiesInfo.Count; ++index)
                {
                    if (OrderCustomPropertyType.Numeric == orderCustomPropertiesInfo[index].Type)
                    {
                        orderCustomProperties[index] = 0.0;
                    }
                }
            }
            else
            {
                // Values separator.
                char[] valuesSeparator = new char[1] {
                    CommonHelpers.SEPARATOR
                };

                // Get array of values splitted by separator.
                string[] propertiesValues = propertiesValuesString.Split(valuesSeparator, StringSplitOptions.None);

                // This condition is not always true.
                //Debug.Assert(propertiesValues.Length == orderCustomPropertiesinfo.Count);

                string strSeparator = new string(valuesSeparator);

                // Iterate through list of order custom properties.
                for (int index = 0; index < orderCustomPropertiesInfo.Count; ++index)
                {
                    // Get current order custom property.
                    OrderCustomProperty orderCustomProperty = orderCustomPropertiesInfo[index];

                    // If index of item in list of order custom properties info is less than
                    // length of array with values.
                    if (index < propertiesValues.Length)
                    {
                        // Get current value for appropriate custom order property.
                        string currentStrValue = propertiesValues[index];
                        if (!string.IsNullOrEmpty(currentStrValue))
                        {
                            currentStrValue = currentStrValue.Replace(CommonHelpers.SEPARATOR_ALIAS, strSeparator);
                        }

                        // Value of current property.
                        object currentPropertyValue = null;

                        // If type of order custom property is Text.
                        if (OrderCustomPropertyType.Text == orderCustomProperty.Type)
                        {
                            // Assign property valus as it is.
                            currentPropertyValue = currentStrValue;
                        }
                        // Type of custom order property is Numeric.
                        else if (OrderCustomPropertyType.Numeric == orderCustomProperty.Type)
                        {
                            // Convert string value to double.
                            double tmp = 0.0;
                            if (!string.IsNullOrEmpty(currentStrValue))
                            {
                                tmp = double.Parse(currentStrValue, CultureInfo.GetCultureInfo(CommonHelpers.STORAGE_CULTURE));
                            }
                            currentPropertyValue = tmp;
                        }
                        else
                        {
                            Debug.Assert(false); // NOTE: not supported
                        }

                        // Assign value of current custom order property.
                        orderCustomProperties[index] = currentPropertyValue;
                    } // if (index < values.Length)
                }     // for (int index = 0; index < info.Count; ++index)
            }         // else of if (null == value)

            return(orderCustomProperties);
        }
        /// <summary>
        /// Converts collection of CustomOrderProperty objects to OrderCustomPropertiesInfo.
        /// </summary>
        /// <returns>OrderCustomPropertiesInfo object.</returns>
        public OrderCustomPropertiesInfo GetOrderCustomPropertiesInfo()
        {
            OrderCustomPropertiesInfo orderCustomPropertiesInfo = new OrderCustomPropertiesInfo();

            foreach (CustomOrderProperty customOrderProperty in _customOrderProperties)
            {
                // Create custom order property info using data of item in collection.
                OrderCustomProperty newOrderCustomProperty =
                    new OrderCustomProperty(customOrderProperty.Name,
                                            OrderCustomPropertyType.Text,
                                            customOrderProperty.MaximumLength,
                                            customOrderProperty.Description,
                                            customOrderProperty.OrderPairKey);

                // Add new custom order property to collection.
                orderCustomPropertiesInfo.Add(newOrderCustomProperty);
            }

            return orderCustomPropertiesInfo;
        }
        /// <summary>
        /// Adds custom order property relative fields.
        /// </summary>
        /// <param name="orderCustomPropertyInfos">Order custom order properties info information.</param>
        /// <param name="info">Field information with data settings.</param>
        private void _AddCustomOrderPropertyRelativeFields(
            OrderCustomPropertiesInfo orderCustomPropertyInfos,
            FieldInfo info)
        {
            for (int index = 0; index < orderCustomPropertyInfos.Count; ++index)
            {
                FieldInfo infoRealtion = (FieldInfo)info.Clone();

                OrderCustomProperty prorety = orderCustomPropertyInfos[index];
                _UpdateInfoWithInfoName(prorety.Name, info, ref infoRealtion);
                infoRealtion.Description = prorety.Description;

                Debug.Assert(!string.IsNullOrEmpty(infoRealtion.Name));

                // NOTE: special issue
                //  support numeric custom order propertiy - need change type description
                if (orderCustomPropertyInfos[index].Type == OrderCustomPropertyType.Numeric)
                {
                    infoRealtion.Type = OleDbType.Double;
                    infoRealtion.Size = 0;
                    infoRealtion.Scale = 2;
                    infoRealtion.Precision = 14;
                }

                _fieldsMap.Add(infoRealtion.Name, infoRealtion);
            }
        }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <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;
        }
예제 #37
0
        /// <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;
        }
예제 #38
0
 ///////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////
 ///////////////////////////////////////////////////////////////////////////////////////////
 private void _CreateCustomProperties(OrderCustomPropertiesInfo info)
 {
     _customPropertiesInfo = info;
     _customProperties = new OrderCustomProperties(info);
     _customProperties.PropertyChanged += new PropertyChangedEventHandler(CustomProperties_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);
        }
예제 #40
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();
        }
예제 #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();
        }
        /// <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);
                    }
                }
            }
        }
예제 #43
0
 private void _InitCustomProperties(DataModel.Orders entity, OrderCustomPropertiesInfo info)
 {
     _customProperties = OrderCustomProperties.CreateFromDBString(entity.CustomProperties, info);
     _customProperties.PropertyChanged += new PropertyChangedEventHandler(CustomProperties_PropertyChanged);
 }
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        /// <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;
                    }
                }
            }
        }
        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);
        }
예제 #46
0
        /// <summary>
        /// Checks maximum length constraint for list of custom order properties.
        /// </summary>
        /// <param name="propertiesInfo">Order custom properties info.</param>
        /// <returns>Maximum length constraint.</returns>
        public static bool CheckMaximumLengthConstraint(OrderCustomPropertiesInfo propertiesInfo)
        {
            Debug.Assert(propertiesInfo != null);

            bool checkMaxLengthConstraint = false;

            // Serialize order custom properties info to XML.
            string customOrderPropertiesSerialized =
                ConfigDataSerializer.SerializeOrderCustomPropertiesInfo(propertiesInfo);

            // Maximum length needed to store values of cusom order properties.
            int maxLengthOfPropertiesValuesString =
                OrderCustomProperties.CalculateMaximumLengthOfDBString(propertiesInfo);

            // Check constraint.
            checkMaxLengthConstraint =
                customOrderPropertiesSerialized.Length <= MAX_DB_FIELD_LENGTH &&
                maxLengthOfPropertiesValuesString <= MAX_DB_FIELD_LENGTH;

            return checkMaxLengthConstraint;
        }