Programmatically  Adding layer to the Arcmap Using C#

7555
10
09-26-2010 01:49 AM
by Anonymous User
Not applicable
Original User: Shrey

Hi All,


     After the user Login to the system I am Invoking the Arcmap by a function. While doing so I am also calling the function to Add the shapefile required in my application .For this I am using the function as mentioned below :



   public void StartArcMap()
        {
            if (m_pDoc == null)
            {
                // Cursor.Current = Cursors.WaitCursor;

                //Start arcmap
                CheckLicence();
                m_pDoc = new MxDocumentClass();

                //Get a reference to the application
                m_application = m_pDoc.Parent;



                m_appHWnd = m_application.hWnd;
                m_application.Caption = "Registeration System V 3.0";
                m_pMxdocument = m_application.Document as IMxDocument;
               
             
                //Show arcmap
                m_application.Visible = true;
               
                //Calling to Add The Shape File
                AddShapefile();

                //Hide All toolbars of Arcmap
              //  m_application.Document.CommandBars.HideAllToolbars();



             
                //Get the commandbars collection
                ICommandBars pCmdBars;
                pCmdBars = m_application.Document.CommandBars;
                //Create New ToolBar
                ICommandBar pNewBar;
                pNewBar = pCmdBars.Create("Adminstrator", ESRI.ArcGIS.SystemUI.esriCmdBarType.esriCmdBarTypeToolbar);

                UIDClass clsSearch = new UIDClass();
                clsSearch.Value = "Tools.clsSearch";
                int intclsSearch = pNewBar.Count;
                object objclsSearch = intclsSearch;
                pNewBar.Add(clsSearch,ref objclsSearch);  

 
                 
             



             
            }
        }//Start the Arcmap Application


  public void AddShapefile()
        {

         
            try
            {


                //IWorkspace pworkspace;
                IWorkspaceFactory pWorkspaceFactory;
                IFeatureWorkspace pFeatureWorkSpace;
                IFeatureClass pFeatureClass;
                IGeoFeatureLayer pGeoFeatureLayer;

                pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
                //pFeatureWorkSpace = (IFeatureWorkspace)pWorkspaceFactory;
                pFeatureWorkSpace = pWorkspaceFactory.OpenFromFile(@"C:\Program Files\ArcGIS\DeveloperKit\SamplesNET\data\AirportsAndGolf", 0) as IFeatureWorkspace;

                pFeatureClass = pFeatureWorkSpace.OpenFeatureClass("STATE");
                pGeoFeatureLayer = new FeatureLayerClass();
                pGeoFeatureLayer.Name = pFeatureClass.AliasName;
                pGeoFeatureLayer.FeatureClass = pFeatureClass;

                m_pMxdocument.AddLayer((ILayer)pGeoFeatureLayer);

                // Ading the Road LAyer
                pFeatureWorkSpace = pWorkspaceFactory.OpenFromFile(@"C:\Program Files\ArcGIS\DeveloperKit\SamplesNET\data\AirportsAndGolf", 0) as IFeatureWorkspace;

                pFeatureClass = pFeatureWorkSpace.OpenFeatureClass("AIRPORT");
                pGeoFeatureLayer = new FeatureLayerClass();
                pGeoFeatureLayer.Name = pFeatureClass.AliasName;
                pGeoFeatureLayer.FeatureClass = pFeatureClass;

                m_pMxdocument.AddLayer((ILayer)pGeoFeatureLayer);
            }
            catch (Exception ex)
            {
                MessageBox.Show(""+ex);

            }
 
        }//End OF Adding the Shapefile


But while doing so the I cannot open the shapefiles and system shows the following error (Attachment one) and if I try some other shape files it Arcmap will shut down and the Error 2 will be show (Attachment)


Please require your help desperately. Thank You
0 Kudos
10 Replies
by Anonymous User
Not applicable
Original User: rchasan

Shrey,

