Create a Mosaic dataset
CreateMosaicDataset.vb
' 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.
' 

Imports System
Imports System.IO
Imports ESRI.ArcGIS
Imports ESRI.ArcGIS.DataSourcesGDB
Imports ESRI.ArcGIS.DataSourcesRaster
Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.Geometry

Namespace RasterSamples
    Class Program
        <STAThread()> _
        Public Shared Sub Main(ByVal args As String())
            ' Initialize
            Dim aoInit As ESRI.ArcGIS.esriSystem.AoInitialize = Nothing
            Try
                Console.WriteLine("Obtaining license")
                ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop)
                aoInit = New AoInitializeClass()
                Dim licStatus As esriLicenseStatus = aoInit.Initialize(esriLicenseProductCode.esriLicenseProductCodeArcInfo)
                Console.WriteLine("Ready with license.")
            Catch exc As Exception
                ' If it fails at this point, shutdown the test and ignore any subsequent errors.
                Console.WriteLine(exc.Message)
            End Try

            ' 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

            ' Create Mosaic Dataset
            Dim createMD As New CreateMosaicDataset()
            createMD.CreateMD()

            ' Shutdown
            ' Shutdown License
            aoInit.Shutdown()
        End Sub
    End Class

    Public Module MDParameters
        ' Define the folder in which the GDB resides or is to be created
        Public fgdbParentFolder As String
        ' Name of the GDB
        Public fgdbName As String
        ' Configuration keyword for the Gdb (optional)
        Public configKeyword As String
        ' Name of the Mosaic Dataset
        Public mosaicDatasetName As String

        ' Mosaic Dataset Properties
        ' Srs for the Mosaic Dataset
        Public mosaicDatasetSrs As String
        ' Number of bands of the Mosaic Dataset
        Public mosaicDatasetBands As Integer
        ' Pixel Type of the Mosaic Dataset
        Public mosaicDatasetBits As rstPixelType

        ' Raster Type Properties
        ' Name of the Raster type to use (or path to the .art file)
        Public rasterTypeName As String
        ' The product filter to set on the Raster Type
        Public rasterTypeProductFilter As String
        ' The name of the product to create from the added data
        Public rasterTypeProductName As String

        ' Crawler Properties
        ' Path to the data.
        Public dataSource As String
        ' File filter to use to crawl data.
        Public dataSourceFilter As String

        ' Operational flags
        Public buildOverviews As Boolean
        ' Delete the parent folder for the GDB
        Public emptyFgdbFolder As Boolean
        ' Create the Parent folder for the GDB
        Public createFgdbParentFolder As Boolean
    End Module

    Public Class CreateMosaicDataset
        Public Sub CreateMD()
            Try
                ' Global Declarations
                Dim fgdbDir As String = (MDParameters.fgdbParentFolder & "\") + MDParameters.fgdbName & ".gdb"

                Dim theMosaicDataset As IMosaicDataset = Nothing
                Dim theMosaicDatasetOperation As IMosaicDatasetOperation = Nothing
                Dim mosaicExtHelper As IMosaicWorkspaceExtensionHelper = Nothing
                Dim mosaicExt As IMosaicWorkspaceExtension = Nothing


                ' Create File GDB
                Console.WriteLine("Creating File GDB: " & MDParameters.fgdbName)
                If MDParameters.emptyFgdbFolder Then
                    Try
                        Console.WriteLine("Emptying Gdb folder")
                        Directory.Delete(MDParameters.fgdbParentFolder, True)
                        Directory.CreateDirectory(MDParameters.fgdbParentFolder)
                    Catch generatedExceptionName As Exception
                    End Try
                End If
                If MDParameters.createFgdbParentFolder Then
                    Directory.CreateDirectory(MDParameters.fgdbParentFolder)
                End If

                ' Create a File Gdb
                Dim factoryType As Type = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory")
                Dim FgdbFactory As IWorkspaceFactory = DirectCast(Activator.CreateInstance(factoryType), IWorkspaceFactory)
                FgdbFactory.Create(MDParameters.fgdbParentFolder, MDParameters.fgdbName, Nothing, 0)

                ' Open File GDB
                Dim workspaceFactory As IWorkspaceFactory = DirectCast(Activator.CreateInstance(factoryType), IWorkspaceFactory)
                Dim fgdbWorkspace As IWorkspace = workspaceFactory.OpenFromFile(fgdbDir, 0)

                ' CreateMosaicDataset
                Try
                    Console.WriteLine("Create Mosaic Dataset: " & MDParameters.mosaicDatasetName & ".amd")
                    ' Create Srs
                    Dim spatialrefFactory As ISpatialReferenceFactory = New SpatialReferenceEnvironmentClass()
                    Dim mosaicSrs As ISpatialReference = spatialrefFactory.CreateProjectedCoordinateSystem(CInt((esriSRProjCSType.esriSRProjCS_World_Mercator)))

                    ' Create the mosaic dataset creation parameters object.
                    Dim creationPars As ICreateMosaicDatasetParameters = New CreateMosaicDatasetParametersClass()
                    ' Set the number of bands for the mosaic dataset.
                    ' If defined as zero leave defaults
                    If MDParameters.mosaicDatasetBands <> 0 Then
                        creationPars.BandCount = MDParameters.mosaicDatasetBands
                    End If
                    ' Set the pixel type of the mosaic dataset.
                    ' If defined as unknown leave defaults
                    If MDParameters.mosaicDatasetBits <> rstPixelType.PT_UNKNOWN Then
                        creationPars.PixelType = MDParameters.mosaicDatasetBits
                    End If
                    ' 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 exc As Exception
                    ' Report"
                    Console.WriteLine("Exception Caught while creating Mosaic Dataset: " & exc.Message)
                    Console.WriteLine("Shutting down.")
                    Console.WriteLine("Press any key...")
                    Console.ReadKey()

                    Exit Sub
                End Try

                ' OpenMosaicDataset
                Console.WriteLine("Opening Mosaic Dataset")
                theMosaicDataset = Nothing
                ' 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 = DirectCast((theMosaicDataset), IMosaicDatasetOperation)

                ' Preparing Raster Type
                Console.WriteLine("Preparing Raster Type")
                ' Create a Raster Type Name object.
                Dim theRasterTypeName As IRasterTypeName = 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.
                Dim theRasterType As IRasterType = DirectCast((DirectCast(theRasterTypeName, IName).Open()), IRasterType)
                If theRasterType Is Nothing Then
                    Console.WriteLine("Raster Type not found " & MDParameters.rasterTypeName)
                End If

                ' Set the URI Filter on the loaded raster type.
                If MDParameters.rasterTypeProductFilter <> "" Then
                    ' Get the supported URI filters from the raster type object using the 
                    ' raster type properties interface.
                    Dim mySuppFilters As IArray = DirectCast(theRasterType, IRasterTypeProperties).SupportedURIFilters
                    Dim productFilter As IItemURIFilter = Nothing
                    For i As Integer = 0 To mySuppFilters.Count - 1
                        ' Set the desired filter from the supported filters.
                        productFilter = DirectCast(mySuppFilters.Element(i), IItemURIFilter)
                        If productFilter.Name = MDParameters.rasterTypeProductFilter Then
                            theRasterType.URIFilter = productFilter
                        End If
                    Next
                End If
                ' Enable the correct templates in the raster type.
                Dim rasterProductNames As String() = MDParameters.rasterTypeProductName.Split(";"c)
                Dim enableTemplate As Boolean = False
                If rasterProductNames.Length >= 1 AndAlso (rasterProductNames(0) <> "") Then
                    ' Get the supported item templates from the raster type.
                    Dim templateArray As IItemTemplateArray = theRasterType.ItemTemplates
                    For i As Integer = 0 To templateArray.Count - 1
                        ' Go through the supported item templates and enable the ones needed.
                        Dim template As IItemTemplate = templateArray.Element(i)
                        enableTemplate = False
                        For j As Integer = 0 To rasterProductNames.Length - 1
                            If template.Name = rasterProductNames(j) Then
                                enableTemplate = True
                            End If
                        Next
                        If enableTemplate Then
                            template.Enabled = True
                        Else
                            template.Enabled = False
                        End If
                    Next
                End If

                ' Preparing Data Source Crawler
                Console.WriteLine("Preparing Data Source Crawler")
                ' Create a new property set to specify crawler properties.
                Dim crawlerProps As IPropertySet = 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.
                Dim theCrawler As IDataSourceCrawler = DirectCast(theRasterType, IRasterBuilder).GetRecommendedCrawler(crawlerProps)

                ' Add Rasters
                Console.WriteLine("Adding Rasters")
                ' Create a AddRaster parameters object.
                Dim AddRastersArgs As IAddRastersParameters = 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, Nothing)

                ' Compute Pixel Size Ranges
                Console.WriteLine("Computing Pixel Size Ranges")
                ' Create a calculate cellsize ranges parameters object.
                Dim computeArgs As ICalculateCellSizeRangesParameters = New CalculateCellSizeRangesParametersClass()
                ' Use the mosaic dataset operation interface to calculate cellsize ranges.
                theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, Nothing)

                ' Building Boundary
                Console.WriteLine("Building Boundary")
                ' Create a build boundary parameters object.
                Dim boundaryArgs As IBuildBoundaryParameters = New BuildBoundaryParametersClass()
                ' Set flags that control boundary generation.
                boundaryArgs.AppendToExistingBoundary = True
                ' Use the mosaic dataset operation interface to build boundary.
                theMosaicDatasetOperation.BuildBoundary(boundaryArgs, Nothing)

                If MDParameters.buildOverviews Then
                    ' Defining Overviews
                    Console.WriteLine("Defining overviews")
                    ' Create a define overview parameters object.
                    Dim defineOvArgs As IDefineOverviewsParameters = New DefineOverviewsParametersClass()
                    ' Use the overview tile parameters interface to specify the overview factor
                    ' used to generate overviews.
                    DirectCast(defineOvArgs, IOverviewTileParameters).OverviewFactor = 3
                    ' Use the mosaic dataset operation interface to define overviews.
                    theMosaicDatasetOperation.DefineOverviews(defineOvArgs, Nothing)

                    ' Compute Pixel Size Ranges
                    Console.WriteLine("Computing Pixel Size Ranges")
                    ' Calculate cell size ranges to update the Min/Max pixel sizes.
                    theMosaicDatasetOperation.CalculateCellSizeRanges(computeArgs, Nothing)

                    ' Generating Overviews
                    Console.WriteLine("Generating Overviews")
                    ' Create a generate overviews parameters object.
                    Dim genPars As IGenerateOverviewsParameters = New GenerateOverviewsParametersClass()
                    ' Set properties to control overview generation.
                    Dim genQuery As IQueryFilter = New QueryFilterClass()
                    DirectCast(genPars, ISelectionParameters).QueryFilter = genQuery
                    genPars.GenerateMissingImages = True
                    genPars.GenerateStaleImages = True
                    ' Use the mosaic dataset operation interface to generate overviews.
                    theMosaicDatasetOperation.GenerateOverviews(genPars, Nothing)
                End If

                ' Report
                Console.WriteLine("Success.")
                Console.WriteLine("Press any key...")
                Console.ReadKey()
            Catch exc As Exception
                ' Report
                Console.WriteLine("Exception Caught in CreateMD: " & exc.Message)
                Console.WriteLine("Failed.")
                Console.WriteLine("Shutting down.")
                Console.WriteLine("Press any key...")
                Console.ReadKey()
            End Try
        End Sub
    End Class
End Namespace