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

0 Members and 1 Guest are viewing this topic.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
.NET MISCELLANEOUS/GENERAL Routines
« on: January 27, 2010, 05:36:16 AM »
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.
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #1 on: January 27, 2010, 05:44:39 AM »
I am using some of the free time offered by this holiday season to finish a routine I had originally posted at AUGI.

It is an alternative to the venerable TxtExp command (Express Tools – Text – Explode Text).  The main difference in my routine is that the underlying geometry is spline based.   That offers performance benefits over the faceted polylines in a few areas; reduced file size, better appearance, more manageable downstream data manipulation, etc.

kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

Chuck Gabriel

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #2 on: January 27, 2010, 10:03:17 AM »
PurgeAll command:

Code: [Select]
using System;
using System.Text;
using System.Collections.Generic;

using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.ApplicationServices;

[assembly: ExtensionApplication(typeof(cgabriel.PurgeTools))]
[assembly: CommandClass(typeof(cgabriel.PurgeTools))]

namespace cgabriel
{
    public class PurgeTools : IExtensionApplication
    {

        public void Initialize() { }
        public void Terminate() { }

        public static bool purgeSymbolTables(Database db, ObjectIdCollection tableIds, bool silent)
        {
            bool itemsPurged = false;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            ObjectIdCollection purgeableIds = new ObjectIdCollection();
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                foreach (ObjectId tableId in tableIds)
                {
                    SymbolTable table = (SymbolTable)tr.GetObject(tableId, OpenMode.ForRead, false);
                    foreach (ObjectId recordId in table)
                        purgeableIds.Add(recordId);
                }

                db.Purge(purgeableIds);

                if (purgeableIds.Count == 0) return false;
                itemsPurged = true;

                foreach (ObjectId id in purgeableIds)
                {
                    try
                    {
                        SymbolTableRecord record = (SymbolTableRecord)tr.GetObject(id, OpenMode.ForWrite);
                        string recordName = record.Name;
                        record.Erase();
                        if (!silent)
                        {
                            if (!recordName.Contains("|"))
                            {
                                ed.WriteMessage("\nPurging " + record.GetType().Name + " " + recordName);
                            }
                        }
                    }
                    catch (Autodesk.AutoCAD.Runtime.Exception e)
                    {
                        if ((e.ErrorStatus == ErrorStatus.CannotBeErasedByCaller) || (e.ErrorStatus == (ErrorStatus)20072))
                            itemsPurged = false;
                        else
                            throw e;
                    }
                }
                tr.Commit();
            }

            return itemsPurged;
        }

        public static bool purgeDictionaries(Database db, ObjectIdCollection dictIds, bool silent)
        {
            bool itemsPurged = false;
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;

            ObjectIdCollection purgeableIds = new ObjectIdCollection();
            using ( Transaction tr = db.TransactionManager.StartTransaction() )
            {
                foreach (ObjectId dictId in dictIds)
                {
                    DBDictionary dict = (DBDictionary)tr.GetObject(dictId, OpenMode.ForRead, false);
                    foreach (DBDictionaryEntry entry in dict)
                    {
                        purgeableIds.Add(entry.m_value);
                    }
                }

                db.Purge(purgeableIds);

                if (purgeableIds.Count == 0) return false;
                itemsPurged = true;

                DBDictionary nod = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead);
                foreach (ObjectId id in purgeableIds)
                {
                    try
                    {
                        DBObject obj = (DBObject)tr.GetObject(id, OpenMode.ForWrite);
                        obj.Erase();
                        if (!silent)
                        {
                            foreach (ObjectId dictId in dictIds)
                            {
                                DBDictionary dict = (DBDictionary)tr.GetObject(dictId, OpenMode.ForRead, false);
                                string dictName = nod.NameAt(dictId);
                                if (dict.Contains(id))
                                {
                                    ed.WriteMessage("\nPurging " + dict.NameAt(id) + " from " + dictName);
                                    break;
                                }
                            }
                        }
                    }
                    catch(Autodesk.AutoCAD.Runtime.Exception e)
                    {
                        if ((e.ErrorStatus == ErrorStatus.CannotBeErasedByCaller) || (e.ErrorStatus == (ErrorStatus)20072))
                            itemsPurged = false;
                        else
                            throw e;
                    }
                }

                tr.Commit();
            }