Not sure if this response will help you, but try the following -- change the line:
"IGeoFeatureLayer pGeoFeatureLayer;"  to   "IFeatureLayer pGeoFeatureLayer;"
and see what happens.

Another thing that might help you debug these things is in the "catch" block to use the Exception's StackTrace.  I like to code it as follows:
" MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);  "
That way you are shown specifically which line is causing the problem.
0 Kudos
ShreyPrasad
New Contributor
Shrey,

Not sure if this response will help you, but try the following -- change the line:
"IGeoFeatureLayer pGeoFeatureLayer;"  to   "IFeatureLayer pGeoFeatureLayer;"
and see what happens.

Another thing that might help you debug these things is in the "catch" block to use the Exception's StackTrace.  I like to code it as follows:
" MessageBox.Show(ex.Message + "\n\n" + ex.StackTrace);  "
That way you are shown specifically which line is causing the problem.



Thank You rchasan

For you help and support but this too is not working . Thank You very much
0 Kudos
by Anonymous User
Not applicable
Original User: Neil

m_pDoc = new MxDocumentClass();

You're starting ArcMap programatically and trying to use automation to manipulate it.  ArcMap was never designed to do this so you may run into some problems depending on what you try to do.  That being said, you can add layers to the map.  However, your application is running in one process and ArcMap is running in another process.  ArcObjects are single apartment threaded, meaning you can't create an instance of an ArcObjects class in one process and use it in another process.  If you want to use ArcObjects classes in conjunction with the instance of ArcMap that you have started then you will need to create the instances of those ArcObjects in the process in which ArcMap is running.  You can do this using the IObjectFactory interface.
0 Kudos
ShreyPrasad
New Contributor
m_pDoc = new MxDocumentClass();

You're starting ArcMap programatically and trying to use automation to manipulate it.  ArcMap was never designed to do this so you may run into some problems depending on what you try to do.  That being said, you can add layers to the map.  However, your application is running in one process and ArcMap is running in another process.  ArcObjects are single apartment threaded, meaning you can't create an instance of an ArcObjects class in one process and use it in another process.  If you want to use ArcObjects classes in conjunction with the instance of ArcMap that you have started then you will need to create the instances of those ArcObjects in the process in which ArcMap is running.  You can do this using the IObjectFactory interface.



Thank You Neil ,

Can you please give an example and show what actually are you trying to say so the picture can be more clear .

I would like to mention that the Arcmap is opening well the Error arises  when I am trying to Load my Custom toolbar  and more specially while I  try and add the shape file to the the my customized Arcmap. IF possible show the Example.
0 Kudos
by Anonymous User
Not applicable
Original User: Neil

If you look at the IObjectFactory help topic in the developer help you'll see there is a code sample as well as a link to additional information.
0 Kudos
ShreyPrasad
New Contributor
If you look at the IObjectFactory help topic in the developer help you'll see there is a code sample as well as a link to additional information.


Neil,

As per your advise I used the following codes :

