option explicit

!INC Local Scripts.EAConstants-VBScript

'
' Example illustrating how to add and delete Elements in a Package. 
' 
' NOTE: Requires a package to be selected in the Project Browser
' 
' Related APIs
' =================================================================================
' Element API - http://www.sparxsystems.com/enterprise_architect_user_guide/12.1/automation_and_scripting/element2.html
'
sub ManageElementsExample()

	' Show the script output window
	Repository.EnsureOutputVisible "Script"
	
	' Get the currently selected package in the tree to work on
	dim thePackage as EA.Package
	set thePackage = Repository.GetTreeSelectedPackage()
		
	if not thePackage is nothing and thePackage.ParentID <> 0 then
	
		dim i, testElementID
	
		Session.Output( "VBScript MANAGE ELEMENTS EXAMPLE" )
		Session.Output( "=======================================" )
		Session.Output( "Working on package '" & thePackage.Name & "' (ID=" & _
			thePackage.PackageID & ")" )
		
		dim elements as EA.Collection
		set elements = thePackage.Elements
		
		' Create a new element in the package
		dim testElement as EA.Element
		set testElement = elements.AddNew( "Login to Website", "UseCase" )
		testElement.Stereotype = "testcase"
		testElement.Update()
		thePackage.Elements.Refresh()
		
		testElementID = testElement.ElementID
		Session.Output( "Added Element: " & testElement.Name & " (ID=" & testElementID & ")" )
		
		set testElement = nothing

		' Navigate the elements collection. Delete the newly added element when we find it
		for i = 0 to elements.Count - 1
			dim currentElement as EA.Element
			set currentElement = elements.GetAt( i )
			
			Session.Output( "Element: " & currentElement.Name )
			
			' If the element is the one we just added, then delete it
			if currentElement.ElementID = testElementID then
				elements.DeleteAt i, false
				Session.Output( "Deleted Element: " & currentElement.Name )
			end if
		next

		Session.Output( "Done!" )
		
	else
		' No package selected in the tree
		MsgBox( "This script requires a package to be selected in the Project Browser." & vbCrLf & _
			"Please select a package in the Project Browser and try again." )
	end if


end sub

ManageElementsExample
