Beispiel #1
0
        /// <summary>
        ///     Executes the geoprocessing function using the given array of parameter values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="trackCancel">The track cancel.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="messages">The messages that are reported to the user.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void Execute(Dictionary <string, IGPValue> parameters, ITrackCancel trackCancel, IGPEnvironmentManager environmentManager, IGPMessages messages, IGPUtilities2 utilities)
        {
            IGPValue      field      = parameters["in_field"];
            IObjectClass  table      = utilities.OpenTable(parameters["in_table"]);
            IGPMultiValue modelNames = (IGPMultiValue)parameters["in_field_model_names"];

            if (!field.IsEmpty() && modelNames.Count > 0)
            {
                var fieldName = field.GetAsText();
                int index     = table.FindField(fieldName);

                foreach (var modelName in modelNames.AsEnumerable().Select(o => o.GetAsText()))
                {
                    messages.Add(esriGPMessageType.esriGPMessageTypeInformative, "Removing the {0} field model name from the {1} field.", modelName, fieldName);

                    ModelNameManager.Instance.RemoveFieldModelName(table, table.Fields.Field[index], modelName);
                }

                // Success.
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
        public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            IGPParameter inputFCParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter;
            IGPValue     osmFCGPValue     = gpUtilities3.UnpackGPValue(inputFCParameter);

            if (osmFCGPValue.IsEmpty())
            {
                return;
            }

            IFeatureClass osmFeatureClass = null;
            IQueryFilter  queryFilter     = null;

            if (osmFCGPValue is IGPFeatureLayer)
            {
                gpUtilities3.DecodeFeatureLayer(osmFCGPValue, out osmFeatureClass, out queryFilter);

                if (osmFeatureClass.EXTCLSID != null)
                {
                    UID osmEditorExtensionCLSID = osmFeatureClass.EXTCLSID;

                    if (osmEditorExtensionCLSID.Value.ToString().Equals("{65CA4847-8661-45eb-8E1E-B2985CA17C78}", StringComparison.InvariantCultureIgnoreCase) == false)
                    {
                        Messages.ReplaceError(in_osmFeaturesNumber, -1, resourceManager.GetString("GPTools_OSMGPRemoveExtension_noEXTCLSID"));
                    }
                }
                else
                {
                    Messages.ReplaceError(in_osmFeaturesNumber, -1, resourceManager.GetString("GPTools_OSMGPRemoveExtension_noEXTCLSID"));
                }
            }
        }
Beispiel #3
0
        /// <summary>
        ///     Executes the geoprocessing function using the given array of parameter values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="trackCancel">The track cancel.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="messages">The messages that are reported to the user.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void Execute(Dictionary <string, IGPValue> parameters, ITrackCancel trackCancel, IGPEnvironmentManager environmentManager, IGPMessages messages, IGPUtilities2 utilities)
        {
            IGPValue           value    = parameters["in_table"];
            IRelationshipClass relClass = utilities.OpenRelationshipClass(value);

            if (relClass != null)
            {
                IMMConfigTopLevel configTopLevel = ConfigTopLevel.Instance;
                configTopLevel.Workspace = utilities.GetWorkspace(value);

                IGPMultiValue onCreate = (IGPMultiValue)parameters["in_create"];
                IGPMultiValue onDelete = (IGPMultiValue)parameters["in_delete"];

                var uids = new Dictionary <mmEditEvent, IEnumerable <IUID> >();
                uids.Add(mmEditEvent.mmEventRelationshipCreated, onCreate.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));
                uids.Add(mmEditEvent.mmEventRelationshipDeleted, onDelete.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));

                // Update the list to have these UIDs.
                ID8List list = (ID8List)configTopLevel.GetRelationshipClass(relClass);
                base.Add(uids, list, messages);

                // Commit the changes to the database.
                configTopLevel.SaveRelationshipClasstoDB(relClass);

                // Success.
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
Beispiel #4
0
 public bool Check(IGPValue val, IGPMessages messages, int idx)
 {
     try {
         m_errored = false;
         m_msgs    = messages;
         m_msgidx  = idx;
         IGPUtilities util = new GPUtilitiesClass();
         IGPValue     c    = util.UnpackGPValue(val);          // make sure its unpacked
         if (null == c)
         {
             if (!m_req)
             {
                 Warning("Will use default value.");
                 return(true);
             }
             else
             {
                 Error("A value is required.");
                 return(false);
             }
         }
         ImpCheck(val);
     } finally {
         //m_msgs = null;// don't hold a ref.
     }
     return(!m_errored);
 }
        // This method will update the output parameter value with the additional area field.
        public void UpdateParameters(IArray paramvalues, IGPEnvironmentManager pEnvMgr)
        {
            m_Parameters = paramvalues;

            // Retrieve the input parameter value
            IGPValue parameterValue = m_GPUtilities.UnpackGPValue(m_Parameters.get_Element(0));

            // Get the derived output feature class schema and empty the additional fields. This will ensure you don't get duplicate entries.
            IGPParameter3    derivedFeatures = (IGPParameter3)paramvalues.get_Element(2);
            IGPFeatureSchema schema          = (IGPFeatureSchema)derivedFeatures.Schema;

            schema.AdditionalFields = null;

            // If we have an input value, create a new field based on the field name the user entered.
            if (parameterValue.IsEmpty() == false)
            {
                IGPParameter3 fieldNameParameter = (IGPParameter3)paramvalues.get_Element(1);
                string        fieldName          = fieldNameParameter.Value.GetAsText();

                // Check if the user's input field already exists
                IField areaField = m_GPUtilities.FindField(parameterValue, fieldName);
                if (areaField == null)
                {
                    IFieldsEdit fieldsEdit = new FieldsClass();
                    IFieldEdit  fieldEdit  = new FieldClass();
                    fieldEdit.Name_2 = fieldName;
                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                    fieldsEdit.AddField(fieldEdit);

                    // Add an additional field for the area values to the derived output.
                    IFields fields = fieldsEdit as IFields;
                    schema.AdditionalFields = fields;
                }
            }
        }
        public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            IGPParameter inputFCParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter;
            IGPValue     osmFCGPValue     = gpUtilities3.UnpackGPValue(inputFCParameter);

            if (osmFCGPValue.IsEmpty())
            {
                return;
            }

            IFeatureClass osmFeatureClass = null;
            IQueryFilter  queryFilter     = null;

            if (osmFCGPValue is IGPFeatureLayer)
            {
                gpUtilities3.DecodeFeatureLayer(osmFCGPValue, out osmFeatureClass, out queryFilter);

                int osmTagFieldIndex = osmFeatureClass.Fields.FindField("osmTags");

                if (osmTagFieldIndex == -1)
                {
                    Messages.ReplaceError(in_osmFeaturesNumber, -1, resourceManager.GetString("GPTools_OSMGPAddExtension_noosmtagfield"));
                }
            }
        }
Beispiel #7
0
        /// <summary>
        /// Helper function to assemble the parameter objects for the GP tool
        /// </summary>
        /// <param name="dir">
        /// The "direction" of the parameter (input, output, ...); one of the
        /// esriGPParameterDirection enum values</param>
        /// <param name="paramType">One of the esriGPParameterType enum values</param>
        /// <param name="dispName">The name of the parameter displayed to the user</param>
        /// <param name="name">The internal name of the parameter</param>
        /// <param name="dataType">The type of data stored by the parameter</param>
        /// <param name="value">The initial value of the parameter</param>
        /// <param name="domainDependsOnWmxDb">
        /// Specifying true will cause the parameter's domain to be set to null when
        /// the selected Workflow Manager database changes; false will leave the domain
        /// unchanged.
        /// </param>
        /// <returns>The GP parameter object that was created</returns>
        protected IGPParameterEdit3 BuildParameter(
            esriGPParameterDirection dir,
            esriGPParameterType paramType,
            string dispName,
            string name,
            IGPDataType dataType,
            IGPValue value,
            bool domainDependsOnWmxDb)
        {
            IGPParameterEdit3 param = new GPParameterClass();

            param.Direction     = dir;
            param.ParameterType = paramType;
            param.Enabled       = true;
            param.DisplayName   = dispName;
            param.Name          = name;
            param.DataType      = dataType;
            if (value == null)
            {
                param.Value = dataType.CreateValue(string.Empty);
            }
            else
            {
                param.Value = value;
            }

            if (domainDependsOnWmxDb)
            {
                m_dependentParamNames.Add(name);
            }

            return(param);
        }
Beispiel #8
0
        /*
         * Called each time the user changes a parameter in the tool dialog or Command Line.
         * This updates the output data of the tool, which extremely useful for building models.
         * After returning from UpdateParameters(), geoprocessing calls its internal validation routine checkng that a given set of parameter values
         * are of the appropriate number, DataType, and value.
         * This method will update the output parameter value with the unique field.
         */
        public void UpdateParameters(IArray paramvalues, IGPEnvironmentManager pEnvMgr)
        {
            m_Parameters = paramvalues;

            // Retrieve the input parameter value
            IGPValue parameterValue = m_GPUtilities.UnpackGPValue(m_Parameters.get_Element(0));

            // Retrieve the unique field parameter value
            IGPParameter3 fieldNameParameter = (IGPParameter3)paramvalues.get_Element(3);

            // Get the output feature class schema and empty the additional fields. This will ensure
            // you don't get dublicate entries.
            IGPParameter3    outputFeatures = (IGPParameter3)paramvalues.get_Element(2);
            IGPFeatureSchema schema         = (IGPFeatureSchema)outputFeatures.Schema;

            schema.AdditionalFields = null;

            // If we have an unique field value, create a new field based on the unique field name the user entered.
            if (fieldNameParameter.Value.IsEmpty() == false)
            {
                string fieldName = fieldNameParameter.Value.GetAsText();

                IField      uniqueField = m_GPUtilities.FindField(parameterValue, fieldName);
                IFieldsEdit fieldsEdit  = new FieldsClass();
                fieldsEdit.AddField(uniqueField);

                IFields fields = fieldsEdit as IFields;
                schema.AdditionalFields = fields;
            }
        }
Beispiel #9
0
        public IGPMessage ValidateValue(IGPValue Value, IGPDomain Domain)
        {
            IGPMessage    validateValueMessage = new GPMessageClass();
            IGPUtilities3 gpUtilities          = new GPUtilitiesClass();

            IHttpBasicGPValue targetValue = gpUtilities.UnpackGPValue(Value) as IHttpBasicGPValue;

            if (targetValue == null)
            {
                IGPString targetValueString = gpUtilities.UnpackGPValue(Value) as IGPString;
                if (targetValueString != null)
                {
                    return(validateValueMessage);
                }
            }


            if (targetValue == null)
            {
                validateValueMessage.Type        = esriGPMessageType.esriGPMessageTypeError;
                validateValueMessage.ErrorCode   = 502;
                validateValueMessage.Description = resourceManager.GetString("GPTools_Authentication_HttpBasicDataType_valuevalidation");
            }

            if (Domain != null)
            {
                validateValueMessage = Domain.MemberOf((IGPValue)targetValue);
            }

            return(validateValueMessage);
        }
        // Called after returning from the update parameters routine.
        // You can examine the messages created from internal validation and change them if desired.
        public void UpdateMessages(IArray paramvalues, IGPEnvironmentManager pEnvMgr, IGPMessages Messages)
        {
            // Check for error messages
            IGPMessage msg = (IGPMessage)Messages;

            if (msg.IsError())
            {
                return;
            }

            // Get the first Input Parameter
            IGPParameter parameter = (IGPParameter)paramvalues.get_Element(0);

            // UnPackGPValue. This ensures you get the value either form the dataelement or GpVariable (ModelBuilder)
            IGPValue parameterValue = m_GPUtilities.UnpackGPValue(parameter);

            // Open the Input Dataset - Use DecodeFeatureLayer as the input might be a layer file or a feature layer from ArcMap.
            IFeatureClass inputFeatureClass;
            IQueryFilter  qf;

            m_GPUtilities.DecodeFeatureLayer(parameterValue, out inputFeatureClass, out qf);

            IGPParameter3 fieldParameter = (IGPParameter3)paramvalues.get_Element(1);
            string        fieldName      = fieldParameter.Value.GetAsText();

            // Check if the field already exists and provide a warning.
            int indexA = inputFeatureClass.FindField(fieldName);

            if (indexA > 0)
            {
                Messages.ReplaceWarning(1, "Field already exists. It will be overwritten.");
            }

            return;
        }
Beispiel #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="vt"></param>
        /// <returns></returns>
        private IJTXAttributeConditionSet ExtractAttributeConditionsFromWhereClause(IGPValueTable vt)
        {
            IJTXAttributeConditionSet attributeConditions = new JTXAttributeConditionSetClass();

            // Preliminary error-checking
            for (int i = 0; i < vt.RecordCount; i++)
            {
                IArray   tempRecord = vt.GetRecord(i);
                IGPValue tempVal    = tempRecord.get_Element(m_whereClauseIndices[C_ID_VT_OPERATOR]) as IGPValue;
                if (!m_optWhereClauseOps.ContainsKey(tempVal.GetAsText()))
                {
                    throw new WmauException(WmauErrorCodes.C_OPERATOR_NOT_FOUND_ERROR);
                }
            }

            // Build out the attribute conditions
            for (int i = 0; i < vt.RecordCount; i++)
            {
                IArray   tempRecord   = vt.GetRecord(i);
                IGPValue attribute    = tempRecord.get_Element(m_whereClauseIndices[C_ID_VT_ATTRIBUTE]) as IGPValue;
                IGPValue compOperator = tempRecord.get_Element(m_whereClauseIndices[C_ID_VT_OPERATOR]) as IGPValue;
                IGPValue value        = tempRecord.get_Element(m_whereClauseIndices[C_ID_VT_VALUE]) as IGPValue;

                IJTXAttributeCondition attributeCondition = new JTXAttributeConditionClass();
                attributeCondition.FieldName    = attribute.GetAsText();
                attributeCondition.Operator     = m_optWhereClauseOps[compOperator.GetAsText()];
                attributeCondition.CompareValue = value.GetAsText();

                attributeConditions.Add(attributeCondition);
            }

            return(attributeConditions);
        }
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            try
            {
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

                if (TrackCancel == null)
                {
                    TrackCancel = new CancelTrackerClass();
                }

                IGPParameter inputFeatureClassParameter = paramvalues.get_Element(in_osmFeaturesNumber) as IGPParameter;
                IGPValue     inputFeatureGPValue        = gpUtilities3.UnpackGPValue(inputFeatureClassParameter) as IGPValue;

                IFeatureClass osmFeatureClass = null;
                IQueryFilter  queryFilter     = null;

                gpUtilities3.DecodeFeatureLayer(inputFeatureGPValue, out osmFeatureClass, out queryFilter);

                ((ITable)osmFeatureClass).RemoveOSMClassExtension();
            }
            catch (Exception ex)
            {
                message.AddError(120057, ex.Message);
            }
        }