public void StartArcMap()
        {
            CheckLicence();
            try
            {
                doc = new ESRI.ArcGIS.ArcMapUI.MxDocumentClass();
            }
            catch (Exception ex)
            {
                MessageBox.Show("" + ex);
            } //Fail if you haven't installed the target application
            finally
            {
            }

            if (doc != null)
            {
                IObjectFactory objFactory = m_application as IObjectFactory;
                //Get a reference of the application and make it visible
                m_application = doc.Parent;


                m_appHWnd = m_application.hWnd;
                m_application.Caption = "Ur Application Name";
                doc = m_application.Document as MxDocument;


                AddShapefile();
                m_application.Visible = true;
                //Hide All toolbars of Arcmap
                m_application.Document.CommandBars.HideAllToolbars();

                //UIDClass puid;
                //puid = new UIDClass();

                // puid.Value = "esriArcMapUI.MxFileMenu";

                // m_application.Document.CommandBars.Find(puid, false, false).Delete(); // remove filemenu


                //Add Editor Toolbar

                ICommandBars pCommandBars;
                pCommandBars = m_application.Document.CommandBars;

                UIDClass u = new UIDClass();
                u.Value = "Tools.Administrator";



                //Get the commandbars collection
                ICommandBars pCmdBars;
                pCmdBars = m_application.Document.CommandBars;

                //Create New ToolBar
                ICommandBar pNewBar;
                pNewBar = pCmdBars.Create("Adminstrator", ESRI.ArcGIS.SystemUI.esriCmdBarType.esriCmdBarTypeToolbar);
               // pNewBar.Dock(esriDockFlags.esriDockBottom,T);


                UIDClass clsSearch = new UIDClass();
                clsSearch.Value = "Tools.clsSearch";
                int intclsSearch = pNewBar.Count;
                object objclsSearch = intclsSearch;
                pNewBar.Add(clsSearch, ref objclsSearch);
            }

       }//Start the Arcmap Application

public void AddShapefile()
        {


            try
            {


                //IWorkspace pworkspace;
                IWorkspaceFactory pWorkspaceFactory;
                IFeatureWorkspace pFeatureWorkSpace;
                IFeatureClass pFeatureClass;
                IGeoFeatureLayer pGeoFeatureLayer;

                pWorkspaceFactory = new ShapefileWorkspaceFactoryClass();
                //pFeatureWorkSpace = (IFeatureWorkspace)pWorkspaceFactory;
                pFeatureWorkSpace = pWorkspaceFactory.OpenFromFile(@"C:\Program Files\ArcGIS\DeveloperKit\SamplesNET\data\Airports AndGolf", 0) as IFeatureWorkspace;

                pFeatureClass = pFeatureWorkSpace.OpenFeatureClass("STATE");
                pGeoFeatureLayer = new FeatureLayerClass();
                pGeoFeatureLayer.Name = pFeatureClass.AliasName;
                pGeoFeatureLayer.FeatureClass = pFeatureClass;

                m_pMxdocument.AddLayer((ILayer)pGeoFeatureLayer);

                // Ading the Road LAyer
                pFeatureWorkSpace = pWorkspaceFactory.OpenFromFile(@"C:\Program Files\ArcGIS\DeveloperKit\SamplesNET\data\Airports AndGolf", 0) as IFeatureWorkspace;

                pFeatureClass = pFeatureWorkSpace.OpenFeatureClass("AIRPORT");
                pGeoFeatureLayer = new FeatureLayerClass();
                pGeoFeatureLayer.Name = pFeatureClass.AliasName;
                pGeoFeatureLayer.FeatureClass = pFeatureClass;

                m_pMxdocument.AddLayer((ILayer)pGeoFeatureLayer);
            }
            catch (Exception ex)
            {
                MessageBox.Show("" + ex);

            }

        }//End OF Adding the Shapefile






I am able to get my Custom tool but while i am adding the shape file i am not able to get the shape file. It throws the exception at the point OpenFromFile   .
The Exception is COM Exception as i mentioned in the earlier mail. 
Can you please help  me in this I want to open the multiple shapefile from pgdb. but while tryin to add the single file also from the pgdb it show the same error . So trie and used the shapeileworkspacefactory  and used the default data provided by esri . but still I am getting that com Exception.
0 Kudos
by Anonymous User
Not applicable
Original User: rchasan

Shrey,

If the feature classes you are trying to open are in a personal geodatabase, then try changing this line: 

pWorkspaceFactory = new ShapefileWorkspaceFactoryClass(); 

to

pWorkspaceFactory = new AccessWorkspaceFactoryClass();

and see what happens.
0 Kudos
ShreyPrasad
New Contributor
Here i have opened arc map programatically add all the shape files from the pgdb. programatically .


