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.
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);
}
}
}
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;
}
}
}
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);
}
}
}
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'~
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;
}
}
}
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.
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
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);
}
}
}
}
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.");
}
}
}
}
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;
}
}
}
}
}
Read / Write Excel examples
(it is necessary to change the file name in the code)
=== VB.NET ===
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
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'~
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
Hi all
Its first time I visit .NET
The question is
How to load this code?
Regards
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);
}
}
}
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)
{
}
}
}
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
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
{
}
}
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
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
[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();
}
}
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace ControlLibrary
{
/// <summary>
/// Defines a control that can be used to display or edit an integer.
/// </summary>
public class IntegerBox : TextBox
{
private ErrorProvider _errorProvider;
private int _value;
/// <summary>
/// Set default values.
/// </summary>
public IntegerBox()
{
_errorProvider = new ErrorProvider();
ErrorMsg = "Incorrect number";
Minimum = -2147483648;
Maximum = 2147483647;
_value = 0;
}
/// <summary>
/// Get or set the error provider message.
/// </summary>
public string ErrorMsg { get; set; }
/// <summary>
/// Get or set the minimum allowed value.
/// </summary>
public int Minimum { get; set; }
/// <summary>
/// Get or set the maximum allowed value.
/// </summary>
public int Maximum { get; set; }
/// <summary>
/// Get or set the value as integer.
/// </summary>
public int Value
{
get { return _value; }
set
{
_value = value;
this.Text = _value.ToString();
this.OnValidating(new CancelEventArgs());
}
}
/// <summary>
/// Evaluates if the value is a valid integer according to MinValue and MaxValue.
/// If not, cancels the validation and displayd an error provider.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnValidating(System.ComponentModel.CancelEventArgs e)
{
base.OnValidating(e);
int i;
if (!int.TryParse(this.Text, out i) || i < Minimum || i > Maximum)
{
e.Cancel = true;
this.Select(0, this.Text.Length);
_errorProvider.SetError(this, ErrorMsg);
}
}
/// <summary>
/// Updates Value.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnValidated(EventArgs e)
{
base.OnValidated(e);
_value = Convert.ToInt32(this.Text);
}
/// <summary>
/// Hide the error provider.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnTextChanged(EventArgs e)
{
base.OnTextChanged(e);
_errorProvider.SetError(this, "");
}
}
}
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace ControlLibrary
{
/// <summary>
/// Defines a control that can be used to display or edit a real number (double).
/// </summary>
public class NumericBox : TextBox
{
private double _value;
private ErrorProvider _errorProvider;
private int _decimalPlaces;
protected string _stringFormat;
/// <summary>
/// Set default values.
/// </summary>
public NumericBox()
{
_value = 0;
_errorProvider = new ErrorProvider();
ErrorMsg = "Incorrect number";
SetFormat();
}
/// <summary>
/// Get or set the number of digits diplayed in the box.
/// </summary>
public int DecimalPlaces
{
get { return _decimalPlaces; }
set { _decimalPlaces = value; SetFormat(); }
}
/// <summary>
/// Get or set the ErrorProvider message.
/// </summary>
public string ErrorMsg { get; set; }
/// <summary>
/// Get or set the number value as double (may be more accurate than the displayed one).
/// Updates the Text according to DecimalPlaces.
/// </summary>
public virtual double Value
{
get { return _value; }
set { _value = value; this.Text = _value.ToString(_stringFormat); }
}
/// <summary>
/// Evaluates if the value is a valid real number.
/// If not, cancels the validation and displayd the ErrorProvider icon.
/// </summary>
/// <param name="e">The event data</param>
protected override void OnValidating(CancelEventArgs e)
{
double d;
if (!double.TryParse(this.Text, out d))
{
e.Cancel = true;
this.Select(0, this.Text.Length);
_errorProvider.SetError(this, ErrorMsg);
}
base.OnValidating(e);
}
/// <summary>
/// Updates Text and Value.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnValidated(EventArgs e)
{
_value = Convert.ToDouble(this.Text);
this.Text = _value.ToString(_stringFormat);
base.OnValidated(e);
}
/// <summary>
/// Hide the ErrorProvider icon.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnTextChanged(EventArgs e)
{
_errorProvider.SetError(this, "");
base.OnTextChanged(e);
}
/// <summary>
/// Creates a format string according to DecimalPlaces value.
/// Updates the Format property.
/// </summary>
private void SetFormat()
{
if (DecimalPlaces < 1)
_stringFormat = "0";
else
{
_stringFormat = "0.";
for (int i = 0; i < DecimalPlaces; i++) _stringFormat += "0";
}
}
}
}
using System;
namespace ControlLibrary
{
/// <summary>
/// Defines a control that can be used to display or edit an angular value (double).
/// </summary>
public class AngleBox : NumericBox
{
private double _value;
/// <summary>
/// Angular units enumeration.
/// </summary>
public enum Unit
{
Degree,
Grade,
Radian
}
/// <summary>
/// Define the default angular unit.
/// </summary>
public AngleBox()
{
this.UnitFormat = Unit.Degree;
}
/// <summary>
/// Get or set the angular format (unit).
/// </summary>
public Unit UnitFormat { get; set; }
/// <summary>
/// Get or set the angle value in radians.
/// Updates the Text property according to UnitFormat and DecimalPlaces.
/// </summary>
public override double Value
{
get { return _value; }
set { _value = value; this.Text = AngleToString(_value); }
}
/// <summary>
/// Updates Text and Value properties.
/// </summary>
/// <param name="e">The event data.</param>
protected override void OnValidated(EventArgs e)
{
_value = StringToAngle(this.Text);
this.Text = AngleToString(_value);
base.OnValidated(e);
}
/// <summary>
/// Converts a string into an angle value in radians.
/// </summary>
/// <param name="txt">The angle expressed according to UnitFormat.</param>
/// <returns>The angle value in radians.</returns>
private double StringToAngle(string txt)
{
switch (UnitFormat)
{
case Unit.Degree:
return Convert.ToDouble(txt) * Math.PI / 180.0;
case Unit.Grade:
return Convert.ToDouble(txt) * Math.PI / 200.0;
default: //Radian
return Convert.ToDouble(txt);
}
}
/// <summary>
/// Converts an angle value in radians into a string.
/// </summary>
/// <param name="val">The angle value in radians..</param>
/// <returns>The angle expressed according to UnitFormat</returns>
private string AngleToString(double val)
{
switch (UnitFormat)
{
case Unit.Degree:
return (val * 180.0 / Math.PI).ToString(_stringFormat);
case Unit.Grade:
return (val * 200.0 / Math.PI).ToString(_stringFormat);
default: // Radian
return val.ToString(_stringFormat);
}
}
}
}
The routines work very very fast !
Hi Gile,Many thanks for reporting Keith.
In some of your methods in the Registry Classes I had to change your OpenSubKey calls to open with ReadWrite status. For instance in the AddPath method of the ProfileKey class I changedCode - C#: [Select]
using (var rkey= Registry.CurrentUser.OpenSubKey(key))
toCode - C#: [Select]
using (var rkey= Registry.CurrentUser.OpenSubKey(key, true))
I had to do this in several places where the value of the key was being modified. Not sure if that was because of my permissions or something else. I think that you are also missing the servicePack private string variable in the ProductKey class. Other than that it worked great for me when installing a dll.
Nice idea kaefer (as usual).
If I have some time, I'd add some WriteRange() method to the ExcelWriter class.
class Program
{
static void Main(string[] args)
{
using (ExcelWriter xlw = new ExcelWriter(@"C:\Users\Riccardo\Documents\Cartel2.xlsx"))
{
xlw.Clear();
xlw.WriteLine(new object[3] { "foo", "bar", "baz" }, 3, 2); //<------ modified by RICVBA to have a usedrange not beginning at cells(1,1)
xlw.WriteLine(new object[3] { 1, 2, 3 }, 4, 3); //<------ modified by RICVBA to have a usedrange not beginning at cells(1,1)
xlw.Save();
}
using (ExcelReader xlr = new ExcelReader(@"C:\Users\Riccardo\Documents\Cartel2.xlsx"))
{
while (!xlr.StreamEnded)
{
foreach (object obj in xlr.ReadLine())
{
Console.Write("{0} ", obj);
}
Console.WriteLine();
}
//------------------------------------------
//added by RICVBA to test some methods after ExcelReader class modifications
wl(xlr.ReadToEnd()); // should work as it was
wl(xlr.ReadRange(2, 1)); // modified
//------------------------------------------
}
Console.ReadLine();
}
//------------------------------------------
//added by RICVBA
static void wl(object[,] range)
{
for (int i = 0; i < range.GetLength(0); i++)
{
for (int j = 0; j < range.GetLength(1); j++)
{
Console.Write("{0} ", range[i, j]);
}
Console.WriteLine();
}
}
//------------------------------------------
Hi,
Some extension methods to perform different kinds of zoom.
public void PurgeFiles()
{
Document doc = Application.DocumentManager.MdiActiveDocument;
Editor ed = doc.Editor;
List<ProcessReport> ListOfCleanFiles = new List<ProcessReport>();
PromptResult pr = ed.GetString("\nEnter folder containing DWGs to process: ");
if (pr.Status != PromptStatus.OK) return;
string pathName = pr.StringResult;
string mReportFileName = pathName + @"\ReportLog.html";
mReportFileName = mReportFileName.Replace("\\", @"\");
string[] fileNames = Directory.GetFiles(pathName, "*.dwg");
// We'll use some counters to keep track
// of how the processing is going
int processed = 0, saved = 0, problem = 0;
DateTime Time_ProcessStart = DateTime.Now;
foreach (string fileName in fileNames)
{
ProcessReport DwgInfo = new ProcessReport();
if (fileName.EndsWith(".dwg", StringComparison.CurrentCultureIgnoreCase))
{
string outputName = fileName;
System.Diagnostics.Debug.Print(outputName + DateTime.Now.ToString());
Database db = new Database(false, true);
using (db)
{
try
{
// Purging
cPurge.purgeAll(db, true);
// Reset Annotation Scale (Not Working)
doc.SendStringToExecute(@"(command ""_-SCALELISTEDIT"" ""_R"" ""_Y"" ""_D"" ""*"" ""_E"") ", false, false, false);
db.CloseInput(true);
//(command ""-purge"" ""a"" ""*"" ""n"" )
}
catch (System.Exception ex)
{
ed.WriteMessage("\nProblem processing file: {0} - \"{1}\"", fileName, ex.Message);
problem++;
}
}
}
}
Hi,Thanks for sharing this Giles. Have you seen also https://github.com/wtertinek/Linq2Acad ?
I created a repo on GitHub (https://github.com/gileCAD/Gile.AutoCAD.Extension) with my most used general extension methods.
I have to thank all the Swampers who provided help and/or ideas to build this library (TheMaster, kaefer, kbub, Jeff H, CADbloke, Jeff_M, Keith Brown, T.Willey, Luis Esquivel, n.yuan, It's Alive!, JohnK, pkohut, Alexander Rivilis...).
Thanks for sharing this Giles. Have you seen also https://github.com/wtertinek/Linq2Acad ?Thanks CADbloke. this one seems really very interesting.