            return itemsPurged;
        }

        public static void purgeAll(Database db, bool silent)
        {
            ObjectIdCollection tableIds = new ObjectIdCollection();
            tableIds.Add(db.BlockTableId);
            tableIds.Add(db.DimStyleTableId);
            tableIds.Add(db.LayerTableId);
            tableIds.Add(db.LinetypeTableId);
            tableIds.Add(db.RegAppTableId);
            tableIds.Add(db.TextStyleTableId);
            tableIds.Add(db.UcsTableId);
            tableIds.Add(db.ViewportTableId);
            tableIds.Add(db.ViewTableId);
            ObjectIdCollection dictIds = new ObjectIdCollection();
            dictIds.Add(db.MaterialDictionaryId);
            dictIds.Add(db.MLStyleDictionaryId);
            dictIds.Add(db.MLeaderStyleDictionaryId);
            dictIds.Add(db.PlotStyleNameDictionaryId);
            dictIds.Add(db.TableStyleDictionaryId);
            dictIds.Add(db.VisualStyleDictionaryId);
            while (purgeSymbolTables(db, tableIds, silent) || purgeDictionaries(db, dictIds, silent))
                continue;
            return;
        }

        [CommandMethod("PurgeTools", "PurgeAll", CommandFlags.Modal | CommandFlags.DocExclusiveLock)]
        public static void purgeAll()
        {
            purgeAll(Application.DocumentManager.MdiActiveDocument.Database, false);
        }
    }
}

Chuck Gabriel

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #3 on: January 27, 2010, 10:08:31 AM »
File dialogs for AutoLISP:

Code: [Select]
using System;
using System.IO;
using System.Text;

using Autodesk.AutoCAD.Windows;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.ApplicationServices;

using ofdFlags = Autodesk.AutoCAD.Windows.OpenFileDialog.OpenFileDialogFlags;
using sfdFlags = Autodesk.AutoCAD.Windows.SaveFileDialog.SaveFileDialogFlags;

namespace cgabriel
{
    public class LispFileDialogs
    {
        public static string title;
        public static string defaultFileName;
        public static string defaultExtension;
        public static short flags;

        [LispFunction("GetOpenFileDialog")]
        public static ResultBuffer GetOpenFileDialog(ResultBuffer args)
        {
            if (!parseArguments(args)) return null;

            ofdFlags dlgFlags = (ofdFlags)flags;
            if (((dlgFlags & ofdFlags.DefaultIsFolder) != 0) && Path.HasExtension(defaultFileName))
                defaultFileName = Path.GetDirectoryName(defaultFileName);

            OpenFileDialog dlg = new OpenFileDialog(title, defaultFileName, defaultExtension, title, dlgFlags);
            if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return null;

            ResultBuffer result = new ResultBuffer();
            foreach (string file in dlg.GetFilenames())
                result.Add(new TypedValue((int)LispDataType.Text, file));
            return result;
        }

        [LispFunction("GetSaveFileDialog")]
        public static TypedValue GetSaveFileDialog(ResultBuffer args)
        {
            if (!parseArguments(args))
                return new TypedValue((int)LispDataType.Nil, null);
         
            sfdFlags dlgFlags = (sfdFlags)flags;
            if (((dlgFlags & sfdFlags.DefaultIsFolder) != 0) && Path.HasExtension(defaultFileName))
                defaultFileName = Path.GetDirectoryName(defaultFileName);

            SaveFileDialog dlg = new SaveFileDialog(title, defaultFileName, defaultExtension, title, dlgFlags);
            if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return new TypedValue((int)LispDataType.Nil, null);

            return new TypedValue((int)LispDataType.Text, dlg.Filename);
        }

        public static bool parseArguments(ResultBuffer args)
        {
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            if (args == null)
                return notEnoughArguments(ed);

            ResultBufferEnumerator iter = args.GetEnumerator();

            iter.MoveNext();
            if (iter.Current.TypeCode != (short)LispDataType.Text)
                return wrongArguments(ed);
            title = (string)iter.Current.Value;

            if (iter.MoveNext() == false)
                return notEnoughArguments(ed);
            if (iter.Current.TypeCode != (short)LispDataType.Text)
                return wrongArguments(ed);
            defaultFileName = (string)iter.Current.Value;

            if (iter.MoveNext() == false)
                return notEnoughArguments(ed);
            if (iter.Current.TypeCode != (short)LispDataType.Text)
                return wrongArguments(ed);
            defaultExtension = (string)iter.Current.Value;

            if (iter.MoveNext() == false)
                return notEnoughArguments(ed);
            if (iter.Current.TypeCode != (short)LispDataType.Int16)
                return wrongArguments(ed);
            flags = (short)iter.Current.Value;

            return true;
        }

        public static bool notEnoughArguments(Editor ed)
        {
            ed.WriteMessage("\nToo few arguments.");
            return false;
        }

