Import shapefile to polylines in C# .NET framework

Import shapefile to polylines in C# .NET framework

m.chavet7MJRB
Enthusiast Enthusiast
2,552 Views
32 Replies
Message 1 of 33

Import shapefile to polylines in C# .NET framework

m.chavet7MJRB
Enthusiast
Enthusiast

Hello,  I don't find how to import a shapefile layer, and then convert it to a 2D polyline through a #C language  code. I know that in Autacad/C3D it's "mapimport". 

0 Likes
Accepted solutions (2)
2,553 Views
32 Replies
Replies (32)
Message 21 of 33

m.chavet7MJRB
Enthusiast
Enthusiast

.

0 Likes
Message 22 of 33

m.chavet7MJRB
Enthusiast
Enthusiast

Yes and it works.

 

But now I get this new error for the two codes I showed. 

 

I read that on this topic: https://forums.autodesk.com/t5/net/the-application-does-not-support-windows-form-debugging-in-just/m...

0 Likes
Message 23 of 33

Alexander.Rivilis
Mentor
Mentor

@m.chavet7MJRB 

What exact exception message C3D show? What code executed in that time?

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

0 Likes
Message 24 of 33

m.chavet7MJRB
Enthusiast
Enthusiast
************** Exception Text **************
System.ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
   at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method, Boolean throwOnBindFailure)
   at System.Delegate.CreateDelegate(Type type, Object firstArgument, MethodInfo method)
   at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorker(MethodInfo mi, Object commandObject, Boolean bLispFunction)
   at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorkerWithExceptionFilter(MethodInfo mi, Object commandObject, Boolean bLispFunction)
   at Autodesk.AutoCAD.Runtime.PerDocumentCommandClass.Invoke(MethodInfo mi, Boolean bLispFunction)
   at Autodesk.AutoCAD.Runtime.CommandClass.CommandThunk.Invoke()





************** Exception Text **************
System.ArgumentException: Value does not fall within the expected range.
   at Autodesk.Civil.DatabaseServices.ProfileEntityCollection.AddFreeSymmetricParabolaByLength(UInt32 previousEntityId, UInt32 nextEntityId, VerticalCurveType curveType, Double length, Boolean preferFlat)
   at CreateProfileView.MyCommands.CreateProfileNoSurface() in C:\Users\maxime.chavet\Documents\RDC29\VISUAL_STUDIO\Profile\Profile\Class1.cs:line 72
   at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorker(MethodInfo mi, Object commandObject, Boolean bLispFunction)
   at Autodesk.AutoCAD.Runtime.CommandClass.InvokeWorkerWithExceptionFilter(MethodInfo mi, Object commandObject, Boolean bLispFunction)
   at Autodesk.AutoCAD.Runtime.PerDocumentCommandClass.Invoke(MethodInfo mi, Boolean bLispFunction)
   at Autodesk.AutoCAD.Runtime.CommandClass.CommandThunk.Invoke()










0 Likes
Message 25 of 33

Alexander.Rivilis
Mentor
Mentor

@m.chavet7MJRB 

Code?

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

0 Likes
Message 26 of 33

m.chavet7MJRB
Enthusiast
Enthusiast

@m.chavet7MJRB wrote:

All the features are not imported with the "map import", and I guess it's what this code does.

 

With this code, I don't find the function ImportShape I created when I import it in C3D with netload:

 

 

 

 

 

using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.Civil;
using Autodesk.Civil.ApplicationServices;
using Autodesk.Civil.DatabaseServices;
using Autodesk.Civil.Settings;
using System.Diagnostics;
using System.IO;
using Autodesk.Gis.Map.ImportExport;
using Autodesk.Gis.Map;

namespace import_shapefile
{
    public class Class1
    {

        #region IExtensionApplication Members

        public void Initialize()
        {
            //    throw new System.Exception("The method or operation is not implemented")
        }

        public void Terminate()
        {
            //    throw new System.Exception("The method or operation is not implemented")
        }

        #endregion


