C# Sheet count

rbh2024
Enthusiast

C# Sheet count

rbh2024
Enthusiast
Enthusiast

I'm not able to load the following code or get it to work correctly.

 

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

namespace AutoCADSheetCounter
{
    public class SheetCounter
    {
        private static int _sheetCount;

        public static void Initialize()
        {
            // Attach layout creation and deletion event handlers
            Application.DocumentManager.DocumentCreated += LayoutCreatedEventHandler;
            Application.DocumentManager.DocumentDestroyed += LayoutDeletedEventHandler;

            // Debug message
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage("\nSheetCounter: Event handlers attached successfully!");

            // Update sheet count initially
            UpdateSheetCount();
        }

        private static void UpdateSheetCount()
        {
            var doc = Application.DocumentManager.MdiActiveDocument;
            var db = doc.Database;

            using (var tr = db.TransactionManager.StartTransaction())
            {
                var layoutDict = (DBDictionary)tr.GetObject(db.LayoutDictionaryId, OpenMode.ForRead);
                _sheetCount = 0;

                foreach (var layoutId in layoutDict)
                {
                    var layout = (Layout)tr.GetObject(layoutId.Value, OpenMode.ForRead);
                    if (layout.LayoutName != "Model") // Exclude the Model tab
                    {
                        _sheetCount++;
                    }
                }

                tr.Commit();
            }

            // Debug message
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage($"\nSheetCounter: Sheet count updated: {_sheetCount}");
        }

        private static void LayoutCreatedEventHandler(object sender, DocumentCollectionEventArgs e)
        {
            UpdateSheetCount();
        }

        private static void LayoutDeletedEventHandler(object sender, DocumentDestroyedEventArgs e)
        {
            UpdateSheetCount();
        }

        [CommandMethod("COUNTSHEETS")]
        public static void CountSheets()
        {
            UpdateSheetCount();

            // Display sheet count
            Editor ed = Application.DocumentManager.MdiActiveDocument.Editor;
            ed.WriteMessage($"\nTotal number of sheets: {_sheetCount}");
        }
    }
}

 

0 Likes
Reply
Accepted solutions (2)
2,258 Views
25 Replies
Replies (25)

ActivistInvestor
Advisor
Advisor
Accepted solution

@rbh2024 wrote:

I'm not able to load the following code or get it to work correctly.


You'll need to be a bit more specific. What problems are you having loading the code?  How are you trying to load it? I'm asking because even if you can get it to load, that code has some problems, but those problems shouldn't prevent the code from being loaded. 

 

Aside from that, I don't see the point to that code, because you can get the number of paper space Layouts in the current document using nothing more than this:

 

LayoutManager.Current.LayoutCount - 1; 

 

LayoutCount includes the model tab, so you just subtract 1 from the result.

0 Likes

rbh2024
Enthusiast
Enthusiast

🤔so this will fill in the field? 

0 Likes

rbh2024
Enthusiast
Enthusiast

Sorry, so I'm doing netload loading it but it's not showing the Message saying it attached successfully.

0 Likes

rbh2024
Enthusiast
Enthusiast

I think I'm missing something here.  would you mind giving me a little bit more of the code?  This is going in a different direction than I was going and I would love to understand this.

0 Likes

Ed__Jobe
Mentor
Mentor

@rbh2024 wrote:

🤔so this will fill in the field? 


What field? Also, you might want to be more accurate in your wording. You are counting Layouts, not sheets, to be confused with sheets in a sheetset.

Ed


Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.
How to post your code.

EESignature

0 Likes

Ed__Jobe
Mentor
Mentor

@rbh2024 wrote:

I think I'm missing something here.  would you mind giving me a little bit more of the code?  This is going in a different direction than I was going and I would love to understand this.


It would be best if you posted your updated code.

Ed


Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.
How to post your code.

EESignature

0 Likes

rbh2024
Enthusiast
Enthusiast

You are correct.  

This Code is intended to count the number of layouts, (I am using these as the different pages (sheets) in my drawing). The Engineering System that I use I'm not able to use the Sheetset Manager.  This code counts the number of Sheets subtracts 1 for the model space and I'm trying to get it to present this as a field to use for total sheets.

0 Likes

ActivistInvestor
Advisor
Advisor

@rbh2024 wrote:

I think I'm missing something here.  would you mind giving me a little bit more of the code?  This is going in a different direction than I was going and I would love to understand this.


A little bit more of what code? 

 

The single line of code I posted does what all of the code you posted does.

 

If you are NETLOADing the code, you aren't gong to see anything until you issue the command it defines (COUNTSHEETS).

 

Did you write the code you originally posted, or did you get it from some other source?

0 Likes

ActivistInvestor
Advisor
Advisor

@rbh2024 wrote:

🤔so this will fill in the field? 


What field are you referring to? 

0 Likes

rbh2024
Enthusiast
Enthusiast

Thank you.  I wrote the code I used the command COUNTSHEETS but it is not recognized at all.  I placed the "\nSheetCounter: Event handlers attached successfully!" in hopes that it would show me if the code actually loaded as well.  This is my first C# program.

 

richardharris_0-1714771889842.png

 

0 Likes

kerry_w_brown
Advisor
Advisor

@rbh2024 

 

How do you run this method ??

 public static void Initialize()

 

Did you mean to include that Method in an ExtensionApplication ??

 

Something similar to :

[assembly: ExtensionApplication(typeof(E240422_D.ExtensionApplication))]

namespace E240422_D
{
   internal class ExtensionApplication : IExtensionApplication
   {
      public void Initialize()
      {
         AcadApp.Idle += OnIdle;
      }

      private void OnIdle(object? sender, EventArgs e)
      {
         var doc = AcadApp.DocumentManager.MdiActiveDocument;
         if (doc != null)
         {
            AcadApp.Idle -= OnIdle;
            doc.Editor.WriteMessage("\nE240422_D loaded.\n");
         }
      }

      public void Terminate()
      { }
   }
}

 

Regards,

 

 

 


// Called Kerry or kdub in my other life.

Everything will work just as you expect it to, unless your expectations are incorrect. ~ kdub
Sometimes the question is more important than the answer. ~ kdub

NZST UTC+12

class keyThumper<T> : Lazy<T>;      another  Swamper

0 Likes

ActivistInvestor
Advisor
Advisor

@rbh2024 wrote:

This is my first C# program.

You should've made that clear from the outset.

 

I would suggest that you go through the basic training materials and labs that are available to familiarize yourself with the managed API, because you can't write applications without that basic familiarity of it.

 

You will not see any message printed when your assembly loads because in order to execute code when an assembly loads you must implement the IExtensionApplication interface and provide an Initialize() method that contains the code you want to run when the assembly loads.

 

An example that displays a message when the assembly loads:

 

public class MyApplication : IExtensionApplication
{
   public void Initialize()
   {
      var doc = Application.DocumentManager.MdiActiveDocument;
      if(doc != null)
         doc.Editor.WriteMessage("\n*** MyApplication loaded ***");
   }

   public void Terminate()
   {
   }
}

 

Aside from that, there's no need for the code you've written. Getting the number of layouts in a drawing can be done with the one line of code I posted previously.

 

0 Likes

Ed__Jobe
Mentor
Mentor

Since you mentioned a FIELD, I did some research and found this solution that might work for you. If you start with a solution based on events, it may modify the sheet number when you don't want it to. This solution just uses a lisp to run when you want to change the field values, plus it does it for all the sheets.

Ed


Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.
How to post your code.

EESignature

0 Likes

ActivistInvestor
Advisor
Advisor

AFAIK, there's no DIESEL expression that can produce the number of layouts in a drawing. The only way to get that value into a field is by using a custom system variable and setting its value from handlers of LayoutManager events. 

0 Likes

rbh2024
Enthusiast
Enthusiast

 

Thank you for taking the time to respond to my post.  I apologize for my lack of knowledge.  I have been taking some paid courses. 

 

Nothing I have learned so far has discussed the snippet of code you posted.

 

I'm honestly still trying to understand that one line of code makes sense but how to implement it is where I am struggling.

 

LayoutManager.Current.LayoutCount - 1;

 

 

I am trying to understand this code but I know there is something that I'm not getting.

 

If you would be so kind as to show me how the code should look in its entirety or just something to get me on the right track, I would appreciate it.

0 Likes

rbh2024
Enthusiast
Enthusiast

Thank you for your response it seems like this should be easy,  due to my lack of knowledge I think I'm making this harder then It should be.

0 Likes

ActivistInvestor
Advisor
Advisor

@rbh2024 wrote:

 

If you would be so kind as to show me how the code should look in its entirety or just something to get me on the right track, I would appreciate it.


I can't really show you how the code should look in its entirety (which is basically asking me to write the complete, working code for you), because you really haven't provided a complete rational description of the problem you are trying to solve. For example, you previously asked if that one line of code I showed will assign the value to the field, without having previously mentioned anything about a field.

 

Mind-reading is only available at an additional charge. 😲

 

If you want to describe the overall problem in detail (e.g., what the end result of the code you are asking me to write for you must do), then maybe I or someone else can guide you to create it, but I'm not going to just write the code for you because that crosses the line separating peer support from professional consulting services. 

 

If someone else here wants to undertake the task of writing code for you, then great, but I'm not going to do that.

 

 

0 Likes

rbh2024
Enthusiast
Enthusiast

@ActivistInvestor,

I can try to understand where you are coming from.  I am not wanting anyone to complete my code but, the line of code that you suggested as is, at least from what I have learned so far cannot be used as is.  I'm trying to learn/understand how to use it.

 

I'm trying to create a .dll that will monitor the number of sheets (ctab) in a drawing assign that to an int that will be assigned to a field named "_sheetCount".  I plan to use the field as the total number of sheets in my titleblock. (I'm subtracting one to remove Model Space)

 

As a lisp it looks like this Compliments of CAD Studio

(defun _totalLayoutsReactor (a r)

(setq totalLayouts (length (layoutlist)))

)

(vlr-command-reactor nil '((:vlr-commandWillStart . _totalLayoutsReactor)))

 

@ActivistInvestor, again I do not want you or anyone else to write my code I'm just, trying to get some help and understand.

0 Likes

_gile
Mentor
Mentor

@ActivistInvestor 's first reply ( # 2 )

 

LayoutManager.Current.LayoutCount - 1;

 

returns exactly the same as:

 

(length (layoutlist))

 

 



Gilles Chanteau
Programmation AutoCAD LISP/.NET
GileCAD
GitHub

0 Likes