I am able to see the names of all layers in the TOC but i cannot see any feature in active view. and after some time the arcmap crashes .


  

    public class Util
    {
        public IApplication m_application;
        public IDocument doc;
        public IAppROT m_pAppRot;
        public  int m_appHWnd = 0;
        public  IMxDocument m_pMxdocument;
        public IMap pMap=null ;

       public IPropertySet pPropset;
       public IWorkspaceFactory pAccessFact;
       public IFeatureWorkspace pFeatureWorkspace;
       public IFeatureLayer pfeaturelayer;
       public IGeoFeatureLayer pGeofeaturelayer;
    
       public IWorkspaceFactory wFact;
       public IWorkspace wSpace;
       public Collection AllFeatclassarray;
       public Collection featureClassCollection;
       public  string[] lyrname;
       public  IFeatureClass pFeatclass;
     
  
        public void StartArcMap()
            {
                CheckLicence();
                    try
                    {
                        doc = new ESRI.ArcGIS.ArcMapUI.MxDocumentClass();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("" + ex);
                    }


                if (doc != null)
                    {
                        IObjectFactory objFactory = m_application as IObjectFactory;
                     
                        m_application = doc.Parent;


                       m_appHWnd = m_application.hWnd;
                       m_application.Caption = "Ur appliction  name ";
                       doc = m_application.Document as MxDocument;


                        AddShapefile();
                        m_application.Visible = true;
                        //Hide All toolbars of Arcmap
                        m_application.Document.CommandBars.HideAllToolbars ();


                        ICommandBars pCommandBars;
                        pCommandBars = m_application.Document.CommandBars;

                        UIDClass u = new UIDClass();
                        u.Value = "Tools.Administrator";



                     
                        ICommandBars pCmdBars;
                        pCmdBars = m_application.Document.CommandBars;

                        ICommandBar pNewBar;
                        pNewBar = pCmdBars.Create("Adminstrator", ESRI.ArcGIS.SystemUI.esriCmdBarType.esriCmdBarTypeToolbar);
                       

                        UIDClass clsSearch = new UIDClass();
                        clsSearch.Value = "Tools.clsSearch";
                        int intclsSearch = pNewBar.Count;
                        object objclsSearch = intclsSearch;
                        pNewBar.Add(clsSearch, ref objclsSearch);
                        }

                }
     

        public void AddShapefile()
            {
                try
                {
                    IObjectFactory objFactory = m_application as IObjectFactory;
                    //Add the layer to document
                    IBasicDocument doc = (IBasicDocument)m_application.Document;
                  //  Type pAccessFact = typeof(AccessWorkspaceFactoryClass);

                    string path = "E:\\Data.mdb";
                    pPropset = new PropertySetClass();
                    pPropset.SetProperty("DATABASE", path);

                    wFact = new AccessWorkspaceFactoryClass();
                    wSpace = wFact.Open(pPropset, 0);
                    IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)wSpace;
                    AllFeatclassarray = GetAllFeatureClasses();
                 
                    featureClassCollection = AllFeatclassarray;
                   
                 
                    for ( int i = 1; i <= featureClassCollection.Count; i++)
                    {
                        IFeatureClass pFeatclass1;
                        pfeaturelayer = new FeatureLayerClass();
                        string pFeatclass = featureClassCollection as string;
                        pfeaturelayer = (IFeatureLayer)objFactory.Create("esriCarto.FeatureLayer");
                        pfeaturelayer.FeatureClass = featureWorkspace.OpenFeatureClass(pFeatclass);
                       // pFeatclass1 = featureWorkspace.OpenFeatureClass(pFeatclass);
                       
                        pfeaturelayer.Name = pfeaturelayer.FeatureClass.AliasName;
                        pGeofeaturelayer = (IGeoFeatureLayer)pfeaturelayer;
                        pGeofeaturelayer.DisplayAnnotation = true;
                        doc.AddLayer(pGeofeaturelayer);
                    }

                   
                   // AllFeatclassarray.Add();  
                   

                   
                }

                catch (Exception ex)
                {
                    MessageBox.Show(""+ex);  
                }
                   
            }//AddShapefile



        private Collection GetAllFeatureClasses()
        {
            Collection featureClassList = new Collection();
            if (wSpace.Type == esriWorkspaceType.esriFileSystemWorkspace)
            {
                GetFeatureClassesForShape(featureClassList);
            }
            else
            {
                GetDatasets(featureClassList);
            }
            return featureClassList;
        }


        private void GetDatasets(Collection featureClassList)
        {
            IEnumDataset eDataset;
            IDataset ds;
            eDataset = wSpace.get_Datasets(esriDatasetType.esriDTAny);
            ds = eDataset.Next();
            while (ds != null)
            {
                LoopThroughClasses(ds, featureClassList);
                ds = eDataset.Next();
            }

        }


        private void LoopThroughClasses(IDataset dataset, Collection featureClassList)
        {
            try
            {


                IFeatureDataset fDataset;
                IFeatureClassContainer fcContainer;
                IEnumFeatureClass enumFeatCls;
                IFeatureClass featCls;

                if (dataset.Type == esriDatasetType.esriDTFeatureDataset)
                {
                    fDataset = (IFeatureDataset)dataset;
                    fcContainer = (IFeatureClassContainer)fDataset;
                    enumFeatCls = fcContainer.Classes;
                    featCls = enumFeatCls.Next();


                    while (featCls != null)
                    {

                        IDataset ds = (IDataset)featCls;
                        featureClassList.Add(featCls, ds.Name, null, null);
                        featCls = enumFeatCls.Next();

                    }
                }
                else
                {
                    IFeatureClass pFeatuclass;
                    pFeatuclass = dataset as IFeatureClass;
                    featureClassList.Add(pFeatuclass.AliasName, null, null, null);
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(""+exp); 
            }
        }



        private void GetFeatureClassesForShape(Collection featureClassList)
        {
            IEnumDataset eDataset;
            IDataset ds;
            IFeatureClass featCls;

            eDataset = wSpace.get_Datasets(esriDatasetType.esriDTFeatureClass);
            ds = eDataset.Next();

            while (ds != null)
            {
                featCls = (IFeatureClass)ds;
                featureClassList.Add(featCls, ds.Name, null, null);
                ds = eDataset.Next();

            }
        }


        public void ShutDownArcMap()
        {
            try
            {
                if (m_application != null)
                {
                    //Try to close any modal dialogs by sending the Escape key
                    //It doesn't handle the followings:
                    //- VBA is up and has a modal dialog
                    //- Modal dialog doesn't close with the Escape key
                    Microsoft.VisualBasic.Interaction.AppActivate(m_application.Caption);
                    int nestModalHwnd = 0;
                 

                    //Manage document dirty flag - abandon changes
                    IDocumentDirty2 docDirtyFlag = (IDocumentDirty2)m_application.Document;
                    docDirtyFlag.SetClean();

                    //Stop listening before exiting
                    //m_appROTEvent.AppRemoved -= new IAppROTEvents_AppRemovedEventHandler(m_appROTEvent_AppRemoved);
                    //m_appROTEvent = null;

                    //Exit
                    m_application.Shutdown();
                    m_application = null;
                    //Reset UI for next automation
                }
            }
            catch { }
        }


    }
}


The arc map open all the  layer are visible in TOC but not in the active view and the arcmap crashes after some time .And the error I have already posted in my earlier post.



Freinds help me my arc map is crashing I cannot know the reason please tell me if any of you know. Because after doing this only i can proceed in my application. Desperately need ur help.
0 Kudos
by Anonymous User
Not applicable
Original User: AnserGIS

Hi,

Did you ever resolve this?

I am trying to do the same thing (in .Net) and getting a similar problem.
0 Kudos