Beispiel #13
0
        /// <summary>
        ///     Executes the geoprocessing function using the given array of parameter values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="trackCancel">The track cancel.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="messages">The messages that are reported to the user.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void Execute(Dictionary <string, IGPValue> parameters, ITrackCancel trackCancel, IGPEnvironmentManager environmentManager, IGPMessages messages, IGPUtilities2 utilities)
        {
            IGPValue     value = parameters["in_table"];
            IObjectClass table = utilities.OpenTable(value);

            if (table != null)
            {
                IMMConfigTopLevel configTopLevel = ConfigTopLevel.Instance;
                configTopLevel.Workspace = utilities.GetWorkspace(value);

                // Load all of the subtypes when the user specified "All" or "-1".
                int subtype      = parameters["in_subtype"].Cast(-1);
                var subtypeCodes = new List <int>(new[] { subtype });
                if (subtype == -1)
                {
                    ISubtypes subtypes = (ISubtypes)table;
                    subtypeCodes.AddRange(subtypes.Subtypes.AsEnumerable().Select(o => o.Key));
                }

                IGPMultiValue onCreate = (IGPMultiValue)parameters["in_create"];
                IGPMultiValue onUpdate = (IGPMultiValue)parameters["in_update"];
                IGPMultiValue onDelete = (IGPMultiValue)parameters["in_delete"];

                // Load the "Attribute" AUs.
                var uids = new Dictionary <mmEditEvent, IEnumerable <IUID> >();
                uids.Add(mmEditEvent.mmEventFeatureCreate, onCreate.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));
                uids.Add(mmEditEvent.mmEventFeatureUpdate, onUpdate.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));
                uids.Add(mmEditEvent.mmEventFeatureDelete, onDelete.AsEnumerable().Cast <IGPAutoValue>().Select(o => o.UID));

                IGPValue field = parameters["in_field"];
                int      index = table.FindField(field.GetAsText());

                // Enumerate through all of the subtypes making changes.
                foreach (var subtypeCode in subtypeCodes)
                {
                    // Load the configurations for the table and subtype.
                    IMMSubtype mmsubtype = configTopLevel.GetSubtypeByID(table, subtypeCode, false);

                    // Load the field configurations.
                    IMMField mmfield = null;
                    mmsubtype.GetField(index, ref mmfield);

                    // Update the list to have these UIDs removed.
                    ID8List list = (ID8List)mmfield;
                    base.Remove(uids, list, messages);
                }

                // Commit the changes to the database.
                configTopLevel.SaveFeatureClassToDB(table);

                // Success.
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
        public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            for (int i = 0; i < Messages.Count; i++)
            {
                IGPMessage blah = Messages.GetMessage(i);
                if (blah.IsError())
                {
                    IGPMessage something = new GPMessageClass();
                    something.Description = String.Empty;
                    something.Type        = esriGPMessageType.esriGPMessageTypeInformative;
                    something.ErrorCode   = 0;
                    Messages.Replace(i, something);
                }
            }

            IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClassNumber) as IGPParameter;
            IGPValue     inputOSMGPValue   = gpUtilities3.UnpackGPValue(inputOSMParameter);

            if (inputOSMGPValue.IsEmpty() == false)
            {
                IFeatureClass osmFeatureClass = null;
                ITable        osmInputTable   = null;
                IQueryFilter  osmQueryFilter  = null;

                try
                {
                    gpUtilities3.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

                try
                {
                    if (osmInputTable == null)
                    {
                        gpUtilities3.DecodeTableView(inputOSMGPValue, out osmInputTable, out osmQueryFilter);
                    }
                }
                catch { }

                if (osmInputTable == null)
                {
                    return;
                }

                // find the field that holds tag binary/xml field
                int osmTagCollectionFieldIndex = osmInputTable.FindField("osmTags");

                if (osmTagCollectionFieldIndex == -1)
                {
                    Messages.ReplaceAbort(in_osmFeatureClassNumber, resourceManager.GetString("GPTools_OSMGPCombineAttributes_inputlayer_missingtagfield"));
                    return;
                }
            }
        }
Beispiel #15
0
        protected override void ImpCheck(IGPValue v)
        {
            VT val;

            if (!CheckT(v, out val))
            {
                Error("Required a " + m_friendly + " but didn't get it. Programmer error?");
            }
            ValueCheck(val);
        }
Beispiel #16
0
 /// <summary>
 /// Helper function to assemble the parameter objects for the GP tool.  Assumes
 /// that the parameter's domain is not dependent on the chosen Workflow Manager
 /// database.
 /// </summary>
 /// <param name="dir">
 /// The "direction" of the parameter (input, output, ...); one of the
 /// esriGPParameterDirection enum values</param>
 /// <param name="paramType">One of the esriGPParameterType enum values</param>
 /// <param name="dispName">The name of the parameter displayed to the user</param>
 /// <param name="name">The internal name of the parameter</param>
 /// <param name="dataType">The type of data stored by the parameter</param>
 /// <param name="value">The initial value of the parameter</param>
 /// <returns>The GP parameter object that was created</returns>
 protected IGPParameterEdit3 BuildParameter(
     esriGPParameterDirection dir,
     esriGPParameterType paramType,
     string dispName,
     string name,
     IGPDataType dataType,
     IGPValue value)
 {
     return(BuildParameter(dir, paramType, dispName, name, dataType, value, false));
 }
        /// <summary>
        /// Updates the internal values used by this tool based on the parameters from an input array
        /// </summary>
        /// <param name="paramValues"></param>
        protected override void ExtractParameters(IArray paramValues)
        {
            // Get the values for any parameters common to all GP tools
            ExtractParametersCommon(paramValues);

            WmauParameterMap paramMap = new WmauParameterMap(paramValues);
            IGPParameter3    param    = null;

            // Ensure that the various parameter values are all restored to their
            // defaults because of how this function works
            ResetVariables();

            // Update the internal values of whatever parameters we're maintaining
            param            = paramMap.GetParam(C_PARAM_PREVIEW_CHANGES);
            m_previewChanges = (param.Value as IGPBoolean).Value;

            param = paramMap.GetParam(C_PARAM_CHECKLIST);
            IGPValue      paramValue      = m_gpUtilities.UnpackGPValue(param);
            IGPMultiValue paramMultiValue = paramValue as IGPMultiValue;

            for (int i = 0; i < paramMultiValue.Count; i++)
            {
                IGPValue check  = paramMultiValue.get_Value(i);
                string   strVal = check.GetAsText();
                if (strVal.Equals(C_OPT_CLEAN_WORKFLOWS))
                {
                    m_cleanWorkflows = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_STEP_TYPES))
                {
                    m_cleanStepTypes = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_STATUS_TYPES))
                {
                    m_cleanStatusTypes = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_PRIORITIES))
                {
                    m_cleanPriorities = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_TA_WORKBOOKS))
                {
                    m_cleanTaWorkbooks = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_USERS))
                {
                    m_cleanUsers = true;
                }
                else if (strVal.Equals(C_OPT_CLEAN_MAP_DOCS))
                {
                    m_cleanMapDocs = true;
                }
            }
        }
Beispiel #18
0
        /// <summary>
        ///     Gets the workspace specified by the given geoprocessing value object.
        /// </summary>
        /// <param name="utilities">The utilities.</param>
        /// <param name="value">The geoprocessing value object.</param>
        /// <returns>
        ///     Returns a <see cref="IWorkspace" /> representing the workspace object.
        /// </returns>
        public static IWorkspace GetWorkspace(this IGPUtilities2 utilities, IGPValue value)
        {
            if (!value.IsEmpty())
            {
                IDataset dataset = utilities.OpenDataset(value);
                if (dataset != null)
                {
                    return(dataset.Workspace);
                }
            }

            return(null);
        }
Beispiel #19
0
        /// <summary>
        ///     Opens the table object specified by the given geoprocessing value object.
        /// </summary>
        /// <param name="utilities">The utilities.</param>
        /// <param name="value">The geoprocessing value object.</param>
        /// <returns>
        ///     Returns a <see cref="IObjectClass" /> representing the table object.
        /// </returns>
        public static IObjectClass OpenTable(this IGPUtilities2 utilities, IGPValue value)
        {
            if (!value.IsEmpty())
            {
                IDataset dataset = utilities.OpenDataset(value);
                if (dataset != null)
                {
                    return(dataset as IObjectClass);
                }
            }

            return(null);
        }
        public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
        {
            IGPUtilities3 execute_Utilities = new GPUtilitiesClass();
            IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(in_featureDatasetParameterNumber));

            // get the name of the feature dataset
            int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\");

            if (fdDemlimiterPosition == -1)
            {
                Messages.ReplaceError(in_featureDatasetParameterNumber, -33, resourceManager.GetString("GPTools_OSMGPExport2OSM_invalid_featuredataset"));
            }
        }
        public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
        {
            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

            IGPParameter3 inputLayersParameter = paramvalues.get_Element(in_LayersNumber) as IGPParameter3;
            IGPMultiValue inputLayersGPValue   = gpUtilities3.UnpackGPValue(inputLayersParameter) as IGPMultiValue;

            if (inputLayersGPValue == null)
            {
                return;
            }

            // check if there are input layer provided
            if (inputLayersGPValue.Count == 0)
            {
                return;
            }

            IGPParameter3 outputLayerParameter = paramvalues.get_Element(out_groupLayerNumber) as IGPParameter3;
            IGPValue      outputLayerGPValue   = gpUtilities3.UnpackGPValue(outputLayerParameter);

            // if the output layer value is still empty and build a proposal for a name
            if (outputLayerGPValue.IsEmpty())
            {
                // read the proposed name from the resources
                string proposedOutputLayerName = resourceManager.GetString("GPTools_GPCombineLayers_outputgrouplayer_proposedname");

                string proposedOutputLayerNameTest = proposedOutputLayerName;
                int    layerIndex = 2;

                // check if a layer with the same name already exists
                // if it does then attempt to append some index numbers to build a unique, new name
                ILayer foundLayer = gpUtilities3.FindMapLayer(proposedOutputLayerNameTest);

                while (foundLayer != null)
                {
                    proposedOutputLayerNameTest = proposedOutputLayerName + " (" + layerIndex + ")";

                    foundLayer = gpUtilities3.FindMapLayer(proposedOutputLayerNameTest);
                    layerIndex = layerIndex + 1;

                    if (layerIndex > 10000)
                    {
                        break;
                    }
                }

                outputLayerGPValue.SetAsText(proposedOutputLayerNameTest);
                gpUtilities3.PackGPValue(outputLayerGPValue, outputLayerParameter);
            }
        }
        public static int GetFeaturesForInput(IGPValue inputValue, out IFeatureClass inputFClass, out IFeatureCursor inputFeatures)
        {
            //
            // GET FEATURECURSOR RESPECTING SELECTION
            IGPUtilities gpUtils = new GPUtilitiesClass();
            int numFeatures = 0;
            IGeoFeatureLayer inputFLayer = null;

            if (inputValue is IDEFeatureClass)
            {
                // IF THE INPUT IS A FEATURECLASS THEN JUST OPEN THE DATASET AND
                // CREATE A FEATURE CURSOR OF ALL THE FEATURES AND RETURN THE TOTAL
                // NUMBER OF FEATURES IN THE FEATURECLASS
                inputFClass = (IFeatureClass)gpUtils.OpenDataset(inputValue);
                inputFeatures = inputFClass.Search(null, false);
                numFeatures = inputFClass.FeatureCount(null);
            }
            else
            {
                // IF THE INPUT IS A FEATURELAYER THEN OPEN THE FEATURELAYER
                // AND USE THE DISPLAYFEATURECLASS THAT RESPECTS JOINED FIELDS.
                inputFLayer = (IGeoFeatureLayer)gpUtils.OpenDataset(inputValue);
                inputFClass = inputFLayer.DisplayFeatureClass;
                IFeatureSelection inputSelection = (IFeatureSelection)inputFLayer;
                if (inputSelection.SelectionSet.Count > 0)
                {
                    // IF THE FEATURELAYER HAS A SELECTION THEN CREATE A FEATURECURSOR
                    // OF ALL THE SELECTED FEATURES AND RETURN THE NUMBER OF FEATURES
                    // IN THE SELECTION
                    ICursor selectionCursor = null;
                    inputSelection.SelectionSet.Search(null, false, out selectionCursor);
                    inputFeatures = (IFeatureCursor)selectionCursor;
                    numFeatures = inputSelection.SelectionSet.Count;
                }
                else
                {
                    // IF THE FEATURELAYER HAS NO SELECTION THEN CREATE A FEATURECURSOR
                    // USING THE DEFINITIONEXPRESSION OF THE LAYER AND RETURN THE NUMBER
                    // OF FEATURES BASED ON THE DEFINITIONEXPRESSION.
                    IFeatureLayerDefinition layerDef = (IFeatureLayerDefinition)inputFLayer;
                    IQueryFilter queryFilter = new QueryFilterClass();
                    queryFilter.WhereClause = layerDef.DefinitionExpression;
                    inputFeatures = inputFLayer.SearchDisplayFeatures(queryFilter, false);
                    numFeatures = inputFLayer.FeatureClass.FeatureCount(queryFilter);
                }
            }

            return numFeatures;
        }
Beispiel #23
0
        /// <summary>
        ///     Pre validates the given set of values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void UpdateParameters(Dictionary <string, IGPParameter> parameters, IGPEnvironmentManager environmentManager, IGPUtilities2 utilities)
        {
            IGPValue value = utilities.UnpackGPValue(parameters["in_table"]);

            if (!value.IsEmpty())
            {
                IObjectClass table = utilities.OpenTable(value);
                if (table != null)
                {
                    // Populate the subtype parameter with the subtypes from the table and ensure the it's editable.
                    IGPParameterEdit3 subtypeParameter = (IGPParameterEdit3)parameters["in_subtype"];
                    subtypeParameter.Domain = this.GetSubtypes(table);

                    // Populate the auto updater values for the object class for the specific subtype.
                    IGPValue subtype = utilities.UnpackGPValue(subtypeParameter);
                    if (!subtype.IsEmpty())
                    {
                        var subtypeCode = subtype.Cast(-1);
                        IMMConfigTopLevel configTopLevel = ConfigTopLevel.Instance;
                        configTopLevel.Workspace = utilities.GetWorkspace(value);

                        var values = configTopLevel.GetAutoValues(table, mmEditEvent.mmEventFeatureCreate);
                        IGPParameterEdit3 parameter = (IGPParameterEdit3)parameters["in_create"];
                        parameter.Domain = base.CreateDomain <IMMSpecialAUStrategyEx>(values[subtypeCode]);

                        values           = configTopLevel.GetAutoValues(table, mmEditEvent.mmEventFeatureUpdate);
                        parameter        = (IGPParameterEdit3)parameters["in_update"];
                        parameter.Domain = base.CreateDomain <IMMSpecialAUStrategyEx>(values[subtypeCode]);

                        values           = configTopLevel.GetAutoValues(table, mmEditEvent.mmEventFeatureDelete);
                        parameter        = (IGPParameterEdit3)parameters["in_delete"];
                        parameter.Domain = base.CreateDomain <IMMSpecialAUStrategyEx>(values[subtypeCode]);

                        values           = configTopLevel.GetAutoValues(table, mmEditEvent.mmEventBeforeFeatureSplit);
                        parameter        = (IGPParameterEdit3)parameters["in_before"];
                        parameter.Domain = base.CreateDomain <IMMSpecialAUStrategyEx>(values[subtypeCode]);

                        values           = configTopLevel.GetAutoValues(table, mmEditEvent.mmEventFeatureSplit);
                        parameter        = (IGPParameterEdit3)parameters["in_split"];
                        parameter.Domain = base.CreateDomain <IMMSpecialAUStrategyEx>(values[subtypeCode]);

                        values           = configTopLevel.GetAutoValues(table, mmEditEvent.mmEventAfterFeatureSplit);
                        parameter        = (IGPParameterEdit3)parameters["in_after"];
                        parameter.Domain = base.CreateDomain <IMMSpecialAUStrategyEx>(values[subtypeCode]);
                    }
                }
            }
        }
Beispiel #24
0
        /// <summary>
        /// Validates the value.
        /// </summary>
        /// <param name="value">The value.</param>
        /// <param name="domain">The domain.</param>
        /// <returns></returns>
        public IGPMessage ValidateValue(IGPValue value, IGPDomain domain)
        {
            IGPMessage    message   = new GPMessageClass();
            IGPUtilities3 utilities = new GPUtilitiesClass();

            IGPAutoValue autoValue = utilities.UnpackGPValue(value) as IGPAutoValue;

            if (autoValue == null)
            {
                message.Type        = esriGPMessageType.esriGPMessageTypeError;
                message.ErrorCode   = 502;
                message.Description = @"The value is not an auto value.";
            }

            return(message);
        }
Beispiel #25
0
        private IGPParameter CreateParameter(IGPDataType dataType, IGPValue value, esriGPParameterDirection direction, string displayName, string name, esriGPParameterType parameterType)
        {
            // Area field parameter
            IGPParameterEdit3 inputParameter = new GPParameterClass();

            inputParameter.DataType = dataType;
            inputParameter.Value    = value;

            // Set field name parameter properties
            inputParameter.Direction     = direction;
            inputParameter.DisplayName   = displayName;
            inputParameter.Name          = name;
            inputParameter.ParameterType = parameterType;


            return((IGPParameter)inputParameter);
        }
Beispiel #26
0
        /// <summary>
        ///     Pre validates the given set of values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void UpdateParameters(Dictionary <string, IGPParameter> parameters, IGPEnvironmentManager environmentManager, IGPUtilities2 utilities)
        {
            IGPValue value = utilities.UnpackGPValue(parameters["in_table"]);

            if (!value.IsEmpty())
            {
                IObjectClass table = utilities.OpenTable(value);
                if (table != null)
                {
                    IGPParameterEdit3 parameter = (IGPParameterEdit3)parameters["in_field"];
                    parameter.Domain = base.GetFields(table);

                    parameter        = (IGPParameterEdit3)parameters["in_subtype"];
                    parameter.Domain = base.GetSubtypes(table);
                }
            }
        }
Beispiel #27
0
        public void UpdateParameters(IArray paramvalues, IGPEnvironmentManager pEnvMgr)
        {
            IGPUtilities2 gpUtil = null;

            try
            {
                gpUtil = new GPUtilitiesClass();

                IGPParameter targetDatasetParameter = paramvalues.get_Element(in_osmFeatureDataset) as IGPParameter;
                IDataElement dataElement            = gpUtil.UnpackGPValue(targetDatasetParameter) as IDataElement;
                string       osmDatasetPath         = dataElement.CatalogPath;

                IGPParameter gppNetworkDataset = paramvalues.get_Element(out_NetworkDataset) as IGPParameter;
                IGPValue     gpvNetworkDataset = gpUtil.UnpackGPValue(gppNetworkDataset);
                string       ndsPath           = gpvNetworkDataset.GetAsText();

                string ndsDir = string.Empty;
                if (!string.IsNullOrEmpty(ndsPath))
                {
                    ndsDir = System.IO.Path.GetDirectoryName(ndsPath);
                }

                if (!ndsDir.Equals(osmDatasetPath))
                {
                    string ndsName = System.IO.Path.GetFileName(ndsPath);
                    if (string.IsNullOrEmpty(ndsName))
                    {
                        ndsName = _defaultNetworkDatasetName;
                    }

                    ndsName = System.IO.Path.GetFileName(osmDatasetPath) + "_" + ndsName;
                    gpvNetworkDataset.SetAsText(System.IO.Path.Combine(osmDatasetPath, ndsName));
                    gpUtil.PackGPValue(gpvNetworkDataset, gppNetworkDataset);
                }
            }
            finally
            {
                if (gpUtil != null)
                {
                    ComReleaser.ReleaseCOMObject(gpUtil);
                }
            }
        }
Beispiel #28
0
        /// <summary>
        ///     Pre validates the given set of values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void UpdateParameters(Dictionary <string, IGPParameter> parameters, IGPEnvironmentManager environmentManager, IGPUtilities2 utilities)
        {
            IGPValue value = utilities.UnpackGPValue(parameters["in_table"]);

            if (!value.IsEmpty())
            {
                IRelationshipClass relClass = utilities.OpenRelationshipClass(value);
                if (relClass != null)
                {
                    var components = this.LoadComponents <IMMRelationshipAUStrategy>(RelationshipAutoupdateStrategy.CatID);

                    IGPParameterEdit3 parameter = (IGPParameterEdit3)parameters["in_create"];
                    parameter.Domain = base.CreateDomain(components, o => o.Enabled[relClass, mmEditEvent.mmEventRelationshipCreated]);

                    parameter        = (IGPParameterEdit3)parameters["in_delete"];
                    parameter.Domain = base.CreateDomain(components, o => o.Enabled[relClass, mmEditEvent.mmEventRelationshipDeleted]);
                }
            }
        }
Beispiel #29
0
        public IFields getFields(string catalogpath)
        {
            IFields flds = null;

            try
            {
                if (exists(catalogpath))
                {
                    param.RemoveAll();
                    param.Add(catalogpath);
                    IGPValue gpValue = (IGPValue)param;
                    flds = gpUtl.GetFields(gpValue);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Error: " + e.ToString());
            }
            return(flds);
        }
Beispiel #30
0
        /// <summary>
        ///     Pre validates the given set of values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void UpdateParameters(Dictionary <string, IGPParameter> parameters, IGPEnvironmentManager environmentManager, IGPUtilities2 utilities)
        {
            // Retrieve the input parameter value.
            IGPValue table = utilities.UnpackGPValue(parameters["in_table"]);

            if (!table.IsEmpty())
            {
                // Create the domain based on the fields on the table.
                IObjectClass oclass = utilities.OpenTable(table);
                if (oclass != null)
                {
                    IFields fields = oclass.Fields;
                    if (fields != null)
                    {
                        IGPCodedValueDomain codedValueDomain = new GPCodedValueDomainClass();
                        foreach (var o in fields.AsEnumerable())
                        {
                            codedValueDomain.AddStringCode(o.Name, o.Name);
                        }

                        IGPParameterEdit3 derivedFields = (IGPParameterEdit3)parameters["in_field"];
                        derivedFields.Domain = (IGPDomain)codedValueDomain;
                    }

                    IGPValue field = utilities.UnpackGPValue(parameters["in_field"]);
                    if (!field.IsEmpty())
                    {
                        int index = oclass.FindField(field.GetAsText());

                        IGPCodedValueDomain codedValueDomain = new GPCodedValueDomainClass();
                        foreach (var o in oclass.GetFieldModelNames(oclass.Fields.Field[index]))
                        {
                            codedValueDomain.AddStringCode(o, o);
                        }

                        IGPParameterEdit3 derivedParameter = (IGPParameterEdit3)parameters["in_field_model_names"];
                        derivedParameter.Domain = (IGPDomain)codedValueDomain;
                    }
                }
            }
        }
Beispiel #31
0
        /// <summary>
        ///     Pre validates the given set of values.
        /// </summary>
        /// <param name="parameters">The parameters.</param>
        /// <param name="environmentManager">Provides access to all the current environments and settings of the current client.</param>
        /// <param name="utilities">
        ///     The utilities object that provides access to the properties and methods of a geoprocessing
        ///     objects.
        /// </param>
        protected override void UpdateParameters(Dictionary <string, IGPParameter> parameters, IGPEnvironmentManager environmentManager, IGPUtilities2 utilities)
        {
            IGPValue value = utilities.UnpackGPValue(parameters["in_table"]);

            if (!value.IsEmpty())
            {
                IObjectClass table = utilities.OpenTable(value);
                if (table != null)
                {
                    IGPParameterEdit3 parameter = (IGPParameterEdit3)parameters["in_field"];
                    parameter.Domain = base.GetFields(table);
                    string fieldName = utilities.UnpackGPValue(parameter).GetAsText();

                    parameter        = (IGPParameterEdit3)parameters["in_subtype"];
                    parameter.Domain = base.GetSubtypes(table);

                    IGPValue subtype = utilities.UnpackGPValue(parameter);
                    if (!subtype.IsEmpty())
                    {
                        if (!string.IsNullOrEmpty(fieldName))
                        {
                            var subtypeCode = subtype.Cast(-1);
                            IMMConfigTopLevel configTopLevel = ConfigTopLevel.Instance;
                            configTopLevel.Workspace = utilities.GetWorkspace(value);

                            var values = configTopLevel.GetAutoValues(table, mmEditEvent.mmEventFeatureCreate, fieldName);
                            parameter        = (IGPParameterEdit3)parameters["in_create"];
                            parameter.Domain = base.CreateDomain <IMMAttrAUStrategy>(values[subtypeCode][fieldName]);

                            values           = configTopLevel.GetAutoValues(table, mmEditEvent.mmEventFeatureUpdate, fieldName);
                            parameter        = (IGPParameterEdit3)parameters["in_update"];
                            parameter.Domain = base.CreateDomain <IMMAttrAUStrategy>(values[subtypeCode][fieldName]);

                            values           = configTopLevel.GetAutoValues(table, mmEditEvent.mmEventFeatureDelete, fieldName);
                            parameter        = (IGPParameterEdit3)parameters["in_delete"];
                            parameter.Domain = base.CreateDomain <IMMAttrAUStrategy>(values[subtypeCode][fieldName]);
                        }
                    }
                }
            }
        }
        internal List<string> loadOSMWays(string osmFileLocation, ref ITrackCancel TrackCancel, ref IGPMessages message, IGPValue targetGPValue, IFeatureClass osmPointFeatureClass, IFeatureClass osmLineFeatureClass, IFeatureClass osmPolygonFeatureClass, bool conserveMemory, bool fastLoad, int wayCapacity, ref Dictionary<string, simplePointRef> osmNodeDictionary, IFeatureWorkspace featureWorkspace, ISpatialReference downloadSpatialReference, OSMDomains availableDomains, bool checkForExisting)
        {
            if (osmLineFeatureClass == null)
            {
                throw new ArgumentNullException("osmLineFeatureClass");
            }

            if (osmPolygonFeatureClass == null)
            {
                throw new ArgumentNullException("osmPolygonFeatureClass");
            }

            XmlReader osmFileXmlReader = null;
            XmlSerializer waySerializer = null;
            List<string> missingWays = null;

            try
            {
                missingWays = new List<string>();

                int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
                int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount");

                int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmLineDomainAttributeFieldLength = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmLineFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmLineDomainAttributeFieldLength.Add(domains.name, osmLineFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }
                int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags");
                int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser");
                int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid");
                int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible");
                int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion");
                int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf");
                int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement");

                int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmPolygonDomainAttributeFieldLength = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmPolygonDomainAttributeFieldLength.Add(domains.name, osmPolygonFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }
                int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags");
                int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser");
                int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid");
                int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible");
                int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion");
                int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf");
                int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement");

                ISpatialReferenceFactory spatialRef = new SpatialReferenceEnvironmentClass();
                ISpatialReference wgs84 = spatialRef.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);

                bool shouldProject = !((IClone)wgs84).IsEqual((IClone)downloadSpatialReference);

                // set up the progress indicator
                IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

                if (stepProgressor != null)
                {
                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = wayCapacity;
                    stepProgressor.Position = 0;
                    stepProgressor.Message = _resourceManager.GetString("GPTools_OSMGPFileReader_loadingWays");
                    stepProgressor.StepValue = 1;
                    stepProgressor.Show();
                }

                bool lineIndexRebuildRequired = false;
                bool polygonIndexRebuildRequired = false;

                int wayCount = 0;
                object missingValue = System.Reflection.Missing.Value;

                // enterprise GDB indicator -- supporting load only mode
                IFeatureClassLoad lineFeatureLoad = null;
                IFeatureClassLoad polygonFeatureLoad = null;

                using (SchemaLockManager lineLock = new SchemaLockManager(osmLineFeatureClass as ITable), polygonLock = new SchemaLockManager(osmPolygonFeatureClass as ITable))
                {
                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        IFeatureCursor insertLineCursor = osmLineFeatureClass.Insert(true);
                        comReleaser.ManageLifetime(insertLineCursor);

                        IFeatureBuffer featureLineBuffer = osmLineFeatureClass.CreateFeatureBuffer();
                        comReleaser.ManageLifetime(featureLineBuffer);

                        IFeatureCursor insertPolygonCursor = osmPolygonFeatureClass.Insert(true);
                        comReleaser.ManageLifetime(insertPolygonCursor);

                        IFeatureBuffer featurePolygonBuffer = osmPolygonFeatureClass.CreateFeatureBuffer();
                        comReleaser.ManageLifetime(featurePolygonBuffer);

                        if (((IWorkspace)featureWorkspace).WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                        {
                            lineFeatureLoad = osmLineFeatureClass as IFeatureClassLoad;
                            polygonFeatureLoad = osmPolygonFeatureClass as IFeatureClassLoad;
                        }

                        if (lineFeatureLoad != null)
                        {
                            lineFeatureLoad.LoadOnlyMode = true;
                        }

                        if (polygonFeatureLoad != null)
                        {
                            polygonFeatureLoad.LoadOnlyMode = true;
                        }

                        ISpatialReference nativeLineSpatialReference = ((IGeoDataset)osmLineFeatureClass).SpatialReference;
                        ISpatialReference nativePolygonSpatialReference = ((IGeoDataset)osmPolygonFeatureClass).SpatialReference;

                        IQueryFilter osmIDQueryFilter = new QueryFilterClass();
                        string sqlPointOSMID = osmPointFeatureClass.SqlIdentifier("OSMID");
                        IFeatureCursor updatePointCursor = null;

                        osmFileXmlReader = System.Xml.XmlReader.Create(osmFileLocation);
                        waySerializer = new XmlSerializer(typeof(way));

                        // the point query filter for updates will not changes, so let's do that ahead of time
                        try
                        {
                            osmIDQueryFilter.SubFields = osmPointFeatureClass.ShapeFieldName + "," + osmPointFeatureClass.Fields.get_Field(osmPointIDFieldIndex).Name + "," + osmPointFeatureClass.Fields.get_Field(osmWayRefCountFieldIndex).Name;
                        }
                        catch
                        { }

                        osmFileXmlReader.MoveToContent();
                        while (osmFileXmlReader.Read())
                        {
                            if (osmFileXmlReader.IsStartElement())
                            {
                                if (osmFileXmlReader.Name == "way")
                                {
                                    string currentwayString = osmFileXmlReader.ReadOuterXml();

                                    // assuming the way to be a polyline is sort of a safe assumption
                                    // and won't cause any topology problem due to orientation and closeness
                                    bool wayIsLine = true;
                                    bool wayIsComplete = true;

                                    way currentWay = null;

                                    try
                                    {
                                        using (StringReader wayReader = new System.IO.StringReader(currentwayString))
                                        {
                                            currentWay = waySerializer.Deserialize(wayReader) as way;
                                        }

                                        // if the deserialization fails then go ahead and read the next xml element
                                        if (currentWay == null)
                                        {
                                            continue;
                                        }

                                        // and we are expecting at least some nodes on the way itself
                                        if (currentWay.nd == null)
                                        {
                                            continue;
                                        }

                                        featureLineBuffer = osmLineFeatureClass.CreateFeatureBuffer();
                                        featurePolygonBuffer = osmPolygonFeatureClass.CreateFeatureBuffer();

                                        IPointCollection wayPointCollection = null;
                                        wayIsLine = IsThisWayALine(currentWay);

                                        if (wayIsLine)
                                        {

                                            // check if a feature with the same OSMID already exists, because the can only be one
                                            if (checkForExisting == true)
                                            {
                                                if (CheckIfExists(osmLineFeatureClass as ITable, currentWay.id))
                                                {
                                                    continue;
                                                }
                                            }

                                            IPolyline wayPolyline = new PolylineClass();
                                            comReleaser.ManageLifetime(wayPointCollection);

                                            wayPolyline.SpatialReference = downloadSpatialReference;

                                            IPointIDAware polylineIDAware = wayPolyline as IPointIDAware;
                                            polylineIDAware.PointIDAware = true;

                                            wayPointCollection = wayPolyline as IPointCollection;

                                            # region generate line geometry
                                            if (conserveMemory == false)
                                            {
                                                for (int ndIndex = 0; ndIndex < currentWay.nd.Length; ndIndex++)
                                                {
                                                    string ndID = currentWay.nd[ndIndex].@ref;
                                                    if (osmNodeDictionary.ContainsKey(ndID))
                                                    {
                                                        IPoint newPoint = new PointClass();
                                                        newPoint.X = osmNodeDictionary[ndID].Longitude;
                                                        newPoint.Y = osmNodeDictionary[ndID].Latitude;

                                                        newPoint.SpatialReference = wgs84;

                                                        if (shouldProject)
                                                        {
                                                            newPoint.Project(((IGeoDataset)osmLineFeatureClass).SpatialReference);
                                                        }

                                                        IPointIDAware idAware = newPoint as IPointIDAware;
                                                        idAware.PointIDAware = true;

                                                        newPoint.ID = osmNodeDictionary[ndID].pointObjectID;

                                                        wayPointCollection.AddPoint(newPoint, ref missingValue, ref missingValue);

                                                        osmNodeDictionary[ndID].RefCounter = osmNodeDictionary[ndID].RefCounter + 1;
                                                    }
                                                    else
                                                    {
                                                        message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedline_node"), currentWay.id, ndID));
                                                        // set the flag that the way is complete due to a missing node
                                                        wayIsComplete = false;
                                                        break;
                                                    }
                                                }

                                            }
                                            else
                                            {
                                                for (int pointIndex = 0; pointIndex < currentWay.nd.Length; pointIndex++)
                                                {
                                                    wayPointCollection.AddPoint(new PointClass());
                                                }

                                                List<string> idRequests = SplitOSMIDRequests(currentWay, 2);

                                                // build a list of node ids we can use to determine the point index in the line geometry
                                                // as well as a dictionary to determine the position in the list in case of duplicates nodes
                                                Dictionary<string, int> nodePositionDictionary = new Dictionary<string, int>(currentWay.nd.Length);
                                                List<string> nodeIDs = new List<string>(currentWay.nd.Length);

                                                foreach (nd wayNode in currentWay.nd)
                                                {
                                                    nodeIDs.Add(wayNode.@ref);

                                                    if (nodePositionDictionary.ContainsKey(wayNode.@ref) == false)
                                                    {
                                                        nodePositionDictionary.Add(wayNode.@ref, 0);
                                                    }
                                                }

                                                try
                                                {
                                                    osmIDQueryFilter.SubFields = osmPointFeatureClass.ShapeFieldName + "," + osmPointFeatureClass.Fields.get_Field(osmPointIDFieldIndex).Name + "," + osmPointFeatureClass.Fields.get_Field(osmWayRefCountFieldIndex).Name;
                                                }
                                                catch
                                                { }

                                                foreach (string request in idRequests)
                                                {
                                                    string idCompareString = request;
                                                    osmIDQueryFilter.WhereClause = sqlPointOSMID + " IN " + request;
                                                    using (ComReleaser innerComReleaser = new ComReleaser())
                                                    {
                                                        updatePointCursor = osmPointFeatureClass.Update(osmIDQueryFilter, true);
                                                        innerComReleaser.ManageLifetime(updatePointCursor);

                                                        IFeature nodeFeature = updatePointCursor.NextFeature();

                                                        while (nodeFeature != null)
                                                        {
                                                            // determine the index of the point in with respect to the node position
                                                            string nodeOSMIDString = Convert.ToString(nodeFeature.get_Value(osmPointIDFieldIndex));

                                                            // remove the ID from the request string
                                                            idCompareString = idCompareString.Replace(nodeOSMIDString, String.Empty);

                                                            int nodePositionIndex = -1;

                                                            while ((nodePositionIndex = nodeIDs.IndexOf(nodeOSMIDString, nodePositionDictionary[nodeOSMIDString])) != -1)
                                                            {
                                                                //// update the new position start search index
                                                                nodePositionDictionary[nodeOSMIDString] = nodePositionIndex + 1;

                                                                wayPointCollection.UpdatePoint(nodePositionIndex, (IPoint)nodeFeature.Shape);

                                                                // increase the reference counter
                                                                if (osmWayRefCountFieldIndex != -1)
                                                                {
                                                                    nodeFeature.set_Value(osmWayRefCountFieldIndex, ((int)nodeFeature.get_Value(osmWayRefCountFieldIndex)) + 1);

                                                                    updatePointCursor.UpdateFeature(nodeFeature);
                                                                }
                                                            }

                                                            if (nodeFeature != null)
                                                                Marshal.ReleaseComObject(nodeFeature);

                                                            nodeFeature = updatePointCursor.NextFeature();
                                                        }

                                                        idCompareString = CleanReportedNodes(idCompareString);

                                                        // after removing the commas we should be left with only paranthesis left, meaning a string of length 2
                                                        // if we have more then we have found a missing node, resulting in an incomplete way geometry
                                                        if (idCompareString.Length > 2)
                                                        {
                                                            message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedline_node"), currentWay.id, idCompareString));
                                                            wayIsComplete = false;
                                                        }
                                                    }
                                                }
                                            }
                                            #endregion

                                            if (wayIsComplete == false)
                                            {
                                                // if the way geometry is incomplete due to a missing node let's continue to the next way element
                                                missingWays.Add(currentWay.id);
                                                continue;
                                            }

                                            featureLineBuffer.Shape = wayPolyline;
                                            featureLineBuffer.set_Value(osmLineIDFieldIndex, currentWay.id);
                                        }
                                        else
                                        {
                                            // check if a feature with the same OSMID already exists, because the can only be one
                                            if (checkForExisting == true)
                                            {
                                                if (CheckIfExists(osmPolygonFeatureClass as ITable, currentWay.id))
                                                {
                                                    continue;
                                                }
                                            }

                                            IPolygon wayPolygon = new PolygonClass();
                                            comReleaser.ManageLifetime(wayPointCollection);

                                            wayPolygon.SpatialReference = downloadSpatialReference;

                                            IPointIDAware polygonIDAware = wayPolygon as IPointIDAware;
                                            polygonIDAware.PointIDAware = true;

                                            wayPointCollection = wayPolygon as IPointCollection;

                                            #region generate polygon geometry
                                            if (conserveMemory == false)
                                            {
                                                for (int ndIndex = 0; ndIndex < currentWay.nd.Length; ndIndex++)
                                                {
                                                    string ndID = currentWay.nd[ndIndex].@ref;
                                                    if (osmNodeDictionary.ContainsKey(ndID))
                                                    {
                                                        IPoint newPoint = new PointClass();
                                                        newPoint.X = osmNodeDictionary[ndID].Longitude;
                                                        newPoint.Y = osmNodeDictionary[ndID].Latitude;
                                                        newPoint.SpatialReference = wgs84;

                                                        if (shouldProject)
                                                        {
                                                            newPoint.Project(nativePolygonSpatialReference);
                                                        }

                                                        IPointIDAware idAware = newPoint as IPointIDAware;
                                                        idAware.PointIDAware = true;

                                                        newPoint.ID = osmNodeDictionary[ndID].pointObjectID;

                                                        wayPointCollection.AddPoint(newPoint, ref missingValue, ref missingValue);
                                                    }
                                                    else
                                                    {
                                                        message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedpolygon_node"), currentWay.id, ndID));
                                                        wayIsComplete = false;
                                                        break;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                for (int pointIndex = 0; pointIndex < currentWay.nd.Length; pointIndex++)
                                                {
                                                    wayPointCollection.AddPoint(new PointClass());
                                                }

                                                List<string> idRequests = SplitOSMIDRequests(currentWay, 2);

                                                // build a list of node ids we can use to determine the point index in the line geometry
                                                // as well as a dictionary to determine the position in the list in case of duplicates nodes
                                                Dictionary<string, int> nodePositionDictionary = new Dictionary<string, int>(currentWay.nd.Length);
                                                List<string> nodeIDs = new List<string>(currentWay.nd.Length);

                                                foreach (nd wayNode in currentWay.nd)
                                                {
                                                    nodeIDs.Add(wayNode.@ref);

                                                    if (nodePositionDictionary.ContainsKey(wayNode.@ref) == false)
                                                    {
                                                        nodePositionDictionary.Add(wayNode.@ref, 0);
                                                    }
                                                }

                                                try
                                                {
                                                    osmIDQueryFilter.SubFields = osmPointFeatureClass.ShapeFieldName + "," + osmPointFeatureClass.Fields.get_Field(osmPointIDFieldIndex).Name + "," + osmPointFeatureClass.Fields.get_Field(osmWayRefCountFieldIndex).Name;
                                                }
                                                catch
                                                { }

                                                foreach (string osmIDRequest in idRequests)
                                                {
                                                    string idCompareString = osmIDRequest;

                                                    using (ComReleaser innercomReleaser = new ComReleaser())
                                                    {
                                                        osmIDQueryFilter.WhereClause = sqlPointOSMID + " IN " + osmIDRequest;
                                                        updatePointCursor = osmPointFeatureClass.Update(osmIDQueryFilter, false);
                                                        innercomReleaser.ManageLifetime(updatePointCursor);

                                                        IFeature nodeFeature = updatePointCursor.NextFeature();

                                                        while (nodeFeature != null)
                                                        {
                                                            // determine the index of the point in with respect to the node position
                                                            string nodeOSMIDString = Convert.ToString(nodeFeature.get_Value(osmPointIDFieldIndex));

                                                            idCompareString = idCompareString.Replace(nodeOSMIDString, String.Empty);

                                                            int nodePositionIndex = nodeIDs.IndexOf(nodeOSMIDString, nodePositionDictionary[nodeOSMIDString]);

                                                            // update the new position start search index
                                                            nodePositionDictionary[nodeOSMIDString] = nodePositionIndex + 1;

                                                            wayPointCollection.UpdatePoint(nodePositionIndex, (IPoint)nodeFeature.Shape);

                                                            // increase the reference counter
                                                            if (osmWayRefCountFieldIndex != -1)
                                                            {
                                                                nodeFeature.set_Value(osmWayRefCountFieldIndex, ((int)nodeFeature.get_Value(osmWayRefCountFieldIndex)) + 1);

                                                                updatePointCursor.UpdateFeature(nodeFeature);
                                                            }

                                                            if (nodeFeature != null)
                                                                Marshal.ReleaseComObject(nodeFeature);

                                                            nodeFeature = updatePointCursor.NextFeature();
                                                        }

                                                        idCompareString = CleanReportedNodes(idCompareString);

                                                        if (idCompareString.Length > 2)
                                                        {
                                                            message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedpolygon_node"), currentWay.id, idCompareString));
                                                            wayIsComplete = false;
                                                        }
                                                    }
                                                }
                                            }
                                            #endregion

                                            if (wayIsComplete == false)
                                            {
                                                continue;
                                            }

                                            // remove the last point as OSM considers them to be coincident
                                            wayPointCollection.RemovePoints(wayPointCollection.PointCount - 1, 1);
                                            ((IPolygon)wayPointCollection).Close();

                                            featurePolygonBuffer.Shape = (IPolygon)wayPointCollection;
                                            featurePolygonBuffer.set_Value(osmPolygonIDFieldIndex, currentWay.id);
                                        }

                                        if (wayIsLine)
                                        {
                                            insertTags(osmLineDomainAttributeFieldIndices, osmLineDomainAttributeFieldLength, tagCollectionPolylineFieldIndex, featureLineBuffer, currentWay.tag);
                                        }
                                        else
                                        {
                                            insertTags(osmPolygonDomainAttributeFieldIndices, osmPolygonDomainAttributeFieldLength, tagCollectionPolygonFieldIndex, featurePolygonBuffer, currentWay.tag);
                                        }

                                        // store the administrative attributes
                                        // user, uid, version, changeset, timestamp, visible
                                        if (fastLoad == false)
                                        {
                                            if (!String.IsNullOrEmpty(currentWay.user))
                                            {
                                                if (wayIsLine)
                                                {
                                                    if (osmUserPolylineFieldIndex != -1)
                                                    {
                                                        featureLineBuffer.set_Value(osmUserPolylineFieldIndex, currentWay.user);
                                                    }
                                                }
                                                else
                                                {
                                                    if (osmUserPolygonFieldIndex != -1)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmUserPolygonFieldIndex, currentWay.user);
                                                    }
                                                }
                                            }

                                            if (!String.IsNullOrEmpty(currentWay.uid))
                                            {
                                                if (wayIsLine)
                                                {
                                                    if (osmUIDPolylineFieldIndex != -1)
                                                    {
                                                        featureLineBuffer.set_Value(osmUIDPolylineFieldIndex, Convert.ToInt32(currentWay.uid));
                                                    }
                                                }
                                                else
                                                {
                                                    if (osmUIDPolygonFieldIndex != -1)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmUIDPolygonFieldIndex, Convert.ToInt32(currentWay.uid));
                                                    }
                                                }
                                            }

                                            if (wayIsLine)
                                            {
                                                if (osmVisiblePolylineFieldIndex != -1)
                                                {
                                                    featureLineBuffer.set_Value(osmVisiblePolylineFieldIndex, currentWay.visible.ToString());
                                                }
                                            }
                                            else
                                            {
                                                if (osmVisiblePolygonFieldIndex != -1)
                                                {
                                                    featurePolygonBuffer.set_Value(osmVisiblePolygonFieldIndex, currentWay.visible.ToString());
                                                }
                                            }

                                            if (!String.IsNullOrEmpty(currentWay.version))
                                            {
                                                if (wayIsLine)
                                                {
                                                    if (osmVersionPolylineFieldIndex != -1)
                                                    {
                                                        featureLineBuffer.set_Value(osmVersionPolylineFieldIndex, Convert.ToInt32(currentWay.version));
                                                    }
                                                }
                                                else
                                                {
                                                    if (osmVersionPolygonFieldIndex != -1)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmVersionPolygonFieldIndex, Convert.ToInt32(currentWay.version));
                                                    }
                                                }
                                            }

                                            if (!String.IsNullOrEmpty(currentWay.changeset))
                                            {
                                                if (wayIsLine)
                                                {
                                                    if (osmChangesetPolylineFieldIndex != -1)
                                                    {
                                                        featureLineBuffer.set_Value(osmChangesetPolylineFieldIndex, Convert.ToInt32(currentWay.changeset));
                                                    }
                                                }
                                                else
                                                {
                                                    if (osmChangesetPolygonFieldIndex != -1)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmChangesetPolygonFieldIndex, Convert.ToInt32(currentWay.changeset));
                                                    }
                                                }
                                            }

                                            if (!String.IsNullOrEmpty(currentWay.timestamp))
                                            {
                                                try
                                                {
                                                    if (wayIsLine)
                                                    {
                                                        if (osmTimeStampPolylineFieldIndex != -1)
                                                        {
                                                            featureLineBuffer.set_Value(osmTimeStampPolylineFieldIndex, Convert.ToDateTime(currentWay.timestamp));
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (osmTimeStampPolygonFieldIndex != -1)
                                                        {
                                                            featurePolygonBuffer.set_Value(osmTimeStampPolygonFieldIndex, Convert.ToDateTime(currentWay.timestamp));
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_invalidTimeFormat"), ex.Message));
                                                }
                                            }

                                            if (wayIsLine)
                                            {
                                                if (osmSupportingElementPolylineFieldIndex > -1)
                                                {
                                                    if (currentWay.tag == null)
                                                    {
                                                        featureLineBuffer.set_Value(osmSupportingElementPolylineFieldIndex, "yes");
                                                    }
                                                    else
                                                    {
                                                        featureLineBuffer.set_Value(osmSupportingElementPolylineFieldIndex, "no");
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (osmSupportingElementPolygonFieldIndex > -1)
                                                {
                                                    if (currentWay.tag == null)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmSupportingElementPolygonFieldIndex, "yes");
                                                    }
                                                    else
                                                    {
                                                        featurePolygonBuffer.set_Value(osmSupportingElementPolygonFieldIndex, "no");
                                                    }
                                                }
                                            }
                                        } // fast load

                                        try
                                        {
                                            if (wayIsLine)
                                            {
                                                insertLineCursor.InsertFeature(featureLineBuffer);
                                                lineIndexRebuildRequired = true;
                                            }
                                            else
                                            {
                                                insertPolygonCursor.InsertFeature(featurePolygonBuffer);
                                                polygonIndexRebuildRequired = true;
                                            }

                                            wayCount = wayCount + 1;

                                            if (stepProgressor != null)
                                            {
                                                stepProgressor.Position = wayCount;
                                            }

                                            if ((wayCount % 50000) == 0)
                                            {
                                                message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_waysloaded"), wayCount));
                                            }

                                        }
                                        catch (Exception ex)
                                        {
                                            message.AddWarning(ex.Message);
                                            message.AddWarning(currentwayString);
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        System.Diagnostics.Debug.WriteLine(ex.Message);
                                        System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                                    }
                                    finally
                                    {
                                        if (featureLineBuffer != null)
                                        {
                                            Marshal.ReleaseComObject(featureLineBuffer);

                                            if (featureLineBuffer != null)
                                                featureLineBuffer = null;
                                        }

                                        if (featurePolygonBuffer != null)
                                        {
                                            Marshal.ReleaseComObject(featurePolygonBuffer);

                                            if (featurePolygonBuffer != null)
                                                featurePolygonBuffer = null;
                                        }

                                        currentWay = null;
                                    }

                                    if (TrackCancel.Continue() == false)
                                    {
                                        insertPolygonCursor.Flush();
                                        if (polygonFeatureLoad != null)
                                        {
                                            polygonFeatureLoad.LoadOnlyMode = false;
                                        }

                                        insertLineCursor.Flush();
                                        if (lineFeatureLoad != null)
                                        {
                                            lineFeatureLoad.LoadOnlyMode = false;
                                        }

                                        return missingWays;
                                    }
                                }
                            }
                        }

                        osmFileXmlReader.Close();

                        if (stepProgressor != null)
                        {
                            stepProgressor.Hide();
                        }

                        message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_waysloaded"), wayCount));

                        insertPolygonCursor.Flush();
                        if (polygonFeatureLoad != null)
                        {
                            polygonFeatureLoad.LoadOnlyMode = false;
                        }

                        insertLineCursor.Flush();
                        if (lineFeatureLoad != null)
                        {
                            lineFeatureLoad.LoadOnlyMode = false;
                        }
                    }
                }

                IGeoProcessor2 geoProcessor = new GeoProcessorClass();
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
                bool storedOriginal = geoProcessor.AddOutputsToMap;
                IVariantArray parameterArrary = null;
                IGeoProcessorResult2 gpResults2 = null;

                try
                {
                    geoProcessor.AddOutputsToMap = false;

                    if (lineIndexRebuildRequired)
                    {
                        IIndexes featureClassIndexes = osmLineFeatureClass.Indexes;
                        int indexPosition = -1;
                        featureClassIndexes.FindIndex("osmID_IDX", out indexPosition);

                        string fcLocation = GetLocationString(targetGPValue, osmLineFeatureClass);

                        if (indexPosition == -1)
                        {
                            message.AddMessage(_resourceManager.GetString("GPTools_buildinglineidx"));

                            // Addd index for osmid column
                            parameterArrary = CreateAddIndexParameterArray(fcLocation, "OSMID", "osmID_IDX", "UNIQUE", "");
                            gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2;
                        }

                        if (wayCount > 100)
                        {
                            // in this case we are dealing with a file geodatabase
                            if (lineFeatureLoad == null)
                            {
                                UpdateSpatialGridIndex(TrackCancel, message, geoProcessor, fcLocation);
                            }
                        }
                    }

                    if (polygonIndexRebuildRequired)
                    {
                        IIndexes featureClassIndexes = osmPolygonFeatureClass.Indexes;
                        int indexPosition = -1;
                        featureClassIndexes.FindIndex("osmID_IDX", out indexPosition);

                        string fcLocation = GetLocationString(targetGPValue, osmPolygonFeatureClass);

                        if (indexPosition == -1)
                        {
                            message.AddMessage(_resourceManager.GetString("GPTools_buildingpolygonidx"));

                            IGPValue polygonFeatureClassGPValue = gpUtilities3.MakeGPValueFromObject(osmPolygonFeatureClass);

                            if (polygonFeatureClassGPValue != null)
                            {
                                // Addd index for osmid column
                                parameterArrary = CreateAddIndexParameterArray(fcLocation, "OSMID", "osmID_IDX", "UNIQUE", "");
                                gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2;
                            }
                        }

                        if (wayCount > 100)
                        {
                            if (polygonFeatureLoad == null)
                            {
                                UpdateSpatialGridIndex(TrackCancel, message, geoProcessor, fcLocation);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    message.AddWarning(ex.Message);
                }
                finally
                {
                    geoProcessor.AddOutputsToMap = storedOriginal;

                    Marshal.FinalReleaseComObject(gpUtilities3);
                    Marshal.FinalReleaseComObject(geoProcessor);
                }
            }
            catch (Exception ex)
            {
                message.AddWarning(ex.Message);
            }
            finally
            {
                if (waySerializer != null)
                    waySerializer = null;

                if (osmFileXmlReader != null)
                    osmFileXmlReader = null;

                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
            }

            return missingWays;
        }
Beispiel #33
0
        private IGPParameter CreateParameter(IGPDataType dataType, IGPValue value, esriGPParameterDirection direction, string displayName, string name, esriGPParameterType parameterType)
        {
            // Area field parameter
            IGPParameterEdit3 inputParameter = new GPParameterClass();
            inputParameter.DataType = dataType;
            inputParameter.Value = value;

            // Set field name parameter properties
            inputParameter.Direction = direction;
            inputParameter.DisplayName = displayName;
            inputParameter.Name = name;
            inputParameter.ParameterType = parameterType;

            return (IGPParameter)inputParameter;
        }
        public static IFeatureClass CreateFeatureClass(IGPValue gpFeatureClass, IGPEnvironmentManager environment, IFields fields = null)
        {
            if (gpFeatureClass == null)
                throw new ArgumentException("Argument can not be null", "gpFeatureClass");
            if (environment == null)
                throw new ArgumentException("Argument can not be null", "environment");

            IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)environment;
            if (gpUtilities.Exists(gpFeatureClass))
            {
                if (gpSettings.OverwriteOutput == true)
                    gpUtilities.Delete(gpFeatureClass);
                else
                    throw new Exception("Output feature class already exists: " + gpFeatureClass.GetAsText());
            }

            IDEFeatureClass deFeatureClass = (IDEFeatureClass)gpUtilities.DecodeDETable(gpFeatureClass);
            if (deFeatureClass == null)
                throw new Exception("Data Element decode return null");

            IObjectClassDescription objectClassDescription = (IObjectClassDescription)new FeatureClassDescriptionClass();
            UID clsid = objectClassDescription.InstanceCLSID;
            UID extclsid = objectClassDescription.ClassExtensionCLSID;

            IDataElement dataElement = (IDataElement)deFeatureClass;
            if (dataElement.CatalogPath == null)
                throw new ArgumentException("Catalog path is null", "CatalogPath");
            IFeatureClassName featureClassName = (IFeatureClassName)gpUtilities.CreateFeatureClassName(dataElement.CatalogPath);

            string path = dataElement.GetPath();
            string name = dataElement.Name;

            IDEGeoDataset geoDataElement = (IDEGeoDataset)deFeatureClass;
            ISpatialReference spatialReference = geoDataElement.SpatialReference;

            IDETable deTable = (IDETable)deFeatureClass;
            string shapeFieldName = deFeatureClass.ShapeFieldName;

            Dictionary<string,IField> fieldBuilder = new Dictionary<string,IField>();
            foreach(var input_fields in new IFields[] { deTable.Fields, fields })
            {
                if (input_fields == null) continue;
                for (int i = 0; i < input_fields.FieldCount; i++)
                {
                    IField field = deTable.Fields.get_Field(i);

                    if (fieldBuilder.ContainsKey(field.Name.ToLower()))
                        fieldBuilder[field.Name.ToLower()] = (IField)((IClone)field).Clone();
                    else
                        fieldBuilder.Add(field.Name.ToLower(), (IField)((IClone)field).Clone());

                    if (field.Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        shapeFieldName = field.Name;
                        break;
                    }
                }
            }

            IFields output_fields = new FieldsClass();
            IFieldsEdit fields_edit = (IFieldsEdit)output_fields;
            foreach(IField field in fieldBuilder.Values)
            {
                fields_edit.AddField(field);
                if(field.Type == esriFieldType.esriFieldTypeGeometry)
                {
                    IGeometryDefEdit defEdit = (IGeometryDefEdit)field.GeometryDef;
                    defEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon;
                }
            }

            string configKeyword = ((IGPString)environment.FindEnvironment(CONFIG_KEYWORD_PROP_NAME).Value).Value;
            //if (String.IsNullOrWhiteSpace(configKeyword)) configKeyword = "DEFAULTS";

            IFeatureClass ret = null;
            if(featureClassName.FeatureDatasetName != null)
            {
                IFeatureDataset featureDataset = (IFeatureDataset)((IName)featureClassName.FeatureDatasetName).Open();
                try
                {
                    ret = featureDataset.CreateFeatureClass(name, output_fields, clsid, extclsid, esriFeatureType.esriFTSimple, shapeFieldName, configKeyword);
                }
                finally
                {
                    Marshal.ReleaseComObject(featureDataset);
                }
            }
            else
            {
                IWorkspace workspace = (IWorkspace)((IName)((IDatasetName)featureClassName).WorkspaceName).Open();
                try
                {
                    IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace;
                    ret = featureWorkspace.CreateFeatureClass(name, output_fields, clsid, extclsid, esriFeatureType.esriFTSimple, shapeFieldName, configKeyword);
                }
                finally
                {
                    Marshal.ReleaseComObject(workspace);
                }
            }
            return ret;
        }
 private void DisableParameter(IGPParameterEdit gpParamEdit, IGPValue emptyValue)
 {
     gpParamEdit.Value = emptyValue;
     gpParamEdit.Enabled = false;
     return;
 }
        internal void loadOSMNodes(string osmFileLocation, ref ITrackCancel TrackCancel, ref IGPMessages message,IGPValue targetGPValue,  IFeatureClass osmPointFeatureClass, bool conserveMemory, bool fastLoad, int nodeCapacity, ref Dictionary<string, simplePointRef> osmNodeDictionary, IFeatureWorkspace featureWorkspace, ISpatialReference downloadSpatialReference, OSMDomains availableDomains, bool checkForExisting)
        {
            XmlReader osmFileXmlReader = null;
            XmlSerializer nodeSerializer = null;

            try
            {
                osmFileXmlReader = System.Xml.XmlReader.Create(osmFileLocation);
                nodeSerializer = new XmlSerializer(typeof(node));

                ISpatialReferenceFactory spatialRef = new SpatialReferenceEnvironmentClass();
                ISpatialReference wgs84 = spatialRef.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);

                bool shouldProject = !((IClone)wgs84).IsEqual((IClone)downloadSpatialReference);

                int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmPointDomainAttributeFieldLength = new Dictionary<string, int>();

                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPointFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmPointDomainAttributeFieldLength.Add(domains.name, osmPointFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }

                int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags");
                int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser");
                int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid");
                int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible");
                int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion");
                int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset");
                int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf");
                int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement");
                int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount");

                // set up the progress indicator
                IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

                if (stepProgressor != null)
                {
                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = nodeCapacity;
                    stepProgressor.StepValue = (1);
                    stepProgressor.Message = _resourceManager.GetString("GPTools_OSMGPFileReader_loadingNodes");
                    stepProgressor.Position = 0;
                    stepProgressor.Show();
                }

                // flag to determine if a computation of indices is required
                bool indexBuildRequired = false;
                if (nodeCapacity > 0)
                    indexBuildRequired = true;

                int pointCount = 0;

                // let's insert all the points first
                if (osmPointFeatureClass != null)
                {
                    IFeatureBuffer pointFeature = null;
                    IFeatureClassLoad pointFeatureLoad = null;

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        using (SchemaLockManager schemaLockManager = new SchemaLockManager(osmPointFeatureClass as ITable))
                        {

                            if (((IWorkspace)featureWorkspace).WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                            {
                                pointFeatureLoad = osmPointFeatureClass as IFeatureClassLoad;
                            }

                            IFeatureCursor pointInsertCursor = osmPointFeatureClass.Insert(true);
                            comReleaser.ManageLifetime(pointInsertCursor);

                            pointFeature = osmPointFeatureClass.CreateFeatureBuffer();
                            comReleaser.ManageLifetime(pointFeature);

                            if (pointFeatureLoad != null)
                            {
                                pointFeatureLoad.LoadOnlyMode = true;
                            }

                            osmFileXmlReader.MoveToContent();

                            while (osmFileXmlReader.Read())
                            {
                                if (osmFileXmlReader.IsStartElement())
                                {
                                    if (osmFileXmlReader.Name == "node")
                                    {
                                        string currentNodeString = osmFileXmlReader.ReadOuterXml();
                                        // turn the xml node representation into a node class representation
                                        ESRI.ArcGIS.OSM.OSMClassExtension.node currentNode = null;
                                        using (StringReader nodeReader = new System.IO.StringReader(currentNodeString))
                                        {
                                            currentNode = nodeSerializer.Deserialize(nodeReader) as ESRI.ArcGIS.OSM.OSMClassExtension.node;
                                        }

                                        // check if a feature with the same OSMID already exists, because the can only be one
                                        if (checkForExisting == true)
                                        {
                                            if (CheckIfExists(osmPointFeatureClass as ITable, currentNode.id))
                                            {
                                                continue;
                                            }
                                        }

                                        try
                                        {
                                            //if (pointFeature == null)
                                            //{
                                            pointFeature = osmPointFeatureClass.CreateFeatureBuffer();
                                            comReleaser.ManageLifetime(pointFeature);
                                            //}

                                            IPoint pointGeometry = new PointClass();
                                            comReleaser.ManageLifetime(pointGeometry);

                                            pointGeometry.X = Convert.ToDouble(currentNode.lon, new CultureInfo("en-US"));
                                            pointGeometry.Y = Convert.ToDouble(currentNode.lat, new CultureInfo("en-US"));
                                            pointGeometry.SpatialReference = wgs84;

                                            if (shouldProject)
                                            {
                                                pointGeometry.Project(downloadSpatialReference);
                                            }

                                            pointFeature.Shape = pointGeometry;

                                            pointFeature.set_Value(osmPointIDFieldIndex, currentNode.id);

                                            string isSupportingNode = "";
                                            if (_osmUtility.DoesHaveKeys(currentNode))
                                            {
                                                // if case it has tags I assume that the node presents an entity of it own,
                                                // hence it is not a supporting node in the context of supporting a way or relation
                                                isSupportingNode = "no";

                                                if (conserveMemory == false)
                                                {
                                                    osmNodeDictionary[currentNode.id] = new simplePointRef(Convert.ToSingle(currentNode.lon, new CultureInfo("en-US")), Convert.ToSingle(currentNode.lat, new CultureInfo("en-US")), 0, 0);
                                                }
                                            }
                                            else
                                            {
                                                // node has no tags -- at this point I assume that the absence of tags indicates that it is a supporting node
                                                // for a way or a relation
                                                isSupportingNode = "yes";

                                                if (conserveMemory == false)
                                                {
                                                    osmNodeDictionary[currentNode.id] = new simplePointRef(Convert.ToSingle(currentNode.lon, new CultureInfo("en-US")), Convert.ToSingle(currentNode.lat, new CultureInfo("en-US")), 0, 0);
                                                }
                                            }

                                            insertTags(osmPointDomainAttributeFieldIndices, osmPointDomainAttributeFieldLength, tagCollectionPointFieldIndex, pointFeature, currentNode.tag);

                                            if (fastLoad == false)
                                            {
                                                if (osmSupportingElementPointFieldIndex > -1)
                                                {
                                                    pointFeature.set_Value(osmSupportingElementPointFieldIndex, isSupportingNode);
                                                }

                                                if (osmWayRefCountFieldIndex > -1)
                                                {
                                                    pointFeature.set_Value(osmWayRefCountFieldIndex, 0);
                                                }

                                                // store the administrative attributes
                                                // user, uid, version, changeset, timestamp, visible
                                                if (osmUserPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.user))
                                                    {
                                                        pointFeature.set_Value(osmUserPointFieldIndex, currentNode.user);
                                                    }
                                                }

                                                if (osmUIDPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.uid))
                                                    {
                                                        pointFeature.set_Value(osmUIDPointFieldIndex, Convert.ToInt32(currentNode.uid));
                                                    }
                                                }

                                                if (osmVisiblePointFieldIndex > -1)
                                                {
                                                    pointFeature.set_Value(osmVisiblePointFieldIndex, currentNode.visible.ToString());
                                                }

                                                if (osmVersionPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.version))
                                                    {
                                                        pointFeature.set_Value(osmVersionPointFieldIndex, Convert.ToInt32(currentNode.version));
                                                    }
                                                }

                                                if (osmChangesetPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.changeset))
                                                    {
                                                        pointFeature.set_Value(osmChangesetPointFieldIndex, Convert.ToInt32(currentNode.changeset));
                                                    }
                                                }

                                                if (osmTimeStampPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.timestamp))
                                                    {
                                                        try
                                                        {
                                                            pointFeature.set_Value(osmTimeStampPointFieldIndex, Convert.ToDateTime(currentNode.timestamp));
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_invalidTimeFormat"), ex.Message));
                                                        }
                                                    }
                                                }
                                            }
                                            try
                                            {
                                                pointInsertCursor.InsertFeature(pointFeature);
                                                pointCount = pointCount + 1;

                                                if (stepProgressor != null)
                                                {
                                                    stepProgressor.Position = pointCount;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                System.Diagnostics.Debug.WriteLine(ex.Message);
                                                message.AddWarning(ex.Message);
                                            }

                                            if (TrackCancel.Continue() == false)
                                            {
                                                return;
                                            }

                                            if ((pointCount % 50000) == 0)
                                            {
                                                message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_pointsloaded"), pointCount));
                                                pointInsertCursor.Flush();
                                                System.GC.Collect();
                                            }

                                            if (pointGeometry != null)
                                                Marshal.ReleaseComObject(pointGeometry);
                                        }
                                        catch (Exception ex)
                                        {
                                            System.Diagnostics.Debug.WriteLine(ex.Message);
                                            message.AddWarning(ex.Message);
                                        }
                                        finally
                                        {
                                            if (pointFeature != null)
                                            {
                                                Marshal.ReleaseComObject(pointFeature);

                                                if (pointFeature != null)
                                                    pointFeature = null;

                                            }
                                        }

                                        currentNode = null;
                                    }
                                }
                            }

                            if (stepProgressor != null)
                            {
                                stepProgressor.Hide();
                            }

                            pointInsertCursor.Flush();
                            osmFileXmlReader.Close();

                            message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_pointsloaded"), pointCount));
                            message.AddMessage(_resourceManager.GetString("GPTools_buildingpointidx"));

                            if (pointFeatureLoad != null)
                            {
                                pointFeatureLoad.LoadOnlyMode = false;
                            }
                        }
                    }

                    if (TrackCancel.Continue() == false)
                    {
                        return;
                    }

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        IFeatureCursor updatePoints = osmPointFeatureClass.Update(null, false);
                        comReleaser.ManageLifetime(updatePoints);

                        IFeature feature2Update = updatePoints.NextFeature();

                        while (feature2Update != null)
                        {
                            IPoint pointGeometry = feature2Update.Shape as IPoint;
                            pointGeometry.ID = feature2Update.OID;
                            feature2Update.Shape = pointGeometry;

                            if (conserveMemory == false)
                            {
                                string osmid = Convert.ToString(feature2Update.get_Value(osmPointIDFieldIndex));
                                if (osmNodeDictionary.ContainsKey(osmid))
                                    osmNodeDictionary[osmid].pointObjectID = feature2Update.OID;
                            }

                            updatePoints.UpdateFeature(feature2Update);

                            if (TrackCancel.Continue() == false)
                            {
                                return;
                            }

                            if (feature2Update != null)
                                Marshal.ReleaseComObject(feature2Update);

                            if (pointGeometry != null)
                                Marshal.ReleaseComObject(pointGeometry);

                            feature2Update = updatePoints.NextFeature();
                        }
                    }

                    if (indexBuildRequired)
                    {

                        IGeoProcessor2 geoProcessor = new GeoProcessorClass();
                        bool storedOriginal = geoProcessor.AddOutputsToMap;

                        try
                        {
                            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

                            IGPValue pointFeatureClass = gpUtilities3.MakeGPValueFromObject(osmPointFeatureClass);

                            string fcLocation = GetLocationString(targetGPValue, osmPointFeatureClass);

                            IIndexes featureClassIndexes = osmPointFeatureClass.Indexes;
                            int indexPosition = -1;
                            featureClassIndexes.FindIndex("osmID_IDX", out indexPosition);

                            if (indexPosition == -1)
                            {
                                {
                                    geoProcessor.AddOutputsToMap = false;

                                    IVariantArray parameterArrary = CreateAddIndexParameterArray(fcLocation, "OSMID", "osmID_IDX", "UNIQUE", "");
                                    IGeoProcessorResult2 gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2;
                                }
                            }
                            if (pointCount > 500)
                            {
                                if (pointFeatureLoad == null)
                                {
                                    UpdateSpatialGridIndex(TrackCancel, message, geoProcessor, fcLocation);
                                }
                            }
                        }
                        catch (COMException comEx)
                        {
                            message.AddWarning(comEx.Message);
                        }
                        catch (Exception ex)
                        {
                            message.AddWarning(ex.Message);
                        }
                        finally
                        {
                            geoProcessor.AddOutputsToMap = storedOriginal;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                message.AddError(120100, String.Format(_resourceManager.GetString("GPTools_Utility_NodeLoadError"), ex.Message));
            }
            finally
            {
                if (osmFileXmlReader != null)
                    osmFileXmlReader = null;

                if (nodeSerializer != null)
                    nodeSerializer = null;
            }
        }
        internal List<string> loadOSMRelations(string osmFileLocation, ref ITrackCancel TrackCancel, ref IGPMessages message, IGPValue targetGPValue, IFeatureClass osmPointFeatureClass, IFeatureClass osmLineFeatureClass, IFeatureClass osmPolygonFeatureClass, int relationCapacity, ITable relationTable, OSMDomains availableDomains, bool fastLoad, bool checkForExisting)
        {
            List<string> missingRelations = null;
            XmlReader osmFileXmlReader = null;
            XmlSerializer relationSerializer = null;

            try
            {

                missingRelations = new List<string>();

                if (osmLineFeatureClass == null)
                {
                    throw new ArgumentNullException("osmLineFeatureClass");
                }

                if (osmPolygonFeatureClass == null)
                {
                    throw new ArgumentNullException("osmPolygonFeatureClass");
                }

                if (relationTable == null)
                {
                    throw new ArgumentNullException("relationTable");
                }

                int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPointFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                    }
                }
                int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags");
                int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser");
                int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid");
                int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible");
                int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion");
                int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset");
                int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf");
                int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement");
                int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount");

                int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmLineDomainAttributeFieldLength = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmLineFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmLineDomainAttributeFieldLength.Add(domains.name, osmLineFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }
                int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags");
                int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser");
                int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid");
                int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible");
                int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion");
                int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf");
                int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement");

                int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmPolygonDomainAttributeFieldLength = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmPolygonDomainAttributeFieldLength.Add(domains.name, osmPolygonFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }
                int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags");
                int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser");
                int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid");
                int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible");
                int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion");
                int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf");
                int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement");

                int osmRelationIDFieldIndex = relationTable.FindField("OSMID");
                int tagCollectionRelationFieldIndex = relationTable.FindField("osmTags");
                int osmUserRelationFieldIndex = relationTable.FindField("osmuser");
                int osmUIDRelationFieldIndex = relationTable.FindField("osmuid");
                int osmVisibleRelationFieldIndex = relationTable.FindField("osmvisible");
                int osmVersionRelationFieldIndex = relationTable.FindField("osmversion");
                int osmChangesetRelationFieldIndex = relationTable.FindField("osmchangeset");
                int osmTimeStampRelationFieldIndex = relationTable.FindField("osmtimestamp");
                int osmMemberOfRelationFieldIndex = relationTable.FindField("osmMemberOf");
                int osmMembersRelationFieldIndex = relationTable.FindField("osmMembers");
                int osmSupportingElementRelationFieldIndex = relationTable.FindField("osmSupportingElement");

                // list for reference count and relation list for lines/polygons/relations
                // set up the progress indicator
                IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

                if (stepProgressor != null)
                {
                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = relationCapacity;
                    stepProgressor.Position = 0;
                    stepProgressor.Message = _resourceManager.GetString("GPTools_OSMGPFileReader_loadingRelations");
                    stepProgressor.StepValue = 1;
                    stepProgressor.Show();
                }

                bool relationIndexRebuildRequired = false;

                if (relationTable != null)
                {
                    osmFileXmlReader = System.Xml.XmlReader.Create(osmFileLocation);
                    relationSerializer = new XmlSerializer(typeof(relation));

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        using (SchemaLockManager linelock = new SchemaLockManager(osmLineFeatureClass as ITable), polygonLock = new SchemaLockManager(osmPolygonFeatureClass as ITable), relationLock = new SchemaLockManager(relationTable))
                        {
                            ICursor rowCursor = relationTable.Insert(true);
                            comReleaser.ManageLifetime(rowCursor);

                            IRowBuffer rowBuffer = relationTable.CreateRowBuffer();
                            comReleaser.ManageLifetime(rowBuffer);

                            IFeatureCursor lineFeatureInsertCursor = osmLineFeatureClass.Insert(true);
                            comReleaser.ManageLifetime(lineFeatureInsertCursor);

                            IFeatureBuffer lineFeatureBuffer = osmLineFeatureClass.CreateFeatureBuffer();
                            comReleaser.ManageLifetime(lineFeatureBuffer);

                            IFeatureCursor polygonFeatureInsertCursor = osmPolygonFeatureClass.Insert(true);
                            comReleaser.ManageLifetime(polygonFeatureInsertCursor);

                            IFeatureBuffer polygonFeatureBuffer = osmPolygonFeatureClass.CreateFeatureBuffer();
                            comReleaser.ManageLifetime(polygonFeatureBuffer);

                            int relationCount = 1;
                            int relationDebugCount = 1;

                            string lineSQLIdentifier = osmLineFeatureClass.SqlIdentifier("OSMID");
                            string polygonSQLIdentifier = osmPolygonFeatureClass.SqlIdentifier("OSMID");

                            message.AddMessage(_resourceManager.GetString("GPTools_OSMGPFileReader_resolvegeometries"));

                            osmFileXmlReader.MoveToContent();
                            while (osmFileXmlReader.Read())
                            {
                                if (osmFileXmlReader.IsStartElement())
                                {
                                    if (osmFileXmlReader.Name == "relation")
                                    {
                                        relation currentRelation = null;
                                        try
                                        {
                                            // read the full relation node
                                            string currentrelationString = osmFileXmlReader.ReadOuterXml();

                                            using (StringReader relationReader = new System.IO.StringReader(currentrelationString))
                                            {
                                                // de-serialize the xml into to the class instance
                                                currentRelation = relationSerializer.Deserialize(relationReader) as relation;
                                            }

                                            if (currentRelation == null)
                                                continue;

                                            relationDebugCount = relationDebugCount + 1;
                                            esriGeometryType detectedGeometryType = determineRelationGeometryType(osmLineFeatureClass, osmPolygonFeatureClass, relationTable, currentRelation);

                                            if (checkForExisting)
                                            {
                                                switch (detectedGeometryType)
                                                {
                                                    case esriGeometryType.esriGeometryAny:
                                                        if (CheckIfExists(relationTable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryBag:
                                                        if (CheckIfExists(relationTable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryBezier3Curve:
                                                        break;
                                                    case esriGeometryType.esriGeometryCircularArc:
                                                        break;
                                                    case esriGeometryType.esriGeometryEllipticArc:
                                                        break;
                                                    case esriGeometryType.esriGeometryEnvelope:
                                                        break;
                                                    case esriGeometryType.esriGeometryLine:
                                                        if (CheckIfExists(osmLineFeatureClass as ITable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryMultiPatch:
                                                        break;
                                                    case esriGeometryType.esriGeometryMultipoint:
                                                        break;
                                                    case esriGeometryType.esriGeometryNull:
                                                        if (CheckIfExists(relationTable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryPath:
                                                        break;
                                                    case esriGeometryType.esriGeometryPoint:
                                                        break;
                                                    case esriGeometryType.esriGeometryPolygon:
                                                        if (CheckIfExists(osmPolygonFeatureClass as ITable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryPolyline:
                                                        if (CheckIfExists(osmLineFeatureClass as ITable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryRay:
                                                        break;
                                                    case esriGeometryType.esriGeometryRing:
                                                        break;
                                                    case esriGeometryType.esriGeometrySphere:
                                                        break;
                                                    case esriGeometryType.esriGeometryTriangleFan:
                                                        break;
                                                    case esriGeometryType.esriGeometryTriangleStrip:
                                                        break;
                                                    case esriGeometryType.esriGeometryTriangles:
                                                        break;
                                                    default:
                                                        break;
                                                }
                                            }

                                            List<tag> relationTagList = new List<tag>();
                                            List<member> relationMemberList = new List<member>();
                                            Dictionary<string, string> wayList = new Dictionary<string, string>();

                                            // sanity check that the overall relation notation contains at least something
                                            if (currentRelation.Items == null)
                                                continue;

                                            List<OSMNodeFeature> osmPointList = null;
                                            List<OSMLineFeature> osmLineList = null;
                                            List<OSMPolygonFeature> osmPolygonList = null;
                                            List<OSMRelation> osmRelationList = null;

                                            rowBuffer = relationTable.CreateRowBuffer();
                                            comReleaser.ManageLifetime(rowBuffer);

                                            lineFeatureBuffer = osmLineFeatureClass.CreateFeatureBuffer();
                                            comReleaser.ManageLifetime(lineFeatureBuffer);

                                            polygonFeatureBuffer = osmPolygonFeatureClass.CreateFeatureBuffer();
                                            comReleaser.ManageLifetime(polygonFeatureBuffer);

                                            foreach (var item in currentRelation.Items)
                                            {
                                                if (item is member)
                                                {
                                                    member memberItem = item as member;
                                                    relationMemberList.Add(memberItem);

                                                    switch (memberItem.type)
                                                    {
                                                        case memberType.way:

                                                            if (!wayList.ContainsKey(memberItem.@ref))
                                                                wayList.Add(memberItem.@ref, memberItem.role);

                                                            if (IsThisWayALine(memberItem.@ref, osmLineFeatureClass, lineSQLIdentifier, osmPolygonFeatureClass, polygonSQLIdentifier))
                                                            {
                                                                if (osmLineList == null)
                                                                {
                                                                    osmLineList = new List<OSMLineFeature>();
                                                                }

                                                                OSMLineFeature lineFeature = new OSMLineFeature();
                                                                lineFeature.relationList = new List<string>();
                                                                lineFeature.lineID = memberItem.@ref;

                                                                if (detectedGeometryType == esriGeometryType.esriGeometryPolygon)
                                                                {
                                                                    lineFeature.relationList.Add(currentRelation.id + "_ply");
                                                                }
                                                                else if (detectedGeometryType == esriGeometryType.esriGeometryPolyline)
                                                                {
                                                                    lineFeature.relationList.Add(currentRelation.id + "_ln");
                                                                }
                                                                else
                                                                {
                                                                    lineFeature.relationList.Add(currentRelation.id + "_rel");
                                                                }

                                                                osmLineList.Add(lineFeature);
                                                            }
                                                            else
                                                            {
                                                                if (osmPolygonList == null)
                                                                {
                                                                    osmPolygonList = new List<OSMPolygonFeature>();
                                                                }

                                                                OSMPolygonFeature polygonFeature = new OSMPolygonFeature();
                                                                polygonFeature.relationList = new List<string>();
                                                                polygonFeature.polygonID = memberItem.@ref;

                                                                if (detectedGeometryType == esriGeometryType.esriGeometryPolygon)
                                                                {
                                                                    polygonFeature.relationList.Add(currentRelation.id + "_ply");
                                                                }
                                                                else if (detectedGeometryType == esriGeometryType.esriGeometryPolyline)
                                                                {
                                                                    polygonFeature.relationList.Add(currentRelation.id + "_ln");
                                                                }
                                                                else
                                                                {
                                                                    polygonFeature.relationList.Add(currentRelation.id + "_rel");
                                                                }

                                                                osmPolygonList.Add(polygonFeature);
                                                            }

                                                            break;
                                                        case memberType.node:

                                                            if (osmPointList == null)
                                                            {
                                                                osmPointList = new List<OSMNodeFeature>();
                                                            }

                                                            OSMNodeFeature nodeFeature = new OSMNodeFeature();
                                                            nodeFeature.relationList = new List<string>();
                                                            nodeFeature.nodeID = memberItem.@ref;

                                                            nodeFeature.relationList.Add(currentRelation.id + "_rel");

                                                            osmPointList.Add(nodeFeature);

                                                            break;
                                                        case memberType.relation:

                                                            if (osmRelationList == null)
                                                            {
                                                                osmRelationList = new List<OSMRelation>();
                                                            }

                                                            OSMRelation relation = new OSMRelation();
                                                            relation.relationList = new List<string>();
                                                            relation.relationID = memberItem.@ref;
                                                            relation.relationList.Add(currentRelation.id + "_rel");

                                                            break;
                                                        default:
                                                            break;
                                                    }

                                                }
                                                else if (item is tag)
                                                {
                                                    relationTagList.Add((tag)item);
                                                }
                                            }

                                            // if there is a defined geometry type use it to generate a multipart geometry
                                            if (detectedGeometryType == esriGeometryType.esriGeometryPolygon)
                                            {
                                                #region create multipart polygon geometry
                                                //IFeature mpFeature = osmPolygonFeatureClass.CreateFeature();

                                                IPolygon relationMPPolygon = new PolygonClass();
                                                relationMPPolygon.SpatialReference = ((IGeoDataset)osmPolygonFeatureClass).SpatialReference;

                                                ISegmentCollection relationPolygonGeometryCollection = relationMPPolygon as ISegmentCollection;

                                                IQueryFilter osmIDQueryFilter = new QueryFilterClass();
                                                string sqlPolyOSMID = osmPolygonFeatureClass.SqlIdentifier("OSMID");
                                                object missing = Type.Missing;
                                                bool relationComplete = true;

                                                // loop through the list of referenced ways that are listed in a relation
                                                // for each of the items we need to make a decision if they have merit to qualify as stand-alone features
                                                // due to the presence of meaningful attributes (tags)
                                                foreach (KeyValuePair<string, string> wayKey in wayList)
                                                {
                                                    if (relationComplete == false)
                                                        break;

                                                    if (TrackCancel.Continue() == false)
                                                    {
                                                        return missingRelations;
                                                    }

                                                    osmIDQueryFilter.WhereClause = sqlPolyOSMID + " = '" + wayKey.Key + "'";

                                                    System.Diagnostics.Debug.WriteLine("Relation (Polygon) #: " + relationDebugCount + " :___: " + currentRelation.id + " :___: " + wayKey.Key);

                                                    using (ComReleaser relationComReleaser = new ComReleaser())
                                                    {
                                                        IFeatureCursor featureCursor = osmPolygonFeatureClass.Search(osmIDQueryFilter, false);
                                                        relationComReleaser.ManageLifetime(featureCursor);

                                                        IFeature partFeature = featureCursor.NextFeature();

                                                        // set the appropriate field attribute to become invisible as a standalone features
                                                        if (partFeature != null)
                                                        {
                                                            IGeometryCollection ringCollection = partFeature.Shape as IGeometryCollection;

                                                            // test for available content in the geometry collection
                                                            if (ringCollection.GeometryCount > 0)
                                                            {
                                                                // test if we dealing with a valid geometry
                                                                if (ringCollection.get_Geometry(0).IsEmpty == false)
                                                                {
                                                                    // add it to the new geometry and mark the added geometry as a supporting element
                                                                    relationPolygonGeometryCollection.AddSegmentCollection((ISegmentCollection)ringCollection.get_Geometry(0));

                                                                    if (osmSupportingElementPolygonFieldIndex > -1)
                                                                    {
                                                                        // if the member of a relation has the role of "inner" and it has tags, then let's keep it
                                                                        // as a standalone feature as well
                                                                        // the geometry is then a hole in the relation but due to the tags it also has merits to be
                                                                        // considered a stand-alone feature
                                                                        if (wayKey.Value.ToLower().Equals("inner"))
                                                                        {
                                                                            if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolygonFieldIndex, null))
                                                                            {
                                                                                partFeature.set_Value(osmSupportingElementPolygonFieldIndex, "yes");
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            // relation member without an explicit role or the role of "outer" are turned into
                                                                            // supporting features if they don't have relevant attribute
                                                                            if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null))
                                                                            {
                                                                                partFeature.set_Value(osmSupportingElementPolygonFieldIndex, "yes");
                                                                            }
                                                                        }
                                                                    }

                                                                    partFeature.Store();
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            // it still can be a line geometry that will be pieced together into a polygon
                                                            IFeatureCursor lineFeatureCursor = osmLineFeatureClass.Search(osmIDQueryFilter, false);
                                                            relationComReleaser.ManageLifetime(lineFeatureCursor);

                                                            partFeature = lineFeatureCursor.NextFeature();

                                                            if (partFeature != null)
                                                            {
                                                                IGeometryCollection ringCollection = partFeature.Shape as IGeometryCollection;

                                                                // test for available content in the geometry collection
                                                                if (ringCollection.GeometryCount > 0)
                                                                {
                                                                    // test if we dealing with a valid geometry
                                                                    if (ringCollection.get_Geometry(0).IsEmpty == false)
                                                                    {
                                                                        // add it to the new geometry and mark the added geometry as a supporting element
                                                                        relationPolygonGeometryCollection.AddSegmentCollection((ISegmentCollection)ringCollection.get_Geometry(0));

                                                                        if (osmSupportingElementPolylineFieldIndex > -1)
                                                                        {
                                                                            // if the member of a relation has the role of "inner" and it has tags, then let's keep it
                                                                            // as a standalone feature as well
                                                                            // the geometry is then a hole in the relation but due to the tags it also has merits to be
                                                                            // considered a stand-alone feature
                                                                            if (wayKey.Value.ToLower().Equals("inner"))
                                                                            {
                                                                                if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null))
                                                                                {
                                                                                    partFeature.set_Value(osmSupportingElementPolylineFieldIndex, "yes");
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                // relation member without an explicit role or the role of "outer" are turned into
                                                                                // supporting features if they don't have relevant attribute
                                                                                if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null))
                                                                                {
                                                                                    partFeature.set_Value(osmSupportingElementPolylineFieldIndex, "yes");
                                                                                }
                                                                            }
                                                                        }

                                                                        partFeature.Store();
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                relationComplete = false;
                                                                continue;
                                                            }
                                                        }
                                                    }
                                                }

                                                // mark the relation as incomplete
                                                if (relationComplete == false)
                                                {
                                                    missingRelations.Add(currentRelation.id);
                                                    continue;
                                                }

                                                // transform the added collections for geometries into a topological correct geometry representation
                                                ((IPolygon4)relationMPPolygon).SimplifyEx(true, false, true);

                                                polygonFeatureBuffer.Shape = relationMPPolygon;

                                                if (_osmUtility.DoesHaveKeys(currentRelation))
                                                {
                                                }
                                                else
                                                {
                                                    relationTagList = MergeTagsFromOuterPolygonToRelation(currentRelation, osmPolygonFeatureClass);
                                                }

                                                insertTags(osmPolygonDomainAttributeFieldIndices, osmPolygonDomainAttributeFieldLength, tagCollectionPolygonFieldIndex, polygonFeatureBuffer, relationTagList.ToArray());

                                                if (fastLoad == false)
                                                {
                                                    if (osmMembersPolygonFieldIndex > -1)
                                                    {
                                                        _osmUtility.insertMembers(osmMembersPolygonFieldIndex, (IFeature)polygonFeatureBuffer, relationMemberList.ToArray());
                                                    }

                                                    // store the administrative attributes
                                                    // user, uid, version, changeset, timestamp, visible
                                                    if (osmUserPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.user))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmUserPolygonFieldIndex, currentRelation.user);
                                                        }
                                                    }

                                                    if (osmUIDPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.uid))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmUIDPolygonFieldIndex, Convert.ToInt32(currentRelation.uid));
                                                        }
                                                    }

                                                    if (osmVisiblePolygonFieldIndex != -1)
                                                    {
                                                        if (String.IsNullOrEmpty(currentRelation.visible) == false)
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmVisiblePolygonFieldIndex, currentRelation.visible.ToString());
                                                        }
                                                        else
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmVisiblePolygonFieldIndex, "unknown");
                                                        }
                                                    }

                                                    if (osmVersionPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.version))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmVersionPolygonFieldIndex, Convert.ToInt32(currentRelation.version));
                                                        }
                                                    }

                                                    if (osmChangesetPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.changeset))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmChangesetPolygonFieldIndex, Convert.ToInt32(currentRelation.changeset));
                                                        }
                                                    }

                                                    if (osmTimeStampPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.timestamp))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmTimeStampPolygonFieldIndex, Convert.ToDateTime(currentRelation.timestamp));
                                                        }
                                                    }

                                                    if (osmPolygonIDFieldIndex != -1)
                                                    {
                                                        polygonFeatureBuffer.set_Value(osmPolygonIDFieldIndex, currentRelation.id);
                                                    }

                                                    if (osmSupportingElementPolygonFieldIndex > -1)
                                                    {
                                                        polygonFeatureBuffer.set_Value(osmSupportingElementPolygonFieldIndex, "no");
                                                    }
                                                }

                                                try
                                                {
                                                    //mpFeature.Store();
                                                    polygonFeatureInsertCursor.InsertFeature(polygonFeatureBuffer);
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddWarning(ex.Message);
                                                }
                                                #endregion
                                            }
                                            else if (detectedGeometryType == esriGeometryType.esriGeometryPolyline)
                                            {
                                                #region create multipart polyline geometry
                                                //IFeature mpFeature = osmLineFeatureClass.CreateFeature();

                                                IPolyline relationMPPolyline = new PolylineClass();
                                                relationMPPolyline.SpatialReference = ((IGeoDataset)osmLineFeatureClass).SpatialReference;

                                                IGeometryCollection relationPolylineGeometryCollection = relationMPPolyline as IGeometryCollection;

                                                IQueryFilter osmIDQueryFilter = new QueryFilterClass();
                                                object missing = Type.Missing;

                                                // loop through the
                                                foreach (KeyValuePair<string, string> wayKey in wayList)
                                                {
                                                    if (TrackCancel.Continue() == false)
                                                    {
                                                        return missingRelations;
                                                    }

                                                    osmIDQueryFilter.WhereClause = osmLineFeatureClass.WhereClauseByExtensionVersion(wayKey.Key, "OSMID", 2);

                                                    System.Diagnostics.Debug.WriteLine("Relation (Polyline) #: " + relationDebugCount + " :___: " + currentRelation.id + " :___: " + wayKey);

                                                    using (ComReleaser relationComReleaser = new ComReleaser())
                                                    {
                                                        IFeatureCursor featureCursor = osmLineFeatureClass.Search(osmIDQueryFilter, false);
                                                        relationComReleaser.ManageLifetime(featureCursor);

                                                        IFeature partFeature = featureCursor.NextFeature();

                                                        // set the appropriate field attribute to become invisible as a standalone features
                                                        if (partFeature != null)
                                                        {
                                                            if (partFeature.Shape.IsEmpty == false)
                                                            {
                                                                IGeometryCollection pathCollection = partFeature.Shape as IGeometryCollection;
                                                                relationPolylineGeometryCollection.AddGeometry(pathCollection.get_Geometry(0), ref missing, ref missing);

                                                                if (osmSupportingElementPolylineFieldIndex > -1)
                                                                {
                                                                    if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null))
                                                                    {
                                                                        partFeature.set_Value(osmSupportingElementPolylineFieldIndex, "yes");
                                                                    }
                                                                }

                                                                partFeature.Store();
                                                            }
                                                        }
                                                    }
                                                }

                                                lineFeatureBuffer.Shape = relationMPPolyline;

                                                insertTags(osmLineDomainAttributeFieldIndices, osmLineDomainAttributeFieldLength, tagCollectionPolylineFieldIndex, lineFeatureBuffer, relationTagList.ToArray());

                                                if (fastLoad == false)
                                                {
                                                    if (osmMembersPolylineFieldIndex > -1)
                                                    {
                                                        _osmUtility.insertMembers(osmMembersPolylineFieldIndex, (IFeature)lineFeatureBuffer, relationMemberList.ToArray());
                                                    }

                                                    // store the administrative attributes
                                                    // user, uid, version, changeset, timestamp, visible
                                                    if (osmUserPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.user))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmUserPolylineFieldIndex, currentRelation.user);
                                                        }
                                                    }

                                                    if (osmUIDPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.uid))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmUIDPolylineFieldIndex, Convert.ToInt32(currentRelation.uid));
                                                        }
                                                    }

                                                    if (osmVisiblePolylineFieldIndex != -1)
                                                    {
                                                        if (String.IsNullOrEmpty(currentRelation.visible) == false)
                                                        {
                                                            lineFeatureBuffer.set_Value(osmVisiblePolylineFieldIndex, currentRelation.visible.ToString());
                                                        }
                                                        else
                                                        {
                                                            lineFeatureBuffer.set_Value(osmVisiblePolylineFieldIndex, "unknown");
                                                        }
                                                    }

                                                    if (osmVersionPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.version))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmVersionPolylineFieldIndex, Convert.ToInt32(currentRelation.version));
                                                        }
                                                    }

                                                    if (osmChangesetPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.changeset))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmChangesetPolylineFieldIndex, Convert.ToInt32(currentRelation.changeset));
                                                        }
                                                    }

                                                    if (osmTimeStampPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.timestamp))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmTimeStampPolylineFieldIndex, Convert.ToDateTime(currentRelation.timestamp));
                                                        }
                                                    }

                                                    if (osmLineIDFieldIndex != -1)
                                                    {
                                                        lineFeatureBuffer.set_Value(osmLineIDFieldIndex, currentRelation.id);
                                                    }

                                                    if (osmSupportingElementPolylineFieldIndex > -1)
                                                    {
                                                        lineFeatureBuffer.set_Value(osmSupportingElementPolylineFieldIndex, "no");
                                                    }
                                                }

                                                try
                                                {
                                                    lineFeatureInsertCursor.InsertFeature(lineFeatureBuffer);
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddWarning(ex.Message);
                                                }
                                                #endregion

                                            }
                                            else if (detectedGeometryType == esriGeometryType.esriGeometryPoint)
                                            {
                                                System.Diagnostics.Debug.WriteLine("Relation #: " + relationDebugCount + " :____: POINT!!!");

                                                if (TrackCancel.Continue() == false)
                                                {
                                                    return missingRelations;
                                                }
                                            }
                                            else
                                            // otherwise it is relation that needs to be dealt with separately
                                            {
                                                if (TrackCancel.Continue() == false)
                                                {
                                                    return missingRelations;
                                                }

                                                System.Diagnostics.Debug.WriteLine("Relation #: " + relationDebugCount + " :____: Kept as relation");

                                                if (tagCollectionRelationFieldIndex != -1)
                                                {
                                                    _osmUtility.insertOSMTags(tagCollectionRelationFieldIndex, rowBuffer, relationTagList.ToArray());
                                                }

                                                if (fastLoad == false)
                                                {
                                                    if (osmMembersRelationFieldIndex != -1)
                                                    {
                                                        _osmUtility.insertMembers(osmMembersRelationFieldIndex, rowBuffer, relationMemberList.ToArray());
                                                    }

                                                    // store the administrative attributes
                                                    // user, uid, version, changeset, timestamp, visible
                                                    if (osmUserRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.user))
                                                        {
                                                            rowBuffer.set_Value(osmUserRelationFieldIndex, currentRelation.user);
                                                        }
                                                    }

                                                    if (osmUIDRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.uid))
                                                        {
                                                            rowBuffer.set_Value(osmUIDRelationFieldIndex, Convert.ToInt64(currentRelation.uid));
                                                        }
                                                    }

                                                    if (osmVisibleRelationFieldIndex != -1)
                                                    {
                                                        if (currentRelation.visible != null)
                                                        {
                                                            rowBuffer.set_Value(osmVisibleRelationFieldIndex, currentRelation.visible.ToString());
                                                        }
                                                    }

                                                    if (osmVersionRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.version))
                                                        {
                                                            rowBuffer.set_Value(osmVersionRelationFieldIndex, Convert.ToInt32(currentRelation.version));
                                                        }
                                                    }

                                                    if (osmChangesetRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.changeset))
                                                        {
                                                            rowBuffer.set_Value(osmChangesetRelationFieldIndex, Convert.ToInt32(currentRelation.changeset));
                                                        }
                                                    }

                                                    if (osmTimeStampRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.timestamp))
                                                        {
                                                            try
                                                            {
                                                                rowBuffer.set_Value(osmTimeStampRelationFieldIndex, Convert.ToDateTime(currentRelation.timestamp));
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_invalidTimeFormat"), ex.Message));
                                                            }
                                                        }
                                                    }

                                                    if (osmRelationIDFieldIndex != -1)
                                                    {
                                                        rowBuffer.set_Value(osmRelationIDFieldIndex, currentRelation.id);
                                                    }
                                                }

                                                try
                                                {
                                                    rowCursor.InsertRow(rowBuffer);
                                                    relationCount = relationCount + 1;

                                                    relationIndexRebuildRequired = true;
                                                }
                                                catch (Exception ex)
                                                {
                                                    System.Diagnostics.Debug.WriteLine(ex.Message);
                                                }

                                                // check for user interruption
                                                if (TrackCancel.Continue() == false)
                                                {
                                                    return missingRelations;
                                                }
                                            }

                                            // update the isMemberOf fields of the attached features
                                            if (osmPointList != null)
                                            {
                                                foreach (OSMNodeFeature nodeFeature in osmPointList)
                                                {
                                                    updateIsMemberOf(osmLineFeatureClass, osmMemberOfPolylineFieldIndex, nodeFeature.nodeID, nodeFeature.relationList);
                                                }
                                            }

                                            if (osmLineList != null)
                                            {
                                                foreach (OSMLineFeature lineFeature in osmLineList)
                                                {
                                                    updateIsMemberOf(osmLineFeatureClass, osmMemberOfPolylineFieldIndex, lineFeature.lineID, lineFeature.relationList);
                                                }
                                            }

                                            if (osmPolygonList != null)
                                            {
                                                foreach (OSMPolygonFeature polygonFeature in osmPolygonList)
                                                {
                                                    updateIsMemberOf(osmLineFeatureClass, osmMemberOfPolylineFieldIndex, polygonFeature.polygonID, polygonFeature.relationList);
                                                }
                                            }

                                            if (stepProgressor != null)
                                            {
                                                stepProgressor.Position = relationCount;
                                            }

                                            if ((relationCount % 50000) == 0)
                                            {
                                                message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_relationsloaded"), relationCount));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            message.AddWarning(ex.Message);
                                        }
                                        finally
                                        {
                                            if (rowBuffer != null)
                                            {
                                                Marshal.ReleaseComObject(rowBuffer);

                                                if (rowBuffer != null)
                                                    rowBuffer = null;
                                            }
                                            if (lineFeatureBuffer != null)
                                            {
                                                Marshal.ReleaseComObject(lineFeatureBuffer);

                                                if (lineFeatureBuffer != null)
                                                    lineFeatureBuffer = null;
                                            }

                                            if (polygonFeatureBuffer != null)
                                            {
                                                Marshal.ReleaseComObject(polygonFeatureBuffer);

                                                if (polygonFeatureBuffer != null)
                                                    polygonFeatureBuffer = null;
                                            }

                                            currentRelation = null;
                                        }
                                    }
                                }
                            }

                            // close the OSM file
                            osmFileXmlReader.Close();

                            // flush any remaining entities from the cursor
                            rowCursor.Flush();
                            polygonFeatureInsertCursor.Flush();
                            lineFeatureInsertCursor.Flush();

                            // force a garbage collection
                            System.GC.Collect();

                            // let the user know that we are done dealing with the relations
                            message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_relationsloaded"), relationCount));
                        }
                    }

                    if (stepProgressor != null)
                    {
                        stepProgressor.Hide();
                    }

                    // Addd index for osmid column as well
                    IGeoProcessor2 geoProcessor = new GeoProcessorClass();
                    bool storedOriginalLocal = geoProcessor.AddOutputsToMap;
                    IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

                    try
                    {
                        geoProcessor.AddOutputsToMap = false;

                        if (relationIndexRebuildRequired)
                        {
                            IIndexes tableIndexes = relationTable.Indexes;
                            int indexPosition = -1;
                            tableIndexes.FindIndex("osmID_IDX", out indexPosition);

                            if (indexPosition == -1)
                            {
                                IGPValue relationTableGPValue = gpUtilities3.MakeGPValueFromObject(relationTable);
                                string sddd = targetGPValue.GetAsText();
                                string tableLocation = GetLocationString(targetGPValue, relationTable);
                                IVariantArray parameterArrary = CreateAddIndexParameterArray(tableLocation, "OSMID", "osmID_IDX", "UNIQUE", "");
                                IGeoProcessorResult2 gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        message.AddWarning(ex.Message);
                    }
                    finally
                    {
                        geoProcessor.AddOutputsToMap = storedOriginalLocal;

                        Marshal.FinalReleaseComObject(gpUtilities3);
                        Marshal.FinalReleaseComObject(geoProcessor);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (relationSerializer != null)
                    relationSerializer = null;

                if (osmFileXmlReader != null)
                    osmFileXmlReader = null;

                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
            }

            return missingRelations;
        }
        public IGPMessage ValidateValue(IGPValue Value, IGPDomain Domain)
        {
            IGPMessage validateValueMessage = new GPMessageClass();
            IGPUtilities3 gpUtilities = new GPUtilitiesClass();

            IHttpBasicGPValue targetValue = gpUtilities.UnpackGPValue(Value) as IHttpBasicGPValue;

            if ( targetValue == null ) {
                IGPString targetValueString = gpUtilities.UnpackGPValue(Value) as IGPString;
                if ( targetValueString != null )
                    return validateValueMessage;
            }

            if (targetValue == null)
            {
                validateValueMessage.Type = esriGPMessageType.esriGPMessageTypeError;
                validateValueMessage.ErrorCode = 502;
                validateValueMessage.Description = resourceManager.GetString("GPTools_Authentication_HttpBasicDataType_valuevalidation");
            }

            if (Domain != null)
            {
                validateValueMessage = Domain.MemberOf((IGPValue)targetValue);
            }

            return validateValueMessage;
        }
        private string GetLocationString(IGPValue gpValue, ITable table)
        {
            string locationString = String.Empty;

            {
                if (((IDataset)table).Workspace.PathName.ToUpper().Contains(".GDS\\"))
                {
                    string partialString = gpValue.GetAsText().Substring(0, gpValue.GetAsText().ToUpper().IndexOf(".GDS\\") + 4);

                    string secondString = gpValue.GetAsText().Substring(0, gpValue.GetAsText().LastIndexOf("\\"));

                    locationString = secondString + System.IO.Path.DirectorySeparatorChar + ((IDataset)table).BrowseName;
                }
                else
                {
                    locationString = ((IDataset)table).Workspace.PathName + System.IO.Path.DirectorySeparatorChar + ((IDataset)table).BrowseName;
                }
            }

            return locationString;
        }
        private string GetLocationString(IGPValue gpValue, IFeatureClass featureClass)
        {
            string locationString = String.Empty;

            if (featureClass.FeatureDataset != null)
            {
                if (featureClass.FeatureDataset.Workspace.PathName.ToUpper().Contains(".GDS\\"))
                {
                    locationString = gpValue.GetAsText() + System.IO.Path.DirectorySeparatorChar + ((IDataset)featureClass).BrowseName;
                }
                else
                    locationString = featureClass.FeatureDataset.Workspace.PathName + System.IO.Path.DirectorySeparatorChar + featureClass.FeatureDataset.BrowseName + System.IO.Path.DirectorySeparatorChar + ((IDataset)featureClass).BrowseName;
            }
            else
            {
                locationString = ((IDataset)featureClass).Workspace.PathName + System.IO.Path.DirectorySeparatorChar + ((IDataset)featureClass).BrowseName;
            }

            return locationString;
        }
        private void BuildSpatialIndex(IGPValue gpFeatureClass, Geoprocessor.Geoprocessor geoProcessor, IGPUtilities gpUtil,
            ITrackCancel trackCancel, IGPMessages message)
        {
            if ((gpFeatureClass == null) || (geoProcessor == null) || (gpUtil == null))
                return;

            // Check if the feature class supports spatial index grids
            IFeatureClass fc = gpUtil.OpenDataset(gpFeatureClass) as IFeatureClass;
            if (fc == null)
                return;

            int idxShapeField = fc.FindField(fc.ShapeFieldName);
            if (idxShapeField >= 0)
            {
                IField shapeField = fc.Fields.get_Field(idxShapeField);
                if (shapeField.GeometryDef.GridCount > 0)
                {
                    if (shapeField.GeometryDef.get_GridSize(0) == -2.0)
                        return;
                }
            }

            // Create the new spatial index grid
            bool storedOriginal = geoProcessor.AddOutputsToMap;

            try
            {
                geoProcessor.AddOutputsToMap = false;

                DataManagementTools.CalculateDefaultGridIndex calculateDefaultGridIndex =
                    new DataManagementTools.CalculateDefaultGridIndex(gpFeatureClass);
                IGeoProcessorResult2 gpResults2 =
                    geoProcessor.Execute(calculateDefaultGridIndex, trackCancel) as IGeoProcessorResult2;
                message.AddMessages(gpResults2.GetResultMessages());

                if (gpResults2 != null)
                {
                    DataManagementTools.RemoveSpatialIndex removeSpatialIndex =
                        new DataManagementTools.RemoveSpatialIndex(gpFeatureClass.GetAsText());
                    removeSpatialIndex.out_feature_class = gpFeatureClass.GetAsText();
                    gpResults2 = geoProcessor.Execute(removeSpatialIndex, trackCancel) as IGeoProcessorResult2;
                    message.AddMessages(gpResults2.GetResultMessages());

                    DataManagementTools.AddSpatialIndex addSpatialIndex =
                        new DataManagementTools.AddSpatialIndex(gpFeatureClass.GetAsText());
                    addSpatialIndex.out_feature_class = gpFeatureClass.GetAsText();

                    addSpatialIndex.spatial_grid_1 = calculateDefaultGridIndex.grid_index1;
                    addSpatialIndex.spatial_grid_2 = calculateDefaultGridIndex.grid_index2;
                    addSpatialIndex.spatial_grid_3 = calculateDefaultGridIndex.grid_index3;

                    gpResults2 = geoProcessor.Execute(addSpatialIndex, trackCancel) as IGeoProcessorResult2;
                    message.AddMessages(gpResults2.GetResultMessages());
                }
            }
            catch (Exception ex)
            {
                message.AddWarning(ex.Message);
            }
            finally
            {
                geoProcessor.AddOutputsToMap = storedOriginal;
            }
        }
        private IVariantArray CreateDefaultGridParamterArrary(IGPValue featureClassName)
        {
            IVariantArray featureClassArray = new VarArrayClass();

            featureClassArray.Add(featureClassName);

            return featureClassArray;
        }