public void GISShutdown() { try { IAoInitialize aoInit = new AoInitializeClass(); aoInit.Shutdown(); } catch (Exception ex) { throw new Exception(string.Format("关闭ESRI许可证时发生错误:{0}", ex.Message)); } }
static void Main(string[] args) { //运行环境初始化 ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.EngineOrDesktop); IAoInitialize aoinitialize = new AoInitializeClass(); esriLicenseStatus status = aoinitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeStandard); string path = System.Environment.CurrentDirectory; string name = "result.tif"; IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)(workspaceFactory.OpenFromFile(path, 0)); IRasterDataset pRasterDataset = rasterWorkspace.OpenRasterDataset(name); //创建栅格瓦片 CreateTilesFromRasterDataset(pRasterDataset, rasterWorkspace as IWorkspace, 500, 500); //修改栅格的值 ChangeRasterValue(pRasterDataset as IRasterDataset2); aoinitialize.Shutdown(); }
static void Main(string[] args) { #region Initialize the license ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeStandard); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); } #endregion //Coordinate system for raster column IGPCoordinateSystem rSR = new GPCoordinateSystemClass(); rSR.SpatialReference = CreateSpatialReference((int)esriSRProjCSType.esriSRProjCS_World_Mercator); //Coordinate system for geometry column IGPSpatialReference gSR = new GPSpatialReferenceClass(); gSR.SpatialReference = CreateSpatialReference((int)esriSRProjCSType.esriSRProjCS_World_Mercator); //Creates raster catalog CreateRasterCatalog_GP(rSR, gSR); //Loads rasters in the given directory to raster catalog LoadDirToRasterCatalog(outRC, rasterFolder); System.Console.WriteLine("Loading completed"); System.Console.ReadLine();//waiting user to click a key to finish //Do not make any call to ArcObjects after license is shut down. aoInit.Shutdown(); }
static void Main(string[] args) { ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null; try { ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic); Console.WriteLine("License Checkout successful."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); } try { //Create temporary unmanaged raster catalog and load all rasters CreateUnmanagedRasterCatalog(); //Open raster catalog IRasterWorkspaceEx rasterWorkspaceEx = (IRasterWorkspaceEx)OpenRasterPGDBWorkspace(tempPGDBPath); IRasterCatalog rasterCatalog = rasterWorkspaceEx.OpenRasterCatalog(tempRasterCatalog); //Mosaic rasters in the raster catalog Mosaic(rasterCatalog); } catch (Exception exc) { Console.WriteLine(exc.Message); } Console.Write("Please press any key to close the application."); Console.ReadKey(); //Do not make any call to ArcObjects after ShutDown() call aoInit.Shutdown(); }
static void Main(string[] args) { //If creating a raster dataset in ArcSDE, it will need Standard or Advanced License ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null; try { ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("License Checkout successful."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); } try { //Creates an empty raster dataset //Make sure parameters of the empty raster dataset match our data (number of bands, bit depth, etc.) CreateRasterDS(); //Loads rasters in the input folder to the new raster dataset LoadDirToRasterDataset(FGDBPath + "\\" + dsName, rasterFolder); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); } Console.Write("Please press any key to close the application."); Console.ReadKey(); //Do not make any call to ArcObjects after ShutDown() aoInit.Shutdown(); }
public Form1() { if (!RuntimeManager.Bind(ProductCode.Desktop)) MessageBox.Show("Could not bind to Desktop"); // Usual engine initialization code follows from here (AoInitialize). IAoInitialize init = new AoInitializeClass(); esriLicenseStatus licStatus = init.IsProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeAdvanced); if (licStatus == esriLicenseStatus.esriLicenseAvailable) { init.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); } else { licStatus = init.IsProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeStandard); if (licStatus == esriLicenseStatus.esriLicenseAvailable) { init.Initialize(esriLicenseProductCode.esriLicenseProductCodeStandard); } else { licStatus = init.IsProductCodeAvailable(esriLicenseProductCode.esriLicenseProductCodeBasic); if (licStatus == esriLicenseStatus.esriLicenseAvailable) { init.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic); } else { MessageBox.Show("No license available for Basic/Standard/Advanced."); } } } InitializeComponent(); init.Shutdown(); }
static void Main(string[] args) { string[] prefixes = new string[] { "/f$", "/t$", "/o$" }; CmdArgExtractor cae = new CmdArgExtractor(prefixes, '/', '$'); WindsorContainer container = new WindsorContainer(new XmlInterpreter()); XmlConfigurator.Configure(); IAoInitialize license = new AoInitializeClass(); license.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcEditor); ConnectionStringSettings connStr = ConfigurationManager.ConnectionStrings["SQL2008"]; SqlConnection sqlConnection = new SqlConnection(connStr.ConnectionString); sqlConnection.Open(); SQL2008Database sqlDatabase = new SQL2008Database(connStr.ConnectionString); if ((args.Length != 0) && (args[0].Contains("?"))) { Console.WriteLine("Please use the /f$ option to specify the shapefile path"); Console.WriteLine("(OPTIONAL) the /t$ option to specify a table name. If not specified, the name of the shapefile will be used as the table name."); Console.WriteLine("(OPTIONAL) the /o$ option to specify whether to overwrite (Y/N) if a table with the same name exists. If not specified, the existing table will not be overwritten and the import will be aborted."); return; } //if( !cae.ValidArgsPrefixes( args ) ) //{ // Console.WriteLine( "Invalid parameters specified." ); // Console.WriteLine( "" ); // Console.WriteLine( "Please use the /f: option to specify the shapefile path" ); // Console.WriteLine( "(OPTIONAL) the /t: option to specify a table name. If not specified, the name of the shapefile will be used as the table name." ); // Console.WriteLine( "(OPTIONAL) the /o: option to specify whether to overwrite if a table with the same name exists. If not specified, the existing table will not be overwritten and the import will be aborted." ); // return; //} string[ , ] inputParameters = cae.GetArgsTwoDimArray(args); Dictionary <string, string> inputParams = new Dictionary <string, string>(); for (int i = 0; i < args.Length; i++) { inputParams.Add(inputParameters[0, i].ToLower(), inputParameters[1, i].ToLower()); } if (!inputParams.ContainsKey("f")) { Console.WriteLine("A shapefile path must be specified to continue."); return; } string inputShapeFile = inputParams["f"]; if (!File.Exists(inputShapeFile)) { Console.WriteLine("The shapefile path is not valid."); return; } string shapefileDirectory = "C:\\SHPData\\WGS84"; string shapefile = "natarea"; shapefileDirectory = Path.GetDirectoryName(Path.GetFullPath(inputShapeFile)); shapefile = Path.GetFileNameWithoutExtension(inputShapeFile); string tableName = shapefile; if (inputParams.ContainsKey("t")) { tableName = inputParams["t"]; } if (sqlDatabase.ContainsTable(tableName)) { Console.WriteLine("A table with the same name '" + tableName + "' already exists in the database."); if (inputParams.ContainsKey("o") && ((inputParams["o"] == "y") || (inputParams["o"] == "yes"))) { Console.WriteLine("Deleting the existing table and creating a new table."); sqlDatabase.DeleteTable(tableName); } else { Console.WriteLine("Aborting import."); return; } } IWorkspace workspace = GeodatabaseUtil.GetShapefileWorkspace(shapefileDirectory); IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; IFeatureClass featureClass = featureWorkspace.OpenFeatureClass(shapefile); DefaultAoGeometryTypeProvider aoGeometryTypeProvider = new DefaultAoGeometryTypeProvider(); string geometryType = aoGeometryTypeProvider.GetGeometryType(featureClass.ShapeType); if (String.IsNullOrEmpty(geometryType)) { Console.WriteLine("The geometry type of the source FeatureClass is not supported."); Console.ReadLine(); return; } System.Collections.IDictionary parameters = new System.Collections.Hashtable(); parameters.Add("featureClass", featureClass); parameters.Add("layerName", tableName); parameters.Add("keyFieldName", featureClass.OIDFieldName); AoFCLayer shapeFileLayer = container.Resolve <AoFCLayer>("Ao" + geometryType, parameters); if (shapeFileLayer == null) { Console.WriteLine("Unable to create the input framework layer for the FeatureClass. Please check the component configuration."); Console.ReadLine(); return; } ISupportsGISFields shapeFileFields = shapeFileLayer as ISupportsGISFields; IGISFields inputFields = shapeFileFields.GetGISFields(); SqlCommand sqlCommand; int?srid = null; if (shapeFileLayer is ISupportsSRID) { srid = (shapeFileLayer as ISupportsSRID).Srid; } IGISLayer sql2008Layer = null; //Create the dictionary with the parameters to create the corresponding SQL 2008 layer System.Collections.IDictionary sqlParameters = new System.Collections.Hashtable(); sqlParameters.Add("tableName", tableName); sqlParameters.Add("shapeFieldName", "SHAPE"); sqlParameters.Add("layerName", tableName); sqlParameters.Add("keyFieldName", featureClass.OIDFieldName); if (srid.HasValue && WKIDRanges.IsGeographic(srid.Value)) { //Create the geography table with the fields from the FeatureClass sqlDatabase.CreateGeographyTable(inputFields, tableName, "SHAPE"); sqlCommand = new SqlCommand("Select * from " + tableName, sqlConnection); sqlParameters.Add("dbCommand", sqlCommand); sql2008Layer = container.Resolve <IGISLayer>("Sql2008Geog" + geometryType, sqlParameters); } else { //Create the geometry table with the fields from the FeatureClass sqlDatabase.CreateGeometryTable(inputFields, tableName, "SHAPE"); sqlCommand = new SqlCommand("Select * from " + tableName, sqlConnection); sqlParameters.Add("dbCommand", sqlCommand); sql2008Layer = container.Resolve <IGISLayer>("Sql2008Geom" + geometryType, sqlParameters); } //Get the editable layer reference to the destination sql table layer IGISEditableLayer editableLayer = sql2008Layer as IGISEditableLayer; //Quit the application if a valid editable layer reference could not be obtained if (editableLayer == null) { Console.WriteLine("The destination is either invalid or does not support editing."); return; } Console.WriteLine("Importing features..."); int count = 0; shapeFileLayer.Search(null); while (shapeFileLayer.MoveNext()) { try { editableLayer.Add(shapeFileLayer.Current); } catch (Exception ex) { _log.Error("An unexpected error occured while adding feature. " + ex.Message, ex); } Console.SetCursorPosition(0, Console.CursorTop); Console.Write(++count); } license.Shutdown(); Console.WriteLine(); Console.WriteLine("Import completed. Press any key to exit."); Console.ReadKey(false); }
public static void Main(string[] args) { #region Initialize License ESRI.ArcGIS.esriSystem.AoInitialize aoInit; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); // To make changes to a Mosaic Dataset, a Standard or Advanced license is required. esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); return; } #endregion try { // Flags to specify the operation to perform bool addToRD = true; // Create NDVI Custom Function Raster Dataset bool addToMD = false; // Add NDVI Custom Function to MD bool writeTemplateToXml = false; // Serialize a template form of the NDVI Custom Funtion to Xml. bool getfromXml = false; // Get a template object back from its serialized xml. #region Specify inputs. // Raster Dataset parameters string workspaceFolder = @"c:\temp"; string rasterDatasetName = "Dubai_ov.tif"; // Output parameters for Function Raster Dataset string outputFolder = @"c:\temp"; string outputName = "NDVICustomFunctionSample.afr"; // Mosaic dataset parameters // GDB containing the Mosaic Dataset string mdWorkspaceFolder = @"c:\temp\testGdb.gdb"; // Name of the mosaic dataset string mdName = "testMD"; // NDVI Custom Function Parameters string bandIndices = @"4 3"; // Xml file path to save to or read from xml. string xmlFilePath = @"e:\Dev\Samples CSharp\CustomRasterFunction\Xml\NDVICustomAFR.xml"; #endregion if (addToRD) { // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(workspaceFolder, 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(rasterDatasetName); AddNDVICustomToRD(rasterDataset, outputFolder, outputName, bandIndices); // Cleanup workspaceFactory = null; rasterWorkspace = null; rasterDataset = null; } if (addToMD) AddNDVICustomDataToMD(mdWorkspaceFolder, mdName, bandIndices, true); if (writeTemplateToXml && xmlFilePath != "") { // Create a template with the NDVI Custom Function. IRasterFunctionTemplate ndviCustomFunctionTemplate = CreateNDVICustomTemplate(bandIndices); // Serialize the template to an xml file. bool status = WriteToXml(ndviCustomFunctionTemplate, xmlFilePath); } if (getfromXml && xmlFilePath != "") { // Create a RasterFunctionTemplate object from the serialized xml. object serializedObj = ReadFromXml(xmlFilePath); if (serializedObj is IRasterFunctionTemplate) Console.WriteLine("Success."); else Console.WriteLine("Failed."); } Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } catch (Exception exc) { Console.WriteLine("Exception Caught in Main: " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } }
public static void Main(string[] args) { ESRI.ArcGIS.esriSystem.AoInitialize aoInit; #region Initialize Licensing try { Console.WriteLine("Obtaining License"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license"); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); return; } #endregion try { #region Specify input directory and dataset name // Specify where to create the File Gdb string fgdbFolder = @"c:\temp\CustomRasterType"; // Specify the folder to add the data from string dataSource = @"c:\data\RasterDatasets"; // Specify whether to DELETE the fgdbFolder and create it again (clearing it). bool clearFGdbFolder = false; // Specify whether to save the Custom Raster Type generated to an art file. bool saveToArtFile = true; // Specify the path and filename to save the custom type. string customTypeFilePath = @"C:\temp\ThumbnailType.art"; #endregion #region Raster Type Parameters string rasterTypeName = @"Thumbnail Raster Dataset"; // Specify the file filter to use to add data (Optional) string dataSourceFilter = "*.tif"; string rasterTypeProductFilter = @""; string rasterTypeProductName = @""; #endregion TestThumbnailBuilder(rasterTypeName, rasterTypeProductFilter, rasterTypeProductName, dataSource, dataSourceFilter, fgdbFolder, saveToArtFile, customTypeFilePath, clearFGdbFolder); #region Shutdown Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); #endregion } catch (Exception exc) { #region Shutdown Console.WriteLine("Exception Caught in Main: " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Shutting down."); Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } }
public static void Main(string[] args) { #region Licensing ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); IAoInitialize aoInitialize = new AoInitializeClass(); esriLicenseStatus licenseStatus = aoInitialize.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); if (licenseStatus != esriLicenseStatus.esriLicenseCheckedOut) { MessageBox.Show("An Advanced License could not be checked out."); return; } #endregion try { // Open the workspace. IWorkspaceFactory workspaceFactory = null; switch (geodatabaseType) { case GeodatabaseType.ArcSDE: workspaceFactory = new SdeWorkspaceFactoryClass(); break; case GeodatabaseType.FileGDB: workspaceFactory = new FileGDBWorkspaceFactoryClass(); break; case GeodatabaseType.PersonalGDB: workspaceFactory = new AccessWorkspaceFactoryClass(); break; } IWorkspace workspace = workspaceFactory.OpenFromFile(workspacePath, 0); IWorkspaceExtensionManager workspaceExtensionManager = (IWorkspaceExtensionManager)workspace; // Create a UID for the workspace extension. UID uid = new UIDClass(); uid.Value = extensionGuid; // Determine whether there are any existing geodatabase-register extensions. // To disambiguate between GDB-register extensions and component category extensions, // check the extension count of a new scratch workspace. IScratchWorkspaceFactory scratchWorkspaceFactory = new FileGDBScratchWorkspaceFactoryClass(); IWorkspace scratchWorkspace = scratchWorkspaceFactory.CreateNewScratchWorkspace(); IWorkspaceExtensionManager scratchExtensionManager = (IWorkspaceExtensionManager)scratchWorkspace; Boolean workspaceExtensionApplied = false; UID gdbRegisteredUID = null; try { workspaceExtensionApplied = (workspaceExtensionManager.ExtensionCount > scratchExtensionManager.ExtensionCount); } catch (COMException comExc) { // This is necessary in case the existing extension could not be initiated. if (comExc.ErrorCode == (int)fdoError.FDO_E_WORKSPACE_EXTENSION_CREATE_FAILED) { // Parse the error message for the current extension's GUID. Regex regex = new Regex("(?<guid>{[^}]+})"); MatchCollection matchCollection = regex.Matches(comExc.Message); if (matchCollection.Count > 0) { Match match = matchCollection[0]; gdbRegisteredUID = new UIDClass(); gdbRegisteredUID.Value = match.Groups["guid"].Value; workspaceExtensionApplied = true; } else { throw comExc; } } else { throw comExc; } } if (workspaceExtensionApplied) { if (gdbRegisteredUID == null) { // There is GDB-registered extension on the SDE workspace. Find the SDE extension that is not // applied to the scratch workspace. for (int i = 0; i < workspaceExtensionManager.ExtensionCount; i++) { IWorkspaceExtension workspaceExtension = workspaceExtensionManager.get_Extension(i); IWorkspaceExtension scratchExtension = scratchExtensionManager.FindExtension(workspaceExtension.GUID); if (scratchExtension == null) { gdbRegisteredUID = workspaceExtension.GUID; } } } } // If the extension could be located, remove it. if (gdbRegisteredUID != null) { workspaceExtensionManager.UnRegisterExtension(gdbRegisteredUID); } // Register the extension. workspaceExtensionManager.RegisterExtension("RasterSyncExtension.RasterSyncWorkspaceExtension", uid); } catch (COMException comExc) { switch (comExc.ErrorCode) { case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_NO_REG_PRIV: MessageBox.Show("The connection file's privileges are insufficient to perform this operation.", "Register Workspace Extension", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_CREATE_FAILED: String createErrorMessage = String.Concat("The workspace extension could not be created.", Environment.NewLine, "Ensure that it has been registered for COM Interop."); MessageBox.Show(createErrorMessage, "Register Workspace Extension", MessageBoxButtons.OK, MessageBoxIcon.Error); break; case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_DUP_GUID: case (int)fdoError.FDO_E_WORKSPACE_EXTENSION_DUP_NAME: String dupErrorMessage = String.Concat("A duplicate name or GUID was detected. Make sure any existing GDB-registered", "workspaces are not component category-registered as well."); MessageBox.Show(dupErrorMessage, "Register Workspace Extension", MessageBoxButtons.OK, MessageBoxIcon.Error); break; default: String otherErrorMessage = String.Format("An unexpected error has occurred:{0}{1}{2}", Environment.NewLine, comExc.Message, comExc.ErrorCode); MessageBox.Show(otherErrorMessage); break; } } catch (Exception exc) { String errorMessage = String.Format("An unexpected error has occurred:{0}{1}", Environment.NewLine, exc.Message); MessageBox.Show(errorMessage); } // Shutdown the AO initializer. aoInitialize.Shutdown(); }
public static void Main(string[] args) { #region Initialize License ESRI.ArcGIS.esriSystem.AoInitialize aoInit; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); // To make changes to a Mosaic Dataset, a Standard or Advanced license is required. esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); return; } #endregion try { // Flags to specify the operation to perform bool addToRD = true; // Create NDVI Custom Function Raster Dataset bool addToMD = false; // Add NDVI Custom Function to MD bool writeTemplateToXml = false; // Serialize a template form of the NDVI Custom Funtion to Xml. bool getfromXml = false; // Get a template object back from its serialized xml. #region Specify inputs. // Raster Dataset parameters string workspaceFolder = @"c:\temp"; string rasterDatasetName = "Dubai_ov.tif"; // Output parameters for Function Raster Dataset string outputFolder = @"c:\temp"; string outputName = "NDVICustomFunctionSample.afr"; // Mosaic dataset parameters // GDB containing the Mosaic Dataset string mdWorkspaceFolder = @"c:\temp\testGdb.gdb"; // Name of the mosaic dataset string mdName = "testMD"; // NDVI Custom Function Parameters string bandIndices = @"4 3"; // Xml file path to save to or read from xml. string xmlFilePath = @"e:\Dev\Samples CSharp\CustomRasterFunction\Xml\NDVICustomAFR.xml"; #endregion if (addToRD) { // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(workspaceFolder, 0); IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(rasterDatasetName); AddNDVICustomToRD(rasterDataset, outputFolder, outputName, bandIndices); // Cleanup workspaceFactory = null; rasterWorkspace = null; rasterDataset = null; } if (addToMD) { AddNDVICustomDataToMD(mdWorkspaceFolder, mdName, bandIndices, true); } if (writeTemplateToXml && xmlFilePath != "") { // Create a template with the NDVI Custom Function. IRasterFunctionTemplate ndviCustomFunctionTemplate = CreateNDVICustomTemplate(bandIndices); // Serialize the template to an xml file. bool status = WriteToXml(ndviCustomFunctionTemplate, xmlFilePath); } if (getfromXml && xmlFilePath != "") { // Create a RasterFunctionTemplate object from the serialized xml. object serializedObj = ReadFromXml(xmlFilePath); if (serializedObj is IRasterFunctionTemplate) { Console.WriteLine("Success."); } else { Console.WriteLine("Failed."); } } Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } catch (Exception exc) { Console.WriteLine("Exception Caught in Main: " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Press any key..."); Console.ReadKey(); aoInit.Shutdown(); } }
static void Main(string[] args) { ESRI.ArcGIS.esriSystem.AoInitialize aoInit; #region Initialize License try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); return; } #endregion try { // Specify input directory and dataset name. string inputWorkspace = @"C:\Data"; string inputDatasetName = "8bitSampleImage.tif"; // Specify output filename. string outputDataset = @"c:\Temp\testArithmaticCS.afr"; // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace workspace = workspaceFactory.OpenFromFile(inputWorkspace, 0); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspace; IRasterDataset myRasterDataset = rasterWorkspace.OpenRasterDataset(inputDatasetName); // Create the Function Arguments object IArithmeticFunctionArguments rasterFunctionArguments = (IArithmeticFunctionArguments)new ArithmeticFunctionArguments(); // Set the parameters for the function: // Specify the operation as addition (esriRasterPlus) rasterFunctionArguments.Operation = esriRasterArithmeticOperation.esriRasterPlus; // Specify the first operand, i.e. the Raster Dataset opened above. rasterFunctionArguments.Raster = myRasterDataset; // For the second operand, create an array of double values // containing the scalar value to be used as the second operand // to each band of the input dataset. // The number of values in the array should equal the number // of bands of the input dataset. double[] scalars = { 128.0, 128.0, 128.0 }; // Create a new Scalar object and specify // the array as its value. IScalar scalarVals = new ScalarClass(); scalarVals.Value = scalars; // Specify the scalar object as the second operand. rasterFunctionArguments.Raster2 = scalarVals; // Create the Raster Function object. IRasterFunction rasterFunction = new ArithmeticFunction(); rasterFunction.PixelType = rstPixelType.PT_USHORT; // Create the Function Raster Dataset Object. IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset(); // Create a name object for the Function Raster Dataset. IFunctionRasterDatasetName functionRasterDatasetName = (IFunctionRasterDatasetName)new FunctionRasterDatasetName(); // Specify the output filename for the new dataset (including // the .afr extension at the end). functionRasterDatasetName.FullName = outputDataset; functionRasterDataset.FullName = (IName)functionRasterDatasetName; // Initialize the new Function Raster Dataset with the Raster Function // and its arguments. functionRasterDataset.Init(rasterFunction, rasterFunctionArguments); // QI for the Temporary Dataset interface ITemporaryDataset myTempDset = (ITemporaryDataset)functionRasterDataset; // and make it a permanent dataset. This creates the afr file. myTempDset.MakePermanent(); // Report Console.WriteLine("Success."); Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); } catch (Exception exc) { // Report Console.WriteLine("Exception Caught while creating Function Raster Dataset. " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); } }
static void Main(string[] args) { ESRI.ArcGIS.esriSystem.AoInitialize aoInit; #region Initialize License try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); return; } #endregion try { #region Specify input directory and dataset name // The directory which contains the Panchromatic Image. string panDir = @"C:\Data\QB\Pan"; // The directory which contains the Multispectral Image. string rgbDir = @"C:\Data\QB\MS"; string panImageName = "05JAN27104436-P1BS-005533787010_01_P002.TIF"; string rgbImageName = "05JAN27104436-M1BS-005533787010_01_P002.TIF"; // Output filename. string outputDataset = @"c:\Temp\QBTemplateCS.afr"; #endregion #region Initialize // Setup Workspaces. Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IRasterWorkspace panRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(panDir, 0); IRasterWorkspace rgbRasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(rgbDir, 0); // Open Datasets IRasterDataset panDataset = panRasterWorkspace.OpenRasterDataset(panImageName); IRasterDataset rgbDataset = rgbRasterWorkspace.OpenRasterDataset(rgbImageName); #endregion #region Create Variables // Create one variable of type IRasterFunctionVariable for each // Raster Dataset opened above // Create a new Raster Function Variable IRasterFunctionVariable panVar = new RasterFunctionVariableClass(); // Set the name of the variable panVar.Name = "panImage"; // Describe the variable panVar.Description = "Panchromatic Image to be used for pansharpening"; // Specify whether it represents a dataset panVar.IsDataset = true; // Create a new Raster Function Variable IRasterFunctionVariable rgbVar = new RasterFunctionVariableClass(); // Set the name of the variable rgbVar.Name = "rgbImage"; // Describe the variable rgbVar.Description = "Multispectral Image to be used for pansharpening"; // Specify whether it represents a dataset rgbVar.IsDataset = true; #endregion #region Prepare the Pan Image // Setup statistics for each band IArray statsArrayPan = new ArrayClass(); IRasterStatistics statsPanBand = new RasterStatisticsClass(); statsPanBand.Minimum = 1; statsPanBand.Maximum = 2047; statsArrayPan.Add(statsPanBand); // Create the arguments object for the stretching function IStretchFunctionArguments stretchingPanFunctionArguements = new StretchFunctionArgumentsClass(); // Set the stretching type stretchingPanFunctionArguements.StretchType = esriRasterStretchType.esriRasterStretchMinimumMaximum; // Set the statistics created above stretchingPanFunctionArguements.Statistics = statsArrayPan; // Set the input raster, in this case, the variable for the Pan Image stretchingPanFunctionArguements.Raster = panVar; // Create the function object to stretch the Pan Image. IRasterFunction stretchingPanFunction = new StretchFunction(); // Create a Raster Function Template object for the stretch function IRasterFunctionTemplate stretchingPanFunctionT = new RasterFunctionTemplateClass(); // Set the function on the template stretchingPanFunctionT.Function = (IRasterFunction)stretchingPanFunction; // Set the arguments for the function stretchingPanFunctionT.Arguments = stretchingPanFunctionArguements; #endregion #region Prepare the Multispectral (RGB) Image // Create an array which defines the order of bands ILongArray bandIDs = new LongArrayClass(); bandIDs.Add(2); bandIDs.Add(1); bandIDs.Add(0); // Create an Extract Band Function Arguments object IExtractBandFunctionArguments extractRgbBandFunctionArgs = (IExtractBandFunctionArguments) new ExtractBandFunctionArguments(); // Set the order of bands of the output extractRgbBandFunctionArgs.BandIDs = bandIDs; // Set the input raster, in this case the variable for the Multispectral Image extractRgbBandFunctionArgs.Raster = rgbVar; // Create the Extract Band Function object IRasterFunction extractRgbBandFunction = new ExtractBandFunction(); // Create a Raster Function Template object for the function created above IRasterFunctionTemplate extractRgbBandFunctionT = new RasterFunctionTemplateClass(); // Set the function on the template extractRgbBandFunctionT.Function = (IRasterFunction)extractRgbBandFunction; // Set the arguments for the function extractRgbBandFunctionT.Arguments = extractRgbBandFunctionArgs; // Setup statistics for each band IArray statsArray = new ArrayClass(); IRasterStatistics statsMulBand1 = new RasterStatisticsClass(); statsMulBand1.Minimum = 100; statsMulBand1.Maximum = 1721; statsArray.Add(statsMulBand1); IRasterStatistics statsMulBand2 = new RasterStatisticsClass(); statsMulBand2.Minimum = 95; statsMulBand2.Maximum = 2047; statsArray.Add(statsMulBand2); IRasterStatistics statsMulBand3 = new RasterStatisticsClass(); statsMulBand3.Minimum = 34; statsMulBand3.Maximum = 2006; statsArray.Add(statsMulBand3); // Create a stretching function for the multispectral image IRasterFunction stretchingRGBFunction = new StretchFunction(); // Create an arguments object for the stretch function IStretchFunctionArguments stretchingRGBFunctionArguments = new StretchFunctionArgumentsClass(); // Set the type of stretchings to perform stretchingRGBFunctionArguments.StretchType = esriRasterStretchType.esriRasterStretchMinimumMaximum; // Set the statistics created above stretchingRGBFunctionArguments.Statistics = statsArray; // Set the extract band function template created above as the input stretchingRGBFunctionArguments.Raster = extractRgbBandFunctionT; // Create a Raster Function Template object for the function created above IRasterFunctionTemplate stretchingRGBFunctionT = new RasterFunctionTemplateClass(); // Set the function on the template stretchingRGBFunctionT.Function = (IRasterFunction)stretchingRGBFunction; // Set the arguments for the function stretchingRGBFunctionT.Arguments = stretchingRGBFunctionArguments; #endregion #region Pansharpen the Pan Image with the Multispectral // Create a Raster Function Arguments object for the pansharpen function IPansharpeningFunctionArguments pansharpFunctionArguements = new PansharpeningFunctionArgumentsClass(); // Set the Panchromatic image which has been prepared above pansharpFunctionArguements.PanImage = stretchingPanFunctionT; // Set the Multispectral image which has been prepared above pansharpFunctionArguements.MSImage = stretchingRGBFunctionT; // Create a new pansharpen raster function object IRasterFunction pansharpenFunction = new PansharpeningFunction(); // Create a new pansharpen function arguments object IPansharpeningFunctionArguments pansharpenFunctionArguements = new PansharpeningFunctionArgumentsClass(); // Set the pansharpening type pansharpenFunctionArguements.PansharpeningType = esriPansharpeningType.esriPansharpeningESRI; // Create an array of doubles that sets the weights for each band IDoubleArray weightsArray = new DoubleArrayClass(); weightsArray.Add(0.167); weightsArray.Add(0.166); weightsArray.Add(0.166); // and set it on the arguments object pansharpenFunctionArguements.Weights = weightsArray; // Create a Raster Function Template object for the pansharpen function IRasterFunctionTemplate rasterFunction = new RasterFunctionTemplateClass(); rasterFunction.Function = (IRasterFunction)pansharpenFunction; rasterFunction.Arguments = pansharpFunctionArguements; ((IRasterFunction)rasterFunction).PixelType = rstPixelType.PT_UCHAR; #endregion #region Resolve variables // Create a PropertySet object to set the values for the // Raster Function Variables created above IPropertySet variables = new PropertySet(); variables.SetProperty("panImage", panDataset); variables.SetProperty("rgbImage", rgbDataset); #endregion #region Create the Function Raster Dataset // Create the Function Raster Dataset Object for the Pansharpened Dataset IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset(); // Create a name object for the Function Raster Dataset. IFunctionRasterDatasetName functionRasterDatasetName = new FunctionRasterDatasetNameClass(); // Specify the output filename for the new dataset (including // the .afr extension at the end). functionRasterDatasetName.FullName = outputDataset; functionRasterDataset.FullName = (IName)functionRasterDatasetName; // Initialize the new Function Raster Dataset with the Raster Function // Template and the property set containing the variables and their values. functionRasterDataset.Init((IRasterFunction)rasterFunction, variables); ITemporaryDataset myTempDset = (ITemporaryDataset)functionRasterDataset; myTempDset.MakePermanent(); #endregion #region Shutdown Console.WriteLine("Success."); Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } catch (Exception exc) { #region Shutdown Console.WriteLine("Exception Caught while creating Function Raster Dataset. " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } }
static void Main(string[] args) { ESRI.ArcGIS.esriSystem.AoInitialize aoInit; #region Initialize License try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); return; } #endregion try { // Specify input directory and dataset name. string inputWorkspace = @"C:\Data"; string inputDatasetName = "8bitSampleImage.tif"; // Specify output filename. string outputDataset = @"c:\Temp\testArithmaticCS.afr"; // Open the Raster Dataset Type factoryType = Type.GetTypeFromProgID("esriDataSourcesRaster.RasterWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType); IWorkspace workspace = workspaceFactory.OpenFromFile(inputWorkspace, 0); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspace; IRasterDataset myRasterDataset = rasterWorkspace.OpenRasterDataset(inputDatasetName); // Create the Function Arguments object IArithmeticFunctionArguments rasterFunctionArguments = (IArithmeticFunctionArguments) new ArithmeticFunctionArguments(); // Set the parameters for the function: // Specify the operation as addition (esriRasterPlus) rasterFunctionArguments.Operation = esriRasterArithmeticOperation.esriRasterPlus; // Specify the first operand, i.e. the Raster Dataset opened above. rasterFunctionArguments.Raster = myRasterDataset; // For the second operand, create an array of double values // containing the scalar value to be used as the second operand // to each band of the input dataset. // The number of values in the array should equal the number // of bands of the input dataset. double[] scalars = { 128.0, 128.0, 128.0 }; // Create a new Scalar object and specify // the array as its value. IScalar scalarVals = new ScalarClass(); scalarVals.Value = scalars; // Specify the scalar object as the second operand. rasterFunctionArguments.Raster2 = scalarVals; // Create the Raster Function object. IRasterFunction rasterFunction = new ArithmeticFunction(); rasterFunction.PixelType = rstPixelType.PT_USHORT; // Create the Function Raster Dataset Object. IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset(); // Create a name object for the Function Raster Dataset. IFunctionRasterDatasetName functionRasterDatasetName = (IFunctionRasterDatasetName) new FunctionRasterDatasetName(); // Specify the output filename for the new dataset (including // the .afr extension at the end). functionRasterDatasetName.FullName = outputDataset; functionRasterDataset.FullName = (IName)functionRasterDatasetName; // Initialize the new Function Raster Dataset with the Raster Function // and its arguments. functionRasterDataset.Init(rasterFunction, rasterFunctionArguments); // QI for the Temporary Dataset interface ITemporaryDataset myTempDset = (ITemporaryDataset)functionRasterDataset; // and make it a permanent dataset. This creates the afr file. myTempDset.MakePermanent(); // Report Console.WriteLine("Success."); Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); } catch (Exception exc) { // Report Console.WriteLine("Exception Caught while creating Function Raster Dataset. " + exc.Message); Console.WriteLine("Failed."); Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); } }
static void Main(string[] args) { #region Initialize License ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); } #endregion try { #region Setup MD Parameters MDParameters.gdbParentFolder = @"e:\MD\CustomRasterType\DMCII"; // Choose which type of gdb to create/open. // 0 - Create File Gdb // 1 - Create Personal Gdb // 2 - Open SDE int gdbOption = 0; // Provide the proper extension based on the gdb you want to create. // e.g. MDParameters.gdbName = "samplePGdb.mdb" to create a personal gdb. // To use an SDE, set SDE connection properties below. MDParameters.gdbName = @"CustomTypeGdb.gdb"; MDParameters.mosaicDatasetName = @"CustomTypeMD"; // Specify the srs of the mosaic dataset ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass(); MDParameters.mosaicDatasetSrs = spatialrefFactory.CreateProjectedCoordinateSystem( (int)(esriSRProjCSType.esriSRProjCS_World_Mercator)); // 0 and PT_UNKNOWN for bits and bands = use defaults. MDParameters.mosaicDatasetBands = 0; MDParameters.mosaicDatasetBits = rstPixelType.PT_UNKNOWN; MDParameters.configKeyword = ""; // Product Definition key choices: // None // NATURAL_COLOR_RGB // NATURAL_COLOR_RGBI // FALSE_COLOR_IRG // FORMOSAT-2_4BANDS // GEOEYE-1_4BANDS // IKONOS_4BANDS // KOMPSAT-2_4BANDS // LANDSAT_6BANDS // LANDSAT_MSS_4BANDS // QUICKBIRD_4BANDS // RAPIDEYE_5BANDS // SPOT-5_4BANDS // WORLDVIEW-2_8BANDS // Setting this property ensures any data added to the MD with its // metadata defined gets added with the correct band combination. MDParameters.productDefinitionKey = "FALSE_COLOR_IRG"; MDParameters.rasterTypeName = "DMCIIRasterType"; // The next two properties can be left blank for defaults // The product filter defines which specific product of the raster // type to add, e.g. To specfiy Quickbird Basic use value "Basic" MDParameters.rasterTypeProductFilter = ""; // The product name specifies which template to use when adding data. // e.g. "Pansharpen and Multispectral" means both multispectral and // pansharpened rasters are added to the mosaic dataset. MDParameters.rasterTypeProductName = "Raw"; // Data source from which to read the data. MDParameters.dataSource = @"F:\Data\DMCii"; MDParameters.dataSourceFilter = @""; // No need to set if data source has an srs or if you want to use the MD srs as data source srs. MDParameters.dataSourceSrs = null; MDParameters.buildOverviews = false; #endregion MDParameters.emptyGdbFolder = false; MDParameters.createGdbParentFolder = false; #region Empty/Create Output Directory if (MDParameters.emptyGdbFolder) { try { Console.WriteLine("Emptying Output Directory"); Directory.Delete(MDParameters.gdbParentFolder, true); Directory.CreateDirectory(MDParameters.gdbParentFolder); } catch (Exception) { } } if (MDParameters.createGdbParentFolder && !System.IO.Directory.Exists(MDParameters.gdbParentFolder)) { Console.WriteLine("Creating Output Directory"); Directory.CreateDirectory(MDParameters.gdbParentFolder); } #endregion CreateMD createMD = new CreateMD(); if (gdbOption == 0) { #region Create MD in File GDB Console.WriteLine("Creating File GDB: " + MDParameters.gdbName); IWorkspace fgdbWorkspace = CreateFileGdbWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName); createMD.CreateMosaicDataset(fgdbWorkspace); #endregion } else if (gdbOption == 1) { #region Create MD in Personal GDB Console.WriteLine("Creating Personal GDB: " + MDParameters.gdbName); IWorkspace pGdbWorkspace = CreateAccessWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName); createMD.CreateMosaicDataset(pGdbWorkspace); #endregion } else if (gdbOption == 2) { #region Open SDE GDB // Set SDE connection properties. IPropertySet sdeProperties = new PropertySetClass(); sdeProperties.SetProperty("SERVER", "barbados"); sdeProperties.SetProperty("INSTANCE", "9411"); sdeProperties.SetProperty("VERSION", "sde.DEFAULT"); sdeProperties.SetProperty("USER", "gdb"); sdeProperties.SetProperty("PASSWORD", "gdb"); sdeProperties.SetProperty("DATABASE", "VTEST"); IWorkspace sdeWorkspace = CreateSdeWorkspace(sdeProperties); if (sdeWorkspace == null) { Console.WriteLine("Could not open SDE workspace: "); return; } #endregion #region Create MD in SDE MDParameters.mosaicDatasetName = @"sampleMD"; createMD.CreateMosaicDataset(sdeWorkspace); #endregion } #region Shutdown Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } catch (Exception exc) { #region Report Console.WriteLine("Exception Caught in Main: " + exc.Message); Console.WriteLine("Shutting down."); #endregion #region Shutdown Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } }
static void Main() { #region Initialize license ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null; try { ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeBasic); Console.WriteLine("License Checkout successful."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); } #endregion try { //Get the location for data installed with .net sdk string versionInfo = RuntimeManager.ActiveRuntime.Version; RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\ESRI\ArcObjectsSDK" + versionInfo + @"\.NET"); string path = System.Convert.ToString(regKey.GetValue("MainDir")); string rasterFolder = System.IO.Path.Combine(path, @"Samples\ArcObjectsNET\CustomNodataFilter"); IPixelOperation raster = (IPixelOperation)OpenRasterDataset(rasterFolder, "testimage.tif"); if (raster == null) { Console.WriteLine("invalid raster"); return; } //create nodatafilter and set properties CustomNodataFilter.INodataFilter nFilter = new CustomNodataFilter.NodataFilter(); //filter out all values between 0 and 50 as nodata nFilter.MinNodataValue = 0; nFilter.MaxNodataValue = 50; //apply the convolutionfilter to raster raster.PixelFilter = nFilter; //set nodata value using the minimum of the nodata range IRasterProps rasterProps = (IRasterProps)raster; rasterProps.NoDataValue = 0; //save the filtered raster to a new raster dataset in TEMP directory ISaveAs saveAs = (ISaveAs)raster; //IWorkspace workspace = OpenWorkspace(Environment.GetEnvironmentVariable("TEMP")); IWorkspace workspace = OpenWorkspace(rasterFolder); saveAs.SaveAs("nodata.tif", workspace, "TIFF"); Console.WriteLine("Completed"); Console.ReadLine(); } catch (Exception e) { Console.WriteLine(e.Message); } //ESRI License Initializer generated code. //Do not make any call to ArcObjects after ShutDown() aoInit.Shutdown(); }
static void Main(string[] args) { #region Initialize License ESRI.ArcGIS.esriSystem.AoInitialize aoInit = null; try { Console.WriteLine("Obtaining license"); ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop); aoInit = new AoInitializeClass(); esriLicenseStatus licStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeAdvanced); Console.WriteLine("Ready with license."); } catch (Exception exc) { // If it fails at this point, shutdown the test and ignore any subsequent errors. Console.WriteLine(exc.Message); } #endregion try { #region Setup MD Parameters MDParameters.gdbParentFolder = @"c:\temp\CreateMD"; // Choose which type of gdb to create/open. // 0 - Create File Gdb // 1 - Create Personal Gdb // 2 - Open SDE int gdbOption = 0; // Provide the proper extension based on the gdb you want to create. // e.g. MDParameters.gdbName = "samplePGdb.mdb" to create a personal gdb. // To use an SDE, set SDE connection properties below. MDParameters.gdbName = @"sampleGdb.gdb"; MDParameters.mosaicDatasetName = @"sampleMD"; // Specify the srs of the mosaic dataset ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass(); MDParameters.mosaicDatasetSrs = spatialrefFactory.CreateProjectedCoordinateSystem( (int)(esriSRProjCSType.esriSRProjCS_World_Mercator)); // 0 and PT_UNKNOWN for bits and bands = use defaults. MDParameters.mosaicDatasetBands = 0; MDParameters.mosaicDatasetBits = rstPixelType.PT_UNKNOWN; MDParameters.configKeyword = ""; // Product Definition key choices: // None // NATURAL_COLOR_RGB // NATURAL_COLOR_RGBI // FALSE_COLOR_IRG // FORMOSAT-2_4BANDS // GEOEYE-1_4BANDS // IKONOS_4BANDS // KOMPSAT-2_4BANDS // LANDSAT_6BANDS // LANDSAT_MSS_4BANDS // QUICKBIRD_4BANDS // RAPIDEYE_5BANDS // SPOT-5_4BANDS // WORLDVIEW-2_8BANDS // Setting this property ensures any data added to the MD with its // metadata defined gets added with the correct band combination. MDParameters.productDefinitionKey = "FALSE_COLOR_IRG"; MDParameters.rasterTypeName = "QuickBird"; // The next two properties can be left blank for defaults // The product filter defines which specific product of the raster // type to add, e.g. To specfiy Quickbird Basic use value "Basic" MDParameters.rasterTypeProductFilter = ""; // The product name specifies which template to use when adding data. // e.g. "Pansharpen and Multispectral" means both multispectral and // pansharpened rasters are added to the mosaic dataset. MDParameters.rasterTypeProductName = "Multispectral"; // Data source from which to read the data. MDParameters.dataSource = //@"\\Qalab_server\data\Raster\DOTNET\Input\DatasourcesRaster\FunctionRasterDataset\RasterDataset"; @"\\qalab_server\data\Raster\DOTNET\Input\DatasourcesRaster\MosaicDataset\QB\Torino"; //@"\\isdemo1\0_sampledata\SampleData\DataSets\QBBasic1b\Baghdad\X0388"; MDParameters.dataSourceFilter = @""; // No need to set if data source has an srs or if you want to use the MD srs as data source srs. MDParameters.dataSourceSrs = null; MDParameters.buildOverviews = true; #endregion MDParameters.emptyFgdbFolder = true; MDParameters.createFgdbParentFolder = false; #region Empty/Create Output Directory if (MDParameters.emptyFgdbFolder) { try { Console.WriteLine("Emptying Output Directory"); Directory.Delete(MDParameters.gdbParentFolder, true); Directory.CreateDirectory(MDParameters.gdbParentFolder); } catch (Exception) { } } if (MDParameters.createFgdbParentFolder && !System.IO.Directory.Exists(MDParameters.gdbParentFolder)) { Console.WriteLine("Creating Output Directory"); Directory.CreateDirectory(MDParameters.gdbParentFolder); } #endregion CreateMD createMD = new CreateMD(); if (gdbOption == 0) { #region Create MD in File GDB Console.WriteLine("Creating File GDB: " + MDParameters.gdbName); IWorkspace fgdbWorkspace = CreateFileGdbWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName); createMD.CreateMosaicDataset(fgdbWorkspace); #endregion } else if (gdbOption == 1) { #region Create MD in Personal GDB Console.WriteLine("Creating Personal GDB: " + MDParameters.gdbName); IWorkspace pGdbWorkspace = CreateAccessWorkspace(MDParameters.gdbParentFolder, MDParameters.gdbName); createMD.CreateMosaicDataset(pGdbWorkspace); #endregion } else if (gdbOption == 2) { #region Open SDE GDB // Set SDE connection properties. IPropertySet sdeProperties = new PropertySetClass(); sdeProperties.SetProperty("SERVER", "barbados"); sdeProperties.SetProperty("INSTANCE", "9411"); sdeProperties.SetProperty("VERSION", "sde.DEFAULT"); sdeProperties.SetProperty("USER", "gdb"); sdeProperties.SetProperty("PASSWORD", "gdb"); sdeProperties.SetProperty("DATABASE", "VTEST"); IWorkspace sdeWorkspace = CreateSdeWorkspace(sdeProperties); if (sdeWorkspace == null) { Console.WriteLine("Could not open SDE workspace: "); return; } #endregion #region Create MD in SDE MDParameters.mosaicDatasetName = @"sampleMD"; createMD.CreateMosaicDataset(sdeWorkspace); #endregion } #region Shutdown Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } catch (Exception exc) { #region Report Console.WriteLine("Exception Caught in Main: " + exc.Message); Console.WriteLine("Shutting down."); #endregion #region Shutdown Console.WriteLine("Press any key..."); Console.ReadKey(); // Shutdown License aoInit.Shutdown(); #endregion } }