Recent Posts

Pages: 1 ... 7 8 [9] 10
81
This site / Cool Site BTW
« Last post by bcinnv on February 24, 2013, 07:00:14 AM »
Was wanting to make a site specifically to be a library for 'How To' concerning coding in lisp and c# that I find and collect online. There is already a good start here. Thank you!
82
C# language / How to offset polyline
« Last post by bcinnv on February 24, 2013, 05:12:39 AM »
Anyone know of an example to offset a polyline that's added to the block record table via c#.net? I've tried to use the developer guide examples but errors out.  I'm looking for automatic selection for offsite side (either inner or outer, doesn't matter). Using centroid was always my preferred method in Lisp but it appears there isn't a centroid option with c# and polyline.

Thanks!
83
Polylines / Regular polygons example
« Last post by fixo on February 21, 2013, 08:19:48 AM »
          C#
Code: [Select]
       // by Tony Tanzillo
        public static Point3d PolarPoint(Point3d basepoint, double angle, double distance)
        {
            return new Point3d(
            basepoint.X + (distance * Math.Cos(angle)),
            basepoint.Y + (distance * Math.Sin(angle)),
            basepoint.Z);
        }
        [CommandMethod("preg", CommandFlags.UsePickSet)]
        public void testPolygonRegular()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            Editor ed = doc.Editor;
            PromptIntegerOptions pio = new PromptIntegerOptions("");
            pio.Message = "\nNumber of sides: ";

            // Restrict input to positive and non-negative values
            pio.AllowZero = false;
            pio.AllowNegative = false;
            // Add default value
            pio.DefaultValue = 3;
            pio.AllowNone = true;
            // Get the value entered by the user
            PromptIntegerResult ires = ed.GetInteger(pio);
            if (ires.Status != PromptStatus.OK) return;
            int n = ires.Value;

            PromptDoubleOptions pdo = new PromptDoubleOptions("\nEnter radius: ");
            pdo.AllowZero = false;
            pdo.AllowNegative = false;
            pdo.AllowNone = true;
            pdo.UseDefaultValue = true;
            pdo.DefaultValue = 3.0;

            PromptDoubleResult res;
            res = ed.GetDouble(pdo);
            if (res.Status != PromptStatus.OK) return;

            double rad = res.Value;

            double ang = Math.PI * 2 / n;
            Point3d cp, p1,p2;
            // Center point
            cp = new Point3d(0, 0,0);

            Polyline poly = new Polyline(n);
            Polyline poly2 = new Polyline(n);
            for (int th = 0; th < n; th++)
            {
                // Circumscribed
                p1 = PolarPoint(cp, th * ang, rad / Math.Cos(ang / 2)).TransformBy(Matrix3d.Identity);
                poly.AddVertexAt(th, new Point2d(p1.X, p1.Y), 0, 0, 0);
                // Inscribed
                 p2 = PolarPoint(cp, th * ang, rad).TransformBy(Matrix3d.Identity);
                poly2.AddVertexAt(th, new Point2d(p2.X, p2.Y), 0, 0, 0);
            }
            poly.Closed = true;
            poly.ColorIndex = 1;
            poly2.Closed = true;
            poly2.ColorIndex = 3;
            // Add circle for imagination only
            Circle circ = new Circle(new Point3d(0, 0, 0), Vector3d.ZAxis, rad);
            circ.ColorIndex = 5;
            Transaction tr = doc.TransactionManager.StartTransaction();

            using (tr)
            {
                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(poly);
                tr.AddNewlyCreatedDBObject(poly, true);
                btr.AppendEntity(poly2);
                tr.AddNewlyCreatedDBObject(poly2, true);
                btr.AppendEntity(circ);
                tr.AddNewlyCreatedDBObject(circ, true);
                tr.Commit();
            }
        }
      VB.NET
