Siemens nx журнал ошибок

нет..написал как выдает :smile: причем через посты которые уже есть нормально генерирует

На сколько я понял через готовые посты программу выдает, а через ваш пост нехочет?

У самого была подобная ошибка, создал пост а программу не выводит!

Поступил следующим способом

Чтобы использовать ваш постпроцессор в NX Вы должены добавить строку в Ваш файл template_post.dat в вашем текущем каталоге постпроцессора. (взято из руководства)

###############################################################################

# template_post config file — Event Handler and Definition files for

# Generic Machine

#

#

#

###############################################################################

Anilam,${UGII_CAM_POST_DIR}Anilam.tcl,${UGII_CAM_POST_DIR}Anilam.def

WIRE_EDM_4_AXIS,${UGII_CAM_POST_DIR}wedm.tcl,${UGII_CAM_POST_DIR}wedm.def

MILL_3_AXIS,${UGII_CAM_POST_DIR}mill3ax.tcl,${UGII_CAM_POST_DIR}mill3ax.def

MILL_3_AXIS_TURBO,${UGII_CAM_POST_DIR}mill3ax_turbo.tcl,${UGII_CAM_POST_DIR}mill3ax_turbo.def

MILL_4_AXIS,${UGII_CAM_POST_DIR}m4bh.tcl,${UGII_CAM_POST_DIR}m4bh.def

MILL_5_AXIS,${UGII_CAM_POST_DIR}m5abtt.tcl,${UGII_CAM_POST_DIR}m5abtt.def

LATHE_2_AXIS_TOOL_TIP,${UGII_CAM_POST_DIR}lathe_tool_tip.tcl,${UGII_CAM_POST_DIR}lathe_tool_tip.def

LATHE_2_AXIS_TURRET_REF,${UGII_CAM_POST_DIR}lathe_turret_ref.tcl,${UGII_CAM_POST_DIR}lathe_turret_ref.def

MILLTURN,${UGII_CAM_POST_DIR}millturn_3axis_mill.tcl,${UGII_CAM_POST_DIR}millturn_3axis_mill.def

MILLTURN_MULTI_SPINDLE,${UGII_CAM_POST_DIR}millturn_4axis_mill.tcl,${UGII_CAM_POS

Добавьте новую строчку аналогично которым есть, только с именем вашего поста!!!

Должно все получится :wink:

NX Logging Business

NX journals everything, basically, into log files from the moment you click the startup icon to the last confirmation to exit. However, there are two different journal logs that you should be familiar with:

  • NX System Log File
  • License Server Debug Log File

NX System Log File

The NX System Log File records the entire startup process including what user, device, network or managed environment, and all the configuration options and sources. After that, it lists each click-by-click event that happens, including cursor movement and object selection. Here’s how the NX System Log File can be used:

  • The log file is accessed most easily within an NX session by selecting File→Help→Log File:

NX Logging Business

  • Once selected, a text window appears, similar to a Notepad display but with no word wrap and no formatting whatsoever. It is strictly static ascii text, meaning, it can’t be changed and imported back into NX to change any settings. It’s simply an export of information; a dead text file that can be saved for a record of session history and it serves to troubleshoot or verify configuration setup and settings installation.

  • At the top of the file is the header containing the user name, date and time, and host machine or node name. The header is framed above and below with lines of equal signs.
  • Immediately below that is the pathname to the log file. When a user has trouble starting NX, whether it’s due to license issues or other problems, this log file cannot be accessed using the File→Help→Log File command, obviously, because NX isn’t running. However, anytime an NX initialization is started, whether by clicking an icon, an executable (.exe) file, or a .bat file, a log file is created in the users “temp” directory. There may actually be many individual log files in that temp directory.
  • After the pathname line, it lists when the log file was created and then the machine details. Sometimes this can tell you something you don’t know about your computer!
  • Next, after a section break containing a line of asterisks, is the Flexera licensing information; information about your Siemens account and the settings used in starting the license service.
  • Then, another section breakline of asterisks and the actual NX software configuration information. This is essentially a report on all the settings of your configuration and environment variables and files such as the Customer Defaults settings derived from the “user.dpv” file. Suffice it to say it is extensive!
  • Near the bottom of the log file, the entries that record the installation and configuration events end and the recording of actual mouse gestures, menu picks, and other input are listed where lines start with “&MACRO” appear. Literally every mouse button pick and movement are recorded. And, as you’ll see below, any internal errors or failures are also noted and that is what makes this file so essential in troubleshooting your NX session and configuration. Usually, if you have a bad enough problem to open an Incident Report (IR) with Siemens GTAC, they’ll ask for this log file to look for errors and other discrepancies.

  • Again, this window is merely an exported report or the journaled events in the session and the file can saved, edited (as I’ve done to remove sensitive Swoosh Webkey account and Sold To information), and exited. Nothing that is done with this file affects anything about an NX session and this log file can be displayed as many times as desired.

License Server Debug Log File

This log file records different information, mostly relative to the license server status and the check out and check in of the NX license features of a license bundle being used during a session.

Normally, most NX users aren’t really concerned with this kind of NX event tracking because it is more relative to the responsibilities of the CAD/CAM manager or IT Administrator of NX customer sites. In fact, this log file can only be generated from the actual license server machine being used, meaning, if a user is on a client machine that has no actual license file on it but accesses NX licenses from a server host machine. Here’s how the NX License Server Debug Log File can be used from a license server machine:

  • Accessing the log file is accommodated by using the Flexera LMTOOLS utility which is an application that is installed on the server host when NX is installed.
  • In a Windows 10 OS, press the windows key on the keyboard to bring up the Windows Start Screen. On the left, scroll down to the “S” section and expand “Siemens”. Select LMTOOLS from the list. This can also be added to the Start Screen (shown on the right) or Task Bar as an icon.

  • On other operating systems, access the LMTOOLS command from the application list as appropriate.
  • Once selected, the LMTOOLS dialog appears. Select the “Config. Services” tab at the top, second from the right:

  • Select the “View Log” button near the bottom right. The log file is displayed in a separate window.

  • However, this is not an ascii text type file but a scrollable, dynamic listing that includes a time stamp for each and every line and it will update as you select different commands and settings interactively in NX. Yet, its parent process is that of the LMTOOLS utility, not NX. When LMTOOLS is exited, this log window also closes.
  • You will also notice that this listing window does not have an OK, Cancel, or Close button in it. Once displayed, closing it is done by selecting the “Close Log” button in the LMTOOLS dialog. The location of this log file is also indicated to the left of the View Log and Close Log buttons.

  • Like the NX system Log file, this log file can also be used by Siemens GTAC to troubleshoot and validate your NX configuration and settings. As it says in the first line, it “is intended for debug purposes only” but it has another cool thing you can do with it.
  • If you scroll down the listing, you will see similar configuration and settings confirmation that you see in the NX System Log File but after that, near the end, you will see a record of the individual license “features” being checked OUT and IN as used by the user in a fixed license (node) environment or by all users in a floating license environment during their NX sessions when an NX license server is being used.
  • In a customer environment where there are ala carte licenses, such as those not used on a daily basis like Freeform Shape, Sheet Metal, Advanced Assemblies, Drafting, etc., instead of complete license bundles for each user in the company, you can track who is using what license feature and for how long.

  • Without getting too deeply into the explanation of all this feature license definition (and this is a layman’s interpretation):
    • The customer license file is generated by Siemens for a specific computer based on that computer’s Composite ID (CID), MAC address, and the actual software functionality purchased. It contains what can most accurately be described as hieroglyphics (hexadecimal code) that triggers the software to enable selective functionality. NX functionality is purchased in license bundles.
    • A license bundle is a predefined grouping of NX applications such as Gateway, Feature Modeling, Assemblies, Drafting, or the various groupings in CAM or CAE. Although NX itself is an application, Siemens has defined sub-applications within the software that are generally relative to the engineering and manufacturing disciplines common in industries today. There are bundles that include only CAD, CAM, or CAE functionality but also a mix of any of these areas of NX, depending on a customer’s needs. Within the various license bundles, there are groups of functions included in license features.
    • License features are, in a sense, a subgrouping of functionality included in a license bundle that have a particular focus relative to a customer’s specific business processes, type of product, industry, or task preferences. Examples would be: 5-axis machining functionality as opposed to lathe or turning definitions or aesthetic free form design capability instead of simpler analytic mechanical shapes.
    • When a user starts NX, the NX configuration will assign a default license bundle or profile assignment of functionality for that user. The user can then select the bundle of choice, if so licensed, or simply open or create a part file and then select any of the licensed NX applications enabled by that user’s configuration. From that point on, this License Server Debug Log File records the license features being used by journaling the feature being taken “out” and then released “in”.
    • Again, this is a rough overview of the process and is not necessarily in very accurate “programmer language speak”.
  • A good example of the value of this would be: a user in an ala carte (individual license feature) license customer environment where there is only one “freeform 2” license feature available, who is trying to use the Bridge Surface command. The user gets a popup notice that the application isn’t available. Upon reading the log file on the server they might see that user’s NX session is trying to access the “freeform 2” license feature that contains the Bridge function but up earlier in the log file, it shows that another user has already taken the only freeform 2 license out and therefore, no other user can use the functions included in that license feature or bundle.
  • There are other ways to do this kind of license usage tracking with other applications, some of which are free and downloadable from the internet but you do need to be aware that unless it is a Siemens software product, Siemens cannot be liable or accountable for the application’s effectiveness or accuracy.

Hope this article has been informative and beneficial.

Garrett Koch

INTELLIGENT WORK FORUMS
FOR ENGINEERING PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you an
Engineering professional?
Join Eng-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Eng-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

NX log file

NX log file

(OP)

27 Jul 20 17:10

Hi all,

I have a large assembly part (NX11 Native), and the parent takes a very long time to load (even with no components) for no apparent reason.

I seem to recall that its possible to turn on additional NX log file logging via some environment variables.

Does anybody recall what the variables are?

Thanks in advance,

B.

Red Flag Submitted

Thank you for helping keep Eng-Tips Forums free from inappropriate posts.
The Eng-Tips staff will check this out and take appropriate action.

Resources

Low-Volume Rapid Injection Molding With 3D Printed Molds

Learn methods and guidelines for using stereolithography (SLA) 3D printed molds in the injection molding process to lower costs and lead time. Discover how this hybrid manufacturing process enables on-demand mold fabrication to quickly produce small batches of thermoplastic parts. Download Now

Design for Additive Manufacturing (DfAM)

Examine how the principles of DfAM upend many of the long-standing rules around manufacturability — allowing engineers and designers to place a part’s function at the center of their design considerations. Download Now

Industry Perspective: Education and Metal 3D Printing

Metal 3D printing has rapidly emerged as a key technology in modern design and manufacturing, so it’s critical educational institutions include it in their curricula to avoid leaving students at a disadvantage as they enter the workforce. Download Now

Taking Control of Engineering Documents

This ebook covers tips for creating and managing workflows, security best practices and protection of intellectual property, Cloud vs. on-premise software solutions, CAD file management, compliance, and more. Download Now

Join Eng-Tips® Today!

Join your peers on the Internet’s largest technical engineering professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Eng-Tips Forums:

  • Eng-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

нет..написал как выдает :smile: причем через посты которые уже есть нормально генерирует

На сколько я понял через готовые посты программу выдает, а через ваш пост нехочет?

У самого была подобная ошибка, создал пост а программу не выводит!

Поступил следующим способом

Чтобы использовать ваш постпроцессор в NX Вы должены добавить строку в Ваш файл template_post.dat в вашем текущем каталоге постпроцессора. (взято из руководства)

###############################################################################

# template_post config file — Event Handler and Definition files for

# Generic Machine

#

#

#

###############################################################################

Anilam,${UGII_CAM_POST_DIR}Anilam.tcl,${UGII_CAM_POST_DIR}Anilam.def

WIRE_EDM_4_AXIS,${UGII_CAM_POST_DIR}wedm.tcl,${UGII_CAM_POST_DIR}wedm.def

MILL_3_AXIS,${UGII_CAM_POST_DIR}mill3ax.tcl,${UGII_CAM_POST_DIR}mill3ax.def

MILL_3_AXIS_TURBO,${UGII_CAM_POST_DIR}mill3ax_turbo.tcl,${UGII_CAM_POST_DIR}mill3ax_turbo.def

MILL_4_AXIS,${UGII_CAM_POST_DIR}m4bh.tcl,${UGII_CAM_POST_DIR}m4bh.def

MILL_5_AXIS,${UGII_CAM_POST_DIR}m5abtt.tcl,${UGII_CAM_POST_DIR}m5abtt.def

LATHE_2_AXIS_TOOL_TIP,${UGII_CAM_POST_DIR}lathe_tool_tip.tcl,${UGII_CAM_POST_DIR}lathe_tool_tip.def

LATHE_2_AXIS_TURRET_REF,${UGII_CAM_POST_DIR}lathe_turret_ref.tcl,${UGII_CAM_POST_DIR}lathe_turret_ref.def

MILLTURN,${UGII_CAM_POST_DIR}millturn_3axis_mill.tcl,${UGII_CAM_POST_DIR}millturn_3axis_mill.def

MILLTURN_MULTI_SPINDLE,${UGII_CAM_POST_DIR}millturn_4axis_mill.tcl,${UGII_CAM_POS

Добавьте новую строчку аналогично которым есть, только с именем вашего поста!!!

Должно все получится :wink:

Open a log file and interpret the data. Review this data to resolve problems in data transfer.

Log file names

Learn the default file naming convention used in generating data transfer log files.

In most cases translators automatically create log files using a user-defined filename with a default filename extension. When storing format files the default file name extensions are as follows:

For IGES

Import translation

.alias2iges (filename.alias2iges)

Export translation

.iges2alias (filename.iges2alias)

For VDAIS

Import translation

.alias2vdais (filename.alias2vdais)

Export translation

.vdais2alias (filename.vdais2alias)

For C4

Import translation

.alias2c4x (filename.alias2c4x)

Export translation

.c4x2alias (filename .c4x2alias )

For NX

Import translation

.alias2unigraphics (filename .alias2unigraphics)

Export translation

.unigraphics2alias (filename .unigraphics2alias)

For JAMA-IS

Import translation

.alias2jamais (filename.alias2jamais)

Export translation

.jamais2alias (filename .jamais2alias)

For Granite

Import translation

.alias2granite (filename .alias2granite )

Export translation

.granite2alias(filename .granite2alias)

For STEP

Import translation

.alias2step (filename.alias2step)

Export translation

.step2alias (filename step2alias)

For CAI

Import translation

.alias2catia (filename.alias2catia)

Export translation

.catia2alias (filename .catia2alias)

For TC VisProducts

Import translation

.alias2jt (filename.alias2jt)

Export translation

.jt2alias (filename.jt2alias)

SAT format

To view STEP log files

  1. Choose Utilities > Errlog to view these messages.

    When retrieval is finished without errors, the following message is displayed:

    STEP files retrieved successfully.

    If there are errors in the retrieval, this message is displayed:

    Problem Reading Step File, refer to log file and/or errlog for details.

    The Alias errlog file and STEP logfile contain a specific error message for each problem entity that is encountered, along with the entity’s STEP ID and type.

Interpreting CATIA translation log files

The translation log file is produced during both import and export of CATIA files. This log file contains entity mappings, entity counts, and Information, Error, and Warning messages.

Interpreting the import log file

On import of a CATIA file, a translation log file is created in the same directory as the CATIA file. The file name of the log file is the same as that of the CATIA file with the extension.catia2alias added to it.

Log file

The log file contains:

  • a translation summary,
  • the time of translation,
  • conversion statistics, and
  • translation time.

If an error or problem occurs while processing an entity, the CATIA entity’s type name, user identifier name, and instance name are printed, followed by the error or warning message.

Extended log file

If you have chosen to have an extended log file produced, then the log file will contain the same information as the log file, with the addition of:

  • CATIA entity name to Alias entity name mapping
  • CATIA entity type to Alias entity type mapping

Interpreting the export log file

On export of a CATIA file, a translation log file is created in the same directory as the CATIA file. The file name of the log file is the same as the CATIA file with the extension .alias2catia added to it.

Log file

If you have chosen to have a log file via the interface options, the log file will contain:

  • a translation summary,
  • the time of translation,
  • conversion statistics, and
  • translation time.

Extended log file

If you have chosen to have an extended log file produced, then the extended log file will contain the same information as the log file with the addition of:

  • product/part contents, and
  • translation time.

Viewing IGES log files

IGES stands for Initial Graphics Exchange Specification. IGES was the first attempt to make a neutral file format. This enables different systems to transfer data without the need of a specific translator for each system.

The first section of an IGES file typically describes the contents of a file. Each line of this section is displayed on the information line.

If there is more than one line in the section, you can browse the contents of the section after file retrieval is complete by using the prompt history window, or by viewing the comments section of the IGES logfile created by the retrieve process.

Open a IGES log file

  1. Choose File > Show Image.

    The Alias errlog file and IGES logfile contain a specific error message for each problem encountered.

    Each error message includes the IGES entity type number and a Directory Section line number where the entity occurs. The errlog file is located at /usr/a1demo/errlog; you can browse it with any UNIX text editor (for example, vi or jot). The IGES logfile is located in the same directory as the retrieved IGES file.

Summary of messages in the IGES logfile

  • IGES file retrieved successfully

    Indicates retrieval is finished.

Identifying IGES supported entities in log files

Learn more about the IGES entities supported on import by Alias.

All other entities with an entity use flag value (Definition) are ignored by the input translator.

Type Form IGES Entity Alias Entity
100 0 circular arc B-spline curve
102 0 composite curve B-spline curves (group)
104 0-3 conic arc B-spline curve
106 1 copious data B-spline curve
106 2 copious data polyline
106 11 copious data polyline
106 12 copious data polyline
106 63 closed area triangle of mesh
108 1 plane face
110 0 line line
112 0 parametric curve B-spline curve
114 0 parametric surface B-spline surface
116 0 point control vertex
118 0-1 ruled surface B-spline surface
120 0 surface of revolution B-spline surface
122 0 tabulated cylinder B-spline surface
124 0 transformation matrix  
126 0-5 rational B-spline curve B-spline curve
128 0-9 rational B-spline surface B-spline surface
130 0 offset curve B-spline curve
140 0 offset surface B-spline surface
141 0 boundary entity trim curve
142 0 curve on surface trim curve
143 0 bounded surface trimmed surface
144 0 trimmed surface trimmed surface
308 0 subfigure definition instance geometry
402 7,16 associativity instance group
408 0 singular subfigure instance instance geometry

IGES levels

All supported geometric IGES entities that are associated with IGES level <n> are added to an Alias layer. For example, if a 126 B-spline entity’s directory entry indicates that it is on level 42, then it is added to Alias as Layer 42.

IGES ASCII format

The IGES translator imports ASCII format IGES files with or without linefeed characters at the end of each record. Binary IGES files are not supported.

NX log files

How to interpret NX log files.

Translation log file

The translation log file is produced during both import and export of NX part files. This log file contains Entity Mappings, Entity Counts, and Information, Error, and Warning messages.

How to interpret an import log file

On import of an NX part file, a translation log file is created in the same directory as the NX part file. The file name of the log file is the same as that of the NX part file with the extension .unigraphics2alias added to it.

Short log file

If you have chosen to use a short log file via the interface options, the log file will contain:

  • the pathname of the importedNX part file and the name of the current Alias stage into which the NX part file is being imported.
  • the contents of the NX part file. This is a table that documents the number of each type of NX entity in the file. This table includes all entities in the NX part file.
  • any information, warning, or error messages that may occur during the translation.

If an error or problem occurs while processing an entity, the NX’s entity’s type name, user identifier name, and instance name are printed, followed by the error or warning message.

Extended log file

If you have chosen to have an extended log file produced, then the log file will contain the same information as the short log file, with the addition of:

  • the Detailed Entity Mapping Report. This report contains a mapping description line for each entity processed.

The mapping description line in an extended import log file contains:

  • the NX entity type name (for example, BsplineSurface)
  • the NX entity’s user id (for example, WHEEL, or <NONE> if the entity does not have a name)
  • the NX entity instance identifier
  • the string converted to, indicating that the following information pertains to the Alias entity
  • the Alias entity type name (for example, Trimmed Surface)
  • the Alias node name (for example, WHEEL or node#50 in the case of a NX entity name of <NONE>).

Interpret an export log file

On export of an NX file, a translation log file is created in the same directory as the NX file. The file name of the log file is the same as the NX file with the extension .alias2unigraphics added to it.

Short log file

If you have chosen to have a short log file via the interface options, the log file will contain:

  • the name of the current Alias stage from which the model was exported (or the name of the Alias Wire file if the command line interface was used) and the pathname of the exported NX file
  • any Information, Warning, or Error messages that may occur during the translation
  • a table that documents the number of each type of Alias entity converted or not converted to an NX entity.

If an error or problem occurs while processing an entity, the Alias entity’s type name and node name are printed, followed by the error or warning message.

Extended log file

If you have chosen to have an extended log file produced, then the log file will contain the same information as the short log file with the addition of:

  • the Detailed Entity Mapping Report which contains a mapping description line for each entity processed.

Interpret an NX translation log

If the log file identifies an error during translation between Alias and NX in either direction, you can trace the information in the error message back to the problem geometry. In some cases once the piece of geometry has been isolated, the nature of the problem will be visually obvious and you will need only to delete or manually fix the surface in question.

(menu locations in this tutorial are based on NX 7.5, programming language is Visual Basic)

Where to start? The best place to start writing a journal is with the journal recorder. This wonder of modern technology will translate your interactions with NX to journal code, in your language of choice! (this article will use Visual Basic, or VB for short). If you are following along, let’s make sure the journal output language is set to VB before we start.

Setting the Journal Programming Language:
In the menu, choosePreferences -> User Interface…; on the Journaltab choose Visual Basic as the language and make sure the Insert Menu/Dialog Box Commentsoption is checked.

Recording the Journal:

For starters, let’s assume you want to change the color of a specified solid body. Start by recording a journal Tools -> Journal -> Record… and specify a file name for your new journal, preferably something that describes its function such as “change_color.vb”. Once the journal recording process starts, you may notice a change in your toolbars and menus. The green marks on the toolbar icons/menu items indicate that journal recording is fully supported by this command; yellow marks indicate the command is partially supported.  

Now that recording is under way, choose Edit -> Object Display… from the menu, pick the solid body of interest, and pick a new display color. OK the changes and then stop the journal recordingTools -> Journal -> Stop recording.

Time to test out the journal. Change the color of the solid body, or perform an Undo to get the original color back; now navigate to Tools -> Journal -> Play… and browse to your new journal file. Select your journal from the list and press the Playbutton. After a short pause, your solid body will change to the color you picked when you recorded the journal.

Understanding the New Journal Code:
Open a Windows file explorer window and browse to your new journal file, open it with a text editor (such as notepad) and take a peek at what goes on behind the scenes. Don’t worry if this looks like mumbo jumbo right now, we’ll step through it to see what is going on.  I created a new file and inserted a block feature, then followed the steps outlined above; here is the resulting journal code:

Option Strict Off
Imports System
Imports NXOpen
 
Module NXJournal
Sub Main
 
Dim theSession As Session = Session.GetSession()
Dim workPart As Part = theSession.Parts.Work
 
Dim displayPart As Part = theSession.Parts.Display
 
' ----------------------------------------------
'   Menu: Edit->Object Display...
' ----------------------------------------------
Dim markId1 As Session.UndoMarkId
markId1 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Start")
 
theSession.SetUndoMarkName(markId1, "Class Selection Dialog")
 
Dim markId2 As Session.UndoMarkId
markId2 = theSession.SetUndoMark(Session.MarkVisibility.Invisible, "Class Selection")
 
theSession.DeleteUndoMark(markId2, Nothing)
 
theSession.SetUndoMarkName(markId1, "Class Selection")
 
theSession.DeleteUndoMark(markId1, Nothing)
 
' ----------------------------------------------
'   Dialog Begin Edit Object Display
' ----------------------------------------------
' ----------------------------------------------
'   Dialog Begin Color
' ----------------------------------------------
Dim markId3 As Session.UndoMarkId
markId3 = theSession.SetUndoMark(Session.MarkVisibility.Visible, "Edit Object Display")
 
Dim displayModification1 As DisplayModification
displayModification1 = theSession.DisplayManager.NewDisplayModification()
 
displayModification1.ApplyToAllFaces = False
 
displayModification1.ApplyToOwningParts = False
 
displayModification1.NewColor = 103
 
Dim objects1(0) As DisplayableObject
Dim body1 As Body = CType(workPart.Bodies.FindObject("BLOCK(0)"), Body)
 
objects1(0) = body1
displayModification1.Apply(objects1)
 
displayModification1.Dispose()
' ----------------------------------------------
'   Menu: Tools->Journal->Stop Recording
' ----------------------------------------------
 
End Sub
End Module

Option Strict Off means the code will allow some types of implicit conversions, but really it isn’t something we’ll need to worry about right now.

Next up are the Imports statements, which import a specified namespace. It is important to note that these statements do not add more functionality to your code (ie they are not analogous to references to external libraries); rather they allow certain declarations to be abbreviated. In addition to NX code, journals are linked by default to certain .NET libraries. These libraries are:

  • mscorlib.dll
  • System.dll
  • System.Windows.Forms.dll
  • System.Drawing.dll

A Module is declared next with the default name of NXJournal. A module is a container where all the code lives, if you skip down to the end of the journal you will see an End Module statement. Any code you add must be between the Module… End Module statements. You can change the module name to something more descriptive if you like, but since there is only one module in our journal, the default name is just fine. The module also determines the scope of variables and code it contains, but this is a topic for another day.

Sub Main is the block of code that gets called when your journal is run. As your journals get longer and more complex, it is helpful to break the code into multiple subroutines and functions and call them as necessary. Sub Main is where the core logic will reside. Every journal must have a Sub Main.

The next 3 lines initialize the session, display part, and work part for us to reference in our journal. Part and Session are classes in NXOpen, these object variables will give us access to other objects in NX.

All of the code we have looked at so far is included in every recorded journal. If you want to start a journal from scratch, including this code is a good idea.

A comment on comments:
A single apostrophe or the keyword rem indicates the start of a comment, the comment continues to the end of the line. Anything contained in the comment will be ignored by the compiler. Comments serve useful functions:

  • They are most often used to document the code. Use comments to explain tricky bits of code or document the input/output requirements of functions and subroutines. Comments are also often used at the beginning of the code file to explain the who when and what: who wrote the program, when they wrote the program, and what problem the code solves or what process the code automates.
  • Comments are also useful in the debugging process. Use comments to temporarily disable a line or entire block of code to try out an alternative solution without having to delete code that may yet prove useful.

Next up in the code, is the creation of a couple of useless undo marks. As you record and modify journals you will find that the journal recorder often throws in extra bits of code. The undo marks, markId1 and markId2, are good examples of this. The undo marks are created, named, renamed, and finally deleted (set to ‘nothing’) ultimately having no effect on the finished journal. If your journal contains similar code, feel free to delete it.

Creating an undo mark is a good way to start a journal as it will allow any changes made by the journal to be undone if necessary. MarkId3 is the real undo mark here. You can see the string “Edit Object Display” as one of the arguments when the id mark is set. This string is what will appear in the undo list after the journal is run. If the undo function is used, the model will roll back to the state it was in when the undo mark was set in code. It is a good idea to set an undo mark before trying to modify features; if there are any errors during the model update, it can roll back to a known state. Multiple undo marks can be set, which comes in handy in larger multi-step journals; changes can be rolled back in chunks rather than an all or nothing approach.

When declaring variables, this is the normal pattern:

Dim [variable name] as [variable type]

so the line:

Dim displayModification1 As DisplayModification

tells the compiler to set aside a block of memory large enough for a DisplayModification object and the name used to refer to it will be displayModification1. A DisplayModification is a temporary helper NX object that assists in changing the display attributes of one or more objects.

Now that we have a display modification object we can set our preferences:

displayModification1.ApplyToAllFaces = False
displayModification1.ApplyToOwningParts = False
displayModification1.NewColor = 103

As you can see, I picked color 103, cornflower blue, as my new object color. At this point our solid body has not yet changed, in fact the journal doesn’t yet know what object(s) these changes are going to apply to. Which brings us to:

Dim objects1(0) As DisplayableObject
Dim body1 As Body = CType(workPart.Bodies.FindObject(«BLOCK(0)»), Body)
objects1(0) = body1

The display modification object requires an array of objects of the type DisplayableObject to work on. The first line creates a 1 element array (arrays are zero based) of DisplayableObjects, line 2 records the solid that I selected (your line of code may be different), and line 3 assigns the body to the array that will be used with the display modification object.

Now that the options are set and the object is specified we can apply our desired changes with

displayModification1.Apply(objects1)

Now that the work is done, we can delete the temporary display modification object and free up the memory it used by calling its Dispose method:

displayModification1.Dispose()

At this point the journal exits and we can see the results in the modeling window. However, should you try to run this journal in a different file you would be met with an error message.

Hand Editing the Journal:
The reason that the journal in its current state will end in a error message when applied to a different file is that your journal is looking for the exact solid that you selected when the journal was recorded. This behavior is referred to as ‘selection stickiness’ and its removal is one of the main reasons for hand-editing journal code. You can greatly increase the usefulness of your code by replacing the hard coded reference to a specific object with a more general selection routine.

Below you will find the same script without the useless undo marks and with the selection stickiness removed.  This journal can now be used on various files to change the selected solid body’s color.

Option Strict Off
 
Imports System
Imports NXOpen
Imports NXOpen.UF
Imports NXOpenUI
 
Module NXJournal
Sub Main
 
Dim theSession As Session = Session.GetSession()
Dim workPart As Part = theSession.Parts.Work
Dim displayPart As Part = theSession.Parts.Display
Dim ufs As UFSession = UFSession.GetUFSession()
 
Dim markId3 As Session.UndoMarkId
markId3 = theSession.SetUndoMark(Session.MarkVisibility.Visible, "Edit Object Display")
 
Dim displayModification1 As DisplayModification
displayModification1 = theSession.DisplayManager.NewDisplayModification()
displayModification1.ApplyToAllFaces = False
displayModification1.ApplyToOwningParts = False
displayModification1.NewColor = 103
 
Dim objects1(0) As DisplayableObject
'Dim body1 As Body = CType(workPart.Bodies.FindObject("BLOCK(0)"), Body)
Dim body1 As Body = SelectSolid()
objects1(0) = body1
displayModification1.Apply(objects1)
displayModification1.Dispose()
 
End Sub
 
Function SelectSolid() As Body
 
    Dim ui As UI = ui.GetUI
    Dim message As String = "Select solid body"
    Dim title As String = "Selection"
 
    Dim scope As Selection.SelectionScope = Selection.SelectionScope.WorkPart
    Dim keepHighlighted As Boolean = False
    Dim includeFeatures As Boolean = True
 
    Dim selectionAction As Selection.SelectionAction = _
       Selection.SelectionAction.ClearAndEnableSpecific
 
    Dim selectionMask_array(0) As Selection.MaskTriple
    With selectionMask_array(0)
       .Type = UFConstants.UF_solid_type
       .Subtype = 0
       .SolidBodySubtype = UFConstants.UF_UI_SEL_FEATURE_SOLID_BODY
    End With
 
    Dim selectedObject As NXObject = Nothing
    Dim cursor As Point3d
 
    ui.SelectionManager.SelectObject(message, title, scope, _
                                    selectionAction, includeFeatures, _
                                    keepHighlighted, selectionMask_array, _
                                    selectedObject, cursor)
 
    Dim solid As Body = CType(selectedObject, Body)
 
    If solid Is Nothing Then
       Return Nothing
    End If
 
    Return solid
 
End Function
 
End Module

Download the code.

Recap:
In review you can see how we can use NX Journal to create a basic journal designed to change the color of a solid body.  Then we evaluated the code generated by the journal recorder and modified the code to be of broader use with just a few hand coded manipulations. The resulting journal can now change the body color of any part.

Objectives:
We learned how to record a journal. How to interpret the code behind the NX Journal and how to adjust the code to allow a journal to be useful across multiple files.

Одним из способов автоматизации работы в Siemens NX является написание программ или журнала при помощи библиотеки NX Open. Часто бывает так: сначала записывается файл журнала, а затем из него убирается все лишнее и оставшийся код копируется в приложение. Можно просто запустить журнал, записанный ранее и ничего не компилировать. Рассмотрим создание атрибута детали в NX.

NX Open - Создание атрибута детали

NX Open — Начальный фрагмент журнала. Пространства имен System и NXOpen, объявление класса NXJournal и переменных для сессии, рабочей и отображаемой детали в методе Main.

Записать журнал: Меню — Инструменты — Журнал — Запись

При записи журнала, на кнопках и меню NX отображаются зеленые и желтые маркеры. Не все действия могут быть записаны в журнал. То, что записывается полностью, отмечено зелеными маркерами.

Установить язык записи журнала (перед созданием): Меню — Настройки — Интерфейс пользователя — Инструменты — Журнал

Приведенный ниже журнал записан на C#. Есть варианты: С++, Java, Python и Visual Basic.

Запустить журнал: Alt+F8, либо Меню — Инструменты — Журнал — Воспроизведение

Файл журнала — это обычный текстовый файл, лучше его открывать редактором с подсветкой синтаксиса (например, Notepad++).

Справка по 10, 11 и 12 версии NX доступна на официальном сайте Siemens PLM (русский, английский). По программированию для NX 10 информация здесь (английский). В системе онлайн-справки некоторые ссылки завязаны на всплывающие окна, которые у большинства нормальных пользователей заблокированы. Иногда приходится единично допускать открытие окон (в Mozilla можно). Кроме того, справка по составу API распространяется в формате chm. При скачивании этого файла, в Windows 7 может потребоваться его разблокировать: ПКМ на файле — Свойства — Вкладка «Общие» — нажать кнопку «Разблокировать». Иначе пишет «Переход на веб-страницу отменен».

Дополнительно, материал по программированию в NX Open есть в пособии Getting Started with NX Open здесь (английский). Пособие новое, поэтому  пространства имен Guide с функциями-помощниками в 10 версии NX нет. Для вывода информации в текстовое окно можно воспользоваться стандартным ListingWindow.

Журнал для установки атрибута «АТР» со значением 23

Приводится журнал, из которого удалены лишние строки, возникающие при записи интерактивной сессии. Для запуска, скопировать в текстовый файл, сохранить с расширением cs, далее создать в NX новую модель и запустить журнал при помощи комбинации Alt+F8 (выбрать тип файла cs, по дефолту всегда vb). Щелкнув ПКМ на модели в дереве навигатора сборки, в свойствах можно найти созданный атрибут.

using System;
using NXOpen;
public class NXJournal
{
 public static void Main(string[] args)
 {
 NXOpen.Session theSession = NXOpen.Session.GetSession();
 NXOpen.Part workPart = theSession.Parts.Work;
 NXOpen.Part displayPart = theSession.Parts.Display;
 // Целевые объекты для задания атрибута с именем "АТР".
 NXOpen.NXObject[] objects1 = new NXOpen.NXObject[1];
 objects1[0] = workPart;
 // Объявление переменной и вызов конструктора для объекта AttributePropertiesBuilder
 NXOpen.AttributePropertiesBuilder attributePropertiesBuilder1;
 attributePropertiesBuilder1 = theSession.AttributeManager.
 CreateAttributePropertiesBuilder(workPart, objects1,
 NXOpen.AttributePropertiesBuilder.OperationType.None);
 // Общие параметры конструктора атрибутов.
 attributePropertiesBuilder1.IsArray = false;
 attributePropertiesBuilder1.DataType = NXOpen.AttributePropertiesBaseBuilder.
 DataTypeOptions.String;
 attributePropertiesBuilder1.Units = "MilliMeter";
 attributePropertiesBuilder1.SetAttributeObjects(objects1);
 attributePropertiesBuilder1.Title = "АТР";
 attributePropertiesBuilder1.StringValue = "23";
 // Создание атрибута.
 bool changed1;
 changed1 = attributePropertiesBuilder1.CreateAttribute();
 NXOpen.NXObject nXObject1;
 nXObject1 = attributePropertiesBuilder1.Commit();
 // Деструктор объекта.
 attributePropertiesBuilder1.Destroy();
 }
 public static int GetUnloadOption(string dummy) 
 { 
 return (int)NXOpen.Session.LibraryUnloadOption.Immediately; 
 }
}

Объектная модель NX Open

Оригинал документа здесь (английский).

TaggedObject — базовый класс для элементов модели NX (линия, вытягивание, рабочая деталь). Теговый объект. Класс определяет т.н. persistent entities, т.е. такие объекты, которые сохраняются после завершения работы c NX (при сохранении измененной модели). В некоторых случаях, объекты этого класса представляют собой несохраняемые элементы. У объектов TaggedObject есть тег, используемый при взаимодействии с UF API.

В противовес этому типу есть класс TransientObject не сохраняемые объекты. У них нет тега и для них есть метод-деструктор Dispose(). При программировании на языках со сборщиками мусора, для таких объектов деструктор вызывается автоматически.

NXObject — наследник TaggedObject. Класс определяет методы и свойства для установки и чтения имен и атрибутов элементов модели NX.

TaggedObjectCollection — базовый класс для классов, представляющих коллекцию объектов TaggedObject. Как правило, в состав этих классов дополнительно входят методы по созданию новых теговых объектов. В приведенном коде, из коллекции деталей в сессии происходит выбор рабочей детали и детали отображаемой:

NXOpen.Part workPart = theSession.Parts.Work;
NXOpen.Part displayPart = theSession.Parts.Display;

Классы Session и UI служат шлюзом для классов API. Ссылки на все объекты в составе API берутся напрямую или посредством методов или свойств этих двух классов. Класс UI доступен только в случае работы программы в пределах интерфейса NX, в пакетном режиме не доступен.

Part является классом детали NX. Содержит множество коллекций TaggedObjectCollection. Элемент построения модели в NX называется feature. Коллекции таких элементов содержатся в каждом экземпляре TaggedObjectCollection внутри объекта класса Part. Коллекции используются для получения объектов класса FeatureBuilder при создании или изменении элементов построения. В нашем случае, Builder создается менеджером атрибутов, а не коллекцией.

Builder. Элементы построения модели и другие объекты создаются и редактируются при помощи объектов класса Builder. Для создания объекта, вызывается метод Commit(). По завершении работы объекта Builder следует вызывать метод Destroy().

Атрибуты детали и атрибуты компонента

Как известно, в NX атрибуты можно задавать для детали и для компонента (которые есть только в рамках сборки). Приведенный код устанавливает атрибут детали. Применимость атрибута определяется тем, какой аргумент передается в качестве целевого массива экземпляров NXObject в функцию CreateAttributePropertiesBuilder. Это второй аргумент. Если в приведенном коде строки 10,11 и 12 заменить на следующие, то будет задан атрибут для компонента, а именно для первого компонента сборки:

NXOpen.Assemblies.Component[] allComps = workPart.
ComponentAssembly.RootComponent.GetChildren();
// Целевые объекты для задания атрибута с именем "АТР".
NXOpen.NXObject[] objects1 = new NXOpen.NXObject[1];
objects1[0] = allComps[0];

INTELLIGENT WORK FORUMS
FOR ENGINEERING PROFESSIONALS

Contact US

Thanks. We have received your request and will respond promptly.

Log In

Come Join Us!

Are you an
Engineering professional?
Join Eng-Tips Forums!

  • Talk With Other Members
  • Be Notified Of Responses
    To Your Posts
  • Keyword Search
  • One-Click Access To Your
    Favorite Forums
  • Automated Signatures
    On Your Posts
  • Best Of All, It’s Free!

*Eng-Tips’s functionality depends on members receiving e-mail. By joining you are opting in to receive e-mail.

Posting Guidelines

Promoting, selling, recruiting, coursework and thesis posting is forbidden.

Students Click Here

NX log file

NX log file

(OP)

27 Jul 20 17:10

Hi all,

I have a large assembly part (NX11 Native), and the parent takes a very long time to load (even with no components) for no apparent reason.

I seem to recall that its possible to turn on additional NX log file logging via some environment variables.

Does anybody recall what the variables are?

Thanks in advance,

B.

Red Flag Submitted

Thank you for helping keep Eng-Tips Forums free from inappropriate posts.
The Eng-Tips staff will check this out and take appropriate action.

Resources

Low-Volume Rapid Injection Molding With 3D Printed Molds

Learn methods and guidelines for using stereolithography (SLA) 3D printed molds in the injection molding process to lower costs and lead time. Discover how this hybrid manufacturing process enables on-demand mold fabrication to quickly produce small batches of thermoplastic parts. Download Now

Design for Additive Manufacturing (DfAM)

Examine how the principles of DfAM upend many of the long-standing rules around manufacturability — allowing engineers and designers to place a part’s function at the center of their design considerations. Download Now

Industry Perspective: Education and Metal 3D Printing

Metal 3D printing has rapidly emerged as a key technology in modern design and manufacturing, so it’s critical educational institutions include it in their curricula to avoid leaving students at a disadvantage as they enter the workforce. Download Now

Taking Control of Engineering Documents

This ebook covers tips for creating and managing workflows, security best practices and protection of intellectual property, Cloud vs. on-premise software solutions, CAD file management, compliance, and more. Download Now

Join Eng-Tips® Today!

Join your peers on the Internet’s largest technical engineering professional community.
It’s easy to join and it’s free.

Here’s Why Members Love Eng-Tips Forums:

  • Eng-Tips ForumsTalk To Other Members
  • Notification Of Responses To Questions
  • Favorite Forums One Click Access
  • Keyword Search Of All Posts, And More…

Register now while it’s still free!

Already a member? Close this window and log in.

Join Us             Close

Предложите, как улучшить StudyLib

(Для жалоб на нарушения авторских прав, используйте

другую форму
)

Ваш е-мэйл

Заполните, если хотите получить ответ

Оцените наш проект

1

2

3

4

5

Понравилась статья? Поделить с друзьями:
  • Siemens micromaster ошибка f231
  • Siemens micromaster 440 ошибка f0090
  • Siemens micromaster 440 ошибка f0022
  • Siemens micromaster 440 ошибка f0015
  • Siemens micromaster 440 ошибка f0003