        [CommandMethod("ImportShape")]
        private void ImportShape(FileInfo file)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            MapApplication mapApp = HostMapApplicationServices.Application;
            using (Importer importer = mapApp.Importer)
            {
                importer.Init("SHP", file.FullName);

                string fileName = Path.GetFileNameWithoutExtension(file.FullName).Replace(" ", "");

                foreach (InputLayer inputLayer in importer)
                {
                    inputLayer.SetLayerName(LayerNameType.LayerNameDirect, fileName);
                    inputLayer.SetDataMapping(ImportDataMapping.NewObjectDataOnly, fileName);

                    inputLayer.Dispose();
                }

                importer.ImportPolygonsAsClosedPolylines = true;

                ImportResults result = importer.Import(true);

                sw.Stop();
                //Quest_Common.ed.WriteMessage(string.Format("\n{0} object(s) imported in {1} sec(s)", result.EntitiesImported.ToString(), sw.Elapsed.Seconds));

                importer.Dispose();
            }

            file.Delete();
        }
    }
}

 

 

 

 

  

 

Moreover, I get a problem when I launch this code to create profile with no surface, because of the style and the label style are not recognized, it says "Name no exists", I tried "Basic" and "Standard":

 

 

 

 

 

using System;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.Civil;
using Autodesk.Civil.ApplicationServices;
using Autodesk.Civil.DatabaseServices;
using Autodesk.Civil.Settings;
using Autodesk.AutoCAD.Geometry;


namespace CreateProfileView
{

    public class MyCommands
    {

        #region IExtensionApplication Members

        public void Initialize()
        {
            //    throw new System.Exception("The method or operation is not implemented")
        }

        public void Terminate()
        {
            //    throw new System.Exception("The method or operation is not implemented")
        }

        #endregion

        [CommandMethod("CreateProfileNoSurface")]
        public void CreateProfileNoSurface()
        {
            CivilDocument doc = CivilApplication.ActiveDocument;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            using (Transaction ts = Application.DocumentManager.MdiActiveDocument.Database.TransactionManager.StartTransaction())
            {
                // Ask the user to select an alignment 
                PromptEntityOptions opt = new PromptEntityOptions("\nSelect an Alignment");
                opt.SetRejectMessage("\nObject must be an alignment.\n");
                opt.AddAllowedClass(typeof(Alignment), false);
                ObjectId alignID = ed.GetEntity(opt).ObjectId;

                Alignment oAlignment = ts.GetObject(alignID, OpenMode.ForRead) as Alignment;

                // use the same layer as the alignment
                ObjectId layerId = oAlignment.LayerId;
                // get the standard style and label set 
                // these calls will fail on templates without a style named "Standard"

                ObjectId styleId = doc.Styles.ProfileStyles["Basic"];
                ObjectId labelSetId = doc.Styles.LabelSetStyles.ProfileLabelSetStyles["Basic"];

                ObjectId oProfileId = Profile.CreateByLayout("My Profile", alignID, layerId, styleId, labelSetId);

                // Now add the entities that define the profile.

                Profile oProfile = ts.GetObject(oProfileId, OpenMode.ForRead) as Profile;

                Point3d startPoint = new Point3d(oAlignment.StartingStation, -40, 0);
                Point3d endPoint = new Point3d(758.2, -70, 0);
                ProfileTangent oTangent1 = oProfile.Entities.AddFixedTangent(startPoint, endPoint);

                startPoint = new Point3d(1508.2, -60.0, 0);
                endPoint = new Point3d(oAlignment.EndingStation, -4.0, 0);
                ProfileTangent oTangent2 = oProfile.Entities.AddFixedTangent(startPoint, endPoint);

                oProfile.Entities.AddFreeSymmetricParabolaByLength(oTangent1.EntityId, oTangent2.EntityId, VerticalCurveType.Sag, 900.1, true);

                ts.Commit();
            }

        }

       
    }
}

 

 

excatly these codes, appart the correction you mentionned before

 


 

0 Likes
Message 27 of 33

Alexander.Rivilis
Mentor
Mentor

You did not read that I and @norman.yuan and @hosneyalaa and @fieldguy wrote above. You ignore all that was written above. So I have no chance to help you.

