ArcObjects Library Reference  

Program

About the ArcGIS GPConsole Sample

[C#]

Program.cs




using System;
using System.Collections.Generic;
using System.Text;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Server;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessor;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.Geometry;

namespace ArcGIS_GPConsole_CSharp
{
    class Program
    {

        private static LicenseInitializer m_AOLicenseInitializer = new ArcGIS_GPConsole_CSharp.LicenseInitializer();

        private static string servername = "localhost";

        [STAThread]
        static void Main(string[] args)
        {
            bool bInitialized = false;
            ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop);

            if (!ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop))
            {
                Console.WriteLine("This application could not load the correct version of ArcGIS.");
                return;
            }

            //ESRI License Initializer generated code.
            if(m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeArcInfo },
            new esriLicenseExtensionCode[]{ })==true)
            {
                bInitialized = true;
                Console.WriteLine("Engine initialized");
                Console.WriteLine("License type: " + esriLicenseProductCode.esriLicenseProductCodeArcInfo.ToString());
            }
            else
            {
                Console.WriteLine("Engine NOT initialized");
            }

            IServerContext serverContext = null;

            try
            {
                System.Console.WriteLine("Start...");

                GISServerConnection serverConnection= new GISServerConnection ();
                serverConnection.Connect(servername);
                IServerObjectManager serverManager = serverConnection.ServerObjectManager;

                serverContext = serverManager.CreateServerContext("", "");

                ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor(serverContext);

                ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactory ffactory = null;
                ESRI.ArcGIS.DataSourcesGDB.AccessWorkspaceFactory afactory = null;
                ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory sfactory = null;
                ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactory sdefactory = null;
                PropertySet sdeServerProperties = null;
                IFeatureLayer shpflayer = null;
                IVariantArray varray = null;
                IFeatureLayer sdeflayer = null;

                if (gp.IServerContext != null)
                {
                    System.Console.WriteLine("Server");
                    ffactory = (ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactory)serverContext.CreateObject("esriDataSourcesGDB.FileGDBWorkspaceFactory");
                    afactory = (ESRI.ArcGIS.DataSourcesGDB.AccessWorkspaceFactory)serverContext.CreateObject("esriDataSourcesGDB.AccessWorkspaceFactory");
                    sfactory = (ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory)serverContext.CreateObject("esriDataSourcesFile.ShapefileWorkspaceFactory");
                    sdefactory = (ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactory)serverContext.CreateObject("esriDataSourcesGDB.SdeWorkspaceFactory");
                    sdeServerProperties = (PropertySet)serverContext.CreateObject("esriSystem.PropertySet");
                    shpflayer = (IFeatureLayer)serverContext.CreateObject("esriCarto.FeatureLayer");
                    varray = (IVariantArray)serverContext.CreateObject("esriSystem.VarArray");
                    sdeflayer = (IFeatureLayer)serverContext.CreateObject("esriCarto.FeatureLayer");
                }
                else
                {
                    System.Console.WriteLine("Local");
                    if (!bInitialized)
                    {
                        System.Console.WriteLine("Engine license must be initialized.");
                        System.Console.ReadLine();
                        return;
                    }
                    ffactory = new ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass();
                    afactory = new ESRI.ArcGIS.DataSourcesGDB.AccessWorkspaceFactoryClass();
                    sfactory = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass();
                    sdefactory = new ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass();
                    sdeServerProperties = new PropertySetClass();
                    shpflayer = new ESRI.ArcGIS.Carto.FeatureLayerClass();
                    varray = (IVariantArray)new VarArrayClass();
                    sdeflayer = new ESRI.ArcGIS.Carto.FeatureLayerClass();
                }

                gp.OverwriteOutput = true;

                ///* Geoprocessor .NET wrapper - Copy Features tool ***
                ESRI.ArcGIS.DataManagementTools.CopyFeatures copyfeatures = new ESRI.ArcGIS.DataManagementTools.CopyFeatures();

                string inputfile = @"C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\Usa\USA.gdb";
                string inputfeatureclass = "states";

                string outputfile = "c:/temp";
                string outputfeatureclass = "output.shp";

                IFeatureWorkspace fws = (IFeatureWorkspace)ffactory.OpenFromFile(inputfile, 0);
                IFeatureClass infc = fws.OpenFeatureClass(inputfeatureclass);

                copyfeatures.in_features = infc;
                copyfeatures.out_feature_class = @outputfile + "/" + outputfeatureclass;

                varray.Add(copyfeatures.in_features);
                varray.Add(copyfeatures.out_feature_class);

                gp.Execute(copyfeatures.ToolName + "_" + copyfeatures.Alias, varray, null);
                processGPMessages(gp);

                /* Work with the IGeoProcessor COM object reference 
                IGeoProcessor igp = gp.IGeoProcessor;

                IWorkspaceFactory iwf = (IWorkspaceFactory)serverContext.CreateObject("esriGeoprocessing.ToolboxWorkspaceFactory");

                IToolboxWorkspace itw = (IToolboxWorkspace)iwf.OpenFromFile(@"c:/Program Files/ArcGIS/ArcToolbox/Toolboxes/", 0);
                IGPToolbox tbox = (IGPToolbox)itw.OpenToolbox(copyfeatures.ToolboxName);
                IGPTool tool = (IGPTool)tbox.OpenTool(copyfeatures.ToolName);
                IArray parameters = tool.ParameterInfo;

                for (int j = 0; j < parameters.Count; j++)
                {
                    IGPParameter gparam = (IGPParameter)parameters.get_Element(j);
 
                    System.Console.WriteLine("Parameter name: " + gparam.Name);
                    System.Console.WriteLine("Parameter Data Type Display Name: " + gparam.DataType.DisplayName);
                    System.Console.WriteLine("Parameter Data Type Name: " + gparam.DataType.Name);
                    System.Console.WriteLine("Is Parameter required?: " + gparam.ParameterType.ToString());
                    
                    System.Console.WriteLine("Parameter Value Data Type: " + gparam.Value.DataType.Name);
                    System.Console.WriteLine("Parameter Value as Text: " + gparam.Value.GetAsText());
                }
                */

                //Use the Geoprocessor with a custom toolbox and model on the server
                Console.WriteLine("Call Geoprocessor Example");
                RunGeoprocessorExample(gp);

                //Use the IGPServer with a published GP service
                Console.WriteLine("Call IGPServer Example");
                RunGPServerExample();

                System.Console.WriteLine("Finish");
                Console.ReadLine();

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
            }
            finally
            {
                serverContext.ReleaseContext();
                if (bInitialized)
                m_AOLicenseInitializer.ShutdownApplication();
            }
        }

        static void processGPMessages(Geoprocessor gp)
        {
            IGPMessages gpMsgs = gp.IGeoProcessor.GetReturnMessages();
            IArray ir = gpMsgs.Messages;
            int ic = ir.Count;
            for (int i = 0; i < ic; i++)
            {
                Console.WriteLine(gpMsgs.GetMessage(i).Description);
            }
        }


        public static void RunGeoprocessorExample(Geoprocessor gp)
        {

            try
            {
                IServerContext serverContext = null;
                if (gp.IServerContext != null)
                {
                    serverContext = gp.IServerContext;
                }
                else
                {
                    return;
                }


                gp.AddToolbox(@"C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\GP\RunBuffer\BufferTools.tbx");
                gp.SetEnvironmentValue("scratchWorkspace", @"c:/temp");
                gp.OverwriteOutput = true;

                // Need reference to GPTool to get parameter type information
                IWorkspaceFactory iwf = (IWorkspaceFactory)serverContext.CreateObject("esriGeoprocessing.ToolboxWorkspaceFactory");
                IToolboxWorkspace itw = (IToolboxWorkspace)iwf.OpenFromFile(@"C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\GP\RunBuffer\", 0);
                IGPToolbox tbox = (IGPToolbox)itw.OpenToolbox("BufferTools");
                IGPTool tool = (IGPTool)tbox.OpenTool("BufferPoints");

                IVariantArray varray = (IVariantArray)serverContext.CreateObject("esriSystem.VarArray");

                IArray parameters = tool.ParameterInfo;

                // Iterate through parameters to get data types                
                /*for (int j = 0; j < parameters.Count; j++)
                {
                    IGPParameter gparam = (IGPParameter)parameters.get_Element(j);

                    System.Console.WriteLine("Parameter name: " + gparam.Name);
                    System.Console.WriteLine("Parameter Data Type Display Name: " + gparam.DataType.DisplayName);
                    System.Console.WriteLine("Parameter Data Type Name: " + gparam.DataType.Name);
                    System.Console.WriteLine("Is Parameter required?: " + gparam.ParameterType.ToString());

                    System.Console.WriteLine("Parameter Value Data Type: " + gparam.Value.DataType.Name);
                    System.Console.WriteLine("Parameter Value as Text: " + gparam.Value.GetAsText());

                }*/

                IGPParameter gpp1 = (IGPParameter)parameters.get_Element(0);
                IGPRecordSet gprecset = (IGPRecordSet)gpp1.Value;

                IRecordSet rs = gprecset.RecordSet;

                IFields flds = rs.Fields;
                int shpfldindex = flds.FindField("Shape");

                IField fld = flds.get_Field(shpfldindex);
                ISpatialReference inputsr = fld.GeometryDef.SpatialReference;

                IRecordSetInit rsi = (IRecordSetInit)rs;
                ICursor cur = rsi.Insert();
                IRowBuffer rb = rsi.CreateRowBuffer();
                IPoint ipnt = (IPoint)serverContext.CreateObject("esriGeometry.Point");
                ipnt.PutCoords(1000000, 1000000);
                rb.set_Value(shpfldindex, ipnt);
                cur.InsertRow(rb);

                varray.Add(gprecset);

                IGPParameter gpp2 = (IGPParameter)parameters.get_Element(1);
                IGPLinearUnit gpLU = (IGPLinearUnit)serverContext.CreateObject("esriGeoprocessing.GPLinearUnit");
                gpLU.Units = ESRI.ArcGIS.esriSystem.esriUnits.esriMeters;
                gpLU.Value = 100000;

                varray.Add(gpLU);

                gp.Execute(tool.Name, varray, null);

                processGPMessages(gp);


            }
            catch (Exception ex)
            {
                processGPMessages(gp);
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
            }
        }

        public static void RunGeoprocessorExampleAddServerToolbox()
        {

            IServerContext serverContext = null;
            ESRI.ArcGIS.Geoprocessor.Geoprocessor gp = null;
            try
            {
                GISServerConnection serverConnection;
                serverConnection = new GISServerConnection();
                serverConnection.Connect(servername);
                IServerObjectManager serverManager = serverConnection.ServerObjectManager;

                serverContext = serverManager.CreateServerContext("BufferTools", "GPServer");

                //* GEOPROCESSOR SECTION
                gp = new ESRI.ArcGIS.Geoprocessor.Geoprocessor(serverContext);
                gp.AddToolbox(@"C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\GP\RunBuffer\BufferTools.tbx");
                gp.SetEnvironmentValue("scratchWorkspace", @"c:/temp");
                gp.OverwriteOutput = true;

                // Need reference to GPTool to get parameter type information
                IWorkspaceFactory iwf = (IWorkspaceFactory)serverContext.CreateObject("esriGeoprocessing.ToolboxWorkspaceFactory");
                IToolboxWorkspace itw = (IToolboxWorkspace)iwf.OpenFromFile(@"C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\GP\RunBuffer\RunBuffer", 0);
                IGPToolbox tbox = (IGPToolbox)itw.OpenToolbox("BufferTools");
                IGPTool tool = (IGPTool)tbox.OpenTool("BufferPoints");

                IVariantArray varray = (IVariantArray)serverContext.CreateObject("esriSystem.VarArray");

                IArray parameters = tool.ParameterInfo;
                // Iterate through parameters to get data types

                for (int j = 0; j < parameters.Count; j++)
                {
                    IGPParameter gparam = (IGPParameter)parameters.get_Element(j);

                    System.Console.WriteLine("Parameter name: " + gparam.Name);
                    System.Console.WriteLine("Parameter Data Type Display Name: " + gparam.DataType.DisplayName);
                    System.Console.WriteLine("Parameter Data Type Name: " + gparam.DataType.Name);
                    System.Console.WriteLine("Is Parameter required?: " + gparam.ParameterType.ToString());

                    System.Console.WriteLine("Parameter Value Data Type: " + gparam.Value.DataType.Name);
                    System.Console.WriteLine("Parameter Value as Text: " + gparam.Value.GetAsText());

                }

                IGPParameter gpp1 = (IGPParameter)parameters.get_Element(0);
                IGPRecordSet gprecset = (IGPRecordSet)gpp1.Value;

                IRecordSet rs = gprecset.RecordSet;

                IFields flds = rs.Fields;
                int shpfldindex = flds.FindField("Shape");

                IField fld = flds.get_Field(shpfldindex);
                ISpatialReference inputsr = fld.GeometryDef.SpatialReference;

                IRecordSetInit rsi = (IRecordSetInit)rs;
                ICursor cur = rsi.Insert();
                IRowBuffer rb = rsi.CreateRowBuffer();
                IPoint ipnt = (IPoint)serverContext.CreateObject("esriGeometry.Point");
                ipnt.PutCoords(1000000, 1000000);
                rb.set_Value(shpfldindex, ipnt);
                cur.InsertRow(rb);

                varray.Add(gprecset);

                IGPParameter gpp2 = (IGPParameter)parameters.get_Element(1);
                IGPLinearUnit gpLU = (IGPLinearUnit)serverContext.CreateObject("esriGeoprocessing.GPLinearUnit");
                gpLU.Units = ESRI.ArcGIS.esriSystem.esriUnits.esriMeters;
                gpLU.Value = 100000;

                varray.Add(gpLU);

                gp.Execute(tool.Name, varray, null);

                processGPMessages(gp);


            }
            catch (Exception ex)
            {
                processGPMessages(gp);
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
            }
            finally
            {
                serverContext.ReleaseContext();
            }
        }


        public static void RunGPServerExample()
        {

            IServerContext serverContext = null;
            try
            {
                GISServerConnection serverConnection;
                serverConnection = new GISServerConnection();
                serverConnection.Connect(servername);
                IServerObjectManager serverManager = serverConnection.ServerObjectManager;

                serverContext = serverManager.CreateServerContext("BufferTools", "GPServer");

                IGPServer gpserver = (IGPServer)serverContext.ServerObject;
                string taskname = "BufferPoints";
                IGPToolInfo task = gpserver.GetToolInfo(taskname);
                IGPValues taskvals = (IGPValues)serverContext.CreateObject("esriGeoprocessing.GPValues");
                IGPParameterInfos paramInfos = task.ParameterInfo;
                IGPParameterInfo paramInfo;

                string parameterNameString = string.Empty;

                for (int i = 0; i < paramInfos.Count; i++)
                {
                    // Data type available as part of IGPParameterInfo
                    paramInfo = paramInfos.get_Element(i);
                    taskvals.Add(paramInfo.Value);

                    //Add to parameter name array
                    parameterNameString += paramInfo.Name;
                    if (i != paramInfos.Count - 1)
                        parameterNameString += ";";
                }

                IGPRecordSet gprecset = (IGPRecordSet)taskvals.get_Element(0);
                IQueryFilter qf = (IQueryFilter)serverContext.CreateObject("esriGeodatabase.QueryFilter");
                gprecset.RecordSet.Table.DeleteSearchedRows(qf);

                IRecordSet rs = gprecset.RecordSet;

                IFields flds = rs.Fields;
                int shpfldindex = flds.FindField("Shape");

                IField fld = flds.get_Field(shpfldindex);
                ISpatialReference inputsr = fld.GeometryDef.SpatialReference;

                IRecordSetInit rsi = (IRecordSetInit)rs;
                ICursor cur = rsi.Insert();
                IRowBuffer rb = rsi.CreateRowBuffer();
                IPoint ipnt = (IPoint)serverContext.CreateObject("esriGeometry.Point");
                ipnt.PutCoords(1000000, 1000000);
                rb.set_Value(shpfldindex, ipnt);
                cur.InsertRow(rb);

                IGPValues invals = (IGPValues)serverContext.CreateObject("esriGeoprocessing.GPValues");
                invals.Add((IGPValue)gprecset);

                IGPLinearUnit gpLU = (IGPLinearUnit)serverContext.CreateObject("esriGeoprocessing.GPLinearUnit");
                gpLU.Units = ESRI.ArcGIS.esriSystem.esriUnits.esriMeters;
                gpLU.Value = 1000000;

                invals.Add((IGPValue)gpLU);

                string JobID = gpserver.SubmitJob(taskname, invals);

                while (gpserver.GetJobStatus(JobID) != esriJobStatus.esriJobSucceeded)
                {
                    System.Threading.Thread.Sleep(5000);
                }

                IStringArray stringArray = (IStringArray)new ESRI.ArcGIS.esriSystem.StrArrayClass();
                foreach (string paramName in parameterNameString.Split(';'))
                {
                    stringArray.Add(paramName);
                }

                /* GetJobResult(): second parameter can be: 
                 * IStringArray of all parameters
                 * IStringArray of only output parameters
                 * null if you want all output parameters
                 */

                //The resultant featureclass gets generated in folder uner <C:\arcgisserver\arcgisJobs\<abd9930839dg9330123
                IGPResult result = gpserver.GetJobResult(JobID, stringArray, null);
                if (result.Messages != null)
                {
                    IJobMessages jobMsgs = result.Messages;
                    for (int i = 0; i < jobMsgs.Count; i++)
                    {
                        Console.WriteLine(jobMsgs.get_Element(i).Description);
                    }
                }

            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);
                System.Diagnostics.Debug.WriteLine(ex.StackTrace);
            }
            finally
            {
                serverContext.ReleaseContext();
            }
        }
    }
}

