ArcGIS GPConsole
ArcGIS_GPConsole_CSharp\ArcGIS_GPConsole\Program.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.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();
            }
        }
    }
}