        public static bool wrongArguments(Editor ed)
        {
            ed.WriteMessage("\nExpected string string string int.");
            return false;
        }
    }
}

Chuck Gabriel

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #4 on: January 27, 2010, 03:55:36 PM »
Toggle visibility of analytical elements in Revit Structure:

Code: [Select]
using System;
using System.Reflection;

using Autodesk.Revit;
using Autodesk.Revit.Elements;

namespace ToggleAnalyticalVisibility
{

    public class Toggles : IExternalApplication
    {
        public IExternalApplication.Result OnShutdown(ControlledApplication application)
        {
            return IExternalApplication.Result.Succeeded;
        }

        public IExternalApplication.Result OnStartup(ControlledApplication application)
        {
            Assembly library = Assembly.GetExecutingAssembly();
            string libraryPath = library.Location;
            MenuItem menuItem = application.CreateTopMenu("Analytical Model");
            menuItem.Append(
                MenuItem.MenuType.BasicMenu,
                "Hide Analytical Model Graphics",
                libraryPath,
                "ToggleAnalyticalVisibility.ToggleOff");
            menuItem.Append(
                MenuItem.MenuType.BasicMenu,
                "Show Analytical Model Graphics",
                libraryPath,
                "ToggleAnalyticalVisibility.ToggleOn");
            return IExternalApplication.Result.Succeeded;
        }
    }

    public class ToggleOn : IExternalCommand
    {
        public IExternalCommand.Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            AnalyticalModelGraphics.setVisibility(commandData, true);
            return IExternalCommand.Result.Succeeded;
        }
    }

    public class ToggleOff : IExternalCommand
    {
        public IExternalCommand.Result Execute(
            ExternalCommandData commandData,
            ref string message,
            ElementSet elements)
        {
            AnalyticalModelGraphics.setVisibility(commandData, false);
            return IExternalCommand.Result.Succeeded;
        }
    }

    public class AnalyticalModelGraphics
    {
        public static void setVisibility(ExternalCommandData commandData, bool state)
        {
            Document doc = commandData.Application.ActiveDocument;
            View curView = doc.ActiveView;
            foreach (Category cat in doc.Settings.Categories)
            {
                if (cat.Name.ToLower().Contains("load"))
                {
                    curView.setVisibility(cat, state);
                }
                foreach (Category subCat in cat.SubCategories)
                {
                    if (subCat.Name.ToLower().Contains("analytical") ||
                        subCat.Name.ToLower().Contains("load"))
                    {
                        curView.setVisibility(subCat, state);
                    }
                }
            }

            // Believe it or not, the method used above is faster than that shown below in spite
            // of the fact that it iterates over every single category and subcategory.

            //Document doc = commandData.Application.ActiveDocument;
            //View curView = doc.ActiveView;
            //Settings settings = doc.Settings;
            //curView.setVisibility(
            //    settings.Categories.get_Item(BuiltInCategory.OST_AnalyticalRigidLinks),
            //    state);
            //curView.setVisibility(
            //    settings.Categories.get_Item(BuiltInCategory.OST_ColumnAnalyticalGeometry),
            //    state);
            //curView.setVisibility(
            //    settings.Categories.get_Item(BuiltInCategory.OST_ColumnAnalyticalRigidLinks),
            //    state);
            //curView.setVisibility(
            //    settings.Categories.get_Item(BuiltInCategory.OST_FloorsAnalyticalGeometry),
            //    state);
            //curView.setVisibility(
            //    settings.Categories.get_Item(BuiltInCategory.OST_FootingAnalyticalGeometry),
            //    state);
            //curView.setVisibility(
            //    settings.Categories.get_Item(BuiltInCategory.OST_FramingAnalyticalGeometry),
            //    state);
            //curView.setVisibility(
            //    settings.Categories.get_Item(BuiltInCategory.OST_WallsAnalyticalGeometry),
            //    state);

        }
    }
}

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #5 on: February 05, 2010, 11:51:29 AM »
Hi,

A custom osnaps example here.
Speaking English as a French Frog

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #6 on: February 13, 2010, 05:41:37 PM »
Quick way to parse text file
Code: [Select]
    Public Function ReadCSV(ByVal filename As String, ByVal sep As String) As List(Of String())
        Dim info As List(Of String()) = New List(Of String())
        Using pars As New FileIO.TextFieldParser(filename)
            pars.SetDelimiters(sep)
            While Not pars.EndOfData
                Dim line() As String
                line = pars.ReadFields()
                info.Add(line)
            End While
        End Using
        Return info
    End Function
~'J'~

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #7 on: February 19, 2010, 05:28:32 AM »
Fast way to read data from Excel