[Visual Basic .NET]

Program.vb

Imports Microsoft.VisualBasic
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports ESRI.ArcGIS.Carto
Imports ESRI.ArcGIS.esriSystem
Imports ESRI.ArcGIS.Server
Imports ESRI.ArcGIS.Geodatabase
Imports ESRI.ArcGIS.Geoprocessor
Imports ESRI.ArcGIS.Geoprocessing
Imports ESRI.ArcGIS.Geometry

Public Class Program

  Private Shared m_AOLicenseInitializer As LicenseInitializer = New LicenseInitializer()

  Private Shared servername As String = "localhost"

  <STAThread()> _
  Shared Sub Main(ByVal args() As String)
    Dim bInitialized As Boolean = False
    ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop)

    If (Not ESRI.ArcGIS.RuntimeManager.Bind(ESRI.ArcGIS.ProductCode.Desktop)) Then
      Console.WriteLine("This application could not load the correct version of ArcGIS.")
      Return
    End If

    'ESRI License Initializer generated code.
    If m_AOLicenseInitializer.InitializeApplication(New esriLicenseProductCode() {esriLicenseProductCode.esriLicenseProductCodeArcInfo}, New esriLicenseExtensionCode() {}) = True Then
      bInitialized = True
      Console.WriteLine("Engine initialized")
      Console.WriteLine("License type: " & esriLicenseProductCode.esriLicenseProductCodeArcInfo.ToString())
    Else
      Console.WriteLine("Engine NOT initialized")
    End If

    Dim serverContext As IServerContext = Nothing

    Try
      System.Console.WriteLine("Start...")

      Dim serverConnection As GISServerConnection
      serverConnection = New GISServerConnection()
      serverConnection.Connect(servername)
      Dim serverManager As IServerObjectManager = serverConnection.ServerObjectManager

      serverContext = serverManager.CreateServerContext("", "")

      Dim gp As New ESRI.ArcGIS.Geoprocessor.Geoprocessor(serverContext)

      Dim ffactory As ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactory = Nothing
      Dim afactory As ESRI.ArcGIS.DataSourcesGDB.AccessWorkspaceFactory = Nothing
      Dim sfactory As ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory = Nothing
      Dim sdefactory As ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactory = Nothing
      Dim sdeServerProperties As PropertySet = Nothing
      Dim shpflayer As IFeatureLayer = Nothing
      Dim varray As IVariantArray = Nothing
      Dim sdeflayer As IFeatureLayer = Nothing

      If gp.IServerContext IsNot Nothing Then
        System.Console.WriteLine("Server")
        ffactory = CType(serverContext.CreateObject("esriDataSourcesGDB.FileGDBWorkspaceFactory"), ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactory)
        afactory = CType(serverContext.CreateObject("esriDataSourcesGDB.AccessWorkspaceFactory"), ESRI.ArcGIS.DataSourcesGDB.AccessWorkspaceFactory)
        sfactory = CType(serverContext.CreateObject("esriDataSourcesFile.ShapefileWorkspaceFactory"), ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactory)
        sdefactory = CType(serverContext.CreateObject("esriDataSourcesGDB.SdeWorkspaceFactory"), ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactory)
        sdeServerProperties = CType(serverContext.CreateObject("esriSystem.PropertySet"), PropertySet)
        shpflayer = CType(serverContext.CreateObject("esriCarto.FeatureLayer"), IFeatureLayer)
        varray = CType(serverContext.CreateObject("esriSystem.VarArray"), IVariantArray)
        sdeflayer = CType(serverContext.CreateObject("esriCarto.FeatureLayer"), IFeatureLayer)
      Else
        System.Console.WriteLine("Local")
        If (Not bInitialized) Then
          System.Console.WriteLine("Engine license must be initialized.")
          System.Console.ReadLine()
          Return
        End If
        ffactory = New ESRI.ArcGIS.DataSourcesGDB.FileGDBWorkspaceFactoryClass()
        afactory = New ESRI.ArcGIS.DataSourcesGDB.AccessWorkspaceFactoryClass()
        sfactory = New ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass()
        sdefactory = New ESRI.ArcGIS.DataSourcesGDB.SdeWorkspaceFactoryClass()
        sdeServerProperties = New PropertySetClass()
        shpflayer = New ESRI.ArcGIS.Carto.FeatureLayerClass()
        varray = CType(New VarArrayClass(), IVariantArray)
        sdeflayer = New ESRI.ArcGIS.Carto.FeatureLayerClass()
      End If

      gp.OverwriteOutput = True

      '''* Geoprocessor .NET wrapper - Copy Features tool ***
      Dim copyfeatures As New ESRI.ArcGIS.DataManagementTools.CopyFeatures()

      Dim inputfile As String = "C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\Usa\USA.gdb"
      Dim inputfeatureclass As String = "states"

      Dim outputfile As String = "c:/temp"
      Dim outputfeatureclass As String = "output.shp"

      Dim fws As IFeatureWorkspace = CType(ffactory.OpenFromFile(inputfile, 0), IFeatureWorkspace)
      Dim infc As IFeatureClass = fws.OpenFeatureClass(inputfeatureclass)

      copyfeatures.in_features = infc
      copyfeatures.out_feature_class = outputfile & "/" & outputfeatureclass

      varray.Add(copyfeatures.in_features)
      varray.Add(copyfeatures.out_feature_class)

      gp.Execute(copyfeatures.ToolName & "_" & copyfeatures.Alias, varray, Nothing)
      processGPMessages(gp)

      ' Work with the IGeoProcessor COM object reference 
      'IGeoProcessor igp = gp.IGeoProcessor;

      'IWorkspaceFactory iwf = (IWorkspaceFactory)serverContext.CreateObject("esriGeoprocessing.ToolboxWorkspaceFactory");

      'IToolboxWorkspace itw = (IToolboxWorkspace)iwf.OpenFromFile(@"c:/Program Files/ArcGIS/ArcToolbox/Toolboxes/", 0);
      'IGPToolbox tbox = (IGPToolbox)itw.OpenToolbox(copyfeatures.ToolboxName);
      'IGPTool tool = (IGPTool)tbox.OpenTool(copyfeatures.ToolName);
      'IArray parameters = tool.ParameterInfo;

      'for (int j = 0; j < parameters.Count; j++)
      '{
      '    IGPParameter gparam = (IGPParameter)parameters.get_Element(j);

      '    System.Console.WriteLine("Parameter name: " + gparam.Name);
      '    System.Console.WriteLine("Parameter Data Type Display Name: " + gparam.DataType.DisplayName);
      '    System.Console.WriteLine("Parameter Data Type Name: " + gparam.DataType.Name);
      '    System.Console.WriteLine("Is Parameter required?: " + gparam.ParameterType.ToString());

      '    System.Console.WriteLine("Parameter Value Data Type: " + gparam.Value.DataType.Name);
      '    System.Console.WriteLine("Parameter Value as Text: " + gparam.Value.GetAsText());
      '}
      '                

      'Use the Geoprocessor with a custom toolbox and model on the server
      Console.WriteLine("Call Geoprocessor Example")
      RunGeoprocessorExample(gp)

      'Use the IGPServer with a published GP service
      Console.WriteLine("Call IGPServer Example")
      RunGPServerExample()

      System.Console.WriteLine("Finish")
      Console.ReadLine()

    Catch ex As Exception
      System.Diagnostics.Debug.WriteLine(ex.Message)
      System.Diagnostics.Debug.WriteLine(ex.StackTrace)
    Finally
      serverContext.ReleaseContext()
      If bInitialized Then
        m_AOLicenseInitializer.ShutdownApplication()
      End If
    End Try
  End Sub

  Private Shared Sub processGPMessages(ByVal gp As ESRI.ArcGIS.Geoprocessor.Geoprocessor)
    Dim gpMsgs As IGPMessages = gp.IGeoProcessor.GetReturnMessages()
    Dim ir As IArray = gpMsgs.Messages
    Dim ic As Integer = ir.Count
    For i As Integer = 0 To ic - 1
      Console.WriteLine(gpMsgs.GetMessage(i).Description)
    Next i
  End Sub


  Public Shared Sub RunGeoprocessorExample(ByVal gp As ESRI.ArcGIS.Geoprocessor.Geoprocessor)

    Try
      Dim serverContext As IServerContext = Nothing
      If gp.IServerContext IsNot Nothing Then
        serverContext = gp.IServerContext
      Else
        Return
      End If


      gp.AddToolbox("C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\GP\RunBuffer\BufferTools.tbx")
      gp.SetEnvironmentValue("scratchWorkspace", "c:/temp")
      gp.OverwriteOutput = True

      ' Need reference to GPTool to get parameter type information
      Dim iwf As IWorkspaceFactory = CType(serverContext.CreateObject("esriGeoprocessing.ToolboxWorkspaceFactory"), IWorkspaceFactory)
      Dim itw As IToolboxWorkspace = CType(iwf.OpenFromFile("C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\GP\RunBuffer\", 0), IToolboxWorkspace)
      Dim tbox As IGPToolbox = CType(itw.OpenToolbox("BufferTools"), IGPToolbox)
      Dim tool As IGPTool = CType(tbox.OpenTool("BufferPoints"), IGPTool)

      Dim varray As IVariantArray = CType(serverContext.CreateObject("esriSystem.VarArray"), IVariantArray)

      Dim parameters As IArray = tool.ParameterInfo

      'Iterate through parameters to get data types                
      'for (int j = 0; j < parameters.Count; j++)
      '{
      '  IGPParameter gparam = (IGPParameter)parameters.get_Element(j);

      '  System.Console.WriteLine("Parameter name: " + gparam.Name);
      '  System.Console.WriteLine("Parameter Data Type Display Name: " + gparam.DataType.DisplayName);
      '  System.Console.WriteLine("Parameter Data Type Name: " + gparam.DataType.Name);
      '  System.Console.WriteLine("Is Parameter required?: " + gparam.ParameterType.ToString());

      '  System.Console.WriteLine("Parameter Value Data Type: " + gparam.Value.DataType.Name);
      '  System.Console.WriteLine("Parameter Value as Text: " + gparam.Value.GetAsText());
      '}

      Dim gpp1 As IGPParameter = CType(parameters.Element(0), IGPParameter)
      Dim gprecset As IGPRecordSet = CType(gpp1.Value, IGPRecordSet)

      Dim rs As IRecordSet = gprecset.RecordSet

      Dim flds As IFields = rs.Fields
      Dim shpfldindex As Integer = flds.FindField("Shape")

      Dim fld As IField = flds.Field(shpfldindex)
      Dim inputsr As ISpatialReference = fld.GeometryDef.SpatialReference

      Dim rsi As IRecordSetInit = CType(rs, IRecordSetInit)
      Dim cur As ICursor = rsi.Insert()
      Dim rb As IRowBuffer = rsi.CreateRowBuffer()
      Dim ipnt As IPoint = CType(serverContext.CreateObject("esriGeometry.Point"), IPoint)
      ipnt.PutCoords(1000000, 1000000)
      rb.Value(shpfldindex) = ipnt
      cur.InsertRow(rb)

      varray.Add(gprecset)

      Dim gpp2 As IGPParameter = CType(parameters.Element(1), IGPParameter)
      Dim gpLU As IGPLinearUnit = CType(serverContext.CreateObject("esriGeoprocessing.GPLinearUnit"), IGPLinearUnit)
      gpLU.Units = ESRI.ArcGIS.esriSystem.esriUnits.esriMeters
      gpLU.Value = 100000

      varray.Add(gpLU)

      gp.Execute(tool.Name, varray, Nothing)

      processGPMessages(gp)


    Catch ex As Exception
      processGPMessages(gp)
      System.Diagnostics.Debug.WriteLine(ex.Message)
      System.Diagnostics.Debug.WriteLine(ex.StackTrace)
    End Try
  End Sub

  Public Shared Sub RunGeoprocessorExampleAddServerToolbox()

    Dim serverContext As IServerContext = Nothing
    Dim gp As ESRI.ArcGIS.Geoprocessor.Geoprocessor = Nothing
    Try
      Dim serverConnection As GISServerConnection
      serverConnection = New GISServerConnection()
      serverConnection.Connect(servername)
      Dim serverManager As IServerObjectManager = serverConnection.ServerObjectManager

      serverContext = serverManager.CreateServerContext("BufferTools", "GPServer")

      '* GEOPROCESSOR SECTION
      gp = New ESRI.ArcGIS.Geoprocessor.Geoprocessor(serverContext)
      gp.AddToolbox("C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\GP\RunBuffer\BufferTools.tbx")
      gp.SetEnvironmentValue("scratchWorkspace", "c:/temp")
      gp.OverwriteOutput = True

      ' Need reference to GPTool to get parameter type information
      Dim iwf As IWorkspaceFactory = CType(serverContext.CreateObject("esriGeoprocessing.ToolboxWorkspaceFactory"), IWorkspaceFactory)
      Dim itw As IToolboxWorkspace = CType(iwf.OpenFromFile("C:\Program Files\ArcGIS\DeveloperKit10.0\Samples\data\GP\RunBuffer\RunBuffer", 0), IToolboxWorkspace)
      Dim tbox As IGPToolbox = CType(itw.OpenToolbox("BufferTools"), IGPToolbox)
      Dim tool As IGPTool = CType(tbox.OpenTool("BufferPoints"), IGPTool)

      Dim varray As IVariantArray = CType(serverContext.CreateObject("esriSystem.VarArray"), IVariantArray)

      Dim parameters As IArray = tool.ParameterInfo
      ' Iterate through parameters to get data types

      For j As Integer = 0 To parameters.Count - 1
        Dim gparam As IGPParameter = CType(parameters.Element(j), IGPParameter)

        System.Console.WriteLine("Parameter name: " & gparam.Name)
        System.Console.WriteLine("Parameter Data Type Display Name: " & gparam.DataType.DisplayName)
        System.Console.WriteLine("Parameter Data Type Name: " & gparam.DataType.Name)
        System.Console.WriteLine("Is Parameter required?: " & gparam.ParameterType.ToString())

        System.Console.WriteLine("Parameter Value Data Type: " & gparam.Value.DataType.Name)
        System.Console.WriteLine("Parameter Value as Text: " & gparam.Value.GetAsText())

      Next j

      Dim gpp1 As IGPParameter = CType(parameters.Element(0), IGPParameter)
      Dim gprecset As IGPRecordSet = CType(gpp1.Value, IGPRecordSet)

      Dim rs As IRecordSet = gprecset.RecordSet

      Dim flds As IFields = rs.Fields
      Dim shpfldindex As Integer = flds.FindField("Shape")

      Dim fld As IField = flds.Field(shpfldindex)
      Dim inputsr As ISpatialReference = fld.GeometryDef.SpatialReference

      Dim rsi As IRecordSetInit = CType(rs, IRecordSetInit)
      Dim cur As ICursor = rsi.Insert()
      Dim rb As IRowBuffer = rsi.CreateRowBuffer()
      Dim ipnt As IPoint = CType(serverContext.CreateObject("esriGeometry.Point"), IPoint)
      ipnt.PutCoords(1000000, 1000000)
      rb.Value(shpfldindex) = ipnt
      cur.InsertRow(rb)

      varray.Add(gprecset)

      Dim gpp2 As IGPParameter = CType(parameters.Element(1), IGPParameter)
      Dim gpLU As IGPLinearUnit = CType(serverContext.CreateObject("esriGeoprocessing.GPLinearUnit"), IGPLinearUnit)
      gpLU.Units = ESRI.ArcGIS.esriSystem.esriUnits.esriMeters
      gpLU.Value = 100000

      varray.Add(gpLU)

      gp.Execute(tool.Name, varray, Nothing)

      processGPMessages(gp)


    Catch ex As Exception
      processGPMessages(gp)
      System.Diagnostics.Debug.WriteLine(ex.Message)
      System.Diagnostics.Debug.WriteLine(ex.StackTrace)
    Finally
      serverContext.ReleaseContext()
    End Try
  End Sub


  Public Shared Sub RunGPServerExample()

    Dim serverContext As IServerContext = Nothing
    Try
      Dim serverConnection As GISServerConnection
      serverConnection = New GISServerConnection()
      serverConnection.Connect(servername)
      Dim serverManager As IServerObjectManager = serverConnection.ServerObjectManager

      serverContext = serverManager.CreateServerContext("BufferTools", "GPServer")

      Dim gpserver As IGPServer = CType(serverContext.ServerObject, IGPServer)
      Dim taskname As String = "BufferPoints"
      Dim task As IGPToolInfo = gpserver.GetToolInfo(taskname)
      Dim taskvals As IGPValues = CType(serverContext.CreateObject("esriGeoprocessing.GPValues"), IGPValues)
      Dim paramInfos As IGPParameterInfos = task.ParameterInfo
      Dim paramInfo As IGPParameterInfo

      Dim parameterNameString As String = String.Empty

      For i As Integer = 0 To paramInfos.Count - 1
        ' Data type available as part of IGPParameterInfo
        paramInfo = paramInfos.Element(i)
        taskvals.Add(paramInfo.Value)

        'Add to parameter name array
        parameterNameString &= paramInfo.Name
        If i <> paramInfos.Count - 1 Then
          parameterNameString &= ";"
        End If
      Next i

      Dim gprecset As IGPRecordSet = CType(taskvals.Element(0), IGPRecordSet)
      Dim qf As IQueryFilter = CType(serverContext.CreateObject("esriGeodatabase.QueryFilter"), IQueryFilter)
      gprecset.RecordSet.Table.DeleteSearchedRows(qf)

      Dim rs As IRecordSet = gprecset.RecordSet

      Dim flds As IFields = rs.Fields
      Dim shpfldindex As Integer = flds.FindField("Shape")

      Dim fld As IField = flds.Field(shpfldindex)
      Dim inputsr As ISpatialReference = fld.GeometryDef.SpatialReference

      Dim rsi As IRecordSetInit = CType(rs, IRecordSetInit)
      Dim cur As ICursor = rsi.Insert()
      Dim rb As IRowBuffer = rsi.CreateRowBuffer()
      Dim ipnt As IPoint = CType(serverContext.CreateObject("esriGeometry.Point"), IPoint)
      ipnt.PutCoords(1000000, 1000000)
      rb.Value(shpfldindex) = ipnt
      cur.InsertRow(rb)

      Dim invals As IGPValues = CType(serverContext.CreateObject("esriGeoprocessing.GPValues"), IGPValues)
      invals.Add(CType(gprecset, IGPValue))

      Dim gpLU As IGPLinearUnit = CType(serverContext.CreateObject("esriGeoprocessing.GPLinearUnit"), IGPLinearUnit)
      gpLU.Units = ESRI.ArcGIS.esriSystem.esriUnits.esriMeters
      gpLU.Value = 1000000

      invals.Add(CType(gpLU, IGPValue))

      Dim JobID As String = gpserver.SubmitJob(taskname, invals)

      Do While gpserver.GetJobStatus(JobID) <> esriJobStatus.esriJobSucceeded
        System.Threading.Thread.Sleep(5000)
      Loop

      Dim stringArray As IStringArray = CType(New ESRI.ArcGIS.esriSystem.StrArrayClass(), IStringArray)
      For Each paramName As String In parameterNameString.Split(";"c)
        stringArray.Add(paramName)
      Next paramName


      'The resultant featureclass gets generated in folder uner <C:\arcgisserver\arcgisJobs\<abd9930839dg9330123
      Dim result As IGPResult = gpserver.GetJobResult(JobID, stringArray, Nothing)
      If result.Messages IsNot Nothing Then
        Dim jobMsgs As IJobMessages = result.Messages
        For i As Integer = 0 To jobMsgs.Count - 1
          Console.WriteLine(jobMsgs.Element(i).Description)
        Next i
      End If

    Catch ex As Exception
      System.Diagnostics.Debug.WriteLine(ex.Message)
      System.Diagnostics.Debug.WriteLine(ex.StackTrace)
    Finally
      serverContext.ReleaseContext()
    End Try
  End Sub
End Class