Create a Mosaic dataset
CreateMosaicDataset.cs
// Copyright 2010 ESRI
// 
// All rights reserved under the copyright laws of the United States
// and applicable international laws, treaties, and conventions.
// 
// You may freely redistribute and use this sample code, with or
// without modification, provided you include the original copyright
// notice and use restrictions.
// 
// See the use restrictions.
// 

using System;
using System.IO;
using ESRI.ArcGIS.DataSourcesGDB;
using ESRI.ArcGIS.DataSourcesRaster;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;

namespace RasterSamples
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            #region Initialize
            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.esriLicenseProductCodeArcInfo);
                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

            #region Setup MD Test Parameters
            MDParameters.fgdbParentFolder = @"c:\temp\CreateMD";
            MDParameters.fgdbName = @"sampleGdb";
            MDParameters.createFgdbParentFolder = true;
            MDParameters.emptyFgdbFolder = true;

            MDParameters.mosaicDatasetName = @"sampleMD";
            // Specify a prj file for the Srs of the mosaic dataset
            MDParameters.mosaicDatasetSrs = @"c:\Program Files\ArcGIS\Desktop10.0\Coordinate Systems\Geographic Coordinate Systems\World\WGS 1984.prj";
            // 0 and Unknown for bits and bands = unchanged.
            MDParameters.mosaicDatasetBands = 0;
            MDParameters.mosaicDatasetBits = rstPixelType.PT_UNKNOWN;
            MDParameters.configKeyword = "";

            MDParameters.rasterTypeName = "QuickBird";
            // The next two properties can be left blank for defaults
            MDParameters.rasterTypeProductFilter = "Basic";
            // This is similar to choosing the Pansharpen option in the UI
            // It enables both the Pansharpen and Multispectral products internally
            MDParameters.rasterTypeProductName = "Pansharpen;Multispectral";
            // Data source from which to read the data.
            MDParameters.dataSource = @"C:\Data\QB";
            MDParameters.dataSourceFilter = "";
            MDParameters.buildOverviews = true;
            #endregion

            #region Create Mosaic Dataset
            CreateMosaicDataset createMD = new CreateMosaicDataset();
            createMD.CreateMD();
            #endregion

            #region Shutdown
            // Shutdown License
            aoInit.Shutdown();
            #endregion
        }
    };

    public static class MDParameters
    {
        // Define the folder in which the GDB resides or is to be created
        public static string fgdbParentFolder;
        // Name of the GDB
        public static string fgdbName;
        // Configuration keyword for the Gdb (optional)
        public static string configKeyword;
        // Name of the Mosaic Dataset
        public static string mosaicDatasetName;

        // Mosaic Dataset Properties
        public static string mosaicDatasetSrs; // Srs for the Mosaic Dataset
        public static int mosaicDatasetBands; // Number of bands of the Mosaic Dataset
        public static rstPixelType mosaicDatasetBits; // Pixel Type of the Mosaic Dataset

        // Raster Type Properties
        public static string rasterTypeName; // Name of the Raster type to use (or path to the .art file)
        public static string rasterTypeProductFilter; // The product filter to set on the Raster Type
        public static string rasterTypeProductName; // The name of the product to create from the added data

        // Crawler Properties
        public static string dataSource; // Path to the data.
        public static string dataSourceFilter; // File filter to use to crawl data.

        // Operational flags
        public static bool buildOverviews; // Generate overviews for the Mosaic Dataset
        public static bool emptyFgdbFolder; // Delete the parent folder for the GDB
        public static bool createFgdbParentFolder; // Create the Parent folder for the GDB
    };

    public class CreateMosaicDataset
    {
        public void CreateMD()
        {
            try
            {
                #region Global Declarations
                string fgdbDir = MDParameters.fgdbParentFolder + "\\" + MDParameters.fgdbName + ".gdb";

                IMosaicDataset theMosaicDataset = null;
                IMosaicDatasetOperation theMosaicDatasetOperation = null;
                IMosaicWorkspaceExtensionHelper mosaicExtHelper = null;
                IMosaicWorkspaceExtension mosaicExt = null;
                #endregion

                #region Create File GDB
                Console.WriteLine("Creating File GDB: " + MDParameters.fgdbName);
                if (MDParameters.emptyFgdbFolder)
                {
                    try
                    {
                        Console.WriteLine("Emptying Gdb folder");
                        Directory.Delete(MDParameters.fgdbParentFolder, true);
                        Directory.CreateDirectory(MDParameters.fgdbParentFolder);
                    }
                    catch (Exception)
                    {
                    }
                }
                if (MDParameters.createFgdbParentFolder)
                    Directory.CreateDirectory(MDParameters.fgdbParentFolder);

                // Create a File Gdb
                Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
                IWorkspaceFactory FgdbFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                FgdbFactory.Create(MDParameters.fgdbParentFolder, MDParameters.fgdbName, null, 0);
                #endregion

                #region Open File GDB
                IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance(factoryType);
                IWorkspace fgdbWorkspace = workspaceFactory.OpenFromFile(fgdbDir, 0);
                #endregion

                #region CreateMosaicDataset
                try
                {
                    Console.WriteLine("Create Mosaic Dataset: " + MDParameters.mosaicDatasetName + ".amd");
                    /// Create Srs
                    ISpatialReferenceFactory spatialrefFactory = new SpatialReferenceEnvironmentClass();
                    ISpatialReference mosaicSrs = spatialrefFactory.CreateProjectedCoordinateSystem(
                        (int)(esriSRProjCSType.esriSRProjCS_World_Mercator));
                    //ISpatialReference mosaicSrs = spatialrefFactory.CreateGeographicCoordinateSystem(
                    //(int)(esriSRGeoCSType.esriSRGeoCS_WGS1984));

                    // Create the mosaic dataset creation parameters object.
                    ICreateMosaicDatasetParameters creationPars = new CreateMosaicDatasetParametersClass();
                    // Set the number of bands for the mosaic dataset.
                    // If defined as zero leave defaults
                    if (MDParameters.mosaicDatasetBands != 0)
                        creationPars.BandCount = MDParameters.mosaicDatasetBands;
                    // Set the pixel type of the mosaic dataset.
                    // If defined as unknown leave defaults
                    if (MDParameters.mosaicDatasetBits != rstPixelType.PT_UNKNOWN)
                        creationPars.PixelType = MDParameters.mosaicDatasetBits;
                    // Create the mosaic workspace extension helper class.
                    mosaicExtHelper = new MosaicWorkspaceExtensionHelperClass();
                    // Find the right extension from the workspace.
                    mosaicExt = mosaicExtHelper.FindExtension(fgdbWorkspace);
                    // Use the extension to create a new mosaic dataset, supplying the 
                    // spatial reference and the creation parameters object created above.
                    theMosaicDataset = mosaicExt.CreateMosaicDataset(MDParameters.mosaicDatasetName,
                        mosaicSrs, creationPars, MDParameters.configKeyword);
                }
                catch (Exception exc)
                {
                    #region Report
                    Console.WriteLine("Exception Caught while creating Mosaic Dataset: " + exc.Message);
                    Console.WriteLine("Shutting down.");
                    Console.WriteLine("Press any key...");
                    Console.ReadKey();
                    #endregion
                    return;
                }
                #endregion

                #region OpenMosaicDataset
                Console.WriteLine("Opening Mosaic Dataset");
                theMosaicDataset = null;
                // Use the extension to open the mosaic dataset.
                theMosaicDataset = mosaicExt.OpenMosaicDataset(MDParameters.mosaicDatasetName);
                // The mosaic dataset operation interface is used to perform operations on 
                // a mosaic dataset.
                theMosaicDatasetOperation = (IMosaicDatasetOperation)(theMosaicDataset);
                #endregion

                #region Preparing Raster Type
                Console.WriteLine("Preparing Raster Type");
                // Create a Raster Type Name object.
                IRasterTypeName theRasterTypeName = new RasterTypeNameClass();
                // Assign the name of the Raster Type to the name object.
                // The Name field accepts a path to an .art file as well 
                // the name for a built in Raster Type.
                theRasterTypeName.Name = MDParameters.rasterTypeName;
                // Use the Open function from the IName interface to get the Raster Type object.
                IRasterType theRasterType = (IRasterType)(((IName)theRasterTypeName).Open());
                if (theRasterType == null)
                    Console.WriteLine("Raster Type not found " + MDParameters.rasterTypeName);

                // Set the URI Filter on the loaded raster type.
                if (MDParameters.rasterTypeProductFilter != "")
                {
                    // Get the supported URI filters from the raster type object using the 
                    // raster type properties interface.
                    IArray mySuppFilters = ((IRasterTypeProperties)theRasterType).SupportedURIFilters;
                    IItemURIFilter productFilter = null;
                    for (int i = 0; i < mySuppFilters.Count; ++i)
                    {
                        // Set the desired filter from the supported filters.
                        productFilter = (IItemURIFilter)mySuppFilters.get_Element(i);
                        if (productFilter.Name == MDParameters.rasterTypeProductFilter)
                            theRasterType.URIFilter = productFilter;
                    }
                }
                // Enable the correct templates in the raster type.
                string[] rasterProductNames = MDParameters.rasterTypeProductName.Split(';');
                bool enableTemplate = false;
                if (rasterProductNames.Length >= 1 && (rasterProductNames[0] != ""))
                {
                    // Get the supported item templates from the raster type.
                    IItemTemplateArray templateArray = theRasterType.ItemTemplates;
                    for (int i = 0; i < templateArray.Count; ++i)
                    {
                        // Go through the supported item templates and enable the ones needed.
                        IItemTemplate template = templateArray.get_Element(i);
                        enableTemplate = false;
                        for (int j = 0; j < rasterProductNames.Length; ++j)
                            if (template.Name == rasterProductNames[j])
                                enableTemplate = true;
                        if (enableTemplate)
                            template.Enabled = true;
                        else
                            template.Enabled = false;
                    }
                }
                #endregion

                #region Preparing Data Source Crawler
                Console.WriteLine("Preparing Data Source Crawler");
                // Create a new property set to specify crawler properties.
                IPropertySet crawlerProps = new PropertySetClass();
                // Specify a file filter
                crawlerProps.SetProperty("Filter", MDParameters.dataSourceFilter);
                // Specify whether to search subdirectories.
                crawlerProps.SetProperty("Recurse", true);
                // Specify the source path.
                crawlerProps.SetProperty("Source", MDParameters.dataSource);
                // Get the recommended crawler from the raster type based on the specified 
                // properties using the IRasterBuilder interface.
                IDataSourceCrawler theCrawler = ((IRasterBuilder)theRasterType).GetRecommendedCrawler(crawlerProps);
                #endregion

                #region Add Rasters
                Console.WriteLine("Adding Rasters");
                // Create a AddRaster parameters object.
                IAddRastersParameters AddRastersArgs = new AddRastersParametersClass();
                // Specify the data crawler to be used to crawl the data.
                AddRastersArgs.Crawler = theCrawler;
                // Specify the raster type to be used to add the data.
                AddRastersArgs.RasterType = theRasterType;
                // Use the mosaic dataset operation interface to add 
                // rasters to the mosaic dataset.
                theMosaicDatasetOperation.AddRasters(AddRastersArgs, null);
                #endregion

                #region Compute Pixel Size Ranges
                Console.WriteLine("Computing Pixel Size Ranges");
                // Create a calculate cellsize ranges parameters object.
                ICalculateCellSizeRangesParameters computeArgs = new CalculateCellSizeRangesParametersClass();
                // Use the mosaic dataset operation interface to calculate cellsize ranges.
                theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null);
                #endregion

                #region Building Boundary
                Console.WriteLine("Building Boundary");
                // Create a build boundary parameters object.
                IBuildBoundaryParameters boundaryArgs = new BuildBoundaryParametersClass();
                // Set flags that control boundary generation.
                boundaryArgs.AppendToExistingBoundary = true;
                // Use the mosaic dataset operation interface to build boundary.
                theMosaicDatasetOperation.BuildBoundary(boundaryArgs, null);
                #endregion

                if (MDParameters.buildOverviews)
                {
                    #region Defining Overviews
                    Console.WriteLine("Defining overviews");
                    // Create a define overview parameters object.
                    IDefineOverviewsParameters defineOvArgs = new DefineOverviewsParametersClass();
                    // Use the overview tile parameters interface to specify the overview factor
                    // used to generate overviews.
                    ((IOverviewTileParameters)defineOvArgs).OverviewFactor = 3;
                    // Use the mosaic dataset operation interface to define overviews.
                    theMosaicDatasetOperation.DefineOverviews(defineOvArgs, null);
                    #endregion

                    #region Compute Pixel Size Ranges
                    Console.WriteLine("Computing Pixel Size Ranges");
                    // Calculate cell size ranges to update the Min/Max pixel sizes.
                    theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, null);
                    #endregion

                    #region Generating Overviews
                    Console.WriteLine("Generating Overviews");
                    // Create a generate overviews parameters object.
                    IGenerateOverviewsParameters genPars = new GenerateOverviewsParametersClass();
                    // Set properties to control overview generation.
                    IQueryFilter genQuery = new QueryFilterClass();
                    ((ISelectionParameters)genPars).QueryFilter = genQuery;
                    genPars.GenerateMissingImages = true;
                    genPars.GenerateStaleImages = true;
                    // Use the mosaic dataset operation interface to generate overviews.
                    theMosaicDatasetOperation.GenerateOverviews(genPars, null);
                    #endregion
                }

                #region Report
                Console.WriteLine("Success.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();
                #endregion
            }
            catch (Exception exc)
            {
                #region Report
                Console.WriteLine("Exception Caught in CreateMD: " + exc.Message);
                Console.WriteLine("Failed.");
                Console.WriteLine("Shutting down.");
                Console.WriteLine("Press any key...");
                Console.ReadKey();
                #endregion
            }
        }
    }
}