Code: [Select]
        ' by Tony Tanzillo
        Public Shared Function PolarPoint(basepoint As Point3d, angle As Double, distance As Double) As Point3d
            Return New Point3d(basepoint.X + (distance * Math.Cos(angle)), basepoint.Y + (distance * Math.Sin(angle)), basepoint.Z)
        End Function

        <CommandMethod("preg", CommandFlags.UsePickSet)> _
        Public Sub testPolygonRegular()
            Dim doc As Document = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument
            Dim db As Database = doc.Database
            Dim ed As Editor = doc.Editor
            Dim pio As New PromptIntegerOptions("")
            pio.Message = vbLf & "Number of sides: "

            ' Restrict input to positive and non-negative values
            pio.AllowZero = False
            pio.AllowNegative = False
            ' Add default value
            pio.DefaultValue = 3
            pio.AllowNone = True
            ' Get the value entered by the user
            Dim ires As PromptIntegerResult = ed.GetInteger(pio)
            If ires.Status <> PromptStatus.OK Then
                Return
            End If
            Dim n As Integer = ires.Value

            Dim pdo As New PromptDoubleOptions(vbLf & "Enter radius: ")
            pdo.AllowZero = False
            pdo.AllowNegative = False
            pdo.AllowNone = True
            pdo.UseDefaultValue = True
            pdo.DefaultValue = 3.0

            Dim res As PromptDoubleResult
            res = ed.GetDouble(pdo)
            If res.Status <> PromptStatus.OK Then
                Return
            End If

            Dim rad As Double = res.Value

            Dim ang As Double = Math.PI * 2 / n
            Dim cp As Point3d, p1 As Point3d, p2 As Point3d
            ' Center point
            cp = New Point3d(0, 0, 0)

            Dim poly As New Polyline(n)
            Dim poly2 As New Polyline(n)
            For th As Integer = 0 To n - 1
                ' Circumscribed
                p1 = PolarPoint(cp, th * ang, rad / Math.Cos(ang / 2)).TransformBy(Matrix3d.Identity)
                poly.AddVertexAt(th, New Point2d(p1.X, p1.Y), 0, 0, 0)
                ' Inscribed
                p2 = PolarPoint(cp, th * ang, rad).TransformBy(Matrix3d.Identity)
                poly2.AddVertexAt(th, New Point2d(p2.X, p2.Y), 0, 0, 0)
            Next
            poly.Closed = True
            poly.ColorIndex = 1
            poly2.Closed = True
            poly2.ColorIndex = 3
            ' Add circle for imagination only
            Dim circ As New Circle(New Point3d(0, 0, 0), Vector3d.ZAxis, rad)
            circ.ColorIndex = 5
            Dim tr As Transaction = doc.TransactionManager.StartTransaction()

            Using tr
                Dim btr As BlockTableRecord = DirectCast(tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite), BlockTableRecord)
                btr.AppendEntity(poly)
                tr.AddNewlyCreatedDBObject(poly, True)
                btr.AppendEntity(poly2)
                tr.AddNewlyCreatedDBObject(poly2, True)
                btr.AppendEntity(circ)
                tr.AddNewlyCreatedDBObject(circ, True)
                tr.Commit()
            End Using
        End Sub
84
Math and Geometry / Draw bisector between 2 lines
« Last post by fixo on February 19, 2013, 08:02:37 PM »
Code: [Select]
        [CommandMethod("bis", CommandFlags.UsePickSet)]
        public static void drawBisector()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Database db = HostApplicationServices.WorkingDatabase;
            Editor ed = doc.Editor;
            PromptEntityOptions peo = new PromptEntityOptions("\nSelect first line: ");
            peo.SetRejectMessage("Wrong object or nothing selected.");
            peo.AddAllowedClass(typeof(Line), false);
            PromptEntityResult res;
            ObjectId objId1 = ObjectId.Null;
            ObjectId objId2 = ObjectId.Null;
            Entity ent;
            Point3d p1, p2;
            res = ed.GetEntity(peo);

            if (res.Status != PromptStatus.OK)
                return;;
            objId1 = res.ObjectId;
            p1 = res.PickedPoint;
            peo.Message="\nSelect second line: ";
            res = ed.GetEntity(peo);

            if (res.Status != PromptStatus.OK)
                return;
            objId2 = res.ObjectId;
            p2 = res.PickedPoint;

            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                ent = tr.GetObject(objId1, OpenMode.ForRead) as Entity;
                if (ent == null)   return;
                Line ln1 = ent as Line;
                if (ln1 == null) return;
                ent = tr.GetObject(objId2, OpenMode.ForRead) as Entity;
                if (ent == null) return;
                Line ln2 = ent as Line;
                if (ln2 == null) return;

                p1 = ln1.GetClosestPointTo(p1,false);
                p2 = ln2.GetClosestPointTo(p2, false);

                Point3d tmp,p1f, p2f, p1n, p2n;

                p1f = ln1.StartPoint;
                p2f = ln1.EndPoint;
                p1n = ln2.StartPoint;
                p2n = ln2.EndPoint;
                // swap poins for easier math
                if (p1f.DistanceTo(p1n) > p1f.DistanceTo(p2n))
                {
                    tmp = p2n;
                    p2n = p1n;
                    p1n=tmp;
                }
   
                Point3d mp1 = new Point3d((p1f.X + p1n.X) / 2, (p1f.Y + p1n.Y) / 2, (p1f.Z + p1n.Z) / 2);
                Point3d mp2 = new Point3d((p2f.X + p2n.X) / 2, (p2f.Y + p2n.Y) / 2, (p2f.Z + p2n.Z) / 2);
                Line bis = new Line(mp1, mp2);

                BlockTableRecord btr = (BlockTableRecord)tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite);
                btr.AppendEntity(bis);
                tr.AddNewlyCreatedDBObject(bis, true);
                tr.Commit();
            }
        }