Відповідь корисна? Клікніть на "ВПОДОБАЙКУ" цім повідомленням! | Do you find the posts helpful? "LIKE" these posts!
Находите сообщения полезными? Поставьте "НРАВИТСЯ" этим сообщениям!
На ваше запитання відповіли? Натисніть кнопку "ПРИЙНЯТИ РІШЕННЯ" | Have your question been answered successfully? Click "ACCEPT SOLUTION" button.
На ваш вопрос успешно ответили? Нажмите кнопку "УТВЕРДИТЬ РЕШЕНИЕ"


Alexander Rivilis / Александр Ривилис / Олександр Рівіліс
Programmer & Teacher & Helper / Программист - Учитель - Помощник / Програміст - вчитель - помічник
Facebook | Twitter | LinkedIn
Expert Elite Member

0 Likes
Message 28 of 33

m.chavet7MJRB
Enthusiast
Enthusiast

I just quoted my previous message. As I said at the end, I changed the correction you mentionned before (private=> public and remove the words inside the () ) and it works

0 Likes
Message 29 of 33

m.chavet7MJRB
Enthusiast
Enthusiast

 

 

[CommandMethod("ImportShape")]
public void ImportShape()
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    MapApplication mapApp = HostMapApplicationServices.Application;
    using (Importer importer = mapApp.Importer)
    {
        importer.Init("SHP", file.FullName);

        string fileName = Path.GetFileNameWithoutExtension(file.FullName).Replace(" ", "");

        foreach (InputLayer inputLayer in importer)
        {
            inputLayer.SetLayerName(LayerNameType.LayerNameDirect, fileName);
            inputLayer.SetDataMapping(ImportDataMapping.NewObjectDataOnly, fileName);

            inputLayer.Dispose();
        }

        importer.ImportPolygonsAsClosedPolylines = true;

        ImportResults result = importer.Import(true);

        sw.Stop();
        //Quest_Common.ed.WriteMessage(string.Format("\n{0} object(s) imported in {1} sec(s)", result.EntitiesImported.ToString(), sw.Elapsed.Seconds));

        importer.Dispose();
    }

    file.Delete();
}

 

 

I still get an error when I delete the "FileInfo file" in the parenthesis. My "file" variable is no longer recognized by the code, do you know how I could fix this please? Sorry for the negligence, I'm a little lost with all this information.

0 Likes
Message 30 of 33

fieldguy
Advisor
Advisor
Accepted solution

You do not show where you get "FileInfo file".  You are trying to pass this "Argument" to the commandmethod and you can't do that.  When you try "importer.Init("SHP", file.FullName)" there is no "file" defined.

My suggestion would be to add a class string variable and use that for the importer.

Something like this:

Before [CommandMethod("ImportShape")] declare a class variable 

public static string _shpname;

Wherever you obtain "FileInfo file", set _shpname to file.Filename.

Then in your importer.Init statement, use _shpname.

IMO - these are very basic programming issues.  Your statements of "...and I guess it's what this code does" and ..."Sorry for the negligence, I'm a little lost with all this information" indicate you need to understand OOP before jumping into autodesk APIs.

 

Message 31 of 33

m.chavet7MJRB
Enthusiast
Enthusiast

.

0 Likes
Message 32 of 33

fieldguy
Advisor
Advisor
Accepted solution

You are still using "file.Fullname".  Where does that come from?  There is no magic available to obtain FileInfo file. 

Try hardcoding a path to any shp file you have on your hard disc.

public static string _shpname = "full path to some shp file on your pc".

If you need help with "FileInfo" use google.  If you want to allow the user to pick a shp file, search google for OpenFileDialog.

I am trying to explain why you can't use file.FullName and now you are trying to use it twice.

importer.Init("SHP", file.Fullname);
string _shpname = Path.GetFileNameWithoutExtension(file.Fullname).Replace(" ", "");

 

0 Likes
Message 33 of 33

m.chavet7MJRB
Enthusiast
Enthusiast

It works, many thanks for your help

 

 

 

0 Likes