Exporting table to sde

2639
3
11-04-2015 09:59 PM
NigelDsouza
Occasional Contributor

HI, My objective is to export a featureclass to sde.

My code is as follows:

  IPropertySet propertySet = new PropertySetClass();

            propertySet.SetProperty("SERVER", "3019-h2-xyz");

            propertySet.SetProperty("INSTANCE", "SDE:SQLSERVER:TEMP-INS-COM");

            propertySet.SetProperty("DATABASE", "foo");

            propertySet.SetProperty("AUTHENTICATION_MODE", "OSA");

            propertySet.SetProperty("VERSION", "dbo.DEFAULT");

            IWorkspaceFactory workspaceFactory = new SdeWorkspaceFactoryClass();

            IFeatureWorkspace pArcSDEFeatureWorksapce = workspaceFactory.Open(propertySet, 0)  as IFeatureWorspace

      IWorkspace2 pWS2 = pArcSDEFeatureWorksapce as IWorkspace2;

                if (pWS2.get_NameExists(esriDatasetType.esriDTTable, intersect_featurename))

                {

                    IDataset pExistingDataset = pArcSDEFeatureWorksapce.OpenTable(intersect_featurename) as IDataset;

                    if (pExistingDataset.CanDelete())

                    {

                    

                        pExistingDataset.Delete();

                    }

                }

              Geoprocessor pGp = new Geoprocessor();

                DisplayMessage("Exporting to SDE....");

                TableToGeodatabase pTableToGeodatabase = new TableToGeodatabase();

                pTableToGeodatabase.Input_Table = intersectOutputFeatureClass.AliasName;

                pTableToGeodatabase.Output_Geodatabase = pArcSDEFeatureWorksapce;

                pGp.Execute(pTableToGeodatabase, null);

The pArcSDEFeatureWorksapce allows me to retrieve and delete any feautureclasses. Also if I connect to this database connection in  arccatalog and then run this code it exports a featureclass to sde. But if the connection in arc-catalog is disconnected the execution fails. If I am connecting to an arcsde workspace programmatically then why do I have to connect to an existing connection and then execute the tool?

Also this connection works fine in model builder without having me connect a connection in catalog.

Regards,

Nigel.

Tags (1)
0 Kudos
3 Replies
FreddieGibson
Occasional Contributor III

I would assume the code is failing because of how you're setting the input_table parameter of the tool. It looks like you're using the name of the feature class and not the path to it on disk. I wouldn't expect this to work because within the code you didn't set the current workspace to your geodatabase.

I would suggest either supplying the ITable to the tool, providing the full path to the table, or setting the environment variable so that you can utilize the name of the feature class (I'd think you'd want to use IDataset.BrowseName instead of the AliasName).

Also, you'll want to avoid create the SdeWorkspaceFactory with the call to new SdeWorkspaceFactory. You'll want to use the activator to create an instance of this class. This is documented on the following page:

Interacting with singleton objects

http://resources.arcgis.com/en/help/arcobjects-net/conceptualhelp/#/Interacting_with_singleton_objec...

FreddieGibson
Occasional Contributor III

Hi Nigel,

I only had about 20 minutes to actually test this out today so I'm going to update you with my assumptions based on what I've seen so far. I'm thinking that there may be a bigger problem at play here. Everything works fine for me when I output the tables to a file geodatabase. When I change the output workspace to an enterprise geodatabase thing begin to fail.

I ran a quick test in ArcMap and the Table to Geodatabaase tool is also failing there when the output workspace is an enterprise geodatabase. I'm not sure if there is something wrong with my enterprise geodatabase or if the tool is having a problem with the sde naming conventions.

I've pasted the code I used to test below. You should be able to modify it and test it on your machine. Could you let me know if you're able to get the Table To Geodatabase tool to work from ArcMap?

2015-11-05_1711.png

using System;
using System.Collections.Generic;
using ESRI.ArcGIS.ConversionTools;
using ESRI.ArcGIS.DataManagementTools;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.Geoprocessor;
using Path = System.IO.Path;


namespace TransportTable
{
    class Program
    {
        private static readonly LicenseInitializer m_aoInit = new LicenseInitializer();
        private static readonly Dictionary<string, string> m_connProps = new Dictionary<string, string>
        {
            {"SERVER", "uzumaki"},
            {"INSTANCE", @"sde:sqlserver:uzumaki\express2014"},
            {"DBCLIENT", "SQLSERVER"},
            {"DATABASE", "gdb"},
            {"AUTHENTICATION_MODE", "DBMS"},
            {"USER", "sde"},
            {"PASSWORD", "sde"},
            {"VERSION", "sde.DEFAULT"}
        };


        static readonly string m_gdbPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"ArcGIS\Default.gdb");
        const string m_tblName = "MyCitiez";


