///<summary>Write a Layer to a file on disk.</summary> /// ///<param name="layerFilePath">A System.String that is the path and filename for the layer file to be created. Example: "C:\temp\cities.lyr"</param> ///<param name="layer">An ILayer interface.</param> /// ///<remarks></remarks> public static void SaveToLayerFile(string layerFilePath, ILayer layer) { if (layer == null) { Log.Warning("No valid layer file was found. Save not completed."); return; } //create a new LayerFile instance ESRI.ArcGIS.Carto.ILayerFile layerFile = new LayerFileClass(); //make sure that the layer file name is valid if (Path.GetExtension(layerFilePath) != ".lyr") { return; } if (layerFile.get_IsPresent(layerFilePath)) { File.Delete(layerFilePath); } var fileInfo = new FileInfo(layerFilePath); if (!fileInfo.Directory.Exists) { Log.Information("Creating output directory {OutputDirectory}.", fileInfo.Directory.FullName); fileInfo.Directory.Create(); } //create a new layer file layerFile.New(layerFilePath); //attach the layer file with the actual layer layerFile.ReplaceContents(layer); //save the layer file layerFile.Save(); layerFile.Close(); Log.Information("Layer saved."); // save output path so that the calling process can get it - useful when unique file name for output string tempFile = Path.Combine(Path.GetTempPath(), "Chameleon.txt"); using (StreamWriter sw = new StreamWriter(tempFile)) { sw.WriteLine(layerFilePath); } }
private static async Task <ILayer> InitLayerFileAsync(string file) { await EsriLicense.GetLicenseAsync(); var layerFile = new LayerFileClass(); var layer = await Task.Run(() => { layerFile.Open(file); var l = layerFile.Layer; layerFile.Close(); return(l); }); return(layer); }
public void Execute() { try { // Create new spatial reference ISpatialReference spatialReference = null; if (this.SRef.ToLowerInvariant().Contains("projcs")) { spatialReference = new ProjectedCoordinateSystemClass(); } else { spatialReference = new GeographicCoordinateSystemClass(); } // Import SpatialReference Definition int bytes2; IESRISpatialReferenceGEN2 gen = (IESRISpatialReferenceGEN2)spatialReference; gen.ImportFromESRISpatialReference(this.SRef, out bytes2); // Create Search Extent IEnvelope extent = new EnvelopeClass(); extent.PutCoords(this.XMin, this.YMin, this.XMax, this.YMax); extent.SpatialReference = spatialReference; // Open Saved Layer File ILayerFile layerFile = new LayerFileClass(); layerFile.Open(this.Path); ILayer layer = layerFile.Layer; layerFile.Close(); // Where clause and list of selected OIDs string where = string.Empty; List <int> ids = new List <int>(); IImageServerLayer imageLayer = null; if (layer is IImageServerLayer) { imageLayer = (IImageServerLayer)layer; // Get Selection Set IFeatureLayerDefinition definition = layer as IFeatureLayerDefinition; if (definition != null) { // Find Selected OIDs if (definition.DefinitionSelectionSet != null) { if (definition.DefinitionSelectionSet.Count > 0) { IEnumIDs emumids = definition.DefinitionSelectionSet.IDs; int id = emumids.Next(); while (id != -1) { ids.Add(id); id = emumids.Next(); } } } // Update Where Clause if (!string.IsNullOrEmpty(definition.DefinitionExpression)) { where = definition.DefinitionExpression; } } } else if (layer is IMosaicLayer) { IMosaicLayer mosaicLayer = (IMosaicLayer)layer; imageLayer = mosaicLayer.PreviewLayer; ITableDefinition tableDefinition = mosaicLayer as ITableDefinition; if (tableDefinition != null) { // Find Selected OIDs if (tableDefinition.DefinitionSelectionSet != null) { if (tableDefinition.DefinitionSelectionSet.Count > 0) { IEnumIDs emumids = tableDefinition.DefinitionSelectionSet.IDs; int id = emumids.Next(); while (id != -1) { ids.Add(id); id = emumids.Next(); } } } // Update Where Clause if (!string.IsNullOrEmpty(tableDefinition.DefinitionExpression)) { where = tableDefinition.DefinitionExpression; } } } // Use FeatureSelected (if any) IFeatureSelection featureSelection = imageLayer as IFeatureSelection; if (featureSelection != null) { if (featureSelection.SelectionSet != null) { if (featureSelection.SelectionSet.Count > 0) { IEnumIDs emumids = featureSelection.SelectionSet.IDs; int id = emumids.Next(); while (id != -1) { ids.Add(id); id = emumids.Next(); } } } } // Get Bands ILongArray bands = new LongArrayClass(); IRasterRenderer rasterRenderer = imageLayer.Renderer; if (rasterRenderer != null) { IRasterRGBRenderer2 rasterRGBRenderer = rasterRenderer as IRasterRGBRenderer2; if (rasterRGBRenderer != null) { bands.Add(rasterRGBRenderer.UseRedBand ? rasterRGBRenderer.RedBandIndex : -1); bands.Add(rasterRGBRenderer.UseGreenBand ? rasterRGBRenderer.GreenBandIndex : -1); bands.Add(rasterRGBRenderer.UseBlueBand ? rasterRGBRenderer.BlueBandIndex : -1); bands.Add(rasterRGBRenderer.UseAlphaBand ? rasterRGBRenderer.AlphaBandIndex : -1); } } // Create Spatial Filter ISpatialFilter spatialFilter = new SpatialFilterClass() { Geometry = extent, SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects, WhereClause = where }; IImageServer imageServer = imageLayer.DataSource as IImageServer; if (imageServer == null) { return; } IImageServer3 imageServer3 = imageServer as IImageServer3; if (imageServer3 == null) { return; } IRecordSet recordSet = imageServer3.GetCatalogItems(spatialFilter); ICursor cursor = recordSet.get_Cursor(false); IFeatureCursor featureCursor = (IFeatureCursor)cursor; IFeature feature = featureCursor.NextFeature(); List <IFeature> list = new List <IFeature>(); int indexCategory = featureCursor.FindField("Category"); while (feature != null) { // Exclude non-primary images (no overviews) if (indexCategory != -1) { int cat = (int)feature.get_Value(indexCategory); if (cat != 1) { feature = featureCursor.NextFeature(); continue; } } // Exclude unselected features if (ids.Count > 0) { int oid = feature.OID; if (!ids.Contains(oid)) { feature = featureCursor.NextFeature(); continue; } } list.Add(feature); feature = featureCursor.NextFeature(); } // If nothing, fire event then exit if (list.Count == 0) { this.OnThumbnailSummary(new SummaryEventArgs()); return; } // Get Full Extent of Features SummaryEventArgs summary = new SummaryEventArgs() { XMin = list.Min(f => f.Shape.Envelope.CloneProject(spatialReference).XMin), YMin = list.Min(f => f.Shape.Envelope.CloneProject(spatialReference).YMin), XMax = list.Max(f => f.Shape.Envelope.CloneProject(spatialReference).XMax), YMax = list.Max(f => f.Shape.Envelope.CloneProject(spatialReference).YMax), Count = list.Count }; // Add Fields IFields fields = featureCursor.Fields; for (int i = 0; i < fields.FieldCount; i++) { IField field = fields.get_Field(i); switch (field.Type) { case esriFieldType.esriFieldTypeBlob: case esriFieldType.esriFieldTypeGeometry: case esriFieldType.esriFieldTypeGlobalID: case esriFieldType.esriFieldTypeGUID: case esriFieldType.esriFieldTypeRaster: case esriFieldType.esriFieldTypeXML: break; case esriFieldType.esriFieldTypeOID: case esriFieldType.esriFieldTypeDate: case esriFieldType.esriFieldTypeDouble: case esriFieldType.esriFieldTypeInteger: case esriFieldType.esriFieldTypeSingle: case esriFieldType.esriFieldTypeSmallInteger: case esriFieldType.esriFieldTypeString: summary.Fields.Add( new Field() { Name = field.Name, Alias = field.AliasName, Type = field.Type } ); break; default: break; } } // Raise Summary Event this.OnThumbnailSummary(summary); // Loop for each feature foreach (IFeature feat in list) { // Project Extent to Current Map Spatial Reference IEnvelope extentMap = feat.Shape.Envelope.CloneProject(spatialReference); int width; int height; if (extentMap.Width > extentMap.Height) { width = this.MaxImageSize; height = Convert.ToInt32((double)this.MaxImageSize * (double)extentMap.Height / (double)extentMap.Width); } else { width = Convert.ToInt32((double)this.MaxImageSize * (double)extentMap.Width / (double)extentMap.Height); height = this.MaxImageSize; } IMosaicRule mosaicRule = new MosaicRuleClass() { MosaicMethod = esriMosaicMethod.esriMosaicLockRaster, LockRasterID = feat.OID.ToString() }; IGeoImageDescription geoImageDescription = new GeoImageDescriptionClass() { BandSelection = bands.Count > 0 ? bands : null, MosaicRule = mosaicRule, Compression = "PNG", Width = width, Height = height, SpatialReference = spatialReference, Extent = extentMap, Interpolation = rstResamplingTypes.RSP_BilinearInterpolation, }; // Assembly MosaicRequest (will be executed in background thread) MosaicRequest mosaicRequest = new MosaicRequest() { MosaicExtractor = this, ImageServer = imageServer3, GeoImageDescription = geoImageDescription, XMin = extentMap.XMin, YMin = extentMap.YMin, XMax = extentMap.XMax, YMax = extentMap.YMax, }; // Add Attributes Names and Values foreach (Field field in summary.Fields) { int index = feat.Fields.FindField(field.Name); if (index < 0) { continue; } mosaicRequest.Attributes.Add(field.Name, feat.get_Value(index)); } // Start Mosaic Request in Background Thread Thread thread = new Thread(new ThreadStart(mosaicRequest.Execute)); MosaicEnvironment.Default.Threads.Add(thread); thread.Start(); } } catch { } }
static void RunJob(CmdArgs args) { Log.Information("Processing file {LayerFile}", args.InputFile); var inputFile = new FileInfo(args.InputFile); ILayerFile inputLayer = new LayerFileClass(); inputLayer.Open(inputFile.FullName); IGeoFeatureLayer geoFeatureLayer = inputLayer.Layer as IGeoFeatureLayer; //var featureLayer = inputLayer.Layer as FeatureLayer; //IFeatureClass featureClass = featureLayer.FeatureClass; //var renderer = geoFeatureLayer.Renderer as ISimpleRenderer; var esriRgb = CreateRGBColor(args.Colour); ISimpleRenderer simpleRenderer = new SimpleRendererClass(); var symbolType = args.SymbolType.ToLowerInvariant(); if (args.GetSymbolTypeFromInputFileName) { var tempSymbolType = inputFile.Name.Replace(inputFile.Extension, "").ToLowerInvariant(); if (string.Equals(tempSymbolType, "point", StringComparison.OrdinalIgnoreCase) || string.Equals(tempSymbolType, "polyline", StringComparison.OrdinalIgnoreCase) || string.Equals(tempSymbolType, "line", StringComparison.OrdinalIgnoreCase) || string.Equals(tempSymbolType, "polygon", StringComparison.OrdinalIgnoreCase)) { symbolType = tempSymbolType; } } switch (symbolType) { case "point": IMarkerSymbol pointSymbol = new SimpleMarkerSymbolClass(); pointSymbol.Size = args.PointSize; pointSymbol.Color = esriRgb; simpleRenderer.Symbol = (ISymbol)pointSymbol; break; case "polyline": case "line": ILineSymbol lineSymbol = new SimpleLineSymbolClass(); lineSymbol.Width = args.LineWidth; lineSymbol.Color = esriRgb; simpleRenderer.Symbol = (ISymbol)lineSymbol; break; case "polygon": ILineSymbol outlineSymbol = new SimpleLineSymbolClass(); outlineSymbol.Width = args.LineWidth; outlineSymbol.Color = CreateRGBColor(args.OutlineColour) ?? esriRgb; ISimpleFillSymbol fillSymbol = new SimpleFillSymbolClass(); fillSymbol.Outline = outlineSymbol; fillSymbol.Color = esriRgb; simpleRenderer.Symbol = (ISymbol)fillSymbol; break; default: inputLayer.Close(); Log.Warning("Unrecognized symbol type {SymbolType}. No symbol set for the layer renderer. Valid symbol types are point, polyline, line or polygon.", args.SymbolType); return; } geoFeatureLayer.Renderer = (IFeatureRenderer)simpleRenderer; var outputFileLocation = args.SaveFileNameUnique ? GetUniqueFilename(Path.Combine(args.OutputFolder, inputFile.Name)) : Path.Combine(args.OutputFolder, inputFile.Name); var outputFile = new FileInfo(outputFileLocation); Log.Information("Saving processed layer file to {OutputFile}", outputFile.FullName); SaveToLayerFile(outputFile.FullName, inputLayer.Layer); inputLayer.Close(); }
internal void BuildLayer(string plant) { //Validate must be called by the user before calling BuildLayers if (_layer == null) throw new Exception("Unable to build this layer due to invalid (or unvalidated) configuration properties."); //reload the layer file to create a new layer (we may get called many times) var layerFile = new LayerFileClass(); layerFile.Open(LayerFileName); _layer = layerFile.Layer; layerFile.Close(); string definitionQuery; if (string.IsNullOrEmpty(plant)) { plant = "unspecified"; definitionQuery = "\"" + FieldName + "\" = '' OR \"" + FieldName + "\" is null"; } else { definitionQuery = "\"" + FieldName + "\" = '" + plant.Replace("'", "''") + "'"; } _layer.Name = string.Format(LayerNameFormat, plant); ((IFeatureLayerDefinition2)_layer).DefinitionExpression = definitionQuery; // Call the layer fixer delegate var layerFixer = LayerFixer; if (layerFixer != null) layerFixer(_layer); ArcMap.Document.AddLayer(_layer); }
private string ValidateLayerFile() { if (string.IsNullOrEmpty(LayerFileName)) return "No layer file template is defined."; if (!File.Exists(LayerFileName)) return "layer file '" + LayerFileName + "' does not exist."; try { var layerFile = new LayerFileClass(); layerFile.Open(LayerFileName); _layer = layerFile.Layer; layerFile.Close(); } catch (Exception ex) { _layer = null; return "Could not load layer file '" + LayerFileName + "'\n" + ex.Message; } if (_layer == null) return "layer file '" + LayerFileName + "' is empty."; if (!(_layer is IFeatureLayerDefinition2)) { _layer = null; return "layer file '" + LayerFileName + "' does not support definition queries."; } return null; }
public void Execute() { try { // Create new spatial reference ISpatialReference spatialReference = null; if (this.SRef.ToLowerInvariant().Contains("projcs")) { spatialReference = new ProjectedCoordinateSystemClass(); } else { spatialReference = new GeographicCoordinateSystemClass(); } // Import SpatialReference Definition int bytes2; IESRISpatialReferenceGEN2 gen = (IESRISpatialReferenceGEN2)spatialReference; gen.ImportFromESRISpatialReference(this.SRef, out bytes2); // Create Search Extent IEnvelope extent = new EnvelopeClass(); extent.PutCoords(this.XMin, this.YMin, this.XMax, this.YMax); extent.SpatialReference = spatialReference; // Open Saved Layer File ILayerFile layerFile = new LayerFileClass(); layerFile.Open(this.Path); ILayer layer = layerFile.Layer; layerFile.Close(); // Where clause and list of selected OIDs string where = string.Empty; List<int> ids = new List<int>(); IImageServerLayer imageLayer = null; if (layer is IImageServerLayer) { imageLayer = (IImageServerLayer)layer; // Get Selection Set IFeatureLayerDefinition definition = layer as IFeatureLayerDefinition; if (definition != null) { // Find Selected OIDs if (definition.DefinitionSelectionSet != null) { if (definition.DefinitionSelectionSet.Count > 0) { IEnumIDs emumids = definition.DefinitionSelectionSet.IDs; int id = emumids.Next(); while (id != -1) { ids.Add(id); id = emumids.Next(); } } } // Update Where Clause if (!string.IsNullOrEmpty(definition.DefinitionExpression)) { where = definition.DefinitionExpression; } } } else if (layer is IMosaicLayer) { IMosaicLayer mosaicLayer = (IMosaicLayer)layer; imageLayer = mosaicLayer.PreviewLayer; ITableDefinition tableDefinition = mosaicLayer as ITableDefinition; if (tableDefinition != null) { // Find Selected OIDs if (tableDefinition.DefinitionSelectionSet != null) { if (tableDefinition.DefinitionSelectionSet.Count > 0) { IEnumIDs emumids = tableDefinition.DefinitionSelectionSet.IDs; int id = emumids.Next(); while (id != -1) { ids.Add(id); id = emumids.Next(); } } } // Update Where Clause if (!string.IsNullOrEmpty(tableDefinition.DefinitionExpression)) { where = tableDefinition.DefinitionExpression; } } } // Use FeatureSelected (if any) IFeatureSelection featureSelection = imageLayer as IFeatureSelection; if (featureSelection != null) { if (featureSelection.SelectionSet != null) { if (featureSelection.SelectionSet.Count > 0) { IEnumIDs emumids = featureSelection.SelectionSet.IDs; int id = emumids.Next(); while (id != -1) { ids.Add(id); id = emumids.Next(); } } } } // Get Bands ILongArray bands = new LongArrayClass(); IRasterRenderer rasterRenderer = imageLayer.Renderer; if (rasterRenderer != null) { IRasterRGBRenderer2 rasterRGBRenderer = rasterRenderer as IRasterRGBRenderer2; if (rasterRGBRenderer != null) { bands.Add(rasterRGBRenderer.UseRedBand ? rasterRGBRenderer.RedBandIndex : -1); bands.Add(rasterRGBRenderer.UseGreenBand ? rasterRGBRenderer.GreenBandIndex : -1); bands.Add(rasterRGBRenderer.UseBlueBand ? rasterRGBRenderer.BlueBandIndex : -1); bands.Add(rasterRGBRenderer.UseAlphaBand ? rasterRGBRenderer.AlphaBandIndex : -1); } } // Create Spatial Filter ISpatialFilter spatialFilter = new SpatialFilterClass() { Geometry = extent, SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects, WhereClause = where }; IImageServer imageServer = imageLayer.DataSource as IImageServer; if (imageServer == null) { return; } IImageServer3 imageServer3 = imageServer as IImageServer3; if (imageServer3 == null) { return; } IRecordSet recordSet = imageServer3.GetCatalogItems(spatialFilter); ICursor cursor = recordSet.get_Cursor(false); IFeatureCursor featureCursor = (IFeatureCursor)cursor; IFeature feature = featureCursor.NextFeature(); List<IFeature> list = new List<IFeature>(); int indexCategory = featureCursor.FindField("Category"); while (feature != null) { // Exclude non-primary images (no overviews) if (indexCategory != -1) { int cat = (int)feature.get_Value(indexCategory); if (cat != 1) { feature = featureCursor.NextFeature(); continue; } } // Exclude unselected features if (ids.Count > 0) { int oid = feature.OID; if (!ids.Contains(oid)) { feature = featureCursor.NextFeature(); continue; } } list.Add(feature); feature = featureCursor.NextFeature(); } // If nothing, fire event then exit if (list.Count == 0) { this.OnThumbnailSummary(new SummaryEventArgs()); return; } // Get Full Extent of Features SummaryEventArgs summary = new SummaryEventArgs() { XMin = list.Min(f => f.Shape.Envelope.CloneProject(spatialReference).XMin), YMin = list.Min(f => f.Shape.Envelope.CloneProject(spatialReference).YMin), XMax = list.Max(f => f.Shape.Envelope.CloneProject(spatialReference).XMax), YMax = list.Max(f => f.Shape.Envelope.CloneProject(spatialReference).YMax), Count = list.Count }; // Add Fields IFields fields = featureCursor.Fields; for (int i = 0; i < fields.FieldCount; i++) { IField field = fields.get_Field(i); switch (field.Type) { case esriFieldType.esriFieldTypeBlob: case esriFieldType.esriFieldTypeGeometry: case esriFieldType.esriFieldTypeGlobalID: case esriFieldType.esriFieldTypeGUID: case esriFieldType.esriFieldTypeRaster: case esriFieldType.esriFieldTypeXML: break; case esriFieldType.esriFieldTypeOID: case esriFieldType.esriFieldTypeDate: case esriFieldType.esriFieldTypeDouble: case esriFieldType.esriFieldTypeInteger: case esriFieldType.esriFieldTypeSingle: case esriFieldType.esriFieldTypeSmallInteger: case esriFieldType.esriFieldTypeString: summary.Fields.Add( new Field() { Name = field.Name, Alias = field.AliasName, Type = field.Type } ); break; default: break; } } // Raise Summary Event this.OnThumbnailSummary(summary); // Loop for each feature foreach (IFeature feat in list) { // Project Extent to Current Map Spatial Reference IEnvelope extentMap = feat.Shape.Envelope.CloneProject(spatialReference); int width; int height; if (extentMap.Width > extentMap.Height) { width = this.MaxImageSize; height = Convert.ToInt32((double)this.MaxImageSize * (double)extentMap.Height / (double)extentMap.Width); } else { width = Convert.ToInt32((double)this.MaxImageSize * (double)extentMap.Width / (double)extentMap.Height); height = this.MaxImageSize; } IMosaicRule mosaicRule = new MosaicRuleClass() { MosaicMethod = esriMosaicMethod.esriMosaicLockRaster, LockRasterID = feat.OID.ToString() }; IGeoImageDescription geoImageDescription = new GeoImageDescriptionClass() { BandSelection = bands.Count > 0 ? bands : null, MosaicRule = mosaicRule, Compression = "PNG", Width = width, Height = height, SpatialReference = spatialReference, Extent = extentMap, Interpolation = rstResamplingTypes.RSP_BilinearInterpolation, }; // Assembly MosaicRequest (will be executed in background thread) MosaicRequest mosaicRequest = new MosaicRequest() { MosaicExtractor = this, ImageServer = imageServer3, GeoImageDescription = geoImageDescription, XMin = extentMap.XMin, YMin = extentMap.YMin, XMax = extentMap.XMax, YMax = extentMap.YMax, }; // Add Attributes Names and Values foreach (Field field in summary.Fields) { int index = feat.Fields.FindField(field.Name); if (index < 0) { continue; } mosaicRequest.Attributes.Add(field.Name, feat.get_Value(index)); } // Start Mosaic Request in Background Thread Thread thread = new Thread(new ThreadStart(mosaicRequest.Execute)); MosaicEnvironment.Default.Threads.Add(thread); thread.Start(); } } catch { } }