85
Polylines / Write polyline points to CSV file
« Last post by fixo on February 19, 2013, 04:37:10 PM »
Code: [Select]
        [CommandMethod("PolylineToCSV", "plcsv",CommandFlags.Modal | CommandFlags.UsePickSet)]
        public static void ExportPolyPointsToCSV()
        {
            Document doc =Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            try
            {

                using (Transaction tr = db.TransactionManager.StartOpenCloseTransaction())
                {
                    string dec = ((short)Autodesk.AutoCAD.ApplicationServices.Application.GetSystemVariable("LUPREC")).ToString();

                    PromptSelectionOptions pso = new PromptSelectionOptions();

                    pso.MessageForRemoval = "\n >>  Nothing selected....";

                    pso.MessageForAdding = "\n  >>  Select a single polyline >> ";

                    pso.AllowDuplicates = false;

                    pso.SingleOnly = true;

                    SelectionFilter sf = new SelectionFilter
                        (new TypedValue[] { new TypedValue(0, "lwpolyline") });

                    PromptSelectionResult res = ed.GetSelection(pso, sf);

                    if (res.Status != PromptStatus.OK)  return;

                    StringBuilder sb = new StringBuilder();
                    ObjectId[] ids = res.Value.GetObjectIds();

                    Polyline poly = (Polyline)tr.GetObject(ids[0], OpenMode.ForRead, false);
                    for (int i = 0; i < poly.NumberOfVertices; i++)
                    {
                        Point2d pt = poly.GetPoint2dAt(i);
                        string vexstr = string.Format("{0:f" + dec + "};{1:f" + dec + "}", pt.X, pt.Y);
                        sb.AppendLine(vexstr);
                    }
                    String csvFile = String.Empty;

                    System.Windows.Forms.SaveFileDialog sfd =  new System.Windows.Forms.SaveFileDialog();
                    sfd.ValidateNames = true;
                    sfd.Title = "Save polyline vertices to CSV file";
                    sfd.DefaultExt = ".csv";
                    sfd.InitialDirectory=@"C:\Test\";
                    sfd.RestoreDirectory = true;
                   
                    if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK)  return;

                    csvFile = sfd.FileName;

                    // write point to defined file
                    using (StreamWriter sw = new StreamWriter(csvFile))
                    {
                        sw.Write(sb.ToString());

                        sw.Flush();
                    }
                    sfd.Dispose();// non resident object, so kill 'em

                    tr.Commit();
                }
           }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("\n" + ex.Message + "\n" + ex.Source + "\n" + ex.StackTrace);
            }
        }