-Create Windows Application project
-Drop button1 and dataGridView1 on form
-Change full path of Excel file
Enjoy  :-)

Code: [Select]

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Data.OleDb;
using System.Reflection;
using System.Runtime.InteropServices;
using System.IO;
using System.Windows.Forms;

namespace ReadExcelJet
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public static void ReadXlWithJet(ref DataGridView dgv)
        {
            // create connection string
            // 'HDR=YES' it means that excel table has headers otherwise write 'HDR=NO'
            string strcon = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + @"c:\Points.xls;" + "Extended Properties=\"Excel 8.0;HDR=YES\"";
            // create connection
            OleDbConnection conn = new OleDbConnection(strcon);
            //create data adapter
            //[Sheet1$A1:C] it means the first 3 columns from Sheet1
            OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Sheet1$A1:C]", conn);
            //create new dataset
            DataSet ds = new DataSet();
            // fill dataset
            da.Fill(ds);
            //populate grid with data
            dgv.DataSource = ds.Tables[0];
            //close connection
            conn.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //clear datagridview
            dataGridView1.DataSource = null;
            dataGridView1.ColumnCount = 0;
            //populate datagridview
            ReadXlWithJet(ref dataGridView1);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            dataGridView1.AllowUserToAddRows = false;//<-- to do not draw empty row at the bottom of grid
            dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
            //adding some flowers in there
            dataGridView1.ForeColor = Color.Navy;
            dataGridView1.GridColor = Color.DarkGreen;
        }
    }
}

~'J'~

Kerry

  • Mesozoic relic
  • Seagull
  • Posts: 11654
  • class keyThumper<T>:ILazy<T>
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #8 on: February 19, 2010, 05:31:31 AM »

I don't think this will work in x64 bit

"Provider=Microsoft.Jet.OLEDB.4.0;"

Microsoft are not producing a 64 bit Jet driver ( by my understanding)

... but I;d like to be told I'm wrong.
kdub, kdub_nz in other timelines.
Perfection is not optional.
Everything will work just as you expect it to, unless your expectations are incorrect.
Discipline: None at all.

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #9 on: February 19, 2010, 06:11:55 AM »

I don't think this will work in x64 bit

"Provider=Microsoft.Jet.OLEDB.4.0;"

Microsoft are not producing a 64 bit Jet driver ( by my understanding)

... but I;d like to be told I'm wrong.

Still working in A2008

~'J'~

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #10 on: February 19, 2010, 06:54:50 AM »
Read / Write Excel examples
(it is necessary to change the file name in the code)

===  VB.NET  ===

Code: [Select]
Imports System.Runtime.InteropServices
Imports System.Globalization
Imports System.Threading
Imports Microsoft.Office.Interop.Excel
Imports Excel = Microsoft.Office.Interop.Excel
'' References -> COM -> Microsoft.Excel XX.0 Object Library
'' Create form and drop Button1 and ListView1 on form

Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        '' This line is very important!
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US") '<-- change culture on

whatever you need
        Dim miss As Object = System.Reflection.Missing.Value
        Dim i As Integer
        Dim j As Integer
        '' Open Excel
        Dim m_objExcel As Excel.Application = New Excel.Application
        m_objExcel.Visible = True
        Dim m_objBooks As Workbooks = m_objExcel.Workbooks
        Try
            '' Open workbook
            m_objBooks.Open("C:\Points.xls", False, False, miss, "", False, miss, Excel.XlPlatform.xlWindows, miss, True,

miss, miss, miss, False)

            Dim m_objBook As Workbook = m_objBooks.Item(1)
            m_objBook.Activate() 'optional
            Dim m_objSheets As Sheets = m_objBook.Sheets
            Dim m_objSheet As Worksheet = m_objSheets.Item(2) '<--"Sheet2"
            m_objSheet.Cells.ClearContents() 'optional
            Dim m_objCells As Range = m_objSheet.Cells

            '' write data starting from cell "A1"
            Dim m_objRange As Range = Nothing
            For i = 1 To 101
                For j = 1 To 3
                    m_objRange = m_objSheet.Range(m_objCells(i, j), m_objCells(i, j))
                    m_objRange.Value = Rnd(5).ToString
                Next
            Next

            '' fill the listview with data
            ListView1.Clear()
            Dim columns() As String = New String() {"X coordinate", "Y coordinate", "Z coordinate"}

            For Each column As String In columns
                ListView1.Columns.Add(column, 96, HorizontalAlignment.Left)
            Next

            ListView1.View = View.Details
            ListView1.GridLines = True
            ListView1.FullRowSelect = True

            For row As Integer = 1 To i - 1

                Dim lvi As New ListViewItem(m_objSheet.Range(m_objCells(row, 1), m_objCells(row, 1)).Value.ToString, 0)
                For col As Integer = 2 To j - 1
                    lvi.SubItems.Add(m_objSheet.Range(m_objCells(row, col), m_objCells(row, col)).Value.ToString)
                Next
                Me.ListView1.Items.Add(lvi)
            Next

            '' Save the file in the typical workbook format
            m_objBook.SaveAs("C:\Points.xls", Excel.XlFileFormat.xlWorkbookNormal, "", "", False, False,

XlSaveAsAccessMode.xlNoChange, miss, miss, miss, miss, miss)
            '' close workbook and quit Excel
            m_objBook.Close(False, miss, miss)
            m_objExcel.Quit()
        Catch ex As System.Exception
            MessageBox.Show(ex.StackTrace)
        Finally
            '' release process if it's still active
            System.Runtime.InteropServices.Marshal.FinalReleaseComObject(m_objExcel)
        End Try
    End Sub