        static readonly string m_gdbPathOut = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "MyGDBData.gdb");
        static readonly string m_sdePathOut = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ConnToSDE.sde");
        
        [STAThread()]
        static void Main(string[] args)
        {
            //ESRI License Initializer generated code.
            m_aoInit.InitializeApplication(new [] { esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { });


            var in_ws = OpenWorkspace(m_gdbPath) as IFeatureWorkspace;
            var table = in_ws.OpenTable(m_tblName);


            var outGdbWs = OpenWorkspace(m_gdbPathOut);
            var outSdeWs = OpenWorkspace(m_connProps);


            foreach (var workspace in new [] {outGdbWs, outSdeWs})
            {
                foreach (var workflow in new [] {Workflow.UseObjects, Workflow.UseStrings})
                {
                    Console.WriteLine("WORKSPACE IS {0} AND WORKFLOW USES {1}", workspace.WorkspaceFactory.WorkspaceType, workflow == Workflow.UseObjects ? "OBJECTS" : "STRINGS");
                    ExportToTable(table, workspace, workflow);    
                }
            }


            Console.WriteLine();
            Console.Write("Press enter to exit...");
            Console.ReadLine();




            //ESRI License Initializer generated code.
            //Do not make any call to ArcObjects after ShutDownApplication()
            m_aoInit.ShutdownApplication();
        }


        private static void ExportToTable(ITable inTable, IWorkspace outWorkspace, Workflow workflow)
        {
            var fws = outWorkspace as IFeatureWorkspace;


            if ((outWorkspace as IWorkspace2).NameExists[esriDatasetType.esriDTFeatureClass, (inTable as IDataset).BrowseName])
            {
                var table = fws.OpenTable((inTable as IDataset).BrowseName) as IDataset;
                if (table.CanDelete())
                    table.Delete();
            }


            Geoprocessor gp = new Geoprocessor {OverwriteOutput = true};


            try
            {
                TableToGeodatabase tool;
                //TableToTable tool;


                if (workflow == Workflow.UseStrings)
                {
                    Console.WriteLine("*** USING OBJECTS ***");
                    tool = new TableToGeodatabase
                    {
                        Input_Table = inTable,
                        Output_Geodatabase = fws
                    };


                    //tool = new TableToTable
                    //{
                    //    in_rows = inTable,
                    //    out_path = workspace,
                    //    out_name = (inTable as IDataset).BrowseName
                    //};
                }
                else
                {
                    Console.WriteLine("*** USING STRINGS ***");
                    var tuul = new CreateDatabaseConnection
                    {
                        out_folder_path = Path.GetDirectoryName(m_sdePathOut),
                        out_name = Path.GetFileName(m_sdePathOut),
                        database_platform = "SQL_SERVER",
                        instance = m_connProps["INSTANCE"],
                        account_authentication =
                            m_connProps["AUTHENTICATION_MODE"] == "DBMS" ? "DATABASE_AUTH" : "OPERATING_SYSTEM_AUTH",
                        username = m_connProps["USER"],
                        password = m_connProps["PASSWORD"],
                        save_user_pass = "SAVE_USERNAME",
                        database = m_connProps["DATABASE"],
                        version = m_connProps["VERSION"]
                    };


                    var rezult = gp.Execute(tuul, null) as IGeoProcessorResult2;
                    gp.ClearMessages();


                    tool = new TableToGeodatabase
                    {
                        Input_Table =
                            string.Format(@"{0}\{1}", (inTable as IDataset).Workspace.PathName,
                                (inTable as IDataset).BrowseName),
                        Output_Geodatabase =
                            outWorkspace.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriLocalDatabaseWorkspace
                                ? outWorkspace.PathName
                                : rezult.GetOutput(0).GetAsText()
                    };


                    //tool = new TableToTable
                    //{
                    //    in_rows = string.Format(@"{0}\{1}", (inTable as IDataset).Workspace.PathName, (inTable as IDataset).BrowseName),
                    //    out_path = rezult.GetOutput(0).GetAsText(),
                    //    out_name = (inTable as IDataset).BrowseName
                    //};
                }


                var result = gp.Execute(tool, null) as IGeoProcessorResult2;
                Console.WriteLine(result.GetMessages(0));


            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                object sev = 2;


                Console.WriteLine(gp.GetMessages(ref sev));
            }
            finally
            {
                Console.WriteLine("");
                Console.WriteLine("##############################");
                Console.WriteLine("");
            }


        }


        private static IWorkspace OpenWorkspace(string wsPath)
        {
            var factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGdbWorkspaceFactory");
            var wsFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory;


            if (System.IO.Directory.Exists(wsPath))
                return wsFactory.OpenFromFile(wsPath, 0);


            var wsName = wsFactory.Create(Path.GetDirectoryName(wsPath), Path.GetFileName(wsPath), null, 0);


            var name = wsName as IName;
            return name.Open() as IWorkspace;
        }


        private static IWorkspace OpenWorkspace(Dictionary<string, string> ConnProps)
        {
            var factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.SdeWorkspaceFactory");
            var wsFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory;


            var propset = new PropertySetClass();
            foreach (var prop in ConnProps)
                propset.SetProperty(prop.Key, prop.Value);


            return wsFactory.Open(propset, 0);
        }
    }


    enum Workflow
    {
        UseStrings,
        UseObjects
    }
}
NigelDsouza
Occasional Contributor

The Only way the tool works successfully is to create a connection in the catalog window and run the toll while that connection is in the "CONNECTED" State. Thanks everyone for your help. Regards, Nigel.

0 Kudos