86
3D entities / Create extruded cylinder
« Last post by fixo on February 19, 2013, 03:20:13 PM »
        [CommandMethod("testCylinder")]
        public void DrawExtrudedCylinder()
        {

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            Point3d cp;

            PromptPointOptions ptopts = new PromptPointOptions("\nSelect center point of circel: ");

            PromptPointResult ptres = ed.GetPoint(ptopts);

            // Exit if the user presses ESC or cancels the command
            if (ptres.Status != PromptStatus.OK) return;

            cp = ptres.Value;
            //base point
           
            PromptDistanceOptions pdo = new PromptDistanceOptions("\nEnter a radius: ");
            pdo.AllowNone = true;
            pdo.UseDefaultValue = true;
            pdo.DefaultValue = 100.0;
            pdo.BasePoint = cp;
            pdo.UseBasePoint = true;
            pdo.UseDashedLine = true;
           
            PromptDoubleResult res;
            res = ed.GetDistance(pdo);
            if (res.Status != PromptStatus.OK)
                return;

            double rad = res.Value;

            ed.WriteMessage("\nRadius Entered\t{0}", rad);
            pdo = new PromptDistanceOptions("\nEnter cylinder height: ");
            pdo.AllowNone = true;
            pdo.UseDefaultValue = true;
            pdo.DefaultValue = 1000.0;
            pdo.BasePoint = cp;
            pdo.UseBasePoint = true;
            pdo.UseDashedLine = true;

            res = ed.GetDistance(pdo);
            if (res.Status != PromptStatus.OK)
                return;

            double height = res.Value;
 
            using (Transaction tr = doc.TransactionManager.StartTransaction())
            {
                Circle circ = new Circle(cp, Vector3d.ZAxis, rad);
               

                BlockTableRecord btr = tr.GetObject(db.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                ObjectId objId = btr.AppendEntity(circ);

                tr.AddNewlyCreatedDBObject(circ, true);

                // Get the boundary curves to create a region
                DBObjectCollection regs = new DBObjectCollection();

                regs.Add(circ);

                // Create a region from the circle.

                DBObjectCollection regions = new DBObjectCollection();

                regions = Region.CreateFromCurves(regs);
               
                if (regions.Count == 0)
                {
                    ed.WriteMessage("\nFailed to create region\n");
                    return;
                }

                Region reg = (Region)regions[0];

                // Extrude the region to create a solid.

                Solid3d sol = new Solid3d();

                sol.RecordHistory = true;// important

                sol.ShowHistory = true;// important

                sol.Extrude(reg, height, 0.0);// < --- set taper angle here

                ObjectId solId = ObjectId.Null;

                solId = btr.AppendEntity(sol);

                tr.AddNewlyCreatedDBObject(sol, true);

                if (!circ.IsWriteEnabled) circ.UpgradeOpen();

                circ.Erase();

                tr.Commit();
            }

        }
87
This site / Re: Welcome on the AutoCAD .NET developer forums
« Last post by cnicho on February 19, 2013, 01:50:13 PM »
Hello All,
I'm still trying to get to grips with AutoCAD .Net development.
Learning C#, WPF, MVVM, AutoCAD 2013 .Net API
Regards
Craig
88
Dimensions / Display sum of selected dimensions
« Last post by fixo on February 15, 2013, 09:30:41 PM »
Code: [Select]
        [CommandMethod("DisplayDimSum", "dds", CommandFlags.Modal | CommandFlags.UsePickSet)]
        public void SumOfDims()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;
            Editor ed = doc.Editor;
            Database db = doc.Database;
            double sum = 0;
            TypedValue[] values = new TypedValue[] { new TypedValue(0, "DIMENSION") };
            SelectionFilter filter = new SelectionFilter(values);
            PromptSelectionOptions opts = new PromptSelectionOptions();

            opts.MessageForRemoval = "\nMust be a type of Dimension!";
            opts.MessageForAdding = "\nSelect dimensions to reset : ";
            opts.PrepareOptionalDetails = false;
            opts.SingleOnly = false;
            opts.SinglePickInSpace = false;
            opts.AllowDuplicates = true;
            PromptSelectionResult result = ed.GetSelection(opts, filter);
            if (result.Status != PromptStatus.OK) return;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    SelectionSet sset = result.Value;
                    foreach (SelectedObject selobj in sset)
                    {
                        DBObject obj = tr.GetObject(selobj.ObjectId, OpenMode.ForWrite, false) as DBObject;
                        Dimension dim = obj as Dimension;

                        if (dim != null)
                        {
                            sum += dim.Measurement;

                        }
                    }

                    tr.Commit();
                }
                Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog(string.Format("Sum of dimensions = {0:f3}", sum));
            }
            catch (System.Exception ex)
            {
                ed.WriteMessage("\nProblem with selection dimensions.\n");
                ed.WriteMessage(ex.Message);
            }
        }
89
Layers / Load base or custom linetypes
« Last post by fixo on February 14, 2013, 06:40:08 PM »
This code allow user to load both linetypes from "acad.lin" or "acadiso.lin" file
and from the custom linetype file,
see attachment, both C# and VB.NET code included
90
AutoCAD talk / Re: Autoload dll from a personal folder
« Last post by (gile) on February 13, 2013, 10:29:59 PM »
Hi,

As far as I know, you cannot use the autoloader from a different folder of those provided by Autodesk:
- %appdata%\Autodesk\ApplicationPlugins
- %programfiles%\Autodesk\ApplicationPlugins
- %programdata%\Autodesk\ApplicationPlugins

If you have rights to write in the registry, you can register your application:
http://through-the-interface.typepad.com/through_the_interface/2006/09/automatic_loadi.html
Pages: 1 ... 7 8 [9] 10