.NET MISCELLANEOUS/GENERAL Routines
LIBRARY THREAD forAutoCAD MISCELLANEOUS/GENERALMembers 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. PurgeAll command:
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;
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;
}
public static void purgeAll()
{
purgeAll(Application.DocumentManager.MdiActiveDocument.Database, false);
}
}
}
File dialogs for AutoLISP:
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;
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;
}
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;
}
}
}
Toggle visibility of analytical elements in Revit Structure:
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);
}
}
}
Hi,
A custom osnaps example . Quick way to parse text file
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'~ Fast way to read data from Excel
-Create Windows Application project
-Drop button1 and dataGridView1 on form
-Change full path of Excel file
Enjoy
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
// it means the first 3 columns from Sheet1
OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM ", conn);
//create new dataset
DataSet ds = new DataSet();
// fill dataset
da.Fill(ds);
//populate grid with data
dgv.DataSource = ds.Tables;
//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;//
~'J'~
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'~ Read / Write Excel examples
(it is necessary to change the file name in the code)
===VB.NET===
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") '
===C#===
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");//
~'J'~
页:
[1]
2