End Class

===  C#  ===

Code: [Select]
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Runtime.InteropServices;
using System.Globalization;
using System.Threading;
using Microsoft.Office.Interop.Excel;
using Excel = Microsoft.Office.Interop.Excel;

//' References -> COM -> Microsoft.Excel XX.0 Object Library
//' Create form and drop Button1 and ListView1 on it
namespace ExcelForumCS
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            //' This line is very important!
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-US");  //<-- change culture on

whatever you need
            object miss = System.Reflection.Missing.Value;
            int i = 0;
            int j = 0;
            //' Open Excel
            Excel.Application m_objExcel = new Excel.Application();
            m_objExcel.Visible = true;
            Workbooks m_objBooks = m_objExcel.Workbooks;
            try
            {
                //' Open workbook

                m_objBooks.Open("C:\\Points.xls", false, false, miss, "", miss, miss, miss, miss, true, miss, miss, miss, miss,

miss);

                Workbook m_objBook = m_objBooks.get_Item(1);
                //m_objBook.Activate();//optional
                Sheets m_objSheets = m_objBook.Sheets;
                Worksheet m_objSheet = (Worksheet)m_objSheets.get_Item(1); //<--"Sheet1"
                m_objSheet.Cells.ClearContents();
                //optional
                Range m_objCells = m_objSheet.Cells;

                //' write data starting from cell "A1"
                Range m_objRange = null;
                Random rand = new Random();
                for (i = 1; i <= 25; i++)//25 - number of rows
                {
                    for (j = 1; j <= 3; j++)//3 - number of point ordinates
                    {
                        m_objRange = m_objSheet.get_Range(m_objCells[i, j], m_objCells[i, j]);
                        m_objRange.set_Value(miss, (i * 0.12345 * rand.Next(1,10)).ToString());//<--set dummy value
                    }
                }

                //' fill the listview with data
                ListView1.Clear();
                string[] columns = new string[] { "X coordinate", "Y coordinate", "Z coordinate" };

                foreach (string column in columns)
                {
                    ListView1.Columns.Add(column, 96, HorizontalAlignment.Left);
                }

                ListView1.View = View.Details;
                ListView1.GridLines = true;
                ListView1.FullRowSelect = true;

                for (int row = 1; row <= i - 1; row++)
                {

                    ListViewItem lvi = new ListViewItem(m_objSheet.get_Range(m_objCells[row, 1], m_objCells[row,

1]).Value2.ToString(), 0);
                    for (int col = 2; col <= j - 1; col++)
                    {

                        lvi.SubItems.Add(m_objSheet.get_Range(m_objCells[row, 1], m_objCells[row, 1]).Value2.ToString());
                    }
                    this.ListView1.Items.Add(lvi);
                }

                //' Save the file in the typical workbook format
                m_objBook.SaveAs("C:\\Points.xls", Excel.XlFileFormat.xlWorkbookNormal, "", "", false, false,

XlSaveAsAccessMode.xlNoChange, miss, miss, miss,
                miss, miss);
                //' close workbook and quit Excel
                m_objBook.Close(false, miss, miss);
                m_objExcel.Quit();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.StackTrace);
            }
            finally
            {
                //' release process if it's still active
                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(m_objExcel);
            }
        }
}
    }

~'J'~


fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #11 on: February 25, 2010, 02:38:29 AM »
Working with OpenOffice Calc document

Code: [Select]

using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using System.Text.RegularExpressions;
//require references to all "cli_*.dll's files from:
//C:/Program Files/OpenOffice 3.0/openofficeorg1.cab/
// set Copy Local = false
//set Specific Version = false
using unoidl.com.sun.star.system;
using unoidl.com.sun.star.lang;
using unoidl.com.sun.star.uno;
using unoidl.com.sun.star.bridge;
using unoidl.com.sun.star.frame;
using unoidl.com.sun.star.text;
using unoidl.com.sun.star.beans;
using unoidl.com.sun.star.sheet;
using unoidl.com.sun.star.container;
using unoidl.com.sun.star.table;


//See original article from there:
//http://c-programming.suite101.com/article.cfm/creating_an_openoffice_calc_document_with_c
namespace OOfficeExm
{
    public class OOfficeTools
    {
        /// <summary>
        ///                 * Write data into the existing Calc document *
        /// </summary>
        public static void WriteToExistingCalc()
        {
            //file name is with back slashes in the OOffice format only:
            string fileName = @"file:///C:/test.ods";
            //The first step is to use
            //the bootstrap method to start OpenOffice.org (or to access any existing instances):
            XComponentContext oStrap = uno.util.Bootstrap.bootstrap();
            //The next step is to use OpenOffice.org's service manager to create a desktop:
            XMultiServiceFactory oServMan = (XMultiServiceFactory)oStrap.getServiceManager();
            XComponentLoader oDesk = (XComponentLoader)oServMan.createInstance("com.sun.star.frame.Desktop");

            PropertyValue[] propVals = new PropertyValue[0];
            //And then an existing Calc document is added to the desktop:
            XComponent oDoc = oDesk.loadComponentFromURL(fileName, "_private:stream", 0, propVals);//OK
            XSpreadsheets oSheets = ((XSpreadsheetDocument)oDoc).getSheets();
            XIndexAccess oSheetsIA = (XIndexAccess)oSheets;
            XSpreadsheet oSheet = (XSpreadsheet)oSheetsIA.getByIndex(0).Value;
            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 100; j++)
                {
                    XCell oCell = oSheet.getCellByPosition(i, j);
//add dummy values
                    //((XText)oCell).setString(((i+1) * (j+1)).ToString());//set strings
                    oCell.setValue((i + 1) * (j + 1));//or set doubles
                }
            }
            ((XStorable)oDoc).storeAsURL(fileName, propVals);//save document

            oDoc.dispose();
            oDoc = null;

        }


        /// <summary>
        ///                 * Read data from existing Calc document *
        /// </summary>
        public static void ReadExistingCalcRange()
        {
            //file name is with back slashes in the OOffice format only:
            string fileName = @"file:///C:/test.ods";
            string target = "A1:D999";
            //The first step is to use
            //the bootstrap method to start OpenOffice.org (or to access any existing instances):
            XComponentContext oStrap = uno.util.Bootstrap.bootstrap();
            //The next step is to use OpenOffice.org's service manager to create a desktop:
            XMultiServiceFactory oServMan = (XMultiServiceFactory)oStrap.getServiceManager();
            //Create loader component
            XComponentLoader oDesk = (XComponentLoader)oServMan.createInstance("com.sun.star.frame.Desktop");

            PropertyValue[] propVals = new PropertyValue[0];
            //And then an existing Calc document is added to the desktop:
            XComponent xDoc = oDesk.loadComponentFromURL(fileName, "_private:stream", 0, propVals);
            // Then use the service manager for current document
            XMultiServiceFactory xDocFactory = (XMultiServiceFactory)xDoc;
            // Get document sheets
            XSpreadsheets oSheets = ((XSpreadsheetDocument)xDoc).getSheets();
            // Create indexer
            XIndexAccess oSheetsIA = (XIndexAccess)oSheets;
            // Get first sheet
            XSpreadsheet oSheet = (XSpreadsheet)oSheetsIA.getByIndex(0).Value;
            // Get desired range
            XCellRange oRange = (XCellRange)oSheet.getCellRangeByName(target);
            // After this line there are few ways for the iteration through cells
            // see help docs here:
            //http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/
            //I'm pretty sure there is an easier way to loop through cells
            //but here is my way to retrive rows and columns from address of range:
            int[] columns = GetColumnsFromString(target);
            int[] rows = GetRowsFromString(target);
            // (row and column indexes are starting from zero)
            int startcol = columns[0] - 1;
            int endcol = columns[1] - 1;
            int startrow = rows[0] - 1;
            int endrow = rows[1] - 1;
            ArrayList arr = new ArrayList();
            for (int r = startrow; r <= endrow; r++)
            {
                string[] line = new string[endcol - startcol + 1];
                for (int c = startcol; c <= endcol; c++)
                {
                    XCell oCell = (XCell)oRange.getCellByPosition(c, r);
                    line[c] = oCell.getFormula();
                }
                arr.Add(line);

            }
            xDoc.dispose();
            xDoc = null;
            // Display data
            foreach (string[] s in arr)
                Console.WriteLine("{0} | {1} | {2} | {3} |", s[0], s[1], s[2], s[3]);
            Console.Read();
        }
        /// <summary>
        ///     *   Get first and last column from range address *
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static int[] GetColumnsFromString(string address)
        {
            int[] columns = new int[2];
            string sep = ":";
            string[] target = address.Split(sep.ToCharArray());
            string head = target[0];
            string tail = target[1];
            columns[0] = Col_AToI(CutNumeric(head));
            columns[1] = Col_AToI(CutNumeric(tail));
            return columns;
        }
        /// <summary>
        ///      *   Get first and last row from range address *
        /// </summary>
        /// <param name="address"></param>
        /// <returns></returns>
        public static int[] GetRowsFromString(string address)
        {
            int[] rows = new int[2];
            string sep = ":";
            string[] target = address.Split(sep.ToCharArray());
            string head = target[0];
            string tail = target[1];
            rows[0] = int.Parse(CutAlpha(head));
            rows[1] = int.Parse(CutAlpha(tail));
            return rows;
        }

        public static string CutNumeric(string str)
        {
            try
            {
                string pattern = @"[0-9]";
                Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
                str = reg.Replace(str, "");
                return str;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
        public static string CutAlpha(string str)
        {
            try
            {
                string pattern = @"[aA-zZ]";
                Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
                str = reg.Replace(str, "");
                return str;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        ///           * Change column letter(s) to integer *
        /// </summary>
        /// from http://www.codekeep.net/snippets/63b58dcb-ab47-4a75-8016-e771fad706c6.aspx
        /// <param name="strColumn"></param>
        /// <returns></returns>
        public static int Col_AToI(string strColumn)
        {
            strColumn = strColumn.ToUpper();

            if (strColumn.Length == 1)
            {
                return Convert.ToByte(Convert.ToChar(strColumn)) - 64;
            }
            else if (strColumn.Length == 2)
            {
                return
                    ((Convert.ToByte(strColumn[0]) - 64) * 26) +
                    (Convert.ToByte(strColumn[1]) - 64);

            }
            else if (strColumn.Length == 3)
            {
                return
                    ((Convert.ToByte(strColumn[0]) - 64) * 26 * 26) +
                    ((Convert.ToByte(strColumn[1]) - 64) * 26) +
                    (Convert.ToByte(strColumn[2]) - 64);
            }
            else
            {
                throw new ApplicationException("Column Length must be between 1 and 3.");
            }
        }
    }
}

gile

  • Gator
  • Posts: 2507
  • Marseille, France
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #12 on: March 06, 2010, 11:31:30 AM »
Getting or Setting Xrecord to a dictionary (or extension dictionary)

Code: [Select]
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Runtime;
using acadApp = Autodesk.AutoCAD.ApplicationServices.Application;

namespace Dictionaries
{
    public class DictSample
    {
        // SetXrecord (overloaded)
        public void SetXrecord(Entity ent, string key, ResultBuffer resbuf)
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                ent.UpgradeOpen();
                ent.CreateExtensionDictionary();
                DBDictionary xDict = (DBDictionary)tr.GetObject(ent.ExtensionDictionary, OpenMode.ForWrite);
                Xrecord xRec = new Xrecord();
                xRec.Data = resbuf;
                xDict.SetAt(key, xRec);
                tr.AddNewlyCreatedDBObject(xRec, true);
                tr.Commit();
            }
        }

        public void SetXrecord(DBDictionary dict, string key, ResultBuffer resbuf)
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                dict.UpgradeOpen();
                Xrecord xRec = new Xrecord();
                xRec.Data = resbuf;
                dict.SetAt(key, xRec);
                tr.AddNewlyCreatedDBObject(xRec, true);
                tr.Commit();
            }
        }

        public void SetXrecord(string dictName, string key, ResultBuffer resbuf)
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                DBDictionary NOD = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForWrite);
                DBDictionary dict;
                try
                {
                    dict = tr.GetObject(NOD.GetAt(dictName), OpenMode.ForWrite) as DBDictionary;
                }
                catch
                {
                    dict = new DBDictionary();
                    NOD.SetAt(dictName, dict);
                    tr.AddNewlyCreatedDBObject(dict, true);
                    dict.UpgradeOpen();
                }
                Xrecord xRec = new Xrecord();
                xRec.Data = resbuf;
                dict.SetAt(key, xRec);
                tr.AddNewlyCreatedDBObject(xRec, true);
                tr.Commit();
            }
        }

        public void SetXrecord(ObjectId id, string key, ResultBuffer resbuf)
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                Entity ent = tr.GetObject(id, OpenMode.ForRead) as Entity;
                if (ent != null)
                {
                    ent.UpgradeOpen();
                    ent.CreateExtensionDictionary();
                    DBDictionary xDict = (DBDictionary)tr.GetObject(ent.ExtensionDictionary, OpenMode.ForWrite);
                    Xrecord xRec = new Xrecord();
                    xRec.Data = resbuf;
                    xDict.SetAt(key, xRec);
                    tr.AddNewlyCreatedDBObject(xRec, true);
                }
                else
                {
                    DBDictionary dict = tr.GetObject(id, OpenMode.ForRead) as DBDictionary;
                    if (dict != null)
                    {
                        dict.UpgradeOpen();
                        Xrecord xRec = new Xrecord();
                        xRec.Data = resbuf;
                        dict.SetAt(key, xRec);
                        tr.AddNewlyCreatedDBObject(xRec, true);
                    }
                }
                tr.Commit();
            }
        }

        // GetXrecord (overloaded)
        public ResultBuffer GetXrecord(Entity ent, string key)
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    DBDictionary xDict =
                        (DBDictionary)tr.GetObject(ent.ExtensionDictionary, OpenMode.ForRead, false);
                    Xrecord xRec = (Xrecord)tr.GetObject(xDict.GetAt(key), OpenMode.ForRead, false);
                    return xRec.Data;
                }
                catch
                {
                    return null;
                }
            }
        }

        public ResultBuffer GetXrecord(DBDictionary dict, string key)
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    Xrecord xRec = (Xrecord)tr.GetObject(dict.GetAt(key), OpenMode.ForRead, false);
                    return xRec.Data;
                }
                catch
                {
                    return null;
                }
            }
        }

        public ResultBuffer GetXrecord(string dictName, string key)
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
            {
                try
                {
                    DBDictionary NOD = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead);
                    DBDictionary dict = (DBDictionary)tr.GetObject(NOD.GetAt(dictName), OpenMode.ForRead, false);
                    Xrecord xRec = (Xrecord)tr.GetObject(dict.GetAt(key), OpenMode.ForRead, false);
                    return xRec.Data;
                }
                catch
                {
                    return null;
                }
            }
        }

        public ResultBuffer GetXrecord(ObjectId id, string key)
        {
            Document doc = acadApp.DocumentManager.MdiActiveDocument;
            Database db = doc.Database;
            using (Transaction tr = db.TransactionManager.StartTransaction())
             {
                Xrecord xRec = new Xrecord();
                Entity ent = tr.GetObject(id, OpenMode.ForRead, false) as Entity;
                if (ent != null)
                {
                    try
                    {
                        DBDictionary xDict = (DBDictionary)tr.GetObject(ent.ExtensionDictionary, OpenMode.ForRead, false);
                        xRec = (Xrecord)tr.GetObject(xDict.GetAt(key), OpenMode.ForRead, false);
                        return xRec.Data;
                    }
                    catch
                    {
                        return null;
                    }
                }
                else
                {
                    DBDictionary dict = tr.GetObject(id, OpenMode.ForRead, false) as DBDictionary;
                    if (dict != null)
                    {
                        try
                        {
                            xRec = (Xrecord)tr.GetObject(dict.GetAt(key), OpenMode.ForRead, false);
                            return xRec.Data;
                        }
                        catch
                        {
                            return null;
                        }
                    }
                    else
                        return null;
                }
            }
        }
    }
}
Speaking English as a French Frog

fixo

  • Guest
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #13 on: March 11, 2010, 03:19:14 AM »
Automation Word using late-binding and interaction with AutoCAD
Oops...
I have removed my message by reason of bad code block
Try substituted code instead  :oops:

Create project 'WordReflection'
Drop on form 'Form1' DataGridView named 'dataGridView1'
Drop on form two buttons named 'button1' and 'button2'
Add text for button1 - "Select Circles"
Add text for button2 - "Export DataGridView To Word Document"
Unzip files from an attached archive and add to the project
Change file name and text for footer inside the code block for 'button2'
Compile project
Draw a several circles then run program

Hope that would helps to somebody from our community

~'J'~

Ken Alexander

  • Newt
  • Posts: 61
Re: .NET MISCELLANEOUS/GENERAL Routines
« Reply #14 on: March 11, 2010, 11:43:20 AM »
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

Ken Alexander