Author Topic: .NET MISCELLANEOUS/GENERAL Routines  (Read 51480 times)

0 Members and 1 Guest are viewing this topic.

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #15 on: March 11, 2010, 12:10:51 PM »
Read / Write Excel examples
(it is necessary to change the file name in the code)

===  VB.NET  ===

When working with a large amount of data, you might use Range.Value; much, much quicker.

Code: [Select]
Dim objCells As Range = objSheet.Range(objSheet.Cells(1, 1), objSheet.Cells(101, 3))
Dim Values(101, 3) As String

For i = 0 To 100
     For j = 0 To 2
          Values(i, j) = Rnd(5).ToString
     Next
Next

'add the entire array at once.
objCells.Value = Values


Feel free to upload your own example here

~'J'~

Ken Alexander

  • Newt
  • Posts: 61
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #16 on: March 11, 2010, 03:30:57 PM »
Quote

Feel free to upload your own example here

~'J'~


Code: [Select]
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim objExcel As Excel.Application = Nothing
        Dim objBooks As Workbooks = Nothing
        Dim objBook As Workbook = Nothing
        Dim objSheets As Sheets = Nothing
        Dim objSheet As Worksheet = Nothing
        Dim objCells As Range = Nothing
        Dim LstColumns() As String = Nothing

        Dim NumberOfRows As Integer = 100
        Dim NumberOfColumns As Integer = 3

        Dim PopulateValues(NumberOfRows, NumberOfColumns) As String
        Dim ReadValues(NumberOfRows, NumberOfColumns) As Object

        Try
            objExcel = New Excel.Application
            objExcel.Visible = True
            objBooks = objExcel.Workbooks
            objBook = objBooks.Add()
            objBook.Activate()
            objSheets = objBook.Sheets
            objSheet = objSheets.Item(1)
            objSheet.Cells.ClearContents()
            objCells = objSheet.Range(objSheet.Cells(1, 1), objSheet.Cells(NumberOfRows, NumberOfColumns))

            For iRow = 0 To NumberOfRows - 1
                For iColumn = 0 To NumberOfColumns - 1
                    PopulateValues(iRow, iColumn) = "Row:" & (iRow + 1).ToString & " Column:" & (iColumn + 1).ToString
                Next
            Next

            'populate entire array (very fast)
            objCells.Value = PopulateValues
            objCells.Columns.AutoFit()
            objBook.SaveAs("C:\SampleReadWriteData.xls", Excel.XlFileFormat.xlWorkbookNormal)
            objBook.Close()


            objBook = objBooks.Open("C:\SampleReadWriteData.xls")
            objBook.Activate()
            objSheets = objBook.Sheets
            objSheet = objSheets.Item(1)
            objCells = objSheet.Range(objSheet.Cells(1, 1), objSheet.Cells(NumberOfRows, NumberOfColumns))

            'populate entire array (very fast)
            ReadValues = objCells.Value

            Me.ListView1.Clear()
            Me.ListView1.View = View.Details
            Me.ListView1.GridLines = True
            Me.ListView1.FullRowSelect = True

            LstColumns = New String() {"X coordinate", "Y coordinate", "Z coordinate"}
            For Each ColHeaderText As String In LstColumns
                Me.ListView1.Columns.Add(ColHeaderText, 96, HorizontalAlignment.Left)
            Next

            For iRow As Integer = 1 To NumberOfRows
                Dim lvi As New ListViewItem(ReadValues(iRow, 1).ToString, 0)
                For iColumn As Integer = 2 To NumberOfColumns
                    lvi.SubItems.Add(ReadValues(iRow, iColumn).ToString)
                Next
                Me.ListView1.Items.Add(lvi)
            Next

            Me.ListView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent)

            objBook.Close()
            objExcel.Quit()
        Catch ex As Exception
            MessageBox.Show(ex.StackTrace)
        Finally
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(objExcel)
        End Try
    End Sub
Ken Alexander

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #17 on: March 12, 2010, 12:02:42 PM »
Thanks,

Keep  sharing :)

Regards,

~'J'~

HasanCAD

  • Swamp Rat
  • Posts: 1420
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #18 on: March 17, 2010, 09:03:43 AM »
Hi all

Its first time I visit .NET
The question is
How to load this code?

Regards

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #19 on: March 18, 2010, 09:02:21 AM »
Hi all

Its first time I visit .NET
The question is
How to load this code?

Regards


See post#1:

LIBRARY THREAD for  AutoCAD MISCELLANEOUS/GENERAL
 Members are encouraged to post any functions, methods, snips regarding
