public static esriFieldType ReturnFieldType(IDataset dataset, String fieldName) { if (dataset == null) { throw new ArgumentNullException("dataset"); } IFields2 fields = null; if (dataset.Type == esriDatasetType.esriDTTable) { fields = ((ITable)dataset).Fields as IFields2; } else if (dataset.Type == esriDatasetType.esriDTFeatureClass) { fields = ((IFeatureClass)dataset).Fields as IFields2; } int fdIdx = -1; ISQLSyntax SQLsyn = dataset.Workspace as ISQLSyntax; fields.FindFieldIgnoreQualification(SQLsyn, fieldName, out fdIdx); if (fdIdx != -1) { IField aFd = fields.Field[fdIdx]; Debug.WriteLine(aFd.Name); Debug.WriteLine(aFd.Type.ToString()); return(aFd.Type); } throw new Exception("Cannot find this field"); }
/// <summary> /// Attempts to open a given table /// </summary> /// <param name="tablename">The unqualified name of the table to be opened. /// The table name will be qualfied within this function</param> /// <returns>A reference to the ITable</returns> public ITable FindTable(String name) { if (name == null || 1 > name.Length) { _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "FindTable", "Name not set."); throw new ArgumentException("table name not specified"); } if (_currentWorkspace == null) { _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "FindTable", "Current workspace not set."); throw new Exception("Telecom workspace is not set."); } // Dictionary cached lookup ITable value = null; if (_tables.ContainsKey(name)) { value = _tables[name]; } else { // get qualified name from connection properties. ISQLSyntax sqlsyntax = _currentWorkspace as ISQLSyntax; string qualifiedName = sqlsyntax.QualifyTableName(_dbName, _ownerName, name); value = _currentWorkspace.OpenTable(qualifiedName); // Store the ITable ref in the cache. _tables.Add(name, value); } return(value); }
/// <summary> /// Checks if the input string contains database specific invalid characters /// </summary> /// <param name="name">string to test for invalid characters</param> /// <param name="message">If name fails then this variable will contain a description</param> /// <returns>False if passed. True if failed.</returns> public bool ContainsInvalidCharacters(string name, out string message) { // Validate Input Arguments if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException("name", "Name argument cannot be null or empty"); } // Get array of invalid characters ISQLSyntax sqlSyntax = (ISQLSyntax)this._workspace; string invalidCharacters = sqlSyntax.GetInvalidCharacters(); char[] invalidCharacters2 = invalidCharacters.ToCharArray(); // Get index of first occuring invalid character int index = name.IndexOfAny(invalidCharacters2); if (index != -1) { message = string.Format( "The text '{0}' contains one or more of the following invalid characters '{1}'", name, invalidCharacters); return(true); } // No Errors message = null; // Return false (Name does NOT contain any invalid characters) return(false); }
public SQLFormatter(ITable table) { _table = table; if (_table != null) { ISQLSyntax sqlSyntax = (ISQLSyntax)((IDataset)_table).Workspace; _isCaseSensitive = (sqlSyntax.GetDelimitedIdentifierCase() == true); _prefix = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); _suffix = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); } }
private List <WorkspaceInfoViewModel> LoadWorkspaceInfosFromArcMap() { var result = new List <WorkspaceInfoViewModel>(); var workspaces = ArcmapUtils.EnumerateAllWorkspaces(Ioc.GetOrCreate <IApplication>()); foreach (IWorkspace workspace in workspaces) { WorkspaceInfoViewModel info = new WorkspaceInfoViewModel(); info.Path = workspace.PathName; info.Name = Path.GetFileNameWithoutExtension(info.Path); ISQLSyntax sqlSyntax = workspace as ISQLSyntax; if (sqlSyntax != null) { info.StringComparisonCaseSensitive = sqlSyntax.GetStringComparisonCase(); info.IdentifierCaseSensitive = sqlSyntax.GetIdentifierCase(); info.QuotedIdentifierCaseSensitive = sqlSyntax.GetDelimitedIdentifierCase(); info.InvalidCharactersForIdentifiers = sqlSyntax.GetInvalidCharacters(); foreach (var enumName in Enum.GetValues(typeof(esriSQLFunctionName))) { string enumValue = sqlSyntax.GetFunctionName((esriSQLFunctionName)enumName); if (string.IsNullOrEmpty(enumValue)) { enumValue = NotAvailable; } info.SqlFunctions.AddOrReplace(enumName.ToString(), enumValue); } info.SqlFunctions.Sort((x, y) => string.Compare(x.Key, y.Key, StringComparison.InvariantCultureIgnoreCase)); foreach (var enumName in Enum.GetValues(typeof(esriSQLSpecialCharacters))) { string enumValue = sqlSyntax.GetSpecialCharacter((esriSQLSpecialCharacters)enumName); if (string.IsNullOrEmpty(enumValue)) { enumValue = string.Empty; } info.SpecialCharacters.AddOrReplace(enumName.ToString(), enumValue); } info.SpecialCharacters.Sort((x, y) => string.Compare(x.Key, y.Key, StringComparison.InvariantCultureIgnoreCase)); foreach (string keyword in sqlSyntax.GetKeywords().Enumerate()) { info.ReservedWords.Add(keyword); } info.ReservedWords.Sort(StringComparer.InvariantCultureIgnoreCase); } result.Add(info); } return(result); }
public static string GetDatasetName(IDataset ds) { if (ds != null) { ISQLSyntax sqlSyntax = ds.Workspace as ISQLSyntax; string dbName, ownerName, tableName; sqlSyntax.ParseTableName(ds.Name, out dbName, out ownerName, out tableName); return(tableName); } return(""); }
public static string ParseTableName(IDataset dataset) { if (dataset == null) { throw new ArgumentNullException("dataset"); } string dbName = string.Empty; string tableName = string.Empty; string ownerName = string.Empty; ISQLSyntax syntax = (ISQLSyntax)dataset.Workspace; syntax.ParseTableName(dataset.Name, out dbName, out ownerName, out tableName); return(tableName); }
//OK public string GetDataSetName(IFeatureClass featureClass) { IDataset dataSet = featureClass as IDataset; ISQLSyntax sqlSyntax = dataSet.Workspace as ISQLSyntax; if (sqlSyntax != null) { string dataName = string.Empty; string dbName = string.Empty; string ownerName = string.Empty; sqlSyntax.ParseTableName(dataSet.Name, out dbName, out ownerName, out dataName); return(dataName); } else { return(dataSet.Name); } }
private bool method_0(string string_0, IWorkspaceReplicas iworkspaceReplicas_0) { ISQLSyntax syntax = iworkspaceReplicas_0 as ISQLSyntax; IEnumReplica replicas = iworkspaceReplicas_0.Replicas; replicas.Reset(); for (IReplica replica2 = replicas.Next(); replica2 != null; replica2 = replicas.Next()) { if (replica2.ReplicaRole == esriReplicaType.esriCheckOutTypeParent) { string str = syntax.QualifyTableName("", replica2.Owner, replica2.Version); if (string_0.ToLower() == str.ToLower()) { return(true); } } } return(false); }
public static string GetSpecialCharacter(IDataset pDS, esriSQLSpecialCharacters specChar) { IWorkspace pWorkspace = pDS.Workspace; //if (pWorkspace is ShapefileWorkspaceFactory) //{ // if (specChar == esriSQLSpecialCharacters.esriSQL_WildcardManyMatch) return "%"; // if (specChar == esriSQLSpecialCharacters.esriSQL_WildcardSingleMatch) return "%"; // if (specChar == esriSQLSpecialCharacters.esriSQL_WildcardManyMatch) return "%"; // if (specChar == esriSQLSpecialCharacters.esriSQL_WildcardManyMatch) return "%"; // if (specChar == esriSQLSpecialCharacters.esriSQL_WildcardManyMatch) return "%"; //} ISQLSyntax sqlSyntax = pWorkspace as ISQLSyntax; if (sqlSyntax == null) { return(""); } return(sqlSyntax.GetSpecialCharacter(specChar)); }
public static string QualifyClassName(IWorkspace theWorkspace, string givenClassName) { if (theWorkspace.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace) { string dbName = ((IDataset)theWorkspace).Name; // ------- TROUBLE --------- // I don't know how to handle situations where the owner is not DBO. // ------- TROUBLE --------- string owner = "DBO"; ISQLSyntax Qualifier = (ISQLSyntax)theWorkspace; return(Qualifier.QualifyTableName(dbName, owner, givenClassName)); } else { return(givenClassName); } }
protected bool InWorkspace(IWorkspace2 wksp2, esriDatasetType type, String name) { ISQLSyntax sqlSyntax = (ISQLSyntax)wksp2; String fqname = sqlSyntax.QualifyTableName(_dbName, _ownerName, name); bool result = true; IWorkspace workspace = wksp2 as IWorkspace; if (wksp2.get_NameExists(type, fqname)) { _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Exists check: " + fqname, "PASS"); } else { _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Exists check: " + fqname, "FAIL"); return(false); } return(result); }
public static ITable OpenTable(string TableName) { string tableName; ITable table; if (CommonClass.m_pWorkspace == null) { CommonClass.m_pWorkspace = AppConfigInfo.GetWorkspace(); } if (CommonClass.m_pWorkspace != null) { object item = CommonClass.m_hash[TableName]; if (item != null) { table = item as ITable; } else { if (TableName.IndexOf(".") != -1) { tableName = TableName; } else { ISQLSyntax workspace = CommonClass.Workspace as ISQLSyntax; tableName = workspace.QualifyTableName(CommonClass.Database, CommonClass.User, TableName); } ITable table1 = (CommonClass.m_pWorkspace as IFeatureWorkspace).OpenTable(tableName); CommonClass.m_hash[TableName] = table1; table = table1; } } else { table = null; } return(table); }
//--------------------------------------------------------------------- /// <summary> /// Determines whether the layer passed is an HLU layer, sets all related fields except _hluView /// (which it cannot obtain from the layer) and sets up the selection changed event handler for the /// layer if it is an HLU layer. /// </summary> /// <param name="layer"></param> /// <returns></returns> private bool IsHluLayer(IFeatureLayer layer) { try { //--------------------------------------------------------------------- // CHANGED: CR31 (Switching between GIS layers) // Don't update the class properties unless an HLU layer (_hluLayer) // has not already been selected so that other feature layers can // be examined to see if they are also valid HLU layers (without // overwritting the class properties of the first layer). int[] hluFieldMap; string[] hluFieldNames; if (HluDbIsRunning && ArcMapAppHelperClass.IsHluLayer(layer, new FieldsClass(), new FieldCheckerClass(), _validWorkspaces, _typeMapSystemToSql, ref _hluLayerStructure, out hluFieldMap, out hluFieldNames)) { IFeatureLayer hluLayer = layer as IFeatureLayer; IFeatureClass hluFeatureClass = hluLayer.FeatureClass; IWorkspace hluWorkspace = ((IDataset)hluFeatureClass).Workspace; IFeatureWorkspace hluWS = hluWorkspace as IFeatureWorkspace; if ((!_pipeCalling) || (_hluLayer == null)) SetupSelectionChangedEvent(hluLayer); int[] hluUidFieldOrdinals = new int[3]; hluUidFieldOrdinals[0] = hluFieldMap[_hluLayerStructure.incidColumn.Ordinal]; hluUidFieldOrdinals[1] = hluFieldMap[_hluLayerStructure.toidColumn.Ordinal]; hluUidFieldOrdinals[2] = hluFieldMap[_hluLayerStructure.toid_fragment_idColumn.Ordinal]; string[] hluFieldSysTypeNames = new string[hluFeatureClass.Fields.FieldCount]; Type sysType; for (int i = 0; i < hluFeatureClass.Fields.FieldCount; i++) { if (_typeMapSQLToSystem.TryGetValue((int)hluFeatureClass.Fields.get_Field(i).Type, out sysType)) hluFieldSysTypeNames[i] = sysType.FullName; } string hluTableName = ((IDataset)hluFeatureClass).Name; ISQLSyntax hluSqlSyntax = (ISQLSyntax)hluWS; string quotePrefix = hluSqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string quoteSuffix = hluSqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); if (_hluLayer == null) { _hluLayer = hluLayer; _hluFeatureClass = hluFeatureClass; _hluWS = hluWS; _hluWSisSDE = hluWorkspace.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace; _hluUidFieldOrdinals = hluUidFieldOrdinals; _hluFieldSysTypeNames = hluFieldSysTypeNames; _hluTableName = hluTableName; _hluSqlSyntax = hluSqlSyntax; _quotePrefix = quotePrefix; _quoteSuffix = quoteSuffix; _hluFieldMap = hluFieldMap; _hluFieldNames = hluFieldNames; } //--------------------------------------------------------------------- return true; } else { return false; } } catch { _hluLayer = null; _hluFeatureClass = null; _hluTableName = null; _hluWS = null; _hluWSisSDE = false; _hluView = null; _hluFieldMap = null; _hluFieldNames = null; _hluUidFieldOrdinals = null; _selectFieldOrdinals = null; _hluSqlSyntax = null; _quotePrefix = null; _quoteSuffix = null; return false; } }
/// <summary> /// Determines whether at least one of the layers in all the maps is an HLU layer /// and returns the field mapping of the first HLU layer found, plus a list of all /// the HLU layers found. /// Triggered from ArcMapApp after the required document has been opened. /// </summary> /// <param></param> /// <returns></returns> public void IsHluWorkspace() { IFeatureLayer hluLayerBak = _hluLayer; int[] hluFieldMapBak = _hluFieldMap; string[] hluFieldNamesBak = _hluFieldNames; IFeatureClass hluFeatureClassBak = _hluFeatureClass; IFeatureWorkspace hluWSBak = _hluWS; string hluTableNameBak = _hluTableName; ISQLSyntax hluSqlSyntaxBak = _hluSqlSyntax; string quotePrefixBak = _quotePrefix; string quoteSuffixBak = _quoteSuffix; _pipeCalling = true; if (_pipeData == null) _pipeData = new List<string>(); try { lock (_pipeData) { // clear the pipe _pipeData.Clear(); _hluLayer = null; IMaps maps = ((IMxDocument)_application.Document).Maps; IMap map = null; UID uid = new UIDClass(); uid.Value = typeof(IFeatureLayer).GUID.ToString("B"); for (int i = 0; i < maps.Count; i++) { map = maps.get_Item(i); int j = 0; IEnumLayer layers = map.get_Layers(uid, true); ILayer layer = layers.Next(); while (layer != null) { //--------------------------------------------------------------------- // CHANGED: CR19 (Feature layer position in GIS) // Only check geofeature layers in the document (to see if they are // valid HLU layers) to save having to check layers (e.g. coverage // annotation layers) that can't possibly be valid. if (layer is IGeoFeatureLayer) { IFeatureLayer featureLayer = layer as IFeatureLayer; if (IsHluLayer(featureLayer)) { _hluView = map as IActiveView; // Return details of the first valid HLU layer found (the map number, // map name, layer number, field indexes and field names). _pipeData.AddRange(new string[] { i.ToString(), map.Name, j.ToString() }); _pipeData.Add(_pipeTransmissionInterrupt); _pipeData.AddRange(_hluFieldMap.Select(ix => ix.ToString())); _pipeData.Add(_pipeTransmissionInterrupt); _pipeData.AddRange(_hluFieldNames); return; } } //--------------------------------------------------------------------- layer = layers.Next(); j++; } } } } catch { } finally { _pipeCalling = false; _hluLayer = hluLayerBak; _hluFieldMap = hluFieldMapBak; _hluFieldNames = hluFieldNamesBak; _hluFeatureClass = hluFeatureClassBak; _hluWS = hluWSBak; _hluTableName = hluTableNameBak; _hluSqlSyntax = hluSqlSyntaxBak; _quotePrefix = quotePrefixBak; _quoteSuffix = quoteSuffixBak; } }
public void FindFieldIgnoreQualification(ISQLSyntax sqlSyntax, string Name, out int Index) { throw new Exception("The method or operation is not implemented."); }
void OnChangeFeature(ESRI.ArcGIS.Geodatabase.IObject obj) { // Don't do anything if the extension is disabled if (IsExtensionEnabled != true) { return; } // Bail if this is not a valid NCGMP workspace if (m_DatabaseIsValid == false) { return; } #region "Groundwork" // Grab the FeatureClass name from the Row's Table (as an IDataset). IRow theRow = obj; ITable theTable = theRow.Table; IDataset theDS = (IDataset)theTable; string TableName = theDS.Name; // Parse the table name in order to strip out unneccessary bits of SDE tables ISQLSyntax nameParser = (ISQLSyntax)theDS.Workspace; string parsedDbName, parsedOwnerName, parsedTableName; nameParser.ParseTableName(TableName, out parsedDbName, out parsedOwnerName, out parsedTableName); #endregion #region "Calculate SymbolRotation" if (m_DatabaseUsesRepresentation == true) { if (parsedTableName == "OrientationPoints") { // Get the Azimuth from the feature - this is ugly -- why is this m_identifier a double? int Azimuth = (int)Math.Round((double)theRow.get_Value(theTable.FindField("Azimuth")), 0); // Calculate the stupid form of rotation... int Rotation = CalculateSymbolRotation(Azimuth); // Set the SymbolRotation Field theRow.set_Value(theTable.FindField("SymbolRotation"), double.Parse(Rotation.ToString())); } } #endregion // Debugging flag to turn off repositioning of related data when stations are edited: bool adjustLocations = false; if (adjustLocations == true) { #region "Adjust Samples/OrientationPoints to Match Stations" if (parsedTableName == "Stations") { // Cast the obj as a Feature in order to access Geometry information IFeature theStation = (IFeature)obj; IGeometry stationGeom = theStation.ShapeCopy; // Find related Samples IRelationshipClass stationSampleLink = commonFunctions.OpenRelationshipClass(m_EditWorkspace, "StationSampleLink"); ESRI.ArcGIS.esriSystem.ISet relatedSamples = stationSampleLink.GetObjectsRelatedToObject(obj); // Loop through the related Samples and set their Geometry to that of the Station relatedSamples.Reset(); IFeature aSample = (IFeature)relatedSamples.Next(); while (aSample != null) { aSample.Shape = stationGeom; aSample.Store(); aSample = (IFeature)relatedSamples.Next(); } // Find related OrientationPoints IRelationshipClass stationStructureLink = commonFunctions.OpenRelationshipClass(m_EditWorkspace, "StationOrientationPointsLink"); ESRI.ArcGIS.esriSystem.ISet relatedStructures = stationStructureLink.GetObjectsRelatedToObject(obj); // Loop through the related OrientationPoints and set their Geometry to that of the Station relatedStructures.Reset(); IFeature aStructure = (IFeature)relatedStructures.Next(); while (aStructure != null) { aStructure.Shape = stationGeom; aStructure.Store(); aStructure = (IFeature)relatedStructures.Next(); } } #endregion } }
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(); } // find feature class inside the given feature dataset IGPParameter osmFeatureDatasetParameter = paramvalues.get_Element(in_osmFeatureDatasetNumber) as IGPParameter; IDEFeatureDataset osmFeatureDataset = gpUtilities3.UnpackGPValue(osmFeatureDatasetParameter) as IDEFeatureDataset; string osmPointFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_pt"; string osmLineFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_ln"; string osmPolygonFeatureClassString = ((IDataElement)osmFeatureDataset).Name + "_osm_ply"; IFeatureClass osmPointFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmPointFeatureClassString); IFeatureClass osmLineFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmLineFeatureClassString); IFeatureClass osmPoylgonFeatureClass = gpUtilities3.OpenFeatureClassFromString(((IDataElement)osmFeatureDataset).CatalogPath + "/" + osmPolygonFeatureClassString); // open the specified layers holding the symbology and editing templates IGPParameter osmPointSymbolTemplateParameter = paramvalues.get_Element(in_osmPointLayerNumber) as IGPParameter; IGPValue osmGPPointLayerValue = gpUtilities3.UnpackGPValue(osmPointSymbolTemplateParameter); IGPParameter outputPointGPParameter = paramvalues.get_Element(out_osmPointLayerNumber) as IGPParameter; IGPValue outputPointLayerGPValue = gpUtilities3.UnpackGPValue(outputPointGPParameter); bool isLayerOnDisk = false; // create a clone of the source layer // we will then go ahead and adjust the data source (dataset) of the cloned layer IObjectCopy objectCopy = new ObjectCopyClass(); ICompositeLayer adjustedPointTemplateLayer = objectCopy.Copy(osmGPPointLayerValue) as ICompositeLayer; IGPGroupLayer osmPointGroupTemplateLayer = adjustedPointTemplateLayer as IGPGroupLayer; ICompositeLayer compositeLayer = gpUtilities3.Open((IGPValue)osmPointGroupTemplateLayer) as ICompositeLayer; //ICompositeLayer adjustedPointTemplateLayer = osmGPPointLayerValue as ICompositeLayer; //IGPGroupLayer osmPointGroupTemplateLayer = osmGPPointLayerValue as IGPGroupLayer; //IClone cloneSource = osmPointGroupTemplateLayer as IClone; //ICompositeLayer compositeLayer = m_gpUtilities3.Open((IGPValue)cloneSource.Clone()) as ICompositeLayer; if (compositeLayer == null) { ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass(); IFileName layerFileName = new FileNameClass(); layerFileName.Path = osmGPPointLayerValue.GetAsText(); IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName); enumLayer.Reset(); compositeLayer = enumLayer.Next() as ICompositeLayer; isLayerOnDisk = true; } IFeatureLayerDefinition2 featureLayerDefinition2 = null; ISQLSyntax sqlSyntax = null; IGPLayer adjustedPointGPLayer = null; if (compositeLayer != null) { for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++) { IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2; if (geoFeatureLayer != null) { if (geoFeatureLayer.ShapeType == osmPointFeatureClass.ShapeType) { try { ((IDataLayer2)geoFeatureLayer).Disconnect(); } catch { } ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmPointFeatureClass).FullName; ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmPointFeatureClass).FullName); featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2; if (featureLayerDefinition2 != null) { string queryDefinition = featureLayerDefinition2.DefinitionExpression; sqlSyntax = ((IDataset)osmPointFeatureClass).Workspace as ISQLSyntax; string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); if (String.IsNullOrEmpty(queryDefinition) == false) { string stringToReplace = queryDefinition.Substring(0, 1); queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier); } featureLayerDefinition2.DefinitionExpression = queryDefinition; } } } } adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); // save the newly adjusted layer information to disk if (isLayerOnDisk == true) { ILayerFile pointLayerFile = new LayerFileClass(); if (pointLayerFile.get_IsPresent(outputPointLayerGPValue.GetAsText())) { try { File.Delete(outputPointLayerGPValue.GetAsText()); } catch (Exception ex) { message.AddError(120041, ex.Message); return; } } pointLayerFile.New(outputPointLayerGPValue.GetAsText()); pointLayerFile.ReplaceContents((ILayer)compositeLayer); pointLayerFile.Save(); adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)pointLayerFile.Layer); } // IGPLayer adjustedPointGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustedPointGPLayer); gpUtilities3.PackGPValue((IGPValue)adjustedPointGPLayer, outputPointGPParameter); } isLayerOnDisk = false; IGPParameter osmLineSymbolTemplateParameter = paramvalues.get_Element(in_osmLineLayerNumber) as IGPParameter; IGPValue osmGPLineLayerValue = gpUtilities3.UnpackGPValue(osmLineSymbolTemplateParameter) as IGPValue; IGPParameter outputLineGPParameter = paramvalues.get_Element(out_osmLineLayerNumber) as IGPParameter; IGPValue outputLineLayerGPValue = gpUtilities3.UnpackGPValue(outputLineGPParameter); IGPValue adjustedLineTemplateLayer = objectCopy.Copy(osmGPLineLayerValue) as IGPValue; IGPGroupLayer osmLineGroupTemplateLayer = adjustedLineTemplateLayer as IGPGroupLayer; compositeLayer = gpUtilities3.Open((IGPValue)osmLineGroupTemplateLayer) as ICompositeLayer; if (compositeLayer == null) { ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass(); IFileName layerFileName = new FileNameClass(); layerFileName.Path = osmGPLineLayerValue.GetAsText(); IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName); enumLayer.Reset(); compositeLayer = enumLayer.Next() as ICompositeLayer; isLayerOnDisk = true; } if (compositeLayer != null) { for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++) { IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2; if (geoFeatureLayer.ShapeType == osmLineFeatureClass.ShapeType) { try { ((IDataLayer2)geoFeatureLayer).Disconnect(); } catch { } ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmLineFeatureClass).FullName; ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmLineFeatureClass).FullName); featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2; if (featureLayerDefinition2 != null) { string queryDefinition = featureLayerDefinition2.DefinitionExpression; sqlSyntax = ((IDataset)osmLineFeatureClass).Workspace as ISQLSyntax; string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); if (string.IsNullOrEmpty(queryDefinition) == false) { string stringToReplace = queryDefinition.Substring(0, 1); queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier); } featureLayerDefinition2.DefinitionExpression = queryDefinition; } } } // save the newly adjusted layer information to disk if (isLayerOnDisk == true) { ILayerFile lineLayerFile = new LayerFileClass(); if (lineLayerFile.get_IsPresent(outputLineLayerGPValue.GetAsText())) { try { File.Delete(outputLineLayerGPValue.GetAsText()); } catch (Exception ex) { message.AddError(120042, ex.Message); return; } } lineLayerFile.New(outputLineLayerGPValue.GetAsText()); lineLayerFile.ReplaceContents((ILayer)compositeLayer); lineLayerFile.Save(); } IGPLayer adjustLineGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustLineGPLayer); gpUtilities3.PackGPValue((IGPValue)adjustLineGPLayer, outputLineGPParameter); } isLayerOnDisk = false; IGPParameter osmPolygonSymbolTemplateParameter = paramvalues.get_Element(in_osmPolygonLayerNumber) as IGPParameter; IGPValue osmGPPolygonLayerValue = gpUtilities3.UnpackGPValue(osmPolygonSymbolTemplateParameter); IGPParameter outputPolygonGPParameter = paramvalues.get_Element(out_osmPolygonLayerNumber) as IGPParameter; IGPValue outputPolygonLayerGPValue = gpUtilities3.UnpackGPValue(outputPolygonGPParameter); IGPValue adjustedPolygonTemplateLayer = objectCopy.Copy(osmGPPolygonLayerValue) as IGPValue; IGPGroupLayer osmPolygonGroupTemplateLayer = adjustedPolygonTemplateLayer as IGPGroupLayer; compositeLayer = gpUtilities3.Open((IGPValue)osmPolygonGroupTemplateLayer) as ICompositeLayer; if (compositeLayer == null) { ILayerFactoryHelper layerFactoryHelper = new LayerFactoryHelperClass(); IFileName layerFileName = new FileNameClass(); layerFileName.Path = osmGPPolygonLayerValue.GetAsText(); IEnumLayer enumLayer = layerFactoryHelper.CreateLayersFromName((IName)layerFileName); enumLayer.Reset(); compositeLayer = enumLayer.Next() as ICompositeLayer; isLayerOnDisk = true; } if (compositeLayer != null) { for (int layerIndex = 0; layerIndex < compositeLayer.Count; layerIndex++) { IFeatureLayer2 geoFeatureLayer = compositeLayer.get_Layer(layerIndex) as IFeatureLayer2; if (geoFeatureLayer.ShapeType == osmPoylgonFeatureClass.ShapeType) { try { ((IDataLayer2)geoFeatureLayer).Disconnect(); } catch { } ((IDataLayer2)geoFeatureLayer).DataSourceName = ((IDataset)osmPoylgonFeatureClass).FullName; ((IDataLayer2)geoFeatureLayer).Connect(((IDataset)osmPoylgonFeatureClass).FullName); featureLayerDefinition2 = geoFeatureLayer as IFeatureLayerDefinition2; if (featureLayerDefinition2 != null) { string queryDefinition = featureLayerDefinition2.DefinitionExpression; sqlSyntax = ((IDataset)osmPoylgonFeatureClass).Workspace as ISQLSyntax; string delimiterIdentifier = sqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); if (String.IsNullOrEmpty(queryDefinition) == false) { string stringToReplace = queryDefinition.Substring(0, 1); queryDefinition = queryDefinition.Replace(stringToReplace, delimiterIdentifier); } featureLayerDefinition2.DefinitionExpression = queryDefinition; } } } // save the newly adjusted layer information to disk if (isLayerOnDisk == true) { ILayerFile polygonLayerFile = new LayerFileClass(); if (polygonLayerFile.get_IsPresent(outputPolygonLayerGPValue.GetAsText())) { try { File.Delete(outputPolygonLayerGPValue.GetAsText()); } catch (Exception ex) { message.AddError(120043, ex.Message); return; } } polygonLayerFile.New(outputPolygonLayerGPValue.GetAsText()); polygonLayerFile.ReplaceContents((ILayer)compositeLayer); polygonLayerFile.Save(); } IGPLayer adjustedPolygonGPLayer = gpUtilities3.MakeGPLayerFromLayer((ILayer)compositeLayer); gpUtilities3.AddInternalLayer2((ILayer)compositeLayer, adjustedPolygonGPLayer); gpUtilities3.PackGPValue((IGPValue)adjustedPolygonGPLayer, outputPolygonGPParameter); } } catch (Exception ex) { message.AddError(-10, ex.Message); } }
protected override void OnClick() { bool bShowProgressor = false; IStepProgressor pStepProgressor = null; //Create a CancelTracker. ITrackCancel pTrackCancel = null; IProgressDialogFactory pProgressorDialogFact; IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); //first get the selected parcel features UID pUID = new UIDClass(); pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}"; ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID); ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID); //check if there is a Manual Mode "modify" job active =========== ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan; if (pCadPacMan.PacketOpen) { MessageBox.Show("The Delete Control command cannot be used when there is an open job.\r\nPlease finish or discard the open job, and try again.", "Delete Selected Control"); return; } IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor"); IActiveView pActiveView = ArcMap.Document.ActiveView; IMap pMap = pActiveView.FocusMap; ICadastralFabric pCadFabric = null; clsFabricUtils FabricUTILS = new clsFabricUtils(); IProgressDialog2 pProgressorDialog = null; //if we're in an edit session then grab the target fabric if (pEd.EditState == esriEditState.esriStateEditing) { pCadFabric = pCadEd.CadastralFabric; } if (pCadFabric == null) {//find the first fabric in the map if (!FabricUTILS.GetFabricFromMap(pMap, out pCadFabric)) { MessageBox.Show ("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again."); return; } } IArray CFControlLayers = new ArrayClass(); if (!(FabricUTILS.GetControlLayersFromFabric(pMap, pCadFabric, out CFControlLayers))) { return; //no fabric sublayers available for the targeted fabric } bool bIsFileBasedGDB = false; bool bIsUnVersioned = false; bool bUseNonVersionedDelete = false; IWorkspace pWS = null; ITable pPointsTable = null; ITable pControlTable = null; try { if (pEd.EditState == esriEditState.esriStateEditing) { try { pEd.StartOperation(); } catch { pEd.AbortOperation();//abort any open edit operations and try again pEd.StartOperation(); } } IFeatureLayer pFL = (IFeatureLayer)CFControlLayers.get_Element(0); IDataset pDS = (IDataset)pFL.FeatureClass; pWS = pDS.Workspace; if (!FabricUTILS.SetupEditEnvironment(pWS, pCadFabric, pEd, out bIsFileBasedGDB, out bIsUnVersioned, out bUseNonVersionedDelete)) { return; } //loop through each control layer and //Get the selection of control int iCnt = 0; int iTotalSelectionCount = 0; for (; iCnt < CFControlLayers.Count; iCnt++) { pFL = (IFeatureLayer)CFControlLayers.get_Element(iCnt); IFeatureSelection pFeatSel = (IFeatureSelection)pFL; ISelectionSet2 pSelSet = (ISelectionSet2)pFeatSel.SelectionSet; iTotalSelectionCount += pSelSet.Count; } if (iTotalSelectionCount == 0) { MessageBox.Show("Please select some fabric control points and try again.", "No Selection", MessageBoxButtons.OK, MessageBoxIcon.Information); if (bUseNonVersionedDelete) { pCadEd.CadastralFabricLayer = null; CFControlLayers = null; } return; } bShowProgressor = (iTotalSelectionCount > 10); if (bShowProgressor) { pProgressorDialogFact = new ProgressDialogFactoryClass(); pTrackCancel = new CancelTrackerClass(); pStepProgressor = pProgressorDialogFact.Create(pTrackCancel, ArcMap.Application.hWnd); pProgressorDialog = (IProgressDialog2)pStepProgressor; pStepProgressor.MinRange = 1; pStepProgressor.MaxRange = iTotalSelectionCount * 2; //(runs through selection twice) pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; } //loop through each control layer and //delete from its selection m_pQF = new QueryFilterClass(); iCnt = 0; for (; iCnt < CFControlLayers.Count; iCnt++) { pFL = (IFeatureLayer)CFControlLayers.get_Element(iCnt); IFeatureSelection pFeatSel = (IFeatureSelection)pFL; ISelectionSet2 pSelSet = (ISelectionSet2)pFeatSel.SelectionSet; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); if (bShowProgressor) { pProgressorDialog.ShowDialog(); pStepProgressor.Message = "Collecting Control point data..."; } //Add the OIDs of all the selected control points into a new feature IDSet string[] sOIDListPoints = { "(" }; int tokenLimit = 995; //int tokenLimit = 5; //temp for testing bool bCont = true; int j = 0; int iCounter = 0; m_pFIDSetControl = new FIDSetClass(); ICursor pCursor = null; pSelSet.Search(null, false, out pCursor);//code deletes all selected control points IFeatureCursor pControlFeatCurs = (IFeatureCursor)pCursor; IFeature pControlFeat = pControlFeatCurs.NextFeature(); int iPointID = pControlFeatCurs.FindField("POINTID"); while (pControlFeat != null) { //Check if the cancel button was pressed. If so, stop process if (bShowProgressor) { bCont = pTrackCancel.Continue(); if (!bCont) { break; } } bool bExists = false; m_pFIDSetControl.Find(pControlFeat.OID, out bExists); if (!bExists) { m_pFIDSetControl.Add(pControlFeat.OID); object obj = pControlFeat.get_Value(iPointID); if (iCounter <= tokenLimit) { //if the PointID is not null add it to a query string as well if (obj != DBNull.Value) { sOIDListPoints[j] += Convert.ToString(obj) + ","; } iCounter++; } else {//maximum tokens reached //set up the next OIDList sOIDListPoints[j] = sOIDListPoints[j].Trim(); iCounter = 0; j++; FabricUTILS.RedimPreserveString(ref sOIDListPoints, 1); sOIDListPoints[j] = "("; if (obj != DBNull.Value) { sOIDListPoints[j] += Convert.ToString(obj) + ","; } } } Marshal.ReleaseComObject(pControlFeat); //garbage collection pControlFeat = pControlFeatCurs.NextFeature(); if (bShowProgressor) { if (pStepProgressor.Position < pStepProgressor.MaxRange) { pStepProgressor.Step(); } } } Marshal.ReleaseComObject(pCursor); //garbage collection if (!bCont) { AbortEdits(bUseNonVersionedDelete, pEd, pWS); return; } if (bUseNonVersionedDelete) { if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) { if (bUseNonVersionedDelete) { pCadEd.CadastralFabricLayer = null; } return; } } //first delete all the control point records if (bShowProgressor) { pStepProgressor.Message = "Deleting control points..."; } bool bSuccess = true; pPointsTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); pControlTable = (ITable)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); if (!bUseNonVersionedDelete) { bSuccess = FabricUTILS.DeleteRowsByFIDSet(pControlTable, m_pFIDSetControl, pStepProgressor, pTrackCancel); } if (bUseNonVersionedDelete) { bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pControlTable, m_pFIDSetControl, pStepProgressor, pTrackCancel); } if (!bSuccess) { AbortEdits(bUseNonVersionedDelete, pEd, pWS); return; } //next need to use an in clause to update the points, ... ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric; //...for each item in the sOIDListPoints array foreach (string inClause in sOIDListPoints) { string sClause = inClause.Trim().TrimEnd(','); if (sClause.EndsWith("(")) { continue; } if (sClause.Length < 3) { continue; } pSchemaEd.ReleaseReadOnlyFields(pPointsTable, esriCadastralFabricTable.esriCFTPoints); m_pQF.WhereClause = (sPref + pPointsTable.OIDFieldName + sSuff).Trim() + " IN " + sClause + ")"; if (!FabricUTILS.ResetPointAssociations(pPointsTable, m_pQF, bIsUnVersioned)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); } } if (bUseNonVersionedDelete) { FabricUTILS.StopEditing(pWS); } if (pEd.EditState == esriEditState.esriStateEditing) { pEd.StopOperation("Delete Control Points"); } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } finally { RefreshMap(pActiveView, CFControlLayers); //update the TOC IMxDocument mxDocument = (ESRI.ArcGIS.ArcMapUI.IMxDocument)(ArcMap.Application.Document); for (int i = 0; i < mxDocument.ContentsViewCount; i++) { IContentsView pCV = (IContentsView)mxDocument.get_ContentsView(i); pCV.Refresh(null); } if (pProgressorDialog != null) { pProgressorDialog.HideDialog(); } if (bUseNonVersionedDelete) { pCadEd.CadastralFabricLayer = null; CFControlLayers = null; } if (pMouseCursor != null) { pMouseCursor.SetCursor(0); } } }
public bool UpdateParcelRecordsByPlanGroup(ITable pParcelsTable, ArrayList sParcelUpdates, Dictionary <string, int> TheNewPlanIDs, Dictionary <int, int> ParcelLookup, bool bUseNonVersionedEdit, IStepProgressor m_pStepProgressor, ITrackCancel TrackCancel) { bool bShowProgressor = (m_pStepProgressor != null && TrackCancel != null); if (bShowProgressor) { m_pStepProgressor.Message = "Updating Parcels..."; } Int32 iPlanID = pParcelsTable.Fields.FindField("PLANID"); IDataset pDS = (IDataset)pParcelsTable; ISQLSyntax pSQLSyntax = (ISQLSyntax)pDS.Workspace; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); IQueryFilter pQF = new QueryFilterClass(); string FieldName = pParcelsTable.OIDFieldName; bool bCont = true; try { foreach (string InClause in sParcelUpdates) { if (InClause.Trim() == "") { continue; } pQF.WhereClause = sPref + FieldName + sSuff + " IN (" + InClause + ")"; ITableWrite2 pParcelsTableWr = (ITableWrite2)pParcelsTable; ICursor pUpdateCur = null; if (bUseNonVersionedEdit) { pUpdateCur = pParcelsTableWr.UpdateRows(pQF, false); } else { pUpdateCur = pParcelsTable.Update(pQF, false); } IRow pRow = pUpdateCur.NextRow(); //now update the parcel planid int iOldPlanID = -1; int iNewPlanID = -1; while (pRow != null) { int iParcelID = pRow.OID; if (!ParcelLookup.TryGetValue(iParcelID, out iOldPlanID)) { continue; } string sNewPlanName = "[" + Convert.ToString(iOldPlanID) + "]"; if (!TheNewPlanIDs.TryGetValue(sNewPlanName, out iNewPlanID)) { continue; } pRow.set_Value(iPlanID, iNewPlanID); pUpdateCur.UpdateRow(pRow); if (bShowProgressor) { if (m_pStepProgressor.Position < m_pStepProgressor.MaxRange) { m_pStepProgressor.Step(); } } Marshal.ReleaseComObject(pRow); //after garbage collection, and before gettng the next row, //check if the cancel button was pressed. If so, stop process if (bShowProgressor) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } pRow = pUpdateCur.NextRow(); } if (pUpdateCur != null) { Marshal.ReleaseComObject(pUpdateCur); } if (!bCont) { break; } } } catch (COMException Ex) { MessageBox.Show("Problem encountered:" + Ex.ErrorCode.ToString() + ":" + Ex.Message, "Update Parcel Records"); if (pQF != null) { Marshal.ReleaseComObject(pQF); } return(false); } if (pQF != null) { Marshal.ReleaseComObject(pQF); } return(bCont); //return the result from the Cancel tracker...true unless cancel was clicked. }
private void RefreshTableArray() { m_array.RemoveAll(); ITable pCadastralTable; IDataset pDS; txtBoxSummary.Text = ""; if (m_pCadaFab == null) { return; } string Suffix; m_RowDropCount = 0; m_ResetAccuracyTableDefaults = false; m_TruncateControl = false; m_TruncateParcelsLinesPoints = false; m_TruncateAdjustmentTables = false; m_TruncateJobTables = false; try { foreach (int checkedItemIndex in checkedListBox1.CheckedIndices) { if (txtBoxSummary.Text.Trim().Length == 0) { Suffix = ""; } else { Suffix = txtBoxSummary.Text + Environment.NewLine; } //Drop all control points if (checkedItemIndex == 0) { pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); m_TruncateControl = true; m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; int RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; string sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = pDS.Name + " (" + sInfo + ")"; } //Drop all plans, parcels, lines, points, and line-points if (checkedItemIndex == 1) { pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); m_TruncateParcelsLinesPoints = true; m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; int RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; string sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = Suffix + pDS.Name + " (" + sInfo + ")" + Environment.NewLine; pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTLines); m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = txtBoxSummary.Text + pDS.Name + " (" + sInfo + ")" + Environment.NewLine; pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = txtBoxSummary.Text + pDS.Name + " (" + sInfo + ")" + Environment.NewLine; pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTLinePoints); m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = txtBoxSummary.Text + pDS.Name + " (" + sInfo + ")" + Environment.NewLine; pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPlans); m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; IQueryFilter pQF = new QueryFilterClass(); IWorkspace pWS = pDS.Workspace; string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); string sFieldName = "NAME"; //pQF.WhereClause = sPref + sFieldName + sSuff + " <> '<map>'"; pQF.WhereClause = sFieldName + " <> '<map>'"; try { RowCnt = pCadastralTable.RowCount(pQF); } catch (COMException ex) { MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode)); return; } m_RowDropCount += RowCnt; sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = txtBoxSummary.Text + pDS.Name + " (" + sInfo + ")"; } //Drop all fabric jobs if (checkedItemIndex == 2) { pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTJobObjects); m_TruncateJobTables = true; m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; int RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; string sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = Suffix + pDS.Name + " (" + sInfo + ")" + Environment.NewLine; pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTJobs); m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = txtBoxSummary.Text + pDS.Name + " (" + sInfo + ")"; } //Drop all feature adjustment information and vectors if (checkedItemIndex == 3) { pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTVectors); m_TruncateAdjustmentTables = true; m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; int RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; string sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = Suffix + pDS.Name + " (" + sInfo + ")" + Environment.NewLine; pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTLevels); m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = txtBoxSummary.Text + pDS.Name + " (" + sInfo + ")" + Environment.NewLine; pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTAdjustments); m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; sInfo = Convert.ToString(RowCnt) + " rows"; if (RowCnt == 0) { sInfo = "empty"; } txtBoxSummary.Text = txtBoxSummary.Text + pDS.Name + " (" + sInfo + ")"; } //Reset Accuracy to default values if (checkedItemIndex == 4) { m_ResetAccuracyTableDefaults = true; pCadastralTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTAccuracy); m_array.Add(pCadastralTable); pDS = (IDataset)pCadastralTable; int RowCnt = pCadastralTable.RowCount(null); m_RowDropCount += RowCnt; txtBoxSummary.Text = Suffix + pDS.Name + " (" + Convert.ToString(RowCnt) + " rows)..." + Environment.NewLine + "=================================" + Environment.NewLine + "...then will re-add these default records" + Environment.NewLine + " to the Accuracy table:" + Environment.NewLine + "==================" + Environment.NewLine + "1 - Highest" + Environment.NewLine + "2 - After 1980" + Environment.NewLine + "3 - 1908 to 1980" + Environment.NewLine + "4 - 1881 to 1907" + Environment.NewLine + "5 - Before 1881" + Environment.NewLine + "6 - 1800" + Environment.NewLine + "7 - Lowest" + Environment.NewLine; } } } catch (COMException ex) { MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode)); } }
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); } }
public SQLCondition(Operator op, ISQLSyntax lhs, ISQLSyntax rhs) { this.op = op; this.lhs = lhs; this.rhs = rhs; }
private void IsHluLayer(int ixMap, int ixLayer) { if (_pipeData == null) _pipeData = new List<string>(); IFeatureLayer hluLayerBak = _hluLayer; int[] hluFieldMapBak = _hluFieldMap; string[] hluFieldNamesBak = _hluFieldNames; IFeatureClass hluFeatureClassBak = _hluFeatureClass; IFeatureWorkspace hluWSBak = _hluWS; string hluTableNameBak = _hluTableName; ISQLSyntax hluSqlSyntaxBak = _hluSqlSyntax; string quotePrefixBak = _quotePrefix; string quoteSuffixBak = _quoteSuffix; _pipeCalling = true; try { lock (_pipeData) { // clear the pipe _pipeData.Clear(); _hluLayer = null; IMap map = ((IMxDocument)_application.Document).Maps.get_Item(ixMap); IFeatureLayer layer = (IFeatureLayer)map.get_Layer(ixLayer); if (IsHluLayer(layer)) { _pipeData.Add("true"); _pipeData.Add(_pipeTransmissionInterrupt); _pipeData.AddRange(_hluFieldMap.Select(ix => ix.ToString())); _pipeData.Add(_pipeTransmissionInterrupt); _pipeData.AddRange(_hluFieldNames); } else { _pipeData.Add("false"); } } } catch { _pipeData.Clear(); } finally { _pipeCalling = false; _hluLayer = hluLayerBak; _hluFieldMap = hluFieldMapBak; _hluFieldNames = hluFieldNamesBak; _hluFeatureClass = hluFeatureClassBak; _hluWS = hluWSBak; _hluTableName = hluTableNameBak; _hluSqlSyntax = hluSqlSyntaxBak; _quotePrefix = quotePrefixBak; _quoteSuffix = quoteSuffixBak; } }
/// <summary> /// Determines whether the layer passed is an HLU layer, sets all related fields except _hluView /// (which it cannot obtain from the layer) and sets up the selection changed event handler for the /// layer if it is an HLU layer. /// </summary> /// <param name="layer"></param> /// <returns></returns> private bool IsHluLayer(IFeatureLayer layer) { try { if ((_hluLayer == null) && HluDbIsRunning && ArcMapAppHelperClass.IsHluLayer(layer, new FieldsClass(), new FieldCheckerClass(), _validWorkspaces, _typeMapSystemToSql, ref _hluLayerStructure, out _hluFieldMap, out _hluFieldNames)) { _hluLayer = layer as IFeatureLayer; _hluFeatureClass = _hluLayer.FeatureClass; IWorkspace hluWorkspace = ((IDataset)_hluFeatureClass).Workspace; _hluWS = hluWorkspace as IFeatureWorkspace; _hluWSisSDE = hluWorkspace.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace; if (!_pipeCalling) SetupSelectionChangedEvent(); _hluUidFieldOrdinals = new int[3]; _hluUidFieldOrdinals[0] = _hluFieldMap[_hluLayerStructure.incidColumn.Ordinal]; _hluUidFieldOrdinals[1] = _hluFieldMap[_hluLayerStructure.toidColumn.Ordinal]; _hluUidFieldOrdinals[2] = _hluFieldMap[_hluLayerStructure.toid_fragment_idColumn.Ordinal]; _hluFieldSysTypeNames = new string[_hluFeatureClass.Fields.FieldCount]; Type sysType; for (int i = 0; i < _hluFeatureClass.Fields.FieldCount; i++ ) { if (_typeMapSQLToSystem.TryGetValue((int)_hluFeatureClass.Fields.get_Field(i).Type, out sysType)) _hluFieldSysTypeNames[i] = sysType.FullName; } _hluTableName = ((IDataset)_hluFeatureClass).Name; _hluSqlSyntax = (ISQLSyntax)_hluWS; _quotePrefix = _hluSqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); _quoteSuffix = _hluSqlSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); return true; } else { return false; } } catch { _hluLayer = null; _hluFeatureClass = null; _hluTableName = null; _hluWS = null; _hluWSisSDE = false; _hluView = null; _hluFieldMap = null; _hluFieldNames = null; _hluUidFieldOrdinals = null; _selectFieldOrdinals = null; _hluSqlSyntax = null; _quotePrefix = null; _quoteSuffix = null; return false; } }
public void IsHluWorkspace() { IFeatureLayer hluLayerBak = _hluLayer; int[] hluFieldMapBak = _hluFieldMap; string[] hluFieldNamesBak = _hluFieldNames; IFeatureClass hluFeatureClassBak = _hluFeatureClass; IFeatureWorkspace hluWSBak = _hluWS; string hluTableNameBak = _hluTableName; ISQLSyntax hluSqlSyntaxBak = _hluSqlSyntax; string quotePrefixBak = _quotePrefix; string quoteSuffixBak = _quoteSuffix; _pipeCalling = true; if (_pipeData == null) _pipeData = new List<string>(); try { lock (_pipeData) { // clear the pipe _pipeData.Clear(); _hluLayer = null; IMaps maps = ((IMxDocument)_application.Document).Maps; IMap map = null; UID uid = new UIDClass(); uid.Value = typeof(IFeatureLayer).GUID.ToString("B"); for (int i = 0; i < maps.Count; i++) { map = maps.get_Item(i); int j = 0; IEnumLayer layers = map.get_Layers(uid, true); ILayer layer = layers.Next(); while (layer != null) { IFeatureLayer featureLayer = layer as IFeatureLayer; if (IsHluLayer(featureLayer)) { _hluView = map as IActiveView; _pipeData.AddRange(new string[] { i.ToString(), j.ToString() }); _pipeData.Add(_pipeTransmissionInterrupt); _pipeData.AddRange(_hluFieldMap.Select(ix => ix.ToString())); _pipeData.Add(_pipeTransmissionInterrupt); _pipeData.AddRange(_hluFieldNames); return; } layer = layers.Next(); j++; } } } } catch { } finally { _pipeCalling = false; _hluLayer = hluLayerBak; _hluFieldMap = hluFieldMapBak; _hluFieldNames = hluFieldNamesBak; _hluFeatureClass = hluFeatureClassBak; _hluWS = hluWSBak; _hluTableName = hluTableNameBak; _hluSqlSyntax = hluSqlSyntaxBak; _quotePrefix = quotePrefixBak; _quoteSuffix = quoteSuffixBak; } }
private void IsHluLayer(int ixMap, int ixLayer) { if (_pipeData == null) _pipeData = new List<string>(); IFeatureLayer hluLayerBak = _hluLayer; int[] hluFieldMapBak = _hluFieldMap; string[] hluFieldNamesBak = _hluFieldNames; IFeatureClass hluFeatureClassBak = _hluFeatureClass; IFeatureWorkspace hluWSBak = _hluWS; string hluTableNameBak = _hluTableName; ISQLSyntax hluSqlSyntaxBak = _hluSqlSyntax; string quotePrefixBak = _quotePrefix; string quoteSuffixBak = _quoteSuffix; _pipeCalling = true; _hluLayer = null; try { lock (_pipeData) { // clear the pipe _pipeData.Clear(); // Get the correct map based on the map number. IMap map = ((IMxDocument)_application.Document).Maps.get_Item(ixMap); UID uid = new UIDClass(); uid.Value = typeof(IFeatureLayer).GUID.ToString("B"); // Loop through each layer in the map looking for the correct layer // by number (order). int j = 0; IEnumLayer layers = map.get_Layers(uid, true); ILayer layer = layers.Next(); while (layer != null) { if (j == ixLayer) { IFeatureLayer featureLayer = layer as IFeatureLayer; if (IsHluLayer(featureLayer)) { _hluView = map as IActiveView; _pipeData.Add("true"); _pipeData.Add(_pipeTransmissionInterrupt); _pipeData.AddRange(_hluFieldMap.Select(ix => ix.ToString())); _pipeData.Add(_pipeTransmissionInterrupt); _pipeData.AddRange(_hluFieldNames); } else { _pipeData.Add("false"); } } layer = layers.Next(); j++; } } } catch { _pipeData.Clear(); } finally { _pipeCalling = false; } //--------------------------------------------------------------------- // CHANGED: CR31 (Switching between GIS layers) // Reset the class properties if there has been an error or if // the layer is not valid. if (_hluLayer == null) { _hluLayer = hluLayerBak; _hluFieldMap = hluFieldMapBak; _hluFieldNames = hluFieldNamesBak; _hluFeatureClass = hluFeatureClassBak; _hluWS = hluWSBak; _hluTableName = hluTableNameBak; _hluSqlSyntax = hluSqlSyntaxBak; _quotePrefix = quotePrefixBak; _quoteSuffix = quoteSuffixBak; } //--------------------------------------------------------------------- }
public bool DeleteRowsUnversioned(IWorkspace TheWorkSpace, ITable inTable, IFIDSet pFIDSet, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); if (StepProgressor != null) { StepProgressor.MinRange = StepProgressor.Position; //reset the progress bar position StepProgressor.MaxRange = StepProgressor.Position + pFIDSet.Count(); if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } IQueryFilter pQF = new QueryFilterClass(); ISQLSyntax pSQLSyntax = (ISQLSyntax)TheWorkSpace; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ICursor ipCursor = null; IRow pRow = null; //make sure that there are no more then 999 tokens for the in clause(ORA- query will otherwise error on an Oracle database) int iTokenLimit = 995; int iTokenSet = 0; //the index of the set of 995 tokens string sWhereClauseLHS = sPref + inTable.OIDFieldName + sSuff + " in ("; string[] ids = { sWhereClauseLHS }; try { ITableWrite pTableWr = (ITableWrite)inTable; pFIDSet.Reset(); bool bCont = true; Int32 iID; Int32 count = pFIDSet.Count(); int j = 0; //inner count for each set of IDs for (int k = 0; k < count; k++) { if (j > iTokenLimit) { //over the limit for this Token set, time to create a new set ids[iTokenSet] += ")"; //close the previous set RedimPreserveString(ref ids, 1); //make space in the string array for the next token set iTokenSet++; //increment the index ids[iTokenSet] = sWhereClauseLHS; //left-hand side of the where clause j = 0; //reset the inner count back to zero } pFIDSet.Next(out iID); if (j > 0) //write a comma if this is not the first ID { ids[iTokenSet] += ","; } ids[iTokenSet] += iID.ToString(); j++; //increment the inner count } ids[iTokenSet] += ")"; if (count > 0) { for (int k = 0; k <= iTokenSet; k++) { pQF.WhereClause = ids[k]; ipCursor = pTableWr.UpdateRows(pQF, false); pRow = ipCursor.NextRow(); while (pRow != null) { ipCursor.DeleteRow(); Marshal.ReleaseComObject(pRow); if (StepProgressor != null) { //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } pRow = ipCursor.NextRow(); } if (!bCont) { AbortEditing(TheWorkSpace); if (ipCursor != null) { Marshal.ReleaseComObject(ipCursor); } if (pRow != null) { Marshal.ReleaseComObject(pRow); } if (pQF != null) { Marshal.ReleaseComObject(pQF); } if (pMouseCursor != null) { Marshal.ReleaseComObject(pMouseCursor); } return(false); } Marshal.ReleaseComObject(ipCursor); } Marshal.ReleaseComObject(pQF); } Marshal.ReleaseComObject(pMouseCursor); return(true); } catch (COMException ex) { if (ipCursor != null) { Marshal.ReleaseComObject(ipCursor); } if (pRow != null) { Marshal.ReleaseComObject(pRow); } if (pQF != null) { Marshal.ReleaseComObject(pQF); } if (pMouseCursor != null) { Marshal.ReleaseComObject(pMouseCursor); } MessageBox.Show(Convert.ToString(ex.ErrorCode)); return(false); } }
public bool MergePlans(ITable ParcelTable, Dictionary <int, int> Lookup, string[] sInClause, bool Unversioned, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { IDataset pDS = (IDataset)ParcelTable; IWorkspace pWS = pDS.Workspace; Int32 iPlanIDX = ParcelTable.Fields.FindField("PLANID"); ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ITableWrite pTableWr = (ITableWrite)ParcelTable; bool bCont = true; int zz = 0; int iCnt = sInClause.GetLength(0); try { foreach (string ss in sInClause) { if (ss == null) { continue; } IQueryFilter pQF = new QueryFilterClass(); string InClause = ss.Replace(",", " ").Trim(); InClause = InClause.Replace(" ", ","); string FieldName = "PLANID"; pQF.WhereClause = sPref + FieldName + sSuff + " IN (" + InClause + ")"; if (!ParcelTable.HasOID) { MessageBox.Show("Has no OID"); } int iRowCnt = ParcelTable.RowCount(pQF); ICursor pCur = null; if (Unversioned) { pCur = pTableWr.UpdateRows(pQF, false); } else { pCur = ParcelTable.Update(pQF, false); } //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } //now for each of these parcels, use the dictionary to re-assign the plan id value IRow pParcel = pCur.NextRow(); if (StepProgressor != null) { StepProgressor.MinRange = StepProgressor.Position; //reset the progress bar position StepProgressor.MaxRange = StepProgressor.Position + iRowCnt; if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } StepProgressor.Message = "Moving parcels to target plans...step " + Convert.ToString(++zz) + " of " + Convert.ToString(iCnt); } if (pQF != null) { Marshal.ReleaseComObject(pQF); } while (pParcel != null) { //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } int MergePlanID = (int)pParcel.get_Value(iPlanIDX); int TargetPlanID = -1; if (Lookup.TryGetValue(MergePlanID, out TargetPlanID)) { pParcel.set_Value(iPlanIDX, TargetPlanID); pCur.UpdateRow(pParcel); } Marshal.ReleaseComObject(pParcel); pParcel = pCur.NextRow(); if (StepProgressor != null) { if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } } if (pCur != null) { Marshal.ReleaseComObject(pCur); } if (!bCont) { break; } } if (pTableWr != null) { Marshal.ReleaseComObject(pTableWr); } Marshal.ReleaseComObject(pWS); if (!bCont) { return(false); } return(true); } catch (COMException ex) { MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode)); return(false); } }
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 { } }
public bool DeleteByInClause(IWorkspace TheWorkSpace, ITable inTable, IField QueryIntegerField, List <string> InClauseIDs, bool IsVersioned, IStepProgressor StepProgressor, ITrackCancel TrackCancel) { IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); IQueryFilter pQF = new QueryFilterClass(); ISQLSyntax pSQLSyntax = (ISQLSyntax)TheWorkSpace; string sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); string sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ICursor ipCursor = null; IRow pRow = null; //make sure that there are no more then 999 tokens for the in clause(ORA- query will otherwise error on an Oracle database) //this code assumes that InClauseIDs holds an arraylist of comma separated OIDs with no more than 995 id's per list item string sWhereClauseLHS = sPref + QueryIntegerField.Name + sSuff + " in ("; try { ITableWrite pTableWr = (ITableWrite)inTable; bool bCont = true; Int32 count = InClauseIDs.Count - 1; for (int k = 0; k <= count; k++) { pQF.WhereClause = sWhereClauseLHS + InClauseIDs[k] + ")"; //left-hand side of the where clause if (pQF.WhereClause.Contains("()")) { continue; } if (!IsVersioned) { ipCursor = pTableWr.UpdateRows(pQF, false); } else { ipCursor = inTable.Update(pQF, false); } pRow = ipCursor.NextRow(); while (pRow != null) { ipCursor.DeleteRow(); Marshal.ReleaseComObject(pRow); if (StepProgressor != null) { //Check if the cancel button was pressed. If so, stop process if (TrackCancel != null) { bCont = TrackCancel.Continue(); } if (!bCont) { break; } if (StepProgressor.Position < StepProgressor.MaxRange) { StepProgressor.Step(); } } pRow = ipCursor.NextRow(); } if (!bCont) { AbortEditing(TheWorkSpace); if (ipCursor != null) { Marshal.ReleaseComObject(ipCursor); } if (pRow != null) { Marshal.ReleaseComObject(pRow); } return(false); } Marshal.ReleaseComObject(ipCursor); } return(true); } catch (Exception ex) { if (ipCursor != null) { Marshal.ReleaseComObject(ipCursor); } if (pRow != null) { Marshal.ReleaseComObject(pRow); } MessageBox.Show(Convert.ToString(ex.Message)); return(false); } }
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); } }
protected override void OnClick() { m_pApp = (IApplication)ArcMap.Application; if (m_pApp == null) { //if the app is null then could be running from ArcCatalog m_pApp = (IApplication)ArcCatalog.Application; } if (m_pApp == null) { MessageBox.Show("Could not access the application.", "No Application found"); return; } IGxApplication pGXApp = (IGxApplication)m_pApp; stdole.IUnknown pUnk = null; try { pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open(); } catch (COMException ex) { if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE || ex.ErrorCode == -2147220944) { MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset"); } else { MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset"); } return; } if (pUnk is ICadastralFabric) { m_pCadaFab = (ICadastralFabric)pUnk; } else { MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric"); return; } IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); clsFabricUtils FabricUTILS = new clsFabricUtils(); IProgressDialog2 pProgressorDialog = null; ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); IDataset pDS = (IDataset)pTable; IWorkspace pWS = pDS.Workspace; bool bIsFileBasedGDB = true; bool bIsUnVersioned = true; FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB, out bIsUnVersioned); if (!bIsFileBasedGDB && !bIsUnVersioned) { MessageBox.Show("Truncate operates on non-versioned fabrics." + Environment.NewLine + "Please unversion the fabric and try again.", "Tables are versioned"); return; } //Do a Start and Stop editing to make sure truncate it not running within an edit session if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } FabricUTILS.StopEditing(pWS); dlgTruncate pTruncateDialog = new dlgTruncate(); IArray TableArray = new ESRI.ArcGIS.esriSystem.ArrayClass(); pTruncateDialog.TheFabric = m_pCadaFab; pTruncateDialog.TheTableArray = TableArray; //Display the dialog DialogResult pDialogResult = pTruncateDialog.ShowDialog(); if (pDialogResult != DialogResult.OK) { pTruncateDialog = null; if (TableArray != null) { TableArray.RemoveAll(); } return; } m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd); pProgressorDialog = (IProgressDialog2)m_pStepProgressor; m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = pTruncateDialog.DropRowCount; m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; bool bSuccess = false; int iControlRowCount = 0; //look in registry to get flag on whether to run truncate on standard tables, or to delete by row. string sDesktopVers = FabricUTILS.GetDesktopVersionFromRegistry(); if (sDesktopVers.Trim() == "") { sDesktopVers = "Desktop10.0"; } else { sDesktopVers = "Desktop" + sDesktopVers; } bool bDeleteTablesByRowInsteadOfTruncate = false; string sValues = FabricUTILS.ReadFromRegistry(RegistryHive.CurrentUser, "Software\\ESRI\\" + sDesktopVers + "\\ArcMap\\Cadastral", "AddIn.DeleteFabricRecords_Truncate"); if (sValues.Trim().ToLower() == "deletebytruncateonstandardtables" || bIsFileBasedGDB) { bDeleteTablesByRowInsteadOfTruncate = false; } if (sValues.Trim().ToLower() == "deletebyrowonstandardtables") { bDeleteTablesByRowInsteadOfTruncate = true; } if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { // get the control point count ITable pControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); iControlRowCount = pControlTable.RowCount(null); } try { //Work on the table array pTable = null; m_pFIDSet = new FIDSetClass(); for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) ...redundant { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; //Following code uses the truncate method //*** if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { ITableWrite2 pTableWr = (ITableWrite2)pTable; m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; int RowCnt = pTable.RowCount(null); pTableWr.Truncate(); m_pStepProgressor.MaxRange -= RowCnt; //now re-insert the default plan string sName = pDataSet.Name.ToUpper().Trim(); if (sName.EndsWith("_PLANS")) { int idxPlanName = pTable.FindField("Name"); int idxPlanDescription = pTable.FindField("Description"); int idxPlanAngleUnits = pTable.FindField("AngleUnits"); int idxPlanAreaUnits = pTable.FindField("AreaUnits"); int idxPlanDistanceUnits = pTable.FindField("DistanceUnits"); int idxPlanDirectionFormat = pTable.FindField("DirectionFormat"); int idxPlanLineParameters = pTable.FindField("LineParameters"); int idxPlanCombinedGridFactor = pTable.FindField("CombinedGridFactor"); int idxPlanTrueMidBrg = pTable.FindField("TrueMidBrg"); int idxPlanAccuracy = pTable.FindField("Accuracy"); int idxPlanInternalAngles = pTable.FindField("InternalAngles"); ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pTable.CreateRowBuffer(); double dOneMeterEquals = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); bool bIsMetric = (dOneMeterEquals == 1); //write category 1 pRowBuff.set_Value(idxPlanName, "<map>"); pRowBuff.set_Value(idxPlanDescription, "System default plan"); pRowBuff.set_Value(idxPlanAngleUnits, 3); // if (bIsMetric) { pRowBuff.set_Value(idxPlanAreaUnits, 5); pRowBuff.set_Value(idxPlanDistanceUnits, 9001); pRowBuff.set_Value(idxPlanDirectionFormat, 1); } else { pRowBuff.set_Value(idxPlanAreaUnits, 4); pRowBuff.set_Value(idxPlanDistanceUnits, 9003); pRowBuff.set_Value(idxPlanDirectionFormat, 4); } pRowBuff.set_Value(idxPlanLineParameters, 4); pRowBuff.set_Value(idxPlanCombinedGridFactor, 1); //pRowBuff.set_Value(idxPlanTrueMidBrg, 1); pRowBuff.set_Value(idxPlanAccuracy, 4); pRowBuff.set_Value(idxPlanInternalAngles, 0); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) { Marshal.ReleaseComObject(pRowBuff); } if (pCur != null) { Marshal.ReleaseComObject(pCur); } } } } } } catch (COMException ex) { MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode)); Cleanup(pProgressorDialog, pMouseCursor); return; } //do the loop again, this time within the edit transaction and using the delete function for the chosen tables try { //Start an Edit Transaction if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { } else { //The following code is in place to workaround a limitation of truncate for fabric classes //without a shapefield. It uses an alternative method for removing all the rows //with the Delete function. //General note: This method could be used exclusively, without needing the truncate method. //One advantage is that it allows the option to cancel the whole //operation using the cancel tracker. Truncate is faster, but is problematic if //the truncate fails, and leaves a partially deleted fabric. For example, if the //lines table is deleted but the points table truncate fails, the fabric would be in a //corrupt state. //**** m_pFIDSet.SetEmpty(); string sName = pDataSet.Name.ToUpper().Trim(); m_pStepProgressor.Message = "Loading rows from " + pDataSet.Name; if (sName.EndsWith("_PLANS")) {//for Plans table make sure the default plan is not deleted IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); string sFieldName = "NAME"; //pQF.WhereClause = sPref + sFieldName + sSuff + " <> '<map>'"; pQF.WhereClause = sFieldName + " <> '<map>'"; if (!BuildFIDSetFromTable(pTable, pQF, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } else { if (!BuildFIDSetFromTable(pTable, null, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } if (m_pFIDSet.Count() == 0) { continue; } m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pTable, m_pFIDSet, m_pStepProgressor, m_pTrackCancel); if (!bSuccess) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } } } //now need to Fix control-to-point associations if one table was truncated //and the other was not if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ITable PointTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.Message = "Resetting control associations on points...please wait."; int idxFld = PointTable.FindField("NAME"); string sFieldName = PointTable.Fields.get_Field(idxFld).Name; //NAME IS NOT NULL AND (NAME <>'' OR NAME <>' ') //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND (" + // sPref + sFieldName + sSuff + "<>'' OR " + sPref + sFieldName + sSuff + " <>' ')"; //pQF.WhereClause = sFieldName + " IS NOT NULL AND (" + sFieldName + "<>'' OR " + sFieldName + " <>' ')"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " > ''"; //changed 1/14/2016 ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(PointTable, esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = iControlRowCount; if (!ResetPointAssociations(PointTable, pQF, true, m_pStepProgressor, m_pTrackCancel)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); } else if (pTruncateDialog.TruncateParcelsLinesPoints && !pTruncateDialog.TruncateControl) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); //POINTID >=0 AND POINTID IS NOT NULL m_pStepProgressor.Message = "Resetting associations on control points...please wait."; ITable ControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); int idxFld = ControlTable.FindField("POINTID"); string sFieldName = ControlTable.Fields.get_Field(idxFld).Name; //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND " + // sPref + sFieldName + sSuff + " >=0"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " >=0"; ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(ControlTable, esriCadastralFabricTable.esriCFTControl); if (!FabricUTILS.ResetControlAssociations(ControlTable, null, true)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); } //now need to re-assign default accuracy table values, if the option was checked if (pTruncateDialog.ResetAccuracyTableDefaults) { double dCat1 = FabricUTILS.ConvertMetersToFabricUnits(0.001, m_pCadaFab); double dCat2 = FabricUTILS.ConvertMetersToFabricUnits(0.01, m_pCadaFab); double dCat3 = FabricUTILS.ConvertMetersToFabricUnits(0.02, m_pCadaFab); double dCat4 = FabricUTILS.ConvertMetersToFabricUnits(0.05, m_pCadaFab); double dCat5 = FabricUTILS.ConvertMetersToFabricUnits(0.2, m_pCadaFab); double dCat6 = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); double dCat7 = FabricUTILS.ConvertMetersToFabricUnits(10, m_pCadaFab); ITable pAccTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTAccuracy); int idxBrgSD = pAccTable.FindField("BrgSD"); int idxDistSD = pAccTable.FindField("DistSD"); int idxPPM = pAccTable.FindField("PPM"); int idxCategory = pAccTable.FindField("Category"); int idxDescription = pAccTable.FindField("Description"); ITableWrite2 pTableWr = (ITableWrite2)pAccTable; ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pAccTable.CreateRowBuffer(); //write category 1 pRowBuff.set_Value(idxCategory, 1); pRowBuff.set_Value(idxBrgSD, 5); pRowBuff.set_Value(idxDistSD, dCat1); pRowBuff.set_Value(idxPPM, 5); pRowBuff.set_Value(idxDescription, "1 - Highest"); pCur.InsertRow(pRowBuff); //write category 2 pRowBuff.set_Value(idxCategory, 2); pRowBuff.set_Value(idxBrgSD, 30); pRowBuff.set_Value(idxDistSD, dCat2); pRowBuff.set_Value(idxPPM, 25); pRowBuff.set_Value(idxDescription, "2 - After 1980"); pCur.InsertRow(pRowBuff); //write category 3 pRowBuff.set_Value(idxCategory, 3); pRowBuff.set_Value(idxBrgSD, 60); pRowBuff.set_Value(idxDistSD, dCat3); pRowBuff.set_Value(idxPPM, 50); pRowBuff.set_Value(idxDescription, "3 - 1908 to 1980"); pCur.InsertRow(pRowBuff); //write category 4 pRowBuff.set_Value(idxCategory, 4); pRowBuff.set_Value(idxBrgSD, 120); pRowBuff.set_Value(idxDistSD, dCat4); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "4 - 1881 to 1907"); pCur.InsertRow(pRowBuff); //write category 5 pRowBuff.set_Value(idxCategory, 5); pRowBuff.set_Value(idxBrgSD, 300); pRowBuff.set_Value(idxDistSD, dCat5); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "5 - Before 1881"); pCur.InsertRow(pRowBuff); //write category 6 pRowBuff.set_Value(idxCategory, 6); pRowBuff.set_Value(idxBrgSD, 3600); pRowBuff.set_Value(idxDistSD, dCat6); pRowBuff.set_Value(idxPPM, 1000); pRowBuff.set_Value(idxDescription, "6 - 1800"); pCur.InsertRow(pRowBuff); //write category 7 pRowBuff.set_Value(idxCategory, 7); pRowBuff.set_Value(idxBrgSD, 6000); pRowBuff.set_Value(idxDistSD, dCat7); pRowBuff.set_Value(idxPPM, 5000); pRowBuff.set_Value(idxDescription, "7 - Lowest"); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) { Marshal.ReleaseComObject(pRowBuff); } if (pCur != null) { Marshal.ReleaseComObject(pCur); } } //now need to cleanup the IDSequence table if ALL the tables were truncated if (pTruncateDialog.TruncateControl && pTruncateDialog.TruncateParcelsLinesPoints && pTruncateDialog.TruncateJobs && pTruncateDialog.TruncateAdjustments) { IWorkspace2 pWS2 = (IWorkspace2)pWS; IDataset TheFabricDS = (IDataset)m_pCadaFab; string sFabricName = TheFabricDS.Name; string sName = sFabricName + "_IDSequencer"; bool bExists = pWS2.get_NameExists(esriDatasetType.esriDTTable, sName); IFeatureWorkspace pFWS = (IFeatureWorkspace)pWS; ITable pSequencerTable; if (bExists) { pSequencerTable = pFWS.OpenTable(sName); IFIDSet pFIDSet = new FIDSetClass(); if (BuildFIDSetFromTable(pSequencerTable, null, ref pFIDSet)) { FabricUTILS.DeleteRowsUnversioned(pWS, pSequencerTable, pFIDSet, null, null); } } } Cleanup(pProgressorDialog, pMouseCursor); if (TableArray != null) { TableArray.RemoveAll(); } FabricUTILS.StopEditing(pWS); } catch (Exception ex) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); MessageBox.Show(Convert.ToString(ex.Message)); } }
void OnCreateFeature(ESRI.ArcGIS.Geodatabase.IObject obj) { // Don't do anything if the extension is disabled if (IsExtensionEnabled != true) { return; } // Bail if this is not a valid NCGMP workspace if (m_DatabaseIsValid == false) { return; } #region "Groundwork" // Grab the FeatureClass name from the Row's Table (as an IDataset). IRow theRow = obj; ITable theTable = theRow.Table; IDataset theDS = (IDataset)theTable; string TableName = theDS.Name; // Parse the table name in order to strip out unneccessary bits of SDE tables ISQLSyntax nameParser = (ISQLSyntax)theDS.Workspace; string parsedDbName, parsedOwnerName, parsedTableName; nameParser.ParseTableName(TableName, out parsedDbName, out parsedOwnerName, out parsedTableName); #endregion #region "Set New ID" // Call the routine to get a new ID int id = m_SysInfo.GetNextIdValue(parsedTableName); // Set the new ID value on the row itself theRow.set_Value(theTable.FindField(parsedTableName + "_ID"), m_SysInfo.ProjAbbr + "." + parsedTableName + "." + id); #endregion #region "Calculate SymbolRotation" if (m_DatabaseUsesRepresentation == true) { if (parsedTableName == "OrientationPoints") { // Get the Azimuth from the feature int Azimuth; bool result = int.TryParse(theRow.get_Value(theTable.FindField("Azimuth")).ToString(), out Azimuth); // Calculate the stupid form of rotation... int Rotation = CalculateSymbolRotation(Azimuth); // Set the SymbolRotation Field theRow.set_Value(theTable.FindField("SymbolRotation"), double.Parse(Rotation.ToString())); } } #endregion #region "Set DataSource" // Bail if the new object is in fact a Data Source if (parsedTableName != "DataSources") { if (globalVariables.currentDataSource == null) { // I can warn the user that they should choose a data source, but I can't keep the feature from being created anyways System.Windows.Forms.MessageBox.Show("You have not selected a valid Data Source for this edit session." + Environment.NewLine + "Your feature was created without a Data Source.", "NCGMP Tools"); return; } else { // Set the DataSourceID value if (parsedTableName == "Glossary") { theRow.set_Value(theTable.FindField("DefinitionSourceID"), globalVariables.currentDataSource); } else if (parsedTableName == "DescriptionOfMapUnits") { theRow.set_Value(theTable.FindField("DescriptionSourceID"), globalVariables.currentDataSource); } else if (obj.get_Value(theTable.FindField("DataSourceID")).ToString() == "") { theRow.set_Value(theTable.FindField("DataSourceID"), globalVariables.currentDataSource); } } } #endregion }
public void Shutdown() { _hluLayer = null; _hluFeatureClass = null; _hluFeatureSelection = null; _hluWS = null; _hluSqlSyntax = null; _hluView = null; _hluFieldMap = null; _hluFieldNames = null; _hluUidFieldOrdinals = null; _selectFieldOrdinals = null; _pipeSelDel = null; _selectedRowsUniqueDel = null; _flashSelFeatDel = null; _splitFeatDel = null; _splitFeatLogDel = null; _mergeFeatDel = null; _mergeFeatLogDel = null; _updAttsDel = null; _updAttsSelDel = null; _updAttsBulkDel = null; _selByQDefDel = null; _selByQFilterDel = null; _selByJoinDel = null; _zoomSelDel = null; _zoomSelCursorDel = null; _exportDel = null; _isHluWorkspaceDel = null; _ListHluLayersDel = null; _isHluLayerDel = null; _isEditingDel = null; if (PipeManager != null) { PipeManager = null; } RemoveActiveViewEvents(_focusMap); }
void OnDeleteFeature(ESRI.ArcGIS.Geodatabase.IObject obj) { // Don't do anything if the extension is disabled if (IsExtensionEnabled != true) { return; } // Bail if this is not a valid NCGMP workspace if (m_DatabaseIsValid == false) { return; } #region "Groundwork" // Grab the FeatureClass name from the Row's Table (as an IDataset). IRow theRow = obj; ITable theTable = theRow.Table; IDataset theDS = (IDataset)theTable; string TableName = theDS.Name; // Parse the table name in order to strip out unneccessary bits of SDE tables ISQLSyntax nameParser = (ISQLSyntax)theDS.Workspace; string parsedDbName, parsedOwnerName, parsedTableName; nameParser.ParseTableName(TableName, out parsedDbName, out parsedOwnerName, out parsedTableName); #endregion // #region "Delete Related Station Data" // if (parsedTableName == "Stations") // { // // Get the related information first, then prompt, then delete if that's what they want. // string stationName = (string)theRow.get_Value(theTable.FindField("FieldID")); // IRelationshipClass stationStructureLink = commonFunctions.OpenRelationshipClass(m_EditWorkspace, "StationOrientationPointsLink"); // IRelationshipClass stationSamplesLink = commonFunctions.OpenRelationshipClass(m_EditWorkspace, "StationSampleLink"); // IRelationshipClass stationNotesLink = commonFunctions.OpenRelationshipClass(m_EditWorkspace, "StationNotesLink"); // IRelationshipClass stationDocsLink = commonFunctions.OpenRelationshipClass(m_EditWorkspace, "StationDocumentLink"); // ESRI.ArcGIS.esriSystem.ISet structureSet = stationStructureLink.GetObjectsRelatedToObject(obj); // ESRI.ArcGIS.esriSystem.ISet sampleSet = stationSamplesLink.GetObjectsRelatedToObject(obj); // ESRI.ArcGIS.esriSystem.ISet noteSet = stationNotesLink.GetObjectsRelatedToObject(obj); // ESRI.ArcGIS.esriSystem.ISet docSet = stationDocsLink.GetObjectsRelatedToObject(obj); // string theMessage = ("Deleting Station " + stationName + " will also delete the following:"); // theMessage += Environment.NewLine; // theMessage += structureSet.Count.ToString() + " structural observations"; // theMessage += Environment.NewLine; // theMessage += sampleSet.Count.ToString() + " sample locations"; // theMessage += Environment.NewLine; // theMessage += noteSet.Count.ToString() + " recorded notes"; // theMessage += Environment.NewLine; // theMessage += docSet.Count.ToString() + " related document links"; // theMessage += Environment.NewLine; // theMessage += Environment.NewLine; // theMessage += "Are you sure you want to do this?"; // // Probably would be wise to warn them first... // System.Windows.Forms.DialogResult result = System.Windows.Forms.MessageBox.Show(theMessage, "NCGMP Tools", System.Windows.Forms.MessageBoxButtons.YesNo); // if (result == System.Windows.Forms.DialogResult.Yes) // { // IFeature theFeature = (IFeature)structureSet.Next(); // while (theFeature != null) // { // theFeature.Delete(); // theFeature = (IFeature)structureSet.Next(); // } // theFeature = (IFeature)sampleSet.Next(); // while (theFeature != null) // { // theFeature.Delete(); // theFeature = (IFeature)sampleSet.Next(); // } // theFeature = (IFeature)noteSet.Next(); // while (theFeature != null) // { // theFeature.Delete(); // theFeature = (IFeature)noteSet.Next(); // } // theFeature = (IFeature)docSet.Next(); // while (theFeature != null) // { // theFeature.Delete(); // theFeature = (IFeature)docSet.Next(); // } // } // } // #endregion }
protected override bool WorkspaceIsValid(IFeatureWorkspace fworkspace) { bool result = true; try { IWorkspace workspace = fworkspace as IWorkspace; ISQLSyntax sqlSyntax = (ISQLSyntax)workspace; // ---------------------------------------------- // Need to get the db name & onwer. This is very // important so we can deal with different types // of table name qualification when dealing with // enterprise and file geodatabases.Names are // only fully qualified with enterprise GDBs. // ---------------------------------------------- IWorkspace wksp = fworkspace as IWorkspace; IEnumDatasetName enumDatasetName = wksp.get_DatasetNames(esriDatasetType.esriDTAny); IDatasetName datasetName = enumDatasetName.Next(); if (datasetName != null) { datasetName = enumDatasetName.Next(); // Parse path name out into db, owner, table. string db = string.Empty; string owner = string.Empty; string tbl = string.Empty; sqlSyntax.ParseTableName(datasetName.Name, out db, out owner, out tbl); _ownerName = owner; _dbName = db; _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Database owner...", _ownerName); _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Database name...", _dbName); } else { // Not a valid workspace if nothing found in it _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Invalid workspace selected."); return(false); } // ---------------------------------------------- // Workspace is valid and is a feature workspace // ---------------------------------------------- if (fworkspace == null || workspace == null) { _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Invalid workspace selected."); return(false); } else { _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Reading Workspace...", workspace.PathName + "," + workspace.Type.ToString()); } // ----------------------------------- // Are we dealing with a geodatabase // ie not shapefiles etc // ----------------------------------- if (workspace.Type != esriWorkspaceType.esriRemoteDatabaseWorkspace && workspace.Type != esriWorkspaceType.esriLocalDatabaseWorkspace) { _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Telecom workspace is not a geodatabase."); return(false); } // -------------------------------- // Get the workspace properties // -------------------------------- IDatabaseConnectionInfo2 dbInfo = workspace as IDatabaseConnectionInfo2; IPropertySet wkPropSet = workspace.ConnectionProperties; object names; object values; wkPropSet.GetAllProperties(out names, out values); if (dbInfo != null) { _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Database Connection Info..."); _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Connected DB: ", dbInfo.ConnectedDatabase); _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Connected User: "******"INFO", "DB Type: ", dbInfo.ConnectionDBMS.ToString()); _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Connection Server: ", dbInfo.ConnectionServer); _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "GDB Server Class: ", dbInfo.GeodatabaseServerClass.ToString()); } // --------------------------------------- // Does it have a dynamic values dataset? // --------------------------------------- IWorkspace2 wksp2 = fworkspace as IWorkspace2; if (!InWorkspace(wksp2, esriDatasetType.esriDTTable, m_defaultsTableName)) { return(false); } // ------------------------------------------------- // Do checks for other FCs and tables in app.config // ------------------------------------------------- if (!InWorkspace(wksp2, esriDatasetType.esriDTFeatureClass, ConfigUtil.FiberCableFtClassName)) { return(false); } if (!InWorkspace(wksp2, esriDatasetType.esriDTTable, ConfigUtil.FiberSpliceTableName)) { return(false); } if (!InWorkspace(wksp2, esriDatasetType.esriDTTable, ConfigUtil.FiberTableName)) { return(false); } if (!InWorkspace(wksp2, esriDatasetType.esriDTTable, ConfigUtil.BufferTubeClassName)) { return(false); } // ---------- // Devices // ---------- string[] devices = ConfigUtil.DeviceFeatureClassNames; foreach (string name in devices) { if (!InWorkspace(wksp2, esriDatasetType.esriDTFeatureClass, name)) { return(false); } } // -------------------------------------------- // Do a check for # Fibers and Strands domains // If these exist, DB will need upgrading first // -------------------------------------------- IFeatureClass cableFc = FindFeatureClass(ConfigUtil.FiberCableFtClassName); if (cableFc == null) { return(false); } int buffersIdx = cableFc.FindField(ConfigUtil.NumberOfBuffersFieldName); if (buffersIdx == -1) { return(false); } IField field = cableFc.Fields.Field[buffersIdx]; if (field.Domain != null) { //MessageBox.Show("An invalid schema was found. Please read the " + // "documentation on how to upgrade old databases to work with the " + // "newer tools. Also view the log for more details. The log is " + // "accessible from telecom toolbar.", "Invalid Telecom Schema"); _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "DB Telecom Schema Version OK?", "False. Invalid Domain found on FiberCable."); // Assume no until they say yes DialogResult dialogResult = DialogResult.No; dialogResult = MessageBox.Show("Do you wish to try to upgrade this database? \n\nPLEASE ENSURE YOU HAVE EXCLUSIVE ACCESS TO THIS DATABASE AND THAT NO SERVICES ARE RUNNING AGAINST IT \n\nPLEASE ALWAYS ENSURE YOU HAVE A BACKUP BEFORE CONSIDERING THIS!", "Upgrade Workspace", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (DialogResult.No == dialogResult) { _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Database upgrade NO.", ""); return(false); } else if (DialogResult.Yes == dialogResult) { _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Database Upgrade YES.", ""); result = RemoveFiberCableConfigDomains(workspace); } } else { _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "DB Telecom Schema Version OK?", "True"); } } catch (Exception e) { result = false; _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "WorkspaceIsValid", e.Message); } return(result); }