乐筑天下

搜索
欢迎各位开发者和用户入驻本平台 尊重版权,从我做起,拒绝盗版,拒绝倒卖 签到、发布资源、邀请好友注册,可以获得银币 请注意保管好自己的密码,避免账户资金被盗
查看: 211|回复: 13

.NET MISCELLANEOUS/GENERAL Routines

[复制链接]

116

主题

996

帖子

9

银币

顶梁支柱

Rank: 50Rank: 50

铜币
1466
发表于 2010-1-27 05:36:16 | 显示全部楼层 |阅读模式
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.
回复

使用道具 举报

15

主题

687

帖子

169

银币

中流砥柱

Rank: 25

铜币
582
发表于 2010-1-27 10:03:17 | 显示全部楼层
PurgeAll command:
  1. using System;
  2. using System.Text;
  3. using System.Collections.Generic;
  4. using Autodesk.AutoCAD.Runtime;
  5. using Autodesk.AutoCAD.EditorInput;
  6. using Autodesk.AutoCAD.DatabaseServices;
  7. using Autodesk.AutoCAD.ApplicationServices;
  8. [assembly: ExtensionApplication(typeof(cgabriel.PurgeTools))]
  9. [assembly: CommandClass(typeof(cgabriel.PurgeTools))]
  10. namespace cgabriel
  11. {
  12.     public class PurgeTools : IExtensionApplication
  13.     {
  14.         public void Initialize() { }
  15.         public void Terminate() { }
  16.         public static bool purgeSymbolTables(Database db, ObjectIdCollection tableIds, bool silent)
  17.         {
  18.             bool itemsPurged = false;
  19.             Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
  20.             ObjectIdCollection purgeableIds = new ObjectIdCollection();
  21.             using (Transaction tr = db.TransactionManager.StartTransaction())
  22.             {
  23.                 foreach (ObjectId tableId in tableIds)
  24.                 {
  25.                     SymbolTable table = (SymbolTable)tr.GetObject(tableId, OpenMode.ForRead, false);
  26.                     foreach (ObjectId recordId in table)
  27.                         purgeableIds.Add(recordId);
  28.                 }
  29.                 db.Purge(purgeableIds);
  30.                 if (purgeableIds.Count == 0) return false;
  31.                 itemsPurged = true;
  32.                 foreach (ObjectId id in purgeableIds)
  33.                 {
  34.                     try
  35.                     {
  36.                         SymbolTableRecord record = (SymbolTableRecord)tr.GetObject(id, OpenMode.ForWrite);
  37.                         string recordName = record.Name;
  38.                         record.Erase();
  39.                         if (!silent)
  40.                         {
  41.                             if (!recordName.Contains("|"))
  42.                             {
  43.                                 ed.WriteMessage("\nPurging " + record.GetType().Name + " " + recordName);
  44.                             }
  45.                         }
  46.                     }
  47.                     catch (Autodesk.AutoCAD.Runtime.Exception e)
  48.                     {
  49.                         if ((e.ErrorStatus == ErrorStatus.CannotBeErasedByCaller) || (e.ErrorStatus == (ErrorStatus)20072))
  50.                             itemsPurged = false;
  51.                         else
  52.                             throw e;
  53.                     }
  54.                 }
  55.                 tr.Commit();
  56.             }
  57.             return itemsPurged;
  58.         }
  59.         public static bool purgeDictionaries(Database db, ObjectIdCollection dictIds, bool silent)
  60.         {
  61.             bool itemsPurged = false;
  62.             Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
  63.             ObjectIdCollection purgeableIds = new ObjectIdCollection();
  64.             using ( Transaction tr = db.TransactionManager.StartTransaction() )
  65.             {
  66.                 foreach (ObjectId dictId in dictIds)
  67.                 {
  68.                     DBDictionary dict = (DBDictionary)tr.GetObject(dictId, OpenMode.ForRead, false);
  69.                     foreach (DBDictionaryEntry entry in dict)
  70.                     {
  71.                         purgeableIds.Add(entry.m_value);
  72.                     }
  73.                 }
  74.                 db.Purge(purgeableIds);
  75.                 if (purgeableIds.Count == 0) return false;
  76.                 itemsPurged = true;
  77.                 DBDictionary nod = (DBDictionary)tr.GetObject(db.NamedObjectsDictionaryId, OpenMode.ForRead);
  78.                 foreach (ObjectId id in purgeableIds)
  79.                 {
  80.                     try
  81.                     {
  82.                         DBObject obj = (DBObject)tr.GetObject(id, OpenMode.ForWrite);
  83.                         obj.Erase();
  84.                         if (!silent)
  85.                         {
  86.                             foreach (ObjectId dictId in dictIds)
  87.                             {
  88.                                 DBDictionary dict = (DBDictionary)tr.GetObject(dictId, OpenMode.ForRead, false);
  89.                                 string dictName = nod.NameAt(dictId);
  90.                                 if (dict.Contains(id))
  91.                                 {
  92.                                     ed.WriteMessage("\nPurging " + dict.NameAt(id) + " from " + dictName);
  93.                                     break;
  94.                                 }
  95.                             }
  96.                         }
  97.                     }
  98.                     catch(Autodesk.AutoCAD.Runtime.Exception e)
  99.                     {
  100.                         if ((e.ErrorStatus == ErrorStatus.CannotBeErasedByCaller) || (e.ErrorStatus == (ErrorStatus)20072))
  101.                             itemsPurged = false;
  102.                         else
  103.                             throw e;
  104.                     }
  105.                 }
  106.                 tr.Commit();
  107.             }
  108.             return itemsPurged;
  109.         }
  110.         public static void purgeAll(Database db, bool silent)
  111.         {
  112.             ObjectIdCollection tableIds = new ObjectIdCollection();
  113.             tableIds.Add(db.BlockTableId);
  114.             tableIds.Add(db.DimStyleTableId);
  115.             tableIds.Add(db.LayerTableId);
  116.             tableIds.Add(db.LinetypeTableId);
  117.             tableIds.Add(db.RegAppTableId);
  118.             tableIds.Add(db.TextStyleTableId);
  119.             tableIds.Add(db.UcsTableId);
  120.             tableIds.Add(db.ViewportTableId);
  121.             tableIds.Add(db.ViewTableId);
  122.             ObjectIdCollection dictIds = new ObjectIdCollection();
  123.             dictIds.Add(db.MaterialDictionaryId);
  124.             dictIds.Add(db.MLStyleDictionaryId);
  125.             dictIds.Add(db.MLeaderStyleDictionaryId);
  126.             dictIds.Add(db.PlotStyleNameDictionaryId);
  127.             dictIds.Add(db.TableStyleDictionaryId);
  128.             dictIds.Add(db.VisualStyleDictionaryId);
  129.             while (purgeSymbolTables(db, tableIds, silent) || purgeDictionaries(db, dictIds, silent))
  130.                 continue;
  131.             return;
  132.         }
  133.         [CommandMethod("PurgeTools", "PurgeAll", CommandFlags.Modal | CommandFlags.DocExclusiveLock)]
  134.         public static void purgeAll()
  135.         {
  136.             purgeAll(Application.DocumentManager.MdiActiveDocument.Database, false);
  137.         }
  138.     }
  139. }
回复

使用道具 举报

1

主题

1069

帖子

1050

银币

初露锋芒

Rank: 3Rank: 3Rank: 3

铜币
69
发表于 2010-1-27 10:08:31 | 显示全部楼层
File dialogs for AutoLISP:
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using Autodesk.AutoCAD.Windows;
  5. using Autodesk.AutoCAD.Runtime;
  6. using Autodesk.AutoCAD.EditorInput;
  7. using Autodesk.AutoCAD.DatabaseServices;
  8. using Autodesk.AutoCAD.ApplicationServices;
  9. using ofdFlags = Autodesk.AutoCAD.Windows.OpenFileDialog.OpenFileDialogFlags;
  10. using sfdFlags = Autodesk.AutoCAD.Windows.SaveFileDialog.SaveFileDialogFlags;
  11. namespace cgabriel
  12. {
  13.     public class LispFileDialogs
  14.     {
  15.         public static string title;
  16.         public static string defaultFileName;
  17.         public static string defaultExtension;
  18.         public static short flags;
  19.         [LispFunction("GetOpenFileDialog")]
  20.         public static ResultBuffer GetOpenFileDialog(ResultBuffer args)
  21.         {
  22.             if (!parseArguments(args)) return null;
  23.             ofdFlags dlgFlags = (ofdFlags)flags;
  24.             if (((dlgFlags & ofdFlags.DefaultIsFolder) != 0) && Path.HasExtension(defaultFileName))
  25.                 defaultFileName = Path.GetDirectoryName(defaultFileName);
  26.             OpenFileDialog dlg = new OpenFileDialog(title, defaultFileName, defaultExtension, title, dlgFlags);
  27.             if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
  28.                 return null;
  29.             ResultBuffer result = new ResultBuffer();
  30.             foreach (string file in dlg.GetFilenames())
  31.                 result.Add(new TypedValue((int)LispDataType.Text, file));
  32.             return result;
  33.         }
  34.         [LispFunction("GetSaveFileDialog")]
  35.         public static TypedValue GetSaveFileDialog(ResultBuffer args)
  36.         {
  37.             if (!parseArguments(args))
  38.                 return new TypedValue((int)LispDataType.Nil, null);
  39.          
  40.             sfdFlags dlgFlags = (sfdFlags)flags;
  41.             if (((dlgFlags & sfdFlags.DefaultIsFolder) != 0) && Path.HasExtension(defaultFileName))
  42.                 defaultFileName = Path.GetDirectoryName(defaultFileName);
  43.             SaveFileDialog dlg = new SaveFileDialog(title, defaultFileName, defaultExtension, title, dlgFlags);
  44.             if (dlg.ShowDialog() != System.Windows.Forms.DialogResult.OK)
  45.                 return new TypedValue((int)LispDataType.Nil, null);
  46.             return new TypedValue((int)LispDataType.Text, dlg.Filename);
  47.         }
  48.         public static bool parseArguments(ResultBuffer args)
  49.         {
  50.             Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
  51.             if (args == null)
  52.                 return notEnoughArguments(ed);
  53.             ResultBufferEnumerator iter = args.GetEnumerator();
  54.             iter.MoveNext();
  55.             if (iter.Current.TypeCode != (short)LispDataType.Text)
  56.                 return wrongArguments(ed);
  57.             title = (string)iter.Current.Value;
  58.             if (iter.MoveNext() == false)
  59.                 return notEnoughArguments(ed);
  60.             if (iter.Current.TypeCode != (short)LispDataType.Text)
  61.                 return wrongArguments(ed);
  62.             defaultFileName = (string)iter.Current.Value;
  63.             if (iter.MoveNext() == false)
  64.                 return notEnoughArguments(ed);
  65.             if (iter.Current.TypeCode != (short)LispDataType.Text)
  66.                 return wrongArguments(ed);
  67.             defaultExtension = (string)iter.Current.Value;
  68.             if (iter.MoveNext() == false)
  69.                 return notEnoughArguments(ed);
  70.             if (iter.Current.TypeCode != (short)LispDataType.Int16)
  71.                 return wrongArguments(ed);
  72.             flags = (short)iter.Current.Value;
  73.             return true;
  74.         }
  75.         public static bool notEnoughArguments(Editor ed)
  76.         {
  77.             ed.WriteMessage("\nToo few arguments.");
  78.             return false;
  79.         }
  80.         public static bool wrongArguments(Editor ed)
  81.         {
  82.             ed.WriteMessage("\nExpected string string string int.");
  83.             return false;
  84.         }
  85.     }
  86. }
回复

使用道具 举报

1

主题

1069

帖子

1050

银币

初露锋芒

Rank: 3Rank: 3Rank: 3

铜币
69
发表于 2010-1-27 15:55:36 | 显示全部楼层
Toggle visibility of analytical elements in Revit Structure:
  1. using System;
  2. using System.Reflection;
  3. using Autodesk.Revit;
  4. using Autodesk.Revit.Elements;
  5. namespace ToggleAnalyticalVisibility
  6. {
  7.     public class Toggles : IExternalApplication
  8.     {
  9.         public IExternalApplication.Result OnShutdown(ControlledApplication application)
  10.         {
  11.             return IExternalApplication.Result.Succeeded;
  12.         }
  13.         public IExternalApplication.Result OnStartup(ControlledApplication application)
  14.         {
  15.             Assembly library = Assembly.GetExecutingAssembly();
  16.             string libraryPath = library.Location;
  17.             MenuItem menuItem = application.CreateTopMenu("Analytical Model");
  18.             menuItem.Append(
  19.                 MenuItem.MenuType.BasicMenu,
  20.                 "Hide Analytical Model Graphics",
  21.                 libraryPath,
  22.                 "ToggleAnalyticalVisibility.ToggleOff");
  23.             menuItem.Append(
  24.                 MenuItem.MenuType.BasicMenu,
  25.                 "Show Analytical Model Graphics",
  26.                 libraryPath,
  27.                 "ToggleAnalyticalVisibility.ToggleOn");
  28.             return IExternalApplication.Result.Succeeded;
  29.         }
  30.     }
  31.     public class ToggleOn : IExternalCommand
  32.     {
  33.         public IExternalCommand.Result Execute(
  34.             ExternalCommandData commandData,
  35.             ref string message,
  36.             ElementSet elements)
  37.         {
  38.             AnalyticalModelGraphics.setVisibility(commandData, true);
  39.             return IExternalCommand.Result.Succeeded;
  40.         }
  41.     }
  42.     public class ToggleOff : IExternalCommand
  43.     {
  44.         public IExternalCommand.Result Execute(
  45.             ExternalCommandData commandData,
  46.             ref string message,
  47.             ElementSet elements)
  48.         {
  49.             AnalyticalModelGraphics.setVisibility(commandData, false);
  50.             return IExternalCommand.Result.Succeeded;
  51.         }
  52.     }
  53.     public class AnalyticalModelGraphics
  54.     {
  55.         public static void setVisibility(ExternalCommandData commandData, bool state)
  56.         {
  57.             Document doc = commandData.Application.ActiveDocument;
  58.             View curView = doc.ActiveView;
  59.             foreach (Category cat in doc.Settings.Categories)
  60.             {
  61.                 if (cat.Name.ToLower().Contains("load"))
  62.                 {
  63.                     curView.setVisibility(cat, state);
  64.                 }
  65.                 foreach (Category subCat in cat.SubCategories)
  66.                 {
  67.                     if (subCat.Name.ToLower().Contains("analytical") ||
  68.                         subCat.Name.ToLower().Contains("load"))
  69.                     {
  70.                         curView.setVisibility(subCat, state);
  71.                     }
  72.                 }
  73.             }
  74.             // Believe it or not, the method used above is faster than that shown below in spite
  75.             // of the fact that it iterates over every single category and subcategory.
  76.             //Document doc = commandData.Application.ActiveDocument;
  77.             //View curView = doc.ActiveView;
  78.             //Settings settings = doc.Settings;
  79.             //curView.setVisibility(
  80.             //    settings.Categories.get_Item(BuiltInCategory.OST_AnalyticalRigidLinks),
  81.             //    state);
  82.             //curView.setVisibility(
  83.             //    settings.Categories.get_Item(BuiltInCategory.OST_ColumnAnalyticalGeometry),
  84.             //    state);
  85.             //curView.setVisibility(
  86.             //    settings.Categories.get_Item(BuiltInCategory.OST_ColumnAnalyticalRigidLinks),
  87.             //    state);
  88.             //curView.setVisibility(
  89.             //    settings.Categories.get_Item(BuiltInCategory.OST_FloorsAnalyticalGeometry),
  90.             //    state);
  91.             //curView.setVisibility(
  92.             //    settings.Categories.get_Item(BuiltInCategory.OST_FootingAnalyticalGeometry),
  93.             //    state);
  94.             //curView.setVisibility(
  95.             //    settings.Categories.get_Item(BuiltInCategory.OST_FramingAnalyticalGeometry),
  96.             //    state);
  97.             //curView.setVisibility(
  98.             //    settings.Categories.get_Item(BuiltInCategory.OST_WallsAnalyticalGeometry),
  99.             //    state);
  100.         }
  101.     }
  102. }
回复

使用道具 举报

116

主题

996

帖子

9

银币

顶梁支柱

Rank: 50Rank: 50

铜币
1466
发表于 2010-2-5 11:51:29 | 显示全部楼层
Hi,
A custom osnaps example .
回复

使用道具 举报

1

主题

1069

帖子

1050

银币

初露锋芒

Rank: 3Rank: 3Rank: 3

铜币
69
发表于 2010-2-13 17:41:37 | 显示全部楼层
Quick way to parse text file
  1.     Public Function ReadCSV(ByVal filename As String, ByVal sep As String) As List(Of String())
  2.         Dim info As List(Of String()) = New List(Of String())
  3.         Using pars As New FileIO.TextFieldParser(filename)
  4.             pars.SetDelimiters(sep)
  5.             While Not pars.EndOfData
  6.                 Dim line() As String
  7.                 line = pars.ReadFields()
  8.                 info.Add(line)
  9.             End While
  10.         End Using
  11.         Return info
  12.     End Function
~'J'~
回复

使用道具 举报

1

主题

1069

帖子

1050

银币

初露锋芒

Rank: 3Rank: 3Rank: 3

铜币
69
发表于 2010-2-19 05:28:32 | 显示全部楼层
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]
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;//
~'J'~
回复

使用道具 举报

1

主题

1069

帖子

1050

银币

初露锋芒

Rank: 3Rank: 3Rank: 3

铜币
69
发表于 2010-2-19 05:31:31 | 显示全部楼层

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.
回复

使用道具 举报

15

主题

687

帖子

169

银币

中流砥柱

Rank: 25

铜币
582
发表于 2010-2-19 06:11:55 | 显示全部楼层

Still working in A2008
~'J'~
回复

使用道具 举报

1

主题

1069

帖子

1050

银币

初露锋芒

Rank: 3Rank: 3Rank: 3

铜币
69
发表于 2010-2-19 06:54:50 | 显示全部楼层
Read / Write Excel examples
(it is necessary to change the file name in the code)
===  VB.NET  ===
[code]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#  ===
[code]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'~
回复

使用道具 举报

发表回复

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

  • 微信公众平台

  • 扫描访问手机版

  • 点击图片下载手机App

QQ|关于我们|小黑屋|乐筑天下 繁体中文

GMT+8, 2025-2-5 22:15 , Processed in 0.220232 second(s), 72 queries .

© 2020-2025 乐筑天下

联系客服 关注微信 帮助中心 下载APP 返回顶部 返回列表