AutoCAD MISCELLANEOUS/GENERAL in .NET : C# ,  VB , F# , Python , etc

Feel free to include comments, descriptive notes, limitations,  and images to document your post.

Please post questions in a regular thread. :x

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #20 on: March 18, 2010, 09:26:39 AM »
Quick way to create HTML report
Code: [Select]

Create Class library project  BlockReport
Add 2 classes: Report.cs and SelectBlocks.cs

//
// code for Report.cs
//

using System;
using System.Collections.Generic;
using System.Text;
using Autodesk.AutoCAD.Runtime;
using System.Diagnostics;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.ComponentModel;

[assembly: CommandClass(typeof(BlockReport.Report))]

namespace BlockReport
{
    public class Report
    {
        System.Data.DataTable tbl;
        string tblname = "BLOCK INFO";
        string filename = @"C:\BLOCKS.html";//<--change path for outputfile here



        [CommandMethod("REPORT")]
        public void Doit()
        {
            tbl = SelectBlocks.BlockInfoToTable();

            DataView dv = tbl.DefaultView;

            dv.Sort = "Name ASC";

            tbl = dv.ToTable();

            BuildHTMLDoc(tbl, tblname, filename);
            Process.Start(filename);
        }

        public void BuildHTMLDoc(System.Data.DataTable dtb, string tblname, string filename)
        {
            string bdcol = "#91b6dd";
            string fcol1 = "#33066";
            string fcol2 = "#3300CC";
            string bcol1 = "#e8e8e8";
            string bcol2 = "#c8c8c8";
            string fcolor = "";
            string bcolor = "";

            //possible HTML colors (a bit of):
            //6799ff royal blue
            //d7b941 dirty yellow
            //3366cc blue
            //ededed light gray 25
            //e0e0e0 light gray 50
            //ff0000 red
            //666699 violet
            //cc3333 indian red
            //3c5b00 green
            //73ad00 light green
            //d0d5c6 light khaki
            //91b6dd light steel blue

            try
            {
                DateTime dt = DateTime.Now;
                string dat = dt.ToString("d");
                string textHTML =
                    SetDocumentStart("Simple Report Example") +
                    SetBodyStart(bdcol) +
                    SetParagraphStartLeft(dat, fcol1) +
                    SetCaption(dat, fcol1) +
                    SetTitle("2", "Report Title") +
                    SetTitle("3", tblname) +
                    SetParagraphStart() +
                    SetTableStart("50");//<--table width in percents
                StringBuilder sb = new StringBuilder();
                sb.Append(textHTML);
                textHTML = SetRowStart(bcolor);
                sb.Append(textHTML);
                int cnt = 0;

                for (int j = 0; j < dtb.Columns.Count; j++)
                {

                    textHTML = SetCellStart(dtb.Columns[j].ColumnName, "blue");
                    sb.Append(textHTML);
                    textHTML = SetCellEnd();
                    sb.Append(textHTML);
                    cnt += 1;
                }
                textHTML = SetRowEnd();
                sb.Append(textHTML);
                cnt = 0;

                for (int i = 0; i < dtb.Rows.Count; i++)
                {

                    if (i % 2 == 0)
                    {
                        bcolor = bcol1;
                        fcolor = fcol1;
                    }
                    else
                    {
                        bcolor = bcol2;
                        fcolor = fcol2;
                    }
                    textHTML = SetRowStart(bcolor);
                    sb.Append(textHTML);
                    DataRow dr = dtb.Rows[i];
                    object[] line = dr.ItemArray;

                    for (int j = 0; j < dtb.Columns.Count; j++)
                    {
                        string celltext = "";
                        object cellvalue = line[j];

                        if (cellvalue == null)
                        {
                            celltext = "--";
                        }
                        else
                        {
                            celltext = cellvalue.ToString();
                        }


                        textHTML = SetCellStart(celltext, fcolor);
                        sb.Append(textHTML);
                        textHTML = SetCellEnd();
                        sb.Append(textHTML);
                        cnt += 1;
                    }
                    textHTML = SetRowEnd();
                    sb.Append(textHTML);
                }
               
                textHTML = SetRowStart(bcol1);
                sb.Append(textHTML);
                for (int j = 0; j < dtb.Columns.Count - 2; j++)
                {
                    string celltext = "";
                    textHTML = SetCellStart(celltext, fcolor);
                    sb.Append(textHTML);
                    textHTML = SetCellEnd();
                    sb.Append(textHTML);
                    cnt += 1;
                }
               
                textHTML = SetCellStart("Blocks Count: ", fcolor);
                sb.Append(textHTML);
                textHTML = SetCellEnd();
                sb.Append(textHTML);

                System.Data.DataColumn count =
                    new System.Data.DataColumn("Count",
                    System.Type.GetType("System.Int16"));
                count.Expression = "COUNT(Name)";
                dtb.Columns.Add(count);


                string num = dtb.Rows[0].ItemArray[dtb.Columns.Count-1].ToString();

                textHTML = SetCellStart(num, fcolor);
                sb.Append(textHTML);
                textHTML = SetCellEnd();
                sb.Append(textHTML);
                textHTML = SetRowEnd();
                sb.Append(textHTML);
                //
                textHTML = SetTableEnd();
                sb.Append(textHTML);
                textHTML = SetParagraphEnd();
                sb.Append(textHTML);
                textHTML = SetBodyEnd();
                sb.Append(textHTML);
                textHTML = SetDocumentEnd();
                sb.Append(textHTML);
                using (StreamWriter sw = new StreamWriter(filename))
                {
                    sw.Write(sb.ToString());
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
            }

        }
        private string SetDocumentStart(string head)
        {
            return "<html><head><title><" + head + ">" + "</title></head>";
        }
        private string SetDocumentEnd()
        {
            return "</html>";
        }
        private string SetBodyStart(string color)
        {
            return "<body><body bgcolor =" + "" + color + "" + " " + Environment.NewLine;
        }
        private string SetBodyEnd()
        {
            return "</body bgcolor></body>" + Environment.NewLine;
        }
        private string SetTitle(string size, string value)
        {
            return "<h" + size + "><p align=center>" + value + "</p align></h" + size + ">";
        }
        private string SetParagraphIndent(string value, string color)
        {
            return "<p><blockquote><font color=" + "" + color + "" + " " + value + "</font><blockquote></p>";
        }
        private string SetParagraphStart()
        {
            return "<p><p align=center>";
        }
        private string SetParagraphStartLeft(string value, string color)
        {
            return "<p><p align=left><font color=" + "" + color + "" + " " + value + "</font></p>";
        }
        private string SetParagraphEnd()
        {
            return "<p><p align=center>" + Environment.NewLine;
        }
        private string SetTableStart(string width)
        {
            return "<table width=" + "" + width + "%%" + "" + "><t align=center>";
        }
        private string SetTableEnd()
        {
            return "<t align></table>" + Environment.NewLine;
        }
        private string SetRowStart(string color)
        {
            return "<tr><tr align=center><tr bgcolor=" + "" + color + "" + ">";
        }
        private string SetRowEnd()
        {
            return "</tr align></tr>" + Environment.NewLine;
        }
        private string SetCellStart(string value, string color)
        {
            string cell = "<td><td align=center><font color=" + "" + color + "" + ">" + value + "</font></td align></td>";
            return cell;
        }
        private string SetCellEnd()
        {
            return "</td align></td>" + Environment.NewLine;
        }

        private string SetCaption(string caption, string color)
        {
            return "<caption><font color=" + "" + color + "" + ">" + "<b>" + caption + "</b></font></caption>";
        }

    }
}



//
// code for SelectBlocks.cs
//
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using System.Threading;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.GraphicsInterface;
using Autodesk.AutoCAD.DatabaseServices;
using AcDb = Autodesk.AutoCAD.DatabaseServices;
using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;
using Autodesk.AutoCAD.ApplicationServices;
using System.Windows.Forms;

[assembly: CommandClass(typeof(BlockReport.SelectBlocks))]

namespace BlockReport
{
    public class SelectBlocks
    {

        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        static public System.Data.DataTable BlockInfoToTable()
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            try
            {

                Document doc = acadApp.DocumentManager.MdiActiveDocument;
                Database db = HostApplicationServices.WorkingDatabase;
                Editor ed = doc.Editor;
                Transaction tr = db.TransactionManager.StartTransaction();
                using (tr)
                {
                    /*blocks just with attributes
//                    TypedValue[] tvs = new TypedValue[]
//{ new TypedValue((int)DxfCode.Start, "INSERT"),
//       new TypedValue((int)DxfCode.HasSubentities, 1)
//                    };*/
                    TypedValue[] tvs = new TypedValue[]
{ new TypedValue((int)DxfCode.Start, "INSERT")};

                    SelectionFilter sf = new SelectionFilter(tvs);

                    PromptSelectionResult psr = ed.SelectAll(sf);

                    SelectionSet sset = psr.Value;

                    MessageBox.Show(sset.Count.ToString());

                    dt.Columns.AddRange(new System.Data.DataColumn[]{
            new System.Data.DataColumn("Name",System.Type.GetType("System.String")),
new System.Data.DataColumn("ObjectID",System.Type.GetType("System.String")),
             new System.Data.DataColumn("X_Coordinate",System.Type.GetType("System.Double")),
              new System.Data.DataColumn("Y_Coordinate",System.Type.GetType("System.Double")),
               new System.Data.DataColumn("Z_Coordinate",System.Type.GetType("System.Double")),
                new System.Data.DataColumn("Rotation",System.Type.GetType("System.Double")),
               });

                    foreach (SelectedObject sobj in sset)
                    {
                        DBObject dbobj = tr.GetObject(sobj.ObjectId, OpenMode.ForRead);
                        BlockReference bref = dbobj as BlockReference;


                        object[] param = new object[6];
                        if (bref != null)
                        {                           
                            param[0] = EffectiveName(bref);
                            param[1] = sobj.ObjectId;
                            param[2] = Math.Round(bref.Position.X, 3);
                            param[3] = Math.Round(bref.Position.Y, 3);
                            param[4] = Math.Round(bref.Position.Z, 3);
                            param[5] = Math.Round(RadianToDegree(bref.Rotation), 3);

                            DataRow dr = dt.NewRow();
                            dr.ItemArray = param;
                            dt.Rows.Add(dr);
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.StackTrace);
            }
            return dt;

        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="blkref"></param>
        /// <returns></returns>
        static public string EffectiveName(BlockReference blkref)
        {
            if (blkref.IsDynamicBlock)
            {
                using (BlockTableRecord obj = (BlockTableRecord)
                blkref.DynamicBlockTableRecord.GetObject(OpenMode.ForRead))
                    return obj.Name;
            }
            return blkref.Name;
        }
        /// <summary>
        ///
        /// </summary>
        /// <param name="angle"></param>
        /// <returns></returns>
        public static double RadianToDegree(double angle)
        {
            return angle * (180.0 / Math.PI);
        }

    }
}




~'J'~

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #21 on: March 21, 2010, 08:43:27 AM »
Export Excel sheet into the Acad table
Tested on Excel2007 only

~'J'~
« Last Edit: March 21, 2010, 12:31:35 PM by fixo »

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #22 on: March 28, 2010, 06:12:07 AM »
Editing the alpha-numeric text(s) / mtext(s)

~'J'~

Oops, wrong thread
Moved in there:

http://www.theswamp.org/index.php?topic=31860.0
« Last Edit: March 28, 2010, 06:16:03 AM by fixo »

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #23 on: June 06, 2010, 06:56:13 PM »
A little Matrix class for general matrix calculus (not exclusively 2d or 3d transformation matrices).
I's quite small but maybe will grow...

Code: [Select]
using System;

namespace MatrixSample
{
    public class Matrix
    {
        // fields
        private int m_numRows;
        private int m_numColumns;
        private double[,] m_matArray;

        // Constructors
        public Matrix(double[,] matArray)
        {
            m_matArray = matArray;
            m_numRows = matArray.GetLength(0);
            m_numColumns = matArray.GetLength(1);
        }

        public Matrix(int numRows, int numColumns)
        {
            m_numRows = numRows;
            m_numColumns = numColumns;
            m_matArray = new double[numRows, numColumns];
        }

        // Indexor
        public double this[int i, int j]
        {
            get { return m_matArray[i, j]; }
            set { m_matArray[i, j] = value; }
        }

        // Properties
        public bool IsSquare
        {
            get { return m_numColumns == m_numRows; }
        }

        public int NumColumns
        {
            get { return m_numColumns; }
        }

        public int NumRows
        {
            get { return m_numRows; }
        }

        // Static method
        public static Matrix Identity(int dim)
        {
            Matrix result = new Matrix(dim, dim);
            for (int i = 0; i < dim; i++)
            {
                double[] row = new double[dim];
                for (int j = 0; j < dim; j++)
                {
                    row[j] = i == j ? 1.0 : 0.0;
                }
                result.SetRowAt(i, row);
            }
            return result;
        }

        // Instance methods
        public Matrix GaussJordan(Matrix mat)
        {
            if (!this.IsSquare)
                throw new MatrixException("First matrix is not square");
            mat = this.Merge(mat);
            int numRows = mat.NumRows;
            int numColumns = mat.NumColumns;
            for (int rowIndex = 0; rowIndex < numRows; rowIndex++)
            {
                double pivot = 0.0;
                int pivotRowIndex = mat.GetPivotRow(rowIndex, ref pivot);
                if (pivot == 0.0)
                    return null;
                double[] pivotRow;
                mat.PermuteAt(pivotRowIndex, rowIndex, out pivotRow);
                pivotRow = Array.ConvertAll<double, double>(pivotRow, x => x / pivot);
                mat.SetRowAt(rowIndex, pivotRow);
                for (int i = 0; i < numRows; i++)
                {
                    if (i == rowIndex)
                        continue;
                    double first = mat[i, 0];
                    for (int j = 0; j < numColumns; j++)
                    {
                        mat[i, j] -= first * pivotRow[j];
                    }
                }
                mat = mat.RemoveFirstColumn();
                numColumns--;
            }
            return mat;
        }

        private Matrix RemoveFirstColumn()
        {
            Matrix result = new Matrix(this.m_numRows, this.m_numColumns - 1);
            for (int i = 0; i < this.m_numRows; i++)
            {
                for (int j = 0; j < this.m_numColumns - 1; j++)
                {
                    result[i, j] = this[i, j + 1];
                }
            }
            return result;
        }

        private void PermuteAt(int pivotRowIndex, int rowIndex, out double[] pivotRow)
        {
            pivotRow = this.GetRowAt(pivotRowIndex);
            for (int i = pivotRowIndex; i > rowIndex; i--)
            {
                this.SetRowAt(i, this.GetRowAt(i - 1));
            }
            this.SetRowAt(rowIndex, pivotRow);
        }

        private int GetPivotRow(int index, ref double pivot)
        {
            int result = 0;
            for (int i = index; i < this.NumRows; i++)
            {
                double p = (this.GetRowAt(i))[0];
                if (Math.Abs(p) > Math.Abs(pivot))
                {
                    pivot = p;
                    result = i;
                }
            }
            return result;
        }

        public Matrix Merge(Matrix mat)
        {
            if (this.NumRows != mat.NumRows)
                throw new MatrixException("Different number of rows");
            Matrix result = new Matrix(this.NumRows, this.NumColumns + mat.NumColumns);
            for (int i = 0; i < this.NumRows; i++)
            {
                double[] row = new double[this.NumColumns + mat.NumColumns]; ;
                this.GetRowAt(i).CopyTo(row, 0);
                mat.GetRowAt(i).CopyTo(row, this.NumColumns);
                result.SetRowAt(i, row);
            }
            return result;
        }

        public Matrix Inverse()
        {
            if (!this.IsSquare)
                throw new MatrixException("First matrix is not square");
            return this.GaussJordan(Identity(this.NumRows));
        }

        public double[] GetColumnAt(int index)
        {
            if (index >= m_numColumns)
                throw new IndexOutOfRangeException();
            double[] result = new double[m_numRows];
            for (int i = 0; i < m_numRows; i++)
            {
                result[i] = m_matArray[i, index];
            }
            return result;
        }

        public double[] GetRowAt(int index)
        {
            if (index >= m_numRows)
                throw new IndexOutOfRangeException();
            double[] result = new double[m_numColumns];
            for (int i = 0; i < m_numColumns; i++)
            {
                result[i] = m_matArray[index, i];
            }
            return result;
        }

        public void SetColumnAt(int index, double[] column)
        {
            if (index >= m_numColumns)
                throw new IndexOutOfRangeException();
            if (column.Length != m_numRows)
                throw new MatrixException("Array length is not valid");
            double[] result = new double[m_numRows];
            for (int i = 0; i < m_numRows; i++)
            {
                m_matArray[index, i] = column[i];
            }
        }

        public void SetRowAt(int index, double[] row)
        {
            if (index >= m_numRows)
                throw new IndexOutOfRangeException();
            if (row.Length != m_numColumns)
                throw new MatrixException("Array length is not valid");
            double[] result = new double[m_numColumns];
            for (int i = 0; i < m_numColumns; i++)
            {
                m_matArray[index, i] = row[i];
            }
        }

        public Matrix Transpose()
        {
            Matrix result = new Matrix(m_numColumns, m_numRows);
            for (int i = 0; i < m_numColumns; i++)
            {
                result.SetRowAt(i, this.GetColumnAt(i));
            }
            return result;
        }
    }

    class MatrixException : Exception
    {
        public MatrixException(string msg)
            : base(msg)
        {
        }
    }
}

Speaking English as a French Frog

jgr

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #24 on: August 20, 2010, 11:46:12 AM »
Reading a CTB file

CTB file it is a file that contains compressed text with zlib
www.zlib.net

File format:

First 52 bytes = header (not compressed, like PIAFILEVERSION_2.0,CTBVER1,compress)
next 4 bytes (UInteger) = decompressed stream size
next 4 bytes (UInteger) = compressed stream size
after this = compressed data

The code in CTBReader.rar (vb.net) is commented, but in spanish (sorry i do not speack english)

The example uses (C# code included) a managed version of zlib , free and open Source:
http://www.componentace.com/zlib_.NET.htm

I do not understand all the uncompressed data, such as color, but ....
« Last Edit: August 20, 2010, 11:54:41 AM by jgr »

Jeff H

  • Needs a day job
  • Posts: 6144
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #25 on: August 23, 2010, 07:14:27 AM »
**************************EDIT****************************************
Need to wrap side database in a using statement also
**************************EDIT****************************************

Here are 4 methods Basiclly are set up for having external drawings storing info and grabbing it.
The first two are plotsettings "PageSetup"  one is for filling a combobox or you get a list plotsettings and the second wblockclones it from the closed drawing by the name of the first functions

The second two are same but for textstyles and this just adds the text styles. Let me know if you have a problem with texthieght of your styles there is a issue but can be eaisly worked around and width factor does not persist and also eaisly be fixed. I am not talking about the code posted There is a issuse with the API that will use the Database TextSize instead

I have other routines but these were the first I saw going through a file, also if you would C# it would give me some practice
Also obviously this code is set up more for use from pallette whatever so you will probably need do handle document Locking

Code: [Select]
Public Function GetPlotSettinsList(ByVal PlotSettingsFile As String) As List(Of String)
            Dim PlotSettinsList As New List(Of String)
            Dim CurrentDatabase As Database = HostApplicationServices.WorkingDatabase
            Dim SourceDatabase As New Database(False, True)
            SourceDatabase.ReadDwgFile(PlotSettingsFile, FileOpenMode.OpenForReadAndAllShare, True, "")
            Using currentTransaction As Transaction = CurrentDatabase.TransactionManager.StartTransaction
                Using sourceTransaction As Transaction = SourceDatabase.TransactionManager.StartTransaction
                    Dim sourcePlotDic As DBDictionary = SourceDatabase.PlotSettingsDictionaryId.GetObject(OpenMode.ForRead)
                    For Each dit As DictionaryEntry In sourcePlotDic
                        PlotSettinsList.Add(dit.Key.ToString)
                    Next
                    currentTransaction.Commit()
                End Using
            End Using
            Return PlotSettinsList
        End Function

        Public Sub AddPlotSettings(ByVal PlotSettingsFile As String, ByVal PlotSettingsName As String)
            Dim CurrentDatabase As Database = HostApplicationServices.WorkingDatabase
            Dim SourceDatabase As New Database(False, True)
            SourceDatabase.ReadDwgFile(PlotSettingsFile, FileOpenMode.OpenForReadAndAllShare, True, "")
            Using currentTransaction As Transaction = CurrentDatabase.TransactionManager.StartTransaction
                Using sourceTransaction As Transaction = SourceDatabase.TransactionManager.StartTransaction
                    Dim sourcePlotDic As DBDictionary = SourceDatabase.PlotSettingsDictionaryId.GetObject(OpenMode.ForRead)
                    If sourcePlotDic.Contains(PlotSettingsName) Then
                        Dim objID As ObjectId = sourcePlotDic.GetAt(PlotSettingsName)
                        Dim pl As PlotSettings = objID.GetObject(OpenMode.ForRead)
                        Dim cpl As New PlotSettings(False)
                        cpl.CopyFrom(pl)
                        cpl.AddToPlotSettingsDictionary(CurrentDatabase)
                        Dim bt As BlockTable = CurrentDatabase.BlockTableId.GetObject(OpenMode.ForRead)
                        Dim btr As BlockTableRecord = bt(BlockTableRecord.PaperSpace).GetObject(OpenMode.ForRead)
                        Dim lytobjID As ObjectId = btr.LayoutId.GetObject(OpenMode.ForRead).ObjectId
                        Dim lytps As PlotSettings = lytobjID.GetObject(OpenMode.ForWrite)
                        lytps.CopyFrom(cpl)
                    End If
                    currentTransaction.Commit()
                End Using
            End Using
        End Sub


        Public Function GetTextStyleList(ByVal TextStyleFile As String) As List(Of String)
            Dim textStyleList As New List(Of String)
            Dim CurrentDatabase As Database = HostApplicationServices.WorkingDatabase
            Dim SourceDatabase As New Database(False, True)
            SourceDatabase.ReadDwgFile(TextStyleFile, FileOpenMode.OpenForReadAndAllShare, True, "")
            Using currentTransaction As Transaction = CurrentDatabase.TransactionManager.StartTransaction
                Using sourceTransaction As Transaction = SourceDatabase.TransactionManager.StartTransaction
                    Dim sourceTextStyleTbl As TextStyleTable = SourceDatabase.TextStyleTableId.GetObject(OpenMode.ForRead)
                    For Each sourceTextStyleTblRecID As ObjectId In sourceTextStyleTbl
                        Dim sourceTextStyleTblRec As TextStyleTableRecord = sourceTextStyleTblRecID.GetObject(OpenMode.ForRead)
                        textStyleList.Add(sourceTextStyleTblRec.Name)
                    Next
                    currentTransaction.Commit()
                End Using
            End Using
            Return textStyleList
        End Function

        Public Function AddTextStyle(ByVal textStyleFile As String, ByVal textStyleName As String) As ObjectId
            Dim CurrentDatabase As Database = HostApplicationServices.WorkingDatabase
            Dim SourceDatabase As New Database(False, True)
            SourceDatabase.ReadDwgFile(textStyleFile, FileOpenMode.OpenForReadAndAllShare, True, "")
            Using currentTransaction As Transaction = CurrentDatabase.TransactionManager.StartTransaction
                Using sourceTransaction As Transaction = SourceDatabase.TransactionManager.StartTransaction
                    Dim CurrentTextStyleTbl As TextStyleTable = CurrentDatabase.TextStyleTableId.GetObject(OpenMode.ForWrite)
                    Dim sourceTextStyleTbl As TextStyleTable = SourceDatabase.TextStyleTableId.GetObject(OpenMode.ForRead)
                    If Not sourceTextStyleTbl.Has(textStyleName) Then Return Nothing
                    Dim sourceTextStyleTblRec As TextStyleTableRecord = sourceTextStyleTbl(textStyleName).GetObject(OpenMode.ForRead)
                    Dim map As New DatabaseServices.IdMapping
                    Dim sourceObj As New DatabaseServices.ObjectIdCollection
                    sourceObj.Add(sourceTextStyleTblRec.ObjectId)
                    CurrentDatabase.WblockCloneObjects(sourceObj, CurrentTextStyleTbl.ObjectId, map, DuplicateRecordCloning.Replace, False)
                    currentTransaction.Commit()
                    Return map(sourceTextStyleTblRec.ObjectId).Value
                End Using
            End Using
        End Function
« Last Edit: March 17, 2014, 10:45:11 AM by Jeff H »

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #26 on: October 16, 2010, 04:35:09 PM »
= Create MlineStyle =
Code: [Select]
        public static void AddCustomMLStyle()
        {
            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Database db = doc.Database;

            Editor ed = doc.Editor;

            try
            {
                using (Transaction tr = db.TransactionManager.StartTransaction())
                {
                    //
                    DBDictionary dm = (DBDictionary)tr.GetObject(db.MLStyleDictionaryId, OpenMode.ForRead, false);

                    bool exists = false;

                    foreach (DBDictionaryEntry de in dm)
                    {
                        if (de.Key.Equals("myStyle", StringComparison.InvariantCulture))//<-- change on appropriate name here
                            exists = true;
                        break;
                    }

                    ObjectId msid = ObjectId.Null;
                    if (!exists)
                    {
                        LinetypeTable ltt = (LinetypeTable)tr.GetObject(db.LinetypeTableId, OpenMode.ForRead);
                        if (!ltt.Has("HIDDEN"))
                        {
                            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("Add code to load linetype \"HIDDEN\"");
                            return;
                        }

                        ObjectId lnid = ltt["HIDDEN"];

                        MlineStyle ms = new MlineStyle();

                        ms.Name = "myStyle";//<-- change on appropriate name here

                        ms.Description = "MLStyle for Beams etc.";//<-- change the description here (optional)

                        ms.EndSquareCap = true;

                        ms.StartSquareCap = true;

                        ms.StartInnerArcs = false;

                        ms.StartRoundCap = false;

                        ms.EndInnerArcs = false;

                        ms.EndRoundCap = false;

                        ms.ShowMiters = false;

                        ms.StartAngle = Math.PI / 2;

                        ms.EndAngle = Math.PI / 2;

                        MlineStyleElement me =
                            new MlineStyleElement(
                                0.0, Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByAci, 160), ltt["Continuous"]);
                        //add elements as many as you need here
                        ms.Elements.Add(me, true);

                        me = new MlineStyleElement(
                            0.1, Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByAci, 7), lnid);

                        ms.Elements.Add(me, true);

                        me = new MlineStyleElement(
                            1.0, Autodesk.AutoCAD.Colors.Color.FromColorIndex(Autodesk.AutoCAD.Colors.ColorMethod.ByAci, 160), ltt["Continuous"]);

                        ms.Elements.Add(me, true);

                        dm.UpgradeOpen();

                        msid = dm.SetAt("myStyle", ms);

                        tr.AddNewlyCreatedDBObject(ms, true);

                        dm.DowngradeOpen();
                     
                        tr.Commit();
                    }

                }
            }
            catch (Autodesk.AutoCAD.Runtime.Exception ex)
            {
                ed.WriteMessage("{0}\n{1}", ex.Message, ex.StackTrace);

            }
            finally
            {

            }
        }

~'J'~

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #27 on: December 07, 2010, 03:11:40 PM »
Hi,

ZoomObjects (F#)

Code: [Select]
module ZoomObjects

open Autodesk.AutoCAD.ApplicationServices
open Autodesk.AutoCAD.DatabaseServices
open Autodesk.AutoCAD.EditorInput
open Autodesk.AutoCAD.Geometry
open Autodesk.AutoCAD.Runtime

let zoomObjects (ids : ObjectId[]) =
    let doc = Application.DocumentManager.MdiActiveDocument
    let db = doc.Database
    let ed = doc.Editor
    use tr = db.TransactionManager.StartTransaction()
    use view = ed.GetCurrentView()
   
    let getEnt id = tr.GetObject(id, OpenMode.ForRead) :?> Entity
   
    let addExts (ext : Extents3d) id =
        ext.AddExtents((getEnt id).GeometricExtents)
        ext
       
    let ext = ids |> Array.fold addExts (getEnt ids.[0]).GeometricExtents
    let WCS2DCS =  Matrix3d
                    .PlaneToWorld(view.ViewDirection)
                    .PreMultiplyBy(Matrix3d.Displacement(view.Target - Point3d.Origin))
                    .PreMultiplyBy(Matrix3d.Rotation(-view.ViewTwist, view.ViewDirection, view.Target))
                    .Inverse()
    ext.TransformBy(WCS2DCS)
    view.Width <- ext.MaxPoint.X - ext.MinPoint.X
    view.Height <- ext.MaxPoint.Y - ext.MinPoint.Y
    view.CenterPoint <- new Point2d((ext.MaxPoint.X + ext.MinPoint.X) / 2.0, (ext.MaxPoint.Y + ext.MinPoint.Y) / 2.0)
    ed.SetCurrentView(view)
    tr.Commit();

[<CommandMethod("ZO")>]
let zo() =
    let ed = Application.DocumentManager.MdiActiveDocument.Editor
    let psr = ed.GetSelection()
    if psr.Status = PromptStatus.OK then
        psr.Value.GetObjectIds() |> zoomObjects
Speaking English as a French Frog

huiz

  • Swamp Rat
  • Posts: 913
  • Certified Prof C3D
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #28 on: July 12, 2011, 08:34:33 AM »
This function checks if a command is available but does not seperate lisp commands or arx commands. Just check if the command exists.

Code: [Select]
  Shared Function IsCommandAvailable(ByVal sCmdName As String) As Boolean
    If Not Autodesk.AutoCAD.Internal.Utils.IsCommandNameInUse(sCmdName) = Autodesk.AutoCAD.Internal.CommandTypeFlags.NoneCmd Then
      Return True
    Else
      Return False
    End If
  End Function
The conclusion is justified that the initialization of the development of critical subsystem optimizes the probability of success to the development of the technical behavior over a given period.

Jeff H

  • Needs a day job
  • Posts: 6144
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #29 on: September 21, 2011, 04:25:46 PM »
Coded this up quickly and was useful for having to reverse some splines because the lintype was a custom linetype with text and the text was upside down
 
Code: [Select]
        [CommandMethod("HpadRevereseSpline")]
        public void HpadRevereseSpline()
        {
       
            using (Transaction trx = db.TransactionManager.StartTransaction())
            {
                PromptEntityOptions peo = new PromptEntityOptions("\nSelect Spline: ");
                peo.SetRejectMessage("\n That was not a Spline");
                peo.AddAllowedClass(typeof(Spline), true);
                PromptEntityResult per = ed.GetEntity(peo);

                if (per.Status != PromptStatus.OK)
                {
                    return;
                }

                Spline spline = (Spline)trx.GetObject(per.ObjectId, OpenMode.ForRead);

                NurbsData nurbData = spline.NurbsData;
                Point3dCollection points = nurbData.GetControlPoints();

                int totalPoints = spline.NumControlPoints;
                int newPointIndex = totalPoints - 1;

                spline.UpgradeOpen();

                for (int i = 0; i < totalPoints; i++)
                {
                    spline.SetControlPointAt(i, points[(totalPoints - 1) - i]);
                }

                trx.Commit();

            }

        }