# Event Scripts The configuration files of powerEvents consist of different sample event [Scripts](#scripts) and [Modules](#modules) that are used to demonstrate the automation processes when working with the Vault Client.\ You can access these directories using the *powerEvents Configuration* shortcut on the desktop or the Start Menu.\ Since powerEvents is a *IWebServiceExtension* its event scripts will be *executed in every application* that uses the *Autodesk.Connectivity.WebServices.dll*: - [powerVault](powervault:index) - [powerJobs Processor](powerjobs_processor:index) - AutoLoader - Vault - Inventor - JobProcessor - AutoCAD ```{note} Keep in mind, that code in the scripts that is executed *without being registered*, provides no connection to the Vault.\ Therefore the usage of Cmdlets from [powerVault](powervault:code_reference/commandlets) is limited.\ In other words: A connection to the Vault is given in the script only after your [registered](/code_reference/commandlets/register-vaultevent) event was triggered. ``` ## Scripts All the event scripts delivered from coolOrange start with the name '*Sample.*'. Their purpose is to help people getting started with the creation of their own powerEvent scripts.\ The goal of the provided samples is to be useful and easy to configure for common scenarios. ```{image} img/powerevents_ise.png :align: right :width: 250px ``` Following sample scripts are located in the directory *%PROGRAMDATA%\\coolOrange\\powerEvents\\Events*: - Sample.SubmitPublishingJobsOnRelease.ps1 - Sample.RestrictDisturbingSubmittedJobs.ps1 - Sample.ValidateProperties.ps1 When creating your own scripts, we recommend duplicating the sample scripts and modifying them with your customizations.\ Restarting your application is not required in this case because all the event scripts and [Modules](#modules) are [automatically reloaded]() by default. In order to get started with creating a custom script either open any powershell IDE or open the *powerEvents ISE* shortcut in the start menu, which already opens one of the [sample event scripts](#sample-submitpublishingjobsonrelease).\ Import the Module by calling {code}`Import-Module powerEvents`. ### Sample.SubmitPublishingJobsOnRelease This sample makes use of the [UpdateFileStates](/code_reference/objects/event_mappings/file_events/updatefilestates) event which gets triggered when the lifecycle state of a file changes. The script registers to the **Post Event**: - It iterates over the changed files and picks the ones which are in a *Released State*. - The script then differentiates between Inventor- and AutoCAD drawings (file extension: *idw* and *dwg* respectively) and sheet metal parts (file extension: *ipt*). - For drawings, a job of type "*Sample.CreatePDF*", which publishes PDF files is added to the queue. - For sheet metal parts, a job of type "*Sample.CreateDXF&STEPfromSheetmetal*", which publishes DXF and STEP files is added to the queue. - To identify sheet metal parts, the script validates the Vault user defined property {code}`Document SubType`.\ The property must contain the value *Sheet Metal* (english environments) or *Blech* (german environments).\ If the property is not available for the current file a warning is logged and the file will be skipped.\ If the property is not configured at all or is not mapped correctly, the event will throw an exception and terminate. Therefore, make sure the Vault is [configured] correctly. **Settings**\ Important settings like the event re- and unregistration, the type (name) of the PDF- and DXF+STEP jobs, the name of the Vault property which holds the information about sheet metal\ and the priority for which the various jobs should be triggered are located in the first lines of the job so that they can be easily changed: ```powershell # To enable/disable the automatic submitting of publishing jobs comment/un-comment the following line. #Register-VaultEvent -EventName UpdateFileStates_Post -Action 'SubmitPublishJobs' # Define the type (name) of the job which is triggered for publishing PDF files. $pdfJobType = "Sample.CreatePDF" # Define the type (name) of the job which is triggered for publishing STEP+DXF files for sheet metal parts. $dxfAndStepJobType = "Sample.CreateDXF&STEPfromSheetmetal" # Specify the name of the Vault user defined property (UDP), which holds the information whether a part is a Sheet Metal. This property must be mapped to the Inventor iProperty 'Doc Sub Type Name'. $subTypePropertyName = "Document SubType" # Set the priority with which the publishing jobs will be queued. The default is 101 to guarantee that other automtically triggered jobs (e.g. "Autodesk.Vault.SyncProperties") are executed before. $jobPriority = 101 ``` **Testing** The script can be tested by doing the following steps: 1. Open the Vault Client 2. Navigate to a file which is either a Inventor- or AutoCAD drawing or a sheet metal part. 3. Change the Lifecycle State to a released state (e.g. from *Work in Progress* to *Released*). 4. Open the Job Queue. 5. The Job Queue contains a publishing job for the changed file. Out of the box the event registration for this script is disabled, therefore you have to enable it by un-commenting the following lines in the settings section: ```PowerShell #Register-VaultEvent -EventName UpdateFileStates_Post ... ``` (configured)= **Vault Configuration** The Vault environments must be configured correctly so that this event script is fully functioning.\ In order to identify sheet metal parts (to trigger DXF+STEP publishing jobs) a Vault UDP (User defined property) must be configured which handles the differentiation between certain document types (i.e. Sheet Metal or regular parts, Weldments or regular Assemblies).\ The name of this propery can be configured in the settings section of the *Sample.CreateDXF& STEPfromSheetmetal* script and is by default {code}`Document SubType`.\ The User Defined Property must be mapped to the Inventor iProperty {code}`Document Sub Type Name`, which returns the required information. To configure the required mapping simply create a new UDP and map it to the Inventor iProperty *Document SubType Name*.\ Navigate to *Tools -> Administration -> Vault Settings -> Behaviours tab -> Properties -> New*\ Define the name for the new UDP (e.g. *Document SubType*) and associate the property with the relevant categories, so it will be automatically listed in the properties panel. ```{image} img/vault-inventor_mapping.png :width: 700px ``` Then got to the *Mappings* tab and define the new mappings. ```{image} img/vault-inventor_mapping_2.png :width: 700px ``` Result ```{image} img/DocSubTypeName.png :width: 350px ``` Autodesk Knowledge Tutorial: [Mapping Inventor iProperty to Vault user defined property](https://knowledge.autodesk.com/support/inventor/learn-explore/caas/screencast/Main/Details/5e4a9bf8-496d-46cb-9090-799c50e32039.html) ### Sample.RestrictDisturbingSubmittedJobs Autodesk Vault environments give users the possibility to submit Jobs while they work with their files, but they are not always processed immediately.\ As a result, it often happens that they either fail or don't produce the expected results if users continue to work with their files in Vault. To prevent these problems, this event script helps for example in the following situations: * When new file versions are created after jobs have been submitted for that file, many Autodesk jobs simply fail.\ A common error that you can then see is e.g. ["Sync properties not allowed on non-tip versions"](https://knowledge.autodesk.com/support/vault-products/learn-explore/caas/CloudHelp/cloudhelp/2022/ENU/Vault-Admin/files/GUID-CDD7E780-3322-4560-AA31-43025A845824-htm.html).\ Autodesk recommends "Administrators can ignore, delete, or filter out this type of error."\ \ **Solution:**\ So that it doesn't even come to the situation that all the jobs fail and fill up the Job Queue, Vault users can also be informed and restricted from creating new file versions, as long as there are still open jobs in the Job Queue. - If [powerJobs Processor jobs]() have been queued at certain lifecycle transitions, such as releases, and in the meantime the status of the file has been reset or changed (e.g. to "Work in Progress") then many Vault users forget about their still open jobs within the Job Queue.\ By default those jobs will be executed for the latest file version, and newly created visualization files may contain incorrect data (e.g. State) and are not attached to the released file version.\ \ **Solution:**\ To prevent this from happening, Vault users can also be prevented from changing the file status if jobs must be processed beforehand. Therefore this sample script registers to the [UpdateFileStates](/code_reference/objects/event_mappings/file_events/updatefilestates) event and adds **Restrictions** when the lifecycle state of a file changes, while jobs were queued for it.\ This way Lifecycle transitions are prevented for all files, for which jobs have been submitted and have not yet been processed successfully. **Testing** The script can be tested by following these steps: 1. Pause all active Job Processors during the test to ensure that the queued Synchronize Properties job will not be processed upfront. 2. Open the Vault Client. 3. Make sure the action ["Synchronize properties using Job Server](https://knowledge.autodesk.com/support/vault-products/learn-explore/caas/CloudHelp/cloudhelp/2022/ENU/Vault-Admin/files/GUID-4D34EE99-3A58-4EDD-BD76-BD99C232E90A-htm.html?st=job%20update%20view) is enabled for a desired Lifecycle transition to a "Released" state. 4. Navigate to an Inventor- or AutoCAD file and change its Lifecycle State to the previously configured "Released" state 5. Open the Job Queue and make sure that a *"Autodesk.Vault.SyncProperties"* job has been automatically submitted for the released file version. 6. Change the Lifecycle State of the seleted file again to any other state. 7. A restriction dialog appears and informs about the still active Synchronize Properties job, which would fail if a new file version gets created. By default this event script is disabled and it must be enabled by un-commenting the following line: ```PowerShell #Register-VaultEvent -EventName UpdateFileStates_Restrictions ... ``` ### Sample.ValidateProperties This sample script registers to the UpdateStates events for all entity types: [File](/code_reference/objects/event_mappings/file_events/updatefilestates), [Item](/code_reference/objects/event_mappings/item_events/updateitemstates), [CustomEntity](/code_reference/objects/event_mappings/customentity_events/updatecustomentitystates) and [ChangeOrder](/code_reference/objects/event_mappings/changeorder_events/updatechangeorderstate).\ The event is triggered when the lifecylce state of an entity is changed. In our example we make use of the **Restrictions event**: - In the Restrictions event we check if the state is about to be changed to Released or in case of a ChangeOrder to Closed. - We also check if the user who is changing the state is the same who last modified the entity. If one of these rules is violated a *restriction* will be set. **Testing** The script can be tested by doing the following steps: 1. Open the Vault Client 2. Navigate to an Item, File, or Custom Entity which can be released and was last modified by another Vault user. 3. Change the Lifecycle State to "Released". 4. A restriction dialog appears telling that the Lifecycle State of the entity can't be changed by another user. In the default delivery the event registration for this script is disabled, therefore you will have to enable it by uncommenting following lines: ```PowerShell #Register-VaultEvent -EventName UpdateFileStates_Restrictions ... #Register-VaultEvent -EventName UpdateItemStates_Restrictions ... #Register-VaultEvent -EventName UpdateCustomEntityStates_Restrictions ... #Register-VaultEvent -EventName UpdateChangeOrderState_Restrictions ... ``` ## Modules Currently only the *Common.psm1* powerShell script module is delivered and installed in the powerEvents module directory *%ProgramData%\\coolOrange\\powerEvents\\Modules*. The module provides the **\$processName** variable which is available in all event scripts.\ This variable returns the name of the process in which the script is currently executed.\ The global flag **\$powerEvents_ReloadPsScripts** can be used to enable/disable the [automatic script reloading](/code_reference/objects/host:automatic script reloading): ```PowerShell $global:powerEvents_ReloadPsScripts = $false ``` ## Errors powerEvents handles errors that occur when executing event [Scripts](#scripts) and [Modules](#modules) during application startup.\ In this case the user is [notified](/code_reference/objects/host:error notifications) because his configured processes might not be executed successfully, because of missing event registrations.\ Even if the execution of one event script fails, this has no effect on other scripts as they are executed independently. When a [registered Vault event](/code_reference/commandlets/register-vaultevent) gets raised and an *exception* is thrown within the action, then an Error Message Box will be shown.\ This happens every time an event is triggered by a Vault API method and has no effect on any other registered Vault events as they will still be executed. In order to raise exceptions manually you can use Powershell's [throw](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_throw?view=powershell-6) keyword in your event scripts and you can handle them by using *try/catch blocks*: ```PowerShell Register-VaultEvent -EventName EditItems_Pre -Action { try { $vault.ItemService.EditItems($null) } catch { throw "A null value was passed in where a null value is not allowed (Vault error code: 155)." } } ``` Details of the failed event execution are displayed in an Error Message Box directly after the powerShell execution terminates. ```{image} img/messagebox_exception.png :width: 1000px ``` The same details and all the Warnings and Errors that where logged during the event execution can be found in the [logfile](). The event script execution continues for [Non-Terminating Errors](https://docs.microsoft.com/en-us/powershell/scripting/developer/cmdlet/non-terminating-errors) by default.\ For changing this PowerShell error handling behavior *globally*, the variable *\$ErrorActionPreference* can be changed to 'Stop' in order to terminate the event script executing even for such errors: ```PowerShell $ErrorActionPreference = "Stop" ``` In case a Vault operation aborts because a *Vault Server Error Code* was returned the according [Post event]() can make use of the `$successful` variable in order to check if the underlying Vault Web Service call was successful or not. ```PowerShell Register-VaultEvent -EventName EditItems_Post -Action { param( $items, $successful) if(-not $successful) { return } #... } ```