Esempio n. 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)
        {
            IGPMultiValue tables     = (IGPMultiValue)parameters["in_tables"];
            IGPMultiValue modelNames = (IGPMultiValue)parameters["in_class_model_names"];
            int           addedCount = 0;

            if (tables.Count > 0 && modelNames.Count > 0)
            {
                foreach (var table in tables.AsEnumerable())
                {
                    IObjectClass dataElement = utilities.OpenTable(table);

                    foreach (var modelName in modelNames.AsEnumerable().Select(o => o.GetAsText()))
                    {
                        messages.Add(esriGPMessageType.esriGPMessageTypeInformative, "Adding the {0} class model name to the {1} table.", modelName, dataElement.AliasName);

                        ModelNameManager.Instance.AddClassModelName(dataElement, modelName);
                        addedCount++;
                    }
                }
            }

            if (addedCount == tables.Count)
            {
                // Success
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
Esempio n. 2
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");
            }
        }
Esempio n. 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      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");
            }
        }
Esempio n. 4
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");
            }
        }
 /// <summary>
 ///     Creates an <see cref="IEnumerable{IGPValue}" /> from an <see cref="IGPMultiValue" />
 /// </summary>
 /// <param name="source">An <see cref="IGPMultiValue" /> to create an <see cref="IEnumerable{IGPValue}" /> from.</param>
 /// <returns>
 ///     An <see cref="IEnumerable{IGPValue}" /> that contains the fields from the input source.
 /// </returns>
 public static IEnumerable <IGPValue> AsEnumerable(this IGPMultiValue source)
 {
     if (source != null)
     {
         for (int i = 0; i < source.Count; i++)
         {
             yield return(source.Value[i]);
         }
     }
 }
        /// <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;
                }
            }
        }
        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);
            }
        }
Esempio n. 8
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)
        {
            IObjectClass  table      = utilities.OpenTable(parameters["in_table"]);
            IGPMultiValue modelNames = (IGPMultiValue)parameters["in_class_model_names"];

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

                    ModelNameManager.Instance.RemoveClassModelName(table, modelName);
                }

                // Success.
                parameters["out_results"].SetAsText("true");
            }
            else
            {
                // Failure.
                parameters["out_results"].SetAsText("false");
            }
        }
Esempio n. 9
0
        // This method will update the output parameter value with the additional area field.
        public void UpdateParameters(IArray paramvalues, IGPEnvironmentManager pEnvMgr)
        {
            m_Parameters = paramvalues;

            IGPMultiValue inputValues = (IGPMultiValue)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(1);
            IGPValue         derivedValue    = m_GPUtilities.UnpackGPValue(derivedFeatures);
            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 (!derivedValue.IsEmpty() && inputValues.Count > 0)
            {
                IFields inputFields = m_GPUtilities.GetFields(inputValues.get_Value(0));
                IField  shapeField  = null;
                for (int i = 0; i < inputFields.FieldCount; i++)
                {
                    if (inputFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        shapeField = inputFields.get_Field(i);
                        break;
                    }
                }

                IFields fields = new FieldsClass();
                fields.AddField("ObjectID", esriFieldType.esriFieldTypeOID);
                fields.AddField(FEATURE_SOURCE_FIELD_NAME, esriFieldType.esriFieldTypeString);
                fields.AddField(FEATURE_ID_FIELD_NAME, esriFieldType.esriFieldTypeInteger);
                fields.AddField(shapeField);

                schema.AdditionalFields = fields;
            }
        }
Esempio n. 10
0
        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 execute_Utilities = new GPUtilitiesClass();

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

                IGPParameter inputOSMParameter = paramvalues.get_Element(in_osmFeatureClass) as IGPParameter;
                IGPValue     inputOSMGPValue   = execute_Utilities.UnpackGPValue(inputOSMParameter);

                IGPParameter  tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter;
                IGPMultiValue tagCollectionGPValue   = execute_Utilities.UnpackGPValue(tagCollectionParameter) as IGPMultiValue;

                if (tagCollectionGPValue == null)
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), tagCollectionParameter.Name));
                    return;
                }

                bool useUpdateCursor = false;

                IFeatureClass osmFeatureClass = null;
                ITable        osmInputTable   = null;
                IQueryFilter  osmQueryFilter  = null;

                try
                {
                    execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
                    if (osmFeatureClass != null)
                    {
                        if (osmFeatureClass.Extension is IOSMClassExtension)
                        {
                            useUpdateCursor = false;
                        }
                        else
                        {
                            useUpdateCursor = true;
                        }
                    }

                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

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

                if (osmInputTable == null)
                {
                    string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText());
                    message.AddError(120053, errorMessage);
                    return;
                }

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


                // if the Field doesn't exist - wasn't found (index = -1) get out
                if (osmTagCollectionFieldIndex == -1)
                {
                    message.AddError(120005, resourceManager.GetString("GPTools_OSMGPAttributeSelector_notagfieldfound"));
                    return;
                }

                // check if the tag collection includes the keyword "ALL", if does then we'll need to extract all tags
                bool extractAll = false;
                for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++)
                {
                    if (tagCollectionGPValue.get_Value(valueIndex).GetAsText().Equals("ALL"))
                    {
                        extractAll = true;
                        break;
                    }
                }
                //if (extractAll)
                //{
                //    if (osmTagKeyCodedValues == null)
                //        extractAllTags(ref osmTagKeyCodedValues, osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex, false);

                //    if (osmTagKeyCodedValues == null)
                //    {
                //        message.AddAbort(resourceManager.GetString("GPTools_OSMGPAttributeSelector_Unable2RetrieveTags"));
                //        return;
                //    }

                //    // empty the existing gp multivalue object
                //    tagCollectionGPValue = new GPMultiValueClass();

                //    // fill the coded domain in gp multivalue object
                //    for (int valueIndex = 0; valueIndex < osmTagKeyCodedValues.CodeCount; valueIndex++)
                //    {
                //        tagCollectionGPValue.AddValue(osmTagKeyCodedValues.get_Value(valueIndex));
                //    }
                //}

                // get an overall feature count as that determines the progress indicator
                int featureCount = osmInputTable.RowCount(osmQueryFilter);

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

                if (stepProgressor != null)
                {
                    stepProgressor.MinRange  = 0;
                    stepProgressor.MaxRange  = featureCount;
                    stepProgressor.Position  = 0;
                    stepProgressor.Message   = resourceManager.GetString("GPTools_OSMGPAttributeSelector_progressMessage");
                    stepProgressor.StepValue = 1;
                    stepProgressor.Show();
                }

                // let's get all the indices of the desired fields
                // if the field already exists get the index and if it doesn't exist create it
                Dictionary <string, int> tagsAttributesIndices = new Dictionary <string, int>();
                Dictionary <int, int>    attributeFieldLength  = new Dictionary <int, int>();

                IFeatureWorkspaceManage featureWorkspaceManage = ((IDataset)osmInputTable).Workspace as IFeatureWorkspaceManage;

                String illegalCharacters = String.Empty;

                ISQLSyntax sqlSyntax = ((IDataset)osmInputTable).Workspace as ISQLSyntax;
                if (sqlSyntax != null)
                {
                    illegalCharacters = sqlSyntax.GetInvalidCharacters();
                }

                IFieldsEdit fieldsEdit = osmInputTable.Fields as IFieldsEdit;


                using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable))
                {
                    try
                    {
                        string tagKey = String.Empty;
                        ESRI.ArcGIS.Geoprocessing.IGeoProcessor2 gp = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass();

                        // if we have explicitly defined tags to extract then go through the list of values now
                        if (extractAll == false)
                        {
                            for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++)
                            {
                                if (TrackCancel.Continue() == false)
                                {
                                    return;
                                }

                                try
                                {
                                    // Check if the input field already exists.
                                    string nameofTag = tagCollectionGPValue.get_Value(valueIndex).GetAsText();
                                    tagKey = convert2AttributeFieldName(nameofTag, illegalCharacters);

                                    int fieldIndex = osmInputTable.FindField(tagKey);

                                    if (fieldIndex < 0)
                                    {
                                        // generate a new attribute field
                                        IFieldEdit fieldEdit = new FieldClass();
                                        fieldEdit.Name_2      = tagKey;
                                        fieldEdit.AliasName_2 = nameofTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition");
                                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                                        fieldEdit.Length_2    = 100;

                                        osmInputTable.AddField(fieldEdit);

                                        message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameofTag));

                                        // re-generate the attribute index
                                        fieldIndex = osmInputTable.FindField(tagKey);
                                    }

                                    if (fieldIndex > 0)
                                    {
                                        tagsAttributesIndices.Add(nameofTag, fieldIndex);
                                        attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    // the key is already there, this might result because from multiple upper and lower-case combinations of the same key
                                    message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")");
                                }
                            }
                        }
                        else
                        {
                            List <string> listofAllTags = extractAllTags(osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex);

                            foreach (string nameOfTag in listofAllTags)
                            {
                                if (TrackCancel.Continue() == false)
                                {
                                    return;
                                }

                                try
                                {
                                    // Check if the input field already exists.
                                    tagKey = convert2AttributeFieldName(nameOfTag, illegalCharacters);

                                    int fieldIndex = osmInputTable.FindField(tagKey);

                                    if (fieldIndex < 0)
                                    {
                                        // generate a new attribute field
                                        IFieldEdit fieldEdit = new FieldClass();
                                        fieldEdit.Name_2      = tagKey;
                                        fieldEdit.AliasName_2 = nameOfTag + resourceManager.GetString("GPTools_OSMGPAttributeSelector_aliasaddition");
                                        fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                                        fieldEdit.Length_2    = 100;

                                        osmInputTable.AddField(fieldEdit);

                                        message.AddMessage(string.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelector_addField"), tagKey, nameOfTag));

                                        // re-generate the attribute index
                                        fieldIndex = osmInputTable.FindField(tagKey);
                                    }

                                    if (fieldIndex > 0)
                                    {
                                        tagsAttributesIndices.Add(nameOfTag, fieldIndex);
                                        attributeFieldLength.Add(fieldIndex, osmInputTable.Fields.get_Field(fieldIndex).Length);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    // the key is already there, this might result because from multiple upper and lower-case combinations of the same key
                                    message.AddWarning(ex.Message + " (" + convert2OSMKey(tagKey, illegalCharacters) + ")");
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        message.AddWarning(ex.Message);
                    }
                }

                try
                {
                    execute_Utilities.DecodeFeatureLayer(inputOSMGPValue, out osmFeatureClass, out osmQueryFilter);
                    if (osmFeatureClass != null)
                    {
                        if (osmFeatureClass.Extension is IOSMClassExtension)
                        {
                            useUpdateCursor = false;
                        }
                        else
                        {
                            useUpdateCursor = true;
                        }
                    }

                    osmInputTable = osmFeatureClass as ITable;
                }
                catch { }

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

                if (osmInputTable == null)
                {
                    string errorMessage = String.Format(resourceManager.GetString("GPTools_OSMGPAttributeSelecto_unableopentable"), inputOSMGPValue.GetAsText());
                    message.AddError(120053, errorMessage);
                    return;
                }

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    using (SchemaLockManager lockMgr = new SchemaLockManager(osmInputTable))
                    {
                        // get an update cursor for all the features to process
                        ICursor rowCursor = null;
                        if (useUpdateCursor)
                        {
                            rowCursor = osmInputTable.Update(osmQueryFilter, false);
                        }
                        else
                        {
                            rowCursor = osmInputTable.Search(osmQueryFilter, false);
                        }

                        comReleaser.ManageLifetime(rowCursor);

                        IRow osmRow = null;


                        Dictionary <string, string> tagKeys = new Dictionary <string, string>();
                        int progessIndex = 0;
#if DEBUG
                        message.AddMessage("useUpdateCursor: " + useUpdateCursor.ToString());
#endif

                        // as long as there are features....
                        while ((osmRow = rowCursor.NextRow()) != null)
                        {
                            // retrieve the tags of the current feature
                            tag[] storedTags = _osmUtility.retrieveOSMTags(osmRow, osmTagCollectionFieldIndex, ((IDataset)osmInputTable).Workspace);

                            bool rowChanged = false;
                            if (storedTags != null)
                            {
                                foreach (tag tagItem in storedTags)
                                {
                                    // Check for matching values so we only change a minimum number of rows
                                    if (tagsAttributesIndices.ContainsKey(tagItem.k))
                                    {
                                        int fieldIndex = tagsAttributesIndices[tagItem.k];

                                        //...then stored the value in the attribute field
                                        // ensure that the content of the tag actually does fit into the field length...otherwise do truncate it
                                        string tagValue = tagItem.v;

                                        int fieldLength = attributeFieldLength[fieldIndex];

                                        if (tagValue.Length > fieldLength)
                                        {
                                            tagValue = tagValue.Substring(0, fieldLength);
                                        }

                                        osmRow.set_Value(fieldIndex, tagValue);
                                        rowChanged = true;
                                    }
                                    else
                                    {
#if DEBUG
                                        //message.AddWarning(tagItem.k);
#endif
                                    }
                                }
                            }

                            storedTags = null;

                            try
                            {
                                if (rowChanged)
                                {
                                    if (useUpdateCursor)
                                    {
                                        rowCursor.UpdateRow(osmRow);
                                    }
                                    else
                                    {
                                        // update the feature through the cursor
                                        osmRow.Store();
                                    }
                                }
                                progessIndex++;
                            }
                            catch (Exception ex)
                            {
                                System.Diagnostics.Debug.WriteLine(ex.Message);
                                message.AddWarning(ex.Message);
                            }

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

                            if (stepProgressor != null)
                            {
                                // update the progress UI
                                stepProgressor.Position = progessIndex;
                            }

                            // check for user cancellation (every 100 rows)
                            if ((progessIndex % 100 == 0) && (TrackCancel.Continue() == false))
                            {
                                return;
                            }
                        }

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

                execute_Utilities.ReleaseInternals();
                Marshal.ReleaseComObject(execute_Utilities);
            }
            catch (Exception ex)
            {
                message.AddError(120054, ex.Message);
            }
        }
Esempio n. 11
0
        public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
        {
            try
            {
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

                IGPValue inputOSMGPValue = gpUtilities3.UnpackGPValue(paramvalues.get_Element(in_osmFeatureClass));

                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;
                }

                String illegalCharacters = String.Empty;

                ISQLSyntax sqlSyntax = ((IDataset)osmInputTable).Workspace as ISQLSyntax;
                if (sqlSyntax != null)
                {
                    illegalCharacters = sqlSyntax.GetInvalidCharacters();
                }

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


                // if the Field doesn't exist - wasn't found (index = -1) get out
                if (osmTagCollectionFieldIndex == -1)
                {
                    return;
                }

                if (((IGPParameter)paramvalues.get_Element(in_attributeSelector)).Altered)
                {
                    IGPParameter  tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter;
                    IGPMultiValue tagCollectionGPValue   = gpUtilities3.UnpackGPValue(tagCollectionParameter) as IGPMultiValue;

                    IGPCodedValueDomain codedTagDomain = tagCollectionParameter.Domain as IGPCodedValueDomain;

                    for (int attributeValueIndex = 0; attributeValueIndex < tagCollectionGPValue.Count; attributeValueIndex++)
                    {
                        string   valueString    = tagCollectionGPValue.get_Value(attributeValueIndex).GetAsText();
                        IGPValue testFieldValue = codedTagDomain.FindValue(valueString);

                        if (testFieldValue == null)
                        {
                            codedTagDomain.AddStringCode(valueString, valueString);
                        }
                    }

                    // Get the derived output feature class schema and empty the additional fields. This ensures
                    // that you don't get dublicate entries.
                    // Derived output is the third parameter, so use index 2 for get_Element.
                    IGPParameter3    derivedFeatures = (IGPParameter3)paramvalues.get_Element(out_osmFeatureClass);
                    IGPFeatureSchema schema          = (IGPFeatureSchema)derivedFeatures.Schema;
                    schema.AdditionalFields = null;

                    IFieldsEdit fieldsEdit = new FieldsClass();

                    for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++)
                    {
                        string tagString = tagCollectionGPValue.get_Value(valueIndex).GetAsText();

                        if (tagString != "ALL")
                        {
                            // Check if the input field already exists.
                            string cleanedTagKey = convert2AttributeFieldName(tagString, illegalCharacters);
                            IField tagField      = gpUtilities3.FindField(inputOSMGPValue, cleanedTagKey);
                            if (tagField == null)
                            {
                                IFieldEdit fieldEdit = new FieldClass();
                                fieldEdit.Name_2      = cleanedTagKey;
                                fieldEdit.AliasName_2 = tagCollectionGPValue.get_Value(valueIndex).GetAsText();
                                fieldEdit.Type_2      = esriFieldType.esriFieldTypeString;
                                fieldEdit.Length_2    = 100;
                                fieldsEdit.AddField(fieldEdit);
                            }
                        }
                    }

                    // Add the additional field to the derived output.
                    IFields fields = fieldsEdit as IFields;
                    schema.AdditionalFields = fields;
                }

                //if (inputOSMGPValue.IsEmpty() == false)
                //{
                //    if (((IGPParameter)paramvalues.get_Element(in_osmFeatureClass)).HasBeenValidated == false)
                //    {
                //        IGPParameter tagCollectionGPParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter;
                //        IGPValue tagCollectionGPValue = gpUtilities3.UnpackGPValue(tagCollectionGPParameter);

                //        IGPCodedValueDomain osmTagKeyCodedValues = new GPCodedValueDomainClass();
                //        if (((IGPMultiValue)tagCollectionGPValue).Count == 0)
                //        {
                //            if (osmTagKeyCodedValues == null)
                //                extractAllTags(ref osmTagKeyCodedValues, osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex, true);

                //            if (osmTagKeyCodedValues != null)
                //            {
                //                tagsParameter = tagCollectionGPParameter as IGPParameterEdit;
                //                tagsParameter.Domain = (IGPDomain)osmTagKeyCodedValues;
                //            }
                //        }
                //        else
                //        {
                //            // let's take the given values and make then part of the domain -- if they are not already
                //            // if we don't do this step then we won't pass the internal validation
                //            IGPCodedValueDomain gpTagDomain = tagCollectionGPParameter.Domain as IGPCodedValueDomain;

                //            if (gpTagDomain != null)
                //            {
                //                if (gpTagDomain.CodeCount == 0)
                //                {
                //                    // let's add the value existing in the mentioned multi value to the domain
                //                    for (int i = 0; i < ((IGPMultiValue)tagCollectionGPValue).Count; i++)
                //                    {
                //                        string tagStringValue = ((IGPMultiValue)tagCollectionGPValue).get_Value(i).GetAsText();
                //                        gpTagDomain.AddStringCode(tagStringValue, tagStringValue);
                //                    }

                //                    ((IGPParameterEdit)tagCollectionGPParameter).Domain = gpTagDomain as IGPDomain;
                //                }
                //            }
                //        }

                //        // Get the derived output feature class schema and empty the additional fields. This ensures
                //        // that you don't get dublicate entries.
                //        // Derived output is the third parameter, so use index 2 for get_Element.
                //        IGPParameter3 derivedFeatures = (IGPParameter3)paramvalues.get_Element(out_osmFeatureClass);
                //        IGPFeatureSchema schema = (IGPFeatureSchema)derivedFeatures.Schema;
                //        schema.AdditionalFields = null;

                //        // Area field name is the second parameter, so use index 1 for get_Element.
                //        IGPMultiValue tagsGPMultiValue = gpUtilities3.UnpackGPValue(paramvalues.get_Element(in_attributeSelector)) as IGPMultiValue;

                //        IFieldsEdit fieldsEdit = new FieldsClass();
                //        bool extractALLTags = false;

                //        // check if the list contains the "ALL" keyword
                //        for (int valueIndex = 0; valueIndex < tagsGPMultiValue.Count; valueIndex++)
                //        {
                //            if (tagsGPMultiValue.get_Value(valueIndex).GetAsText().Equals("ALL"))
                //            {
                //                extractALLTags = true;
                //            }
                //        }

                //        if (extractALLTags)
                //        {
                //            if (osmTagKeyCodedValues == null)
                //            {
                //                extractAllTags(ref osmTagKeyCodedValues, osmInputTable, osmQueryFilter, osmTagCollectionFieldIndex, false);
                //            }

                //            if (osmTagKeyCodedValues != null)
                //            {
                //                for (int valueIndex = 0; valueIndex < osmTagKeyCodedValues.CodeCount; valueIndex++)
                //                {
                //                    // Check if the input field already exists.
                //                    string cleanedTagKey = convert2AttributeFieldName(osmTagKeyCodedValues.get_Value(valueIndex).GetAsText(), illegalCharacters);
                //                    IField tagField = gpUtilities3.FindField(inputOSMGPValue, cleanedTagKey);
                //                    if (tagField == null)
                //                    {
                //                        IFieldEdit fieldEdit = new FieldClass();
                //                        fieldEdit.Name_2 = cleanedTagKey;
                //                        fieldEdit.AliasName_2 = osmTagKeyCodedValues.get_Value(valueIndex).GetAsText();
                //                        fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                //                        fieldEdit.Length_2 = 100;
                //                        fieldsEdit.AddField(fieldEdit);
                //                    }
                //                }
                //            }
                //        }
                //        else
                //        {
                //            for (int valueIndex = 0; valueIndex < tagsGPMultiValue.Count; valueIndex++)
                //            {
                //                // Check if the input field already exists.
                //                string cleanedTagKey = convert2AttributeFieldName(tagsGPMultiValue.get_Value(valueIndex).GetAsText(), illegalCharacters);
                //                IField tagField = gpUtilities3.FindField(inputOSMGPValue, cleanedTagKey);
                //                if (tagField == null)
                //                {
                //                    IFieldEdit fieldEdit = new FieldClass();
                //                    fieldEdit.Name_2 = cleanedTagKey;
                //                    fieldEdit.AliasName_2 = tagsGPMultiValue.get_Value(valueIndex).GetAsText();
                //                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                //                    fieldEdit.Length_2 = 100;
                //                    fieldsEdit.AddField(fieldEdit);
                //                }
                //            }
                //        }

                //        // Add the additional field to the derived output.
                //        IFields fields = fieldsEdit as IFields;
                //        schema.AdditionalFields = fields;

                //    }
                //}
            }
            catch { }
        }
Esempio n. 12
0
        // Execute: Execute the function given the array of the parameters
        public void Execute(IArray paramvalues, ITrackCancel trackcancel, IGPEnvironmentManager envMgr, IGPMessages message)
        {
            IFeatureClass outputFeatureClass = null;

            try
            {
                // get the input feature class
                IGPMultiValue inputFeatureClasses_Parameter = (IGPMultiValue)m_GPUtilities.UnpackGPValue(paramvalues.get_Element(0));
                layer[]       input_featureClasses          = new layer[inputFeatureClasses_Parameter.Count];
                for (int i = 0; i < inputFeatureClasses_Parameter.Count; i++)
                {
                    IGPValue inputFeatureClass_Parameter = inputFeatureClasses_Parameter.get_Value(i);

                    IFeatureClass inputFeatureClass;
                    IQueryFilter  inputQF;

                    m_GPUtilities.DecodeFeatureLayer(inputFeatureClass_Parameter, out inputFeatureClass, out inputQF);

                    input_featureClasses[i] = new layer()
                    {
                        featureclass = inputFeatureClass, qFilter = inputQF
                    };
                }


                if (input_featureClasses.Length == 0 || input_featureClasses.Any(w => w.featureclass == null))
                {
                    message.AddError(2, "Could not open one or more input dataset.");
                    return;
                }

                //IFields additionalFields = new FieldsClass();
                //additionalFields.AddField(FEATURE_SOURCE_FIELD_NAME, esriFieldType.esriFieldTypeString);
                //additionalFields.AddField(FEATURE_ID_FIELD_NAME, esriFieldType.esriFieldTypeInteger);
                //additionalFields.AddField(
                //    input_featureClasses[0].featureclass.Fields.get_Field(
                //    input_featureClasses[0].featureclass.Fields.FindField(
                //    input_featureClasses[0].featureclass.ShapeFieldName)));

                // create the output feature class
                IGPValue outputFeatureClass_Parameter = m_GPUtilities.UnpackGPValue(paramvalues.get_Element(1));
                outputFeatureClass = GPHelperFunctions.CreateFeatureClass(outputFeatureClass_Parameter, envMgr);

                if (outputFeatureClass == null)
                {
                    message.AddError(2, "Could not create output dataset.");
                    return;
                }



                IGPString curveTypeParameter = (IGPString)m_GPUtilities.UnpackGPValue(paramvalues.get_Element(2));
                ArcConstructionMethods method;
                if (!Enum.TryParse <ArcConstructionMethods>(curveTypeParameter.Value, true, out method))
                {
                    message.AddError(2, string.Format("The value {0} is not expected.  Expected values are: {1}.",
                                                      curveTypeParameter.Value,
                                                      string.Join(",", Enum.GetNames(typeof(ArcConstructionMethods)))));
                    return;
                }

                IStepProgressor stepPro = (IStepProgressor)trackcancel;
                GPHelperFunctions.dropSpatialIndex(outputFeatureClass);

                BoostVoronoi bv = new BoostVoronoi(100);

                double          minX = int.MaxValue, minY = int.MaxValue, maxX = int.MinValue, maxY = int.MinValue;
                List <site_key> point_sites   = new List <site_key>();
                List <site_key> segment_sites = new List <site_key>();

                for (short i = 0; i < input_featureClasses.Length; i++)
                {
                    layer l         = input_featureClasses[i];
                    int   featcount = l.featureclass.FeatureCount(l.qFilter);

                    stepPro.MinRange  = 0;
                    stepPro.MaxRange  = featcount;
                    stepPro.StepValue = (1);
                    stepPro.Message   = "Reading features";
                    stepPro.Position  = 0;
                    stepPro.Show();

                    IFeatureCursor cursor = null;
                    IFeature       row    = null;

                    try
                    {
                        cursor = l.featureclass.Search(l.qFilter, false);
                        while ((row = cursor.NextFeature()) != null)
                        {
                            stepPro.Step();
                            IPoint point = row.Shape as IPoint;
                            if (point != null)
                            {
                                double X = point.X;
                                double Y = point.Y;

                                minX = Math.Min(minX, X);
                                maxX = Math.Max(maxX, X);

                                minY = Math.Min(minY, Y);
                                maxY = Math.Max(maxY, Y);

                                bv.AddPoint(point.X, point.Y);
                                point_sites.Add(new site_key(i, row.OID));
                            }

                            IMultipoint multipoint = row.Shape as IMultipoint;
                            if (multipoint != null)
                            {
                                IPointCollection pointCollection = (IPointCollection)multipoint;
                                IEnumVertex      vertices        = pointCollection.EnumVertices;

                                IPoint vertex = null; int part, index;
                                vertices.Next(out vertex, out part, out index);

                                minX = Math.Min(minX, multipoint.Envelope.XMin);
                                maxX = Math.Max(maxX, multipoint.Envelope.XMax);

                                minY = Math.Min(minY, multipoint.Envelope.YMin);
                                maxY = Math.Max(maxY, multipoint.Envelope.YMax);

                                while (vertex != null)
                                {
                                    bv.AddPoint(vertex.X, vertex.Y);
                                    point_sites.Add(new site_key(i, row.OID));

                                    vertices.Next(out vertex, out part, out index);
                                }
                            }

                            IPolyline polyline = row.Shape as IPolyline;
                            if (polyline != null)
                            {
                                double fromX = polyline.FromPoint.X;
                                double fromY = polyline.FromPoint.Y;
                                double toX   = polyline.ToPoint.X;
                                double toY   = polyline.ToPoint.Y;

                                if (toX < fromX)
                                {
                                    minX = Math.Min(minX, toX);
                                    maxX = Math.Max(maxX, fromX);
                                }
                                else
                                {
                                    minX = Math.Min(minX, fromX);
                                    maxX = Math.Max(maxX, toX);
                                }

                                if (toY < fromY)
                                {
                                    minY = Math.Min(minY, toY);
                                    maxY = Math.Max(maxY, fromY);
                                }
                                else
                                {
                                    minY = Math.Min(minY, fromY);
                                    maxY = Math.Max(maxY, toY);
                                }

                                bv.AddSegment(
                                    polyline.FromPoint.X, polyline.FromPoint.Y,
                                    polyline.ToPoint.X, polyline.ToPoint.Y
                                    );


                                segment_sites.Add(new site_key(i, row.OID));
                            }

                            Marshal.ReleaseComObject(row);
                        }
                    }
                    finally
                    {
                        if (row != null)
                        {
                            Marshal.ReleaseComObject(row);
                        }
                        if (cursor != null)
                        {
                            Marshal.ReleaseComObject(cursor);
                        }

                        stepPro.Hide();
                    }
                }

                message.AddMessage(String.Format("{0}, {1} -> {2}, {3}", minX, minY, maxX, maxY));

                int width  = Math.Max((int)((maxX - minX) * 0.1), 1);
                int height = Math.Max((int)((maxY - minY) * 0.1), 1);

                maxX = maxX + width;
                minX = minX - width;
                maxY = maxY + height;
                minY = minY - height;

                message.AddMessage(String.Format("{0}, {1} -> {2}, {3}", minX, minY, maxX, maxY));
                bv.AddSegment(minX, minY, maxX, minY);
                segment_sites.Add(new site_key(-1, -1));
                bv.AddSegment(maxX, minY, maxX, maxY);
                segment_sites.Add(new site_key(-1, -1));
                bv.AddSegment(maxX, maxY, minX, maxY);
                segment_sites.Add(new site_key(-1, -1));
                bv.AddSegment(minX, maxY, minX, minY);
                segment_sites.Add(new site_key(-1, -1));

                stepPro.Message  = "Solve Voronoi";
                stepPro.MaxRange = 0;
                stepPro.MaxRange = 0;
                stepPro.Show();

                bv.Construct();

                stepPro.Hide();

                int featureSourceIndx = outputFeatureClass.Fields.FindField(FEATURE_SOURCE_FIELD_NAME);
                int featureIDIndx     = outputFeatureClass.Fields.FindField(FEATURE_ID_FIELD_NAME);

                IFeatureCursor inserts = null;
                IFeatureBuffer buffer  = null;
                try
                {
                    object            missing          = Type.Missing;
                    ISpatialReference spatialReference = ((IGeoDataset)outputFeatureClass).SpatialReference;
                    inserts = outputFeatureClass.Insert(false);
                    buffer  = outputFeatureClass.CreateFeatureBuffer();

                    List <Cell> cells = bv.Cells;
                    message.AddMessage(string.Format("{0} cells calculated", cells.Count));
                    List <Edge> edges = bv.Edges;
                    message.AddMessage(string.Format("{0} edges calculated", edges.Count));
                    List <Vertex> vertices = bv.Vertices;
                    message.AddMessage(string.Format("{0} vertexes calculated", vertices.Count));

                    stepPro.Message  = "Write cells";
                    stepPro.MaxRange = 0;
                    stepPro.MaxRange = cells.Count;
                    stepPro.Show();


                    for (int cellIndex = 0; cellIndex < cells.Count; cellIndex++)
                    {
                        try
                        {
                            if (cellIndex % 5000 == 0)
                            {
                                message.AddMessage(String.Format("{0}. {1} cells processed.", DateTime.Now, cellIndex));
                            }

                            Cell cell        = cells[cellIndex];
                            int  currentSite = cell.Site;
                            IGeometryCollection geometryCollection = new GeometryBagClass()
                            {
                                SpatialReference = spatialReference
                            };

                            //ignores any sliver cells
                            if (cell.IsOpen || cell.EdgesIndex.Count < 3)
                            {
                                continue;
                            }

                            ISegmentCollection segmentCollection = createSegments(cell, bv, method, spatialReference);

                            if (((IArea)segmentCollection).Area <= 0)
                            {
                                message.AddMessage("A invalid geometry has been detected, try reversing the orientation.");
                                ISegmentCollection reversed_segmentCollection = new PolygonClass()
                                {
                                    SpatialReference = spatialReference
                                };
                                for (int i = segmentCollection.SegmentCount - 1; i >= 0; i--)
                                {
                                    ISegment segment = (ISegment)segmentCollection.get_Segment(i);
                                    segment.ReverseOrientation();
                                    reversed_segmentCollection.AddSegment(segment);
                                }
                                segmentCollection = reversed_segmentCollection;
                            }

                            ((IPolygon)segmentCollection).SpatialReference = spatialReference;
                            if (((IArea)segmentCollection).Area <= 0)
                            {
                                message.AddWarning("An empty shell has been created");

                                for (int i = 0; i < segmentCollection.SegmentCount; i++)
                                {
                                    ISegment segment = (ISegment)segmentCollection.get_Segment(i);
                                    message.AddMessage(String.Format("From {0}, {1} To {2},{3}",
                                                                     segment.FromPoint.X, segment.FromPoint.Y,
                                                                     segment.ToPoint.X, segment.ToPoint.Y));
                                }
                            }


                            //set attributes
                            site_key sk = (currentSite >= point_sites.Count) ? segment_sites[currentSite - point_sites.Count] : point_sites[currentSite];
                            if (!sk.isEmpty)
                            {
                                buffer.set_Value(featureSourceIndx, input_featureClasses[sk.featureClassIndex].featureclass.AliasName);
                                buffer.set_Value(featureIDIndx, sk.objectID);
                            }
                            else
                            {
                                buffer.set_Value(featureSourceIndx, DBNull.Value);
                                buffer.set_Value(featureIDIndx, DBNull.Value);
                            }


                            IPolygon voronoiPolygon = (IPolygon)segmentCollection;
                            buffer.Shape = (IPolygon)voronoiPolygon;
                            inserts.InsertFeature(buffer);
                        }
                        catch (Exception e)
                        {
                            message.AddWarning("Failed to create a cell");
                        }
                    }
                }
                finally
                {
                    if (buffer != null)
                    {
                        Marshal.ReleaseComObject(buffer);
                    }
                    if (inserts != null)
                    {
                        Marshal.ReleaseComObject(inserts);
                    }
                }

                GPHelperFunctions.createSpatialIndex(outputFeatureClass);
            }
            catch (Exception exx)
            {
                message.AddError(2, exx.Message);
                message.AddMessage(exx.ToString());
            }
            finally
            {
                if (outputFeatureClass != null)
                {
                    Marshal.ReleaseComObject(outputFeatureClass);
                }

                ((IProgressor)trackcancel).Hide();
            }
        }
Esempio n. 13
0
        public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
        {
            IGPUtilities3 gpUtilities3  = new GPUtilitiesClass();
            OSMToolHelper osmToolHelper = new OSMToolHelper();

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

            IGPEnvironment configKeyword = OSMToolHelper.getEnvironment(envMgr, "configKeyword");
            IGPString      gpString      = configKeyword.Value as IGPString;

            string storageKeyword = String.Empty;

            if (gpString != null)
            {
                storageKeyword = gpString.Value;
            }

            IGPParameter osmFileParameter      = paramvalues.get_Element(0) as IGPParameter;
            IGPValue     osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue;

            IGPParameter loadSuperRelationParameter = paramvalues.get_Element(1) as IGPParameter;
            IGPBoolean   loadSuperRelationGPValue   = gpUtilities3.UnpackGPValue(loadSuperRelationParameter) as IGPBoolean;

            IGPParameter osmSourceLineFeatureClassParameter = paramvalues.get_Element(2) as IGPParameter;
            IGPValue     osmSourceLineFeatureClassGPValue   = gpUtilities3.UnpackGPValue(osmSourceLineFeatureClassParameter) as IGPValue;

            IGPParameter osmSourcePolygonFeatureClassParameter = paramvalues.get_Element(3) as IGPParameter;
            IGPValue     osmSourcePolygonFeatureClassGPValue   = gpUtilities3.UnpackGPValue(osmSourcePolygonFeatureClassParameter) as IGPValue;


            IGPParameter osmTargetLineFeatureClassParameter = paramvalues.get_Element(6) as IGPParameter;
            IGPValue     osmTargetLineFeatureClassGPValue   = gpUtilities3.UnpackGPValue(osmTargetLineFeatureClassParameter) as IGPValue;

            IName       workspaceName        = gpUtilities3.CreateParentFromCatalogPath(osmTargetLineFeatureClassGPValue.GetAsText());
            IWorkspace2 lineFeatureWorkspace = workspaceName.Open() as IWorkspace2;

            string[] lineFCNameElements = osmTargetLineFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar);

            IFeatureClass osmLineFeatureClass = null;

            IGPParameter  tagLineCollectionParameter = paramvalues.get_Element(4) as IGPParameter;
            IGPMultiValue tagLineCollectionGPValue   = gpUtilities3.UnpackGPValue(tagLineCollectionParameter) as IGPMultiValue;

            List <String> lineTagstoExtract = null;

            if (tagLineCollectionGPValue.Count > 0)
            {
                lineTagstoExtract = new List <string>();

                for (int valueIndex = 0; valueIndex < tagLineCollectionGPValue.Count; valueIndex++)
                {
                    string nameOfTag = tagLineCollectionGPValue.get_Value(valueIndex).GetAsText();

                    lineTagstoExtract.Add(nameOfTag);
                }
            }
            else
            {
                lineTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields();
            }

            // lines
            try
            {
                osmLineFeatureClass = osmToolHelper.CreateSmallLineFeatureClass(lineFeatureWorkspace,
                                                                                lineFCNameElements[lineFCNameElements.Length - 1], storageKeyword, "", "", lineTagstoExtract);
            }
            catch (Exception ex)
            {
                message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message));
                return;
            }

            if (osmLineFeatureClass == null)
            {
                return;
            }


            IGPParameter osmTargetPolygonFeatureClassParameter = paramvalues.get_Element(7) as IGPParameter;
            IGPValue     osmTargetPolygonFeatureClassGPValue   = gpUtilities3.UnpackGPValue(osmTargetPolygonFeatureClassParameter) as IGPValue;

            workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmTargetPolygonFeatureClassGPValue.GetAsText());
            IWorkspace2 polygonFeatureWorkspace = workspaceName.Open() as IWorkspace2;

            string[] polygonFCNameElements = osmTargetPolygonFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar);

            IFeatureClass osmPolygonFeatureClass = null;

            IGPParameter  tagPolygonCollectionParameter = paramvalues.get_Element(5) as IGPParameter;
            IGPMultiValue tagPolygonCollectionGPValue   = gpUtilities3.UnpackGPValue(tagPolygonCollectionParameter) as IGPMultiValue;

            List <String> polygonTagstoExtract = null;

            if (tagPolygonCollectionGPValue.Count > 0)
            {
                polygonTagstoExtract = new List <string>();

                for (int valueIndex = 0; valueIndex < tagPolygonCollectionGPValue.Count; valueIndex++)
                {
                    string nameOfTag = tagPolygonCollectionGPValue.get_Value(valueIndex).GetAsText();

                    polygonTagstoExtract.Add(nameOfTag);
                }
            }
            else
            {
                polygonTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields();
            }
            // polygons
            try
            {
                osmPolygonFeatureClass = osmToolHelper.CreateSmallPolygonFeatureClass(polygonFeatureWorkspace,
                                                                                      polygonFCNameElements[polygonFCNameElements.Length - 1], storageKeyword, "", "", polygonTagstoExtract);
            }
            catch (Exception ex)
            {
                message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message));
                return;
            }

            if (osmPolygonFeatureClass == null)
            {
                return;
            }

            ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass);
            ComReleaser.ReleaseCOMObject(osmLineFeatureClass);


            string[] gdbComponents = new string[polygonFCNameElements.Length - 1];
            System.Array.Copy(lineFCNameElements, gdbComponents, lineFCNameElements.Length - 1);
            string fileGDBLocation = String.Join(System.IO.Path.DirectorySeparatorChar.ToString(), gdbComponents);

            osmToolHelper.smallLoadOSMRelations(osmFileLocationString.GetAsText(),
                                                osmSourceLineFeatureClassGPValue.GetAsText(),
                                                osmSourcePolygonFeatureClassGPValue.GetAsText(),
                                                osmTargetLineFeatureClassGPValue.GetAsText(),
                                                osmTargetPolygonFeatureClassGPValue.GetAsText(),
                                                lineTagstoExtract, polygonTagstoExtract, loadSuperRelationGPValue.Value);
        }
        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 execute_Utilities = new GPUtilitiesClass();
                OSMUtility    osmUtility        = new OSMUtility();

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

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

                IGPParameter  tagFieldsParameter   = paramvalues.get_Element(in_attributeSelectorNumber) as IGPParameter;
                IGPMultiValue tagCollectionGPValue = execute_Utilities.UnpackGPValue(tagFieldsParameter) as IGPMultiValue;

                if (tagCollectionGPValue == null)
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), tagFieldsParameter.Name));
                    return;
                }


                IFeatureClass osmFeatureClass = null;
                ITable        osmInputTable   = null;
                IQueryFilter  osmQueryFilter  = null;

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

                try
                {
                    if (osmInputTable == null)
                    {
                        execute_Utilities.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 the Field doesn't exist - wasn't found (index = -1) get out
                if (osmTagCollectionFieldIndex == -1)
                {
                    message.AddError(120005, resourceManager.GetString("GPTools_OSMGPAttributeSelector_notagfieldfound"));
                    return;
                }

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

                if (stepProgressor != null)
                {
                    int featureCount = osmInputTable.RowCount(osmQueryFilter);

                    stepProgressor.MinRange  = 0;
                    stepProgressor.MaxRange  = featureCount;
                    stepProgressor.Position  = 0;
                    stepProgressor.Message   = resourceManager.GetString("GPTools_OSMGPCombineAttributes_progressMessage");
                    stepProgressor.StepValue = 1;
                    stepProgressor.Show();
                }

                String illegalCharacters = String.Empty;

                ISQLSyntax sqlSyntax = ((IDataset)osmInputTable).Workspace as ISQLSyntax;
                if (sqlSyntax != null)
                {
                    illegalCharacters = sqlSyntax.GetInvalidCharacters();
                }

                // establish the list of field indexes only once
                Dictionary <string, int> fieldIndexes = new Dictionary <string, int>();
                for (int selectedGPValueIndex = 0; selectedGPValueIndex < tagCollectionGPValue.Count; selectedGPValueIndex++)
                {
                    // find the field index
                    int fieldIndex = osmInputTable.FindField(tagCollectionGPValue.get_Value(selectedGPValueIndex).GetAsText());

                    if (fieldIndex != -1)
                    {
                        string tagKeyName = osmInputTable.Fields.get_Field(fieldIndex).Name;

                        tagKeyName = OSMToolHelper.convert2OSMKey(tagKeyName, illegalCharacters);

                        fieldIndexes.Add(tagKeyName, fieldIndex);
                    }
                }

                ICursor updateCursor = null;
                IRow    osmRow       = null;

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    updateCursor = osmInputTable.Update(osmQueryFilter, false);
                    comReleaser.ManageLifetime(updateCursor);

                    osmRow = updateCursor.NextRow();
                    int progressIndex = 0;

                    while (osmRow != null)
                    {
                        // get the current tag collection from the row
                        ESRI.ArcGIS.OSM.OSMClassExtension.tag[] osmTags = osmUtility.retrieveOSMTags(osmRow, osmTagCollectionFieldIndex, ((IDataset)osmInputTable).Workspace);

                        Dictionary <string, string> tagsDictionary = new Dictionary <string, string>();
                        for (int tagIndex = 0; tagIndex < osmTags.Length; tagIndex++)
                        {
                            tagsDictionary.Add(osmTags[tagIndex].k, osmTags[tagIndex].v);
                        }

                        // look if the tag needs to be updated or added
                        bool tagsUpdated = false;
                        foreach (var fieldItem in fieldIndexes)
                        {
                            object fldValue = osmRow.get_Value(fieldItem.Value);
                            if (fldValue != System.DBNull.Value)
                            {
                                if (tagsDictionary.ContainsKey(fieldItem.Key))
                                {
                                    if (!tagsDictionary[fieldItem.Key].Equals(fldValue))
                                    {
                                        tagsDictionary[fieldItem.Key] = Convert.ToString(fldValue);
                                        tagsUpdated = true;
                                    }
                                }
                                else
                                {
                                    tagsDictionary.Add(fieldItem.Key, Convert.ToString(fldValue));
                                    tagsUpdated = true;
                                }
                            }
                            else
                            {
                                if (tagsDictionary.ContainsKey(fieldItem.Key))
                                {
                                    tagsDictionary.Remove(fieldItem.Key);
                                    tagsUpdated = true;
                                }
                            }
                        }

                        if (tagsUpdated)
                        {
                            List <ESRI.ArcGIS.OSM.OSMClassExtension.tag> updatedTags = new List <ESRI.ArcGIS.OSM.OSMClassExtension.tag>();

                            foreach (var tagItem in tagsDictionary)
                            {
                                ESRI.ArcGIS.OSM.OSMClassExtension.tag newTag = new ESRI.ArcGIS.OSM.OSMClassExtension.tag();
                                newTag.k = tagItem.Key;
                                newTag.v = tagItem.Value;
                                updatedTags.Add(newTag);
                            }

                            // insert the tags back into the collection field
                            if (updatedTags.Count != 0)
                            {
                                osmUtility.insertOSMTags(osmTagCollectionFieldIndex, osmRow, updatedTags.ToArray(), ((IDataset)osmInputTable).Workspace);

                                updateCursor.UpdateRow(osmRow);
                            }
                        }

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

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

                        osmRow = updateCursor.NextRow();
                    }

                    if (stepProgressor != null)
                    {
                        stepProgressor.Hide();
                    }
                }
            }
            catch (Exception ex)
            {
                message.AddError(120007, ex.Message);
            }
        }
Esempio n. 15
0
        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();
                }

                IGPValue      inputLayersGPValue    = gpUtilities3.UnpackGPValue(paramvalues.get_Element(in_LayersNumber));
                IGPMultiValue inputLayersMultiValue = gpUtilities3.UnpackGPValue(inputLayersGPValue) as IGPMultiValue;

                IGPParameter      outputGroupLayerParameter = paramvalues.get_Element(out_groupLayerNumber) as IGPParameter;
                IGPValue          outputGPGroupLayer        = gpUtilities3.UnpackGPValue(outputGroupLayerParameter);
                IGPCompositeLayer outputCompositeLayer      = outputGPGroupLayer as IGPCompositeLayer;

                if (outputCompositeLayer == null)
                {
                    message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), outputGroupLayerParameter.Name));
                    return;
                }


                IGroupLayer groupLayer = null;

                // find the last position of the "\" string
                // in case we find such a thing, i.e. position is >= -1 then let's assume that we are dealing with a layer file on disk
                // otherwise let's create a new group layer instance
                string outputGPLayerNameAsString = outputGPGroupLayer.GetAsText();
                int    separatorPosition         = outputGPLayerNameAsString.LastIndexOf(System.IO.Path.DirectorySeparatorChar);
                string layerName = String.Empty;

                if (separatorPosition > -1)
                {
                    layerName = outputGPGroupLayer.GetAsText().Substring(separatorPosition + 1);
                }
                else
                {
                    layerName = outputGPGroupLayer.GetAsText();
                }

                ILayer   foundLayer      = null;
                IGPLayer existingGPLayer = gpUtilities3.FindMapLayer2(layerName, out foundLayer);

                if (foundLayer != null)
                {
                    gpUtilities3.RemoveFromMapEx((IGPValue)existingGPLayer);
                    gpUtilities3.RemoveInternalLayerEx(foundLayer);
                }

                groupLayer = new GroupLayer();
                ((ILayer)groupLayer).Name = layerName;

                for (int layerIndex = 0; layerIndex < inputLayersMultiValue.Count; layerIndex++)
                {
                    IGPValue gpLayerToAdd = inputLayersMultiValue.get_Value(layerIndex) as IGPValue;

                    ILayer sourceLayer = gpUtilities3.DecodeLayer(gpLayerToAdd);

                    groupLayer.Add(sourceLayer);
                }

                outputGPGroupLayer = gpUtilities3.MakeGPValueFromObject(groupLayer);

                if (separatorPosition > -1)
                {
                    try
                    {
                        // in the case that we are dealing with a layer file on disk
                        // let's persist the group layer information into the file
                        ILayerFile pointLayerFile = new LayerFileClass();

                        if (System.IO.Path.GetExtension(outputGPLayerNameAsString).ToUpper().Equals(".LYR"))
                        {
                            if (pointLayerFile.get_IsPresent(outputGPLayerNameAsString))
                            {
                                try
                                {
                                    gpUtilities3.Delete(outputGPGroupLayer);
                                }
                                catch (Exception ex)
                                {
                                    message.AddError(120001, ex.Message);
                                    return;
                                }
                            }

                            pointLayerFile.New(outputGPLayerNameAsString);

                            pointLayerFile.ReplaceContents(groupLayer);

                            pointLayerFile.Save();
                        }

                        outputGPGroupLayer = gpUtilities3.MakeGPValueFromObject(pointLayerFile.Layer);
                    }
                    catch (Exception ex)
                    {
                        message.AddError(120002, ex.Message);
                        return;
                    }
                }

                gpUtilities3.PackGPValue(outputGPGroupLayer, outputGroupLayerParameter);
            }
            catch (Exception ex)
            {
                message.AddError(120049, ex.Message);
            }
        }
        /// <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_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_DIFF_STEP_NAMES))
                {
                    m_flagDifferingStepNames = true;
                }
                else if (strVal.Equals(C_OPT_GROUPS_WITHOUT_EMAILS))
                {
                    m_flagGroupsWithoutEmails = true;
                }
                else if (strVal.Equals(C_OPT_GROUPS_WITHOUT_PRIVILEGES))
                {
                    m_flagGroupsWithoutPrivileges = true;
                }
                else if (strVal.Equals(C_OPT_GROUPS_WITHOUT_USERS))
                {
                    m_flagGroupsWithoutUsers = true;
                }
                else if (strVal.Equals(C_OPT_INVALID_JOB_ASSIGN))
                {
                    m_flagInvalidJobAssign = true;
                }
                else if (strVal.Equals(C_OPT_INVALID_JOB_TYPE_ASSIGN))
                {
                    m_flagInvalidJobTypeAssign = true;
                }
                else if (strVal.Equals(C_OPT_INVALID_STEP_ASSIGN))
                {
                    m_flagInvalidStepAssign = true;
                }
                else if (strVal.Equals(C_OPT_IS_SELF_PARENT))
                {
                    m_flagIsSelfParent = true;
                }
                else if (strVal.Equals(C_OPT_JOBS_WITHOUT_TYPES))
                {
                    m_flagJobsWithoutTypes = true;
                }
                else if (strVal.Equals(C_OPT_JOB_TYPES_WITHOUT_WORKFLOWS))
                {
                    m_flagJobTypesWithoutWorkflows = true;
                }
                else if (strVal.Equals(C_OPT_MISSING_AOI_MXDS))
                {
                    m_flagMissingAoiMxds = true;
                }
                else if (strVal.Equals(C_OPT_MISSING_BASE_MXDS))
                {
                    m_flagMissingBaseMxds = true;
                }
                else if (strVal.Equals(C_OPT_NON_ACTIVE_JOB_TYPES))
                {
                    m_flagNonActiveJobTypes = true;
                }
                else if (strVal.Equals(C_OPT_UNASSIGNED_STEPS))
                {
                    m_flagUnassignedSteps = true;
                }
                else if (strVal.Equals(C_OPT_USERS_WITHOUT_EMAILS))
                {
                    m_flagUsersWithoutEmails = true;
                }
                else if (strVal.Equals(C_OPT_USERS_WITHOUT_GROUPS))
                {
                    m_flagUsersWithoutGroups = true;
                }
                else if (strVal.Equals(C_OPT_ZERO_PCT_STEPS))
                {
                    m_flagZeroPctSteps = true;
                }
            }

            param         = paramMap.GetParam(C_PARAM_OUT_LOG_FILE_PATH);
            m_logFilePath = param.Value.GetAsText();
        }