Announcements
Attention for Customers without Multi-Factor Authentication or Single Sign-On - OTP Verification rolls out April 2025. Read all about it here.

Need help to make a better code ( purge & update ) with ilogic

Darkforce_the_ilogic_guy
Advisor

Need help to make a better code ( purge & update ) with ilogic

Darkforce_the_ilogic_guy
Advisor
Advisor

I have a good the purge og update Drawing and part and assembly. 

 

My current code is this 

Sub Main()
	Dim currentDocPath2
	currentDocPath2 = ""
	Try 
		 currentDocPath2 = ThisDoc.PathAndFileName(False)
		Logger.Info("er gemt i " &  currentDocPath)
Logger.Info("Er gemt før")

		Catch
			Exit Sub
		End Try
		Logger.Info("Se om den lægge i factory mappen", "Title")

		Logger.Info("er gemt i " &  Left(currentDocPath2, 40))
	If Left(currentDocPath2, 40) = "C:\Working Folder\Designs\Factory Models" Then
	Logger.Info("Factory model ")

Exit Sub
End If 

 If Left(currentDocPath2, 40) = "C:\Working Folder\Designs\Factory Assets" Then
Logger.Info("Factory Assets")

Exit Sub
Else
	Logger.Info("Kør purge og Update Style")

	UpdateStyle3d
	PurgeStyle3d
	End If
		
	
End Sub

Sub UpdateStyle3d()'Try
Logger.Info("update")

Dim oCM As CommandManager
     oCM = ThisApplication.CommandManager
    Dim oCD As ControlDefinitions
     oCD = oCM.ControlDefinitions
    Dim oUpdateStyles As ControlDefinition
     oUpdateStyles = oCD.Item("PurgeStylesCmd")
    oUpdateStyles.Execute2 (False)
    AppActivate(ThisApplication.Caption)
	
	'SendKeys.Send("y")
	SendKeys.SendWait("y" & "{Enter}")
   ' SendKeys.Send("{Enter}")
    
    ThisApplication.UserInterfaceManager.DoEvents
	 ThisApplication.UserInterfaceManager.DoEvents
	'Catch
		Logger.Info("fejl")

	'End Try
	
End Sub


Sub PurgeStyle3d()'Try
Logger.Info("Purge")

Dim oCM As CommandManager
     oCM = ThisApplication.CommandManager
    Dim oCD As ControlDefinitions
     oCD = oCM.ControlDefinitions
    Dim oUpdateStyles As ControlDefinition
     oUpdateStyles = oCD.Item("UpdateStylesCmd")
    oUpdateStyles.Execute2 (False)
    AppActivate(ThisApplication.Caption)
	
	'SendKeys.Send("y")
	SendKeys.SendWait("y" & "{Enter}")
   ' SendKeys.Send("{Enter}")
    
    ThisApplication.UserInterfaceManager.DoEvents
	 ThisApplication.UserInterfaceManager.DoEvents
	'Catch
		Logger.Info("fejl")

	'End Try
	
End Sub

 

This code have at less 2 problem .. You can´t do anything else .. or it will fail to press the yes buttom.  Second when in the factory  design utilties it calcel  if you try to puclich an Assets. 

 

 

The first code I made did not seens to have this problem , but if only wrong on drawing  and only dated it .  Can anyone help make a code that does not have this problem ? and both Purge and update , iam , ipt and idw ?

 

Dim oTargetDoc, oSourceDoc As DrawingDocument
oTargetDoc = ThisDrawing.Document
oStyles = oTargetDoc.StylesManager.Styles
	For Each oStyle In oStyles
		If oStyle.UpToDate = False Then
			oStyle.UpdateFromGlobal()
		End If
	Next

 

 

 

 

 

 

 

0 Likes
Reply
633 Views
9 Replies
Replies (9)

Michael.Navara
Advisor
Advisor

Usage of ControlDefinition.Execute() and SendKeys is the last chance, how to solve the task (emergency break).

This code sample purges styles in drawing document. Similar method can be used to purge another styles and materials in models.

I hope it helps

 

Dim drw As DrawingDocument = ThisDoc.Document
Dim styleDeleted As Boolean
Do
	someStyleDeleted = False
	Dim i As Integer = 1
	Do

		Dim s As Style = drw.StylesManager.Styles(i)
		If s.InUse Or s.StyleLocation = StyleLocationEnum.kLibraryStyleLocation Then
			i += 1
		Else
			Dim msg = s.Name
			Try
				s.Delete()
				someStyleDeleted = True
			Catch
				msg = msg & " Not deleted"
				i += 1
			End Try
			Logger.Debug(msg)
		End If

	Loop While drw.StylesManager.Styles.Count >= i
Loop While someStyleDeleted
Logger.Info("Done")

 

 

Darkforce_the_ilogic_guy
Advisor
Advisor

Well by combine your code and my old code it seens to work on Drawing(idw).  but I still need somthing that work at iam or ipt files 

'' Work on Drawing

' Update style 

Dim oTargetDoc, oSourceDoc As DrawingDocument
oTargetDoc = ThisDrawing.Document
oStyles = oTargetDoc.StylesManager.Styles
	For Each oStyle In oStyles
		If oStyle.UpToDate = False Then
			oStyle.UpdateFromGlobal()
		End If
	Next
	
	
	
	'Purge Style
Dim drw As DrawingDocument = ThisDoc.Document
Dim styleDeleted As Boolean
Do
	someStyleDeleted = False
	Dim i As Integer = 1
	Do

		Dim s As Style = drw.StylesManager.Styles(i)
		If s.InUse Or s.StyleLocation = StyleLocationEnum.kLibraryStyleLocation Then
			i += 1
		Else
			Dim msg = s.Name
			Try
				s.Delete()
				someStyleDeleted = True
			Catch
				msg = msg & " Not deleted"
				i += 1
			End Try
			Logger.Debug(msg)
		End If

	Loop While drw.StylesManager.Styles.Count >= i
Loop While someStyleDeleted
Logger.Info("Done")

 

 

I have try to change DrawingDocument to Ducument and ThisDrawing.Document to ThisDoc.Dument .. it still work on a 2d(idw) but still Fail on ipt ...( have not test on iam jet)... any idear on a code that do the same on Ipt and iam ?

0 Likes

WCrihfield
Mentor
Mentor

Hi @Darkforce_the_ilogic_guy.  Updating documents in general can be a pretty big task, depending on the extent you want to take it.  Especially for drawings.  Each document type has different types of things that you may (or may not) be able to update and/or purge.  And there is often a different process that you have to use handle each type.  Things like drawing document styles, model document LightingStyles, and model document text styles offer a built-in UpdateFromGlobal method you can use for updating them.  But things like materials and appearances are a different story.  They are an Asset object, which has the IsUsed property, and a IsReadOnly property, but no UpdateFromGlobal method.  So for now, because the code below is already so long, I am just purging unused Assets from model documents.  However, you can make a longer, more complex routine for that situation if you wanted.  In that routine, after purging unused Assets, you could also try copying the original from the library to the document using the CopyTo method, with the option 'ReplaceExisting' set to True.  I have made each process its own Sub routine, so that they could be reused within something like a 'Straight VB' external rule that can be referenced.

Here is the code:

Sub Main
	Dim oDoc As Document = ThisDoc.Document
	Dim oDocType = oDoc.DocumentType
	If oDocType = DocumentTypeEnum.kDrawingDocumentObject Then
		UpdateAllDrawingStyles(oDoc)
		PurgeAllUnusedDrawingStyles(oDoc)
	ElseIf oDocType = DocumentTypeEnum.kPartDocumentObject Then
		UpdateAndPurgeLightingStyles(oDoc)
		UpdateAndPurgeTextStyles(oDoc)
		PurgeUnusedAssets(oDoc)
	ElseIf oDocType = DocumentTypeEnum.kAssemblyDocumentObject Then
		UpdateAndPurgeLightingStyles(oDoc)
		UpdateAndPurgeTextStyles(oDoc)
		PurgeUnusedAssets(oDoc)
	End If
End Sub

Sub UpdateAllDrawingStyles(oDrawingDoc As DrawingDocument)
	If IsNothing(oDrawingDoc) Then Exit Sub
	Dim oStyles As Inventor.Styles = oDrawingDoc.StylesManager.Styles
	For Each oStyle As Inventor.Style In oStyles
		If oStyle.InUse And oStyle.UpToDate = False Then
			Try
				oStyle.UpdateFromGlobal
			Catch oEx As Exception
				'Logger.Error("Error updating style named '" & oStyle.Name & "'.")
			End Try
		End If
	Next
	oDrawingDoc.Update2(True)
End Sub

Sub PurgeAllUnusedDrawingStyles(oDrawingDoc As DrawingDocument)
	If IsNothing(oDrawingDoc) Then Exit Sub
	Dim oStyles As Inventor.Styles = oDrawingDoc.StylesManager.Styles
	For Each oStyle As Inventor.Style In oStyles
		If oStyle.InUse Or
			oStyle.StyleLocation = StyleLocationEnum.kLibraryStyleLocation Then
			Continue For
		End If
		Try
			oStyle.Delete
		Catch oEx As Exception
			'Logger.Error("Error deleting style named '" & oStyle.Name & "'.")
		End Try
	Next
	oDrawingDoc.Update2(True)
End Sub

Sub UpdateAndPurgeLightingStyles(oModelDoc As Document)
	If IsNothing(oModelDoc) Then Exit Sub
	Dim oLStyles As LightingStyles = oModelDoc.LightingStyles
	For Each oLStyle As LightingStyle In oLStyles
		If oLStyle.StyleLocation <> StyleLocationEnum.kLibraryStyleLocation Then
			If oLStyle.InUse = False Then
				Try
					oLStyle.Delete
				Catch
					'Logger.Error("Error deleting LightingStyle named '" & oLStyle.Name & "'.")
				End Try
			ElseIf oLStyle.InUse = True And oLStyle.UpToDate = False Then
				Try
					oLStyle.UpdateFromGlobal
				Catch
					'Logger.Error("Error updating LightingStyle named '" & oLStyle.Name & "' from global.")
				End Try
			End If
		End If
	Next
End Sub

Sub UpdateAndPurgeTextStyles(oModelDoc As Document)
	If IsNothing(oModelDoc) Then Exit Sub
	Dim oTextStyles As TextStylesEnumerator = oModelDoc.TextStyles
	For Each oTextStyle As TextStyle In oTextStyles
		If oTextStyle.StyleLocation <> StyleLocationEnum.kLibraryStyleLocation Then
			If oTextStyle.InUse = False Then
				Try
					oTextStyle.Delete
				Catch
					'Logger.Error("Error deleting TextStyle named '" & oTextStyle.Name & "'.")
				End Try
			ElseIf oTextStyle.InUse = True And oTextStyle.UpToDate = False Then
				Try
					oTextStyle.UpdateFromGlobal
				Catch
					'Logger.Error("Error updating TextStyle named '" & oTextStyle.Name & "' from global.")
				End Try
			End If
		End If
	Next
End Sub

Sub PurgeUnusedAssets(oModelDoc As Document)
	If IsNothing(oModelDoc) Then Exit Sub
	Dim oAssets As Inventor.Assets = oModelDoc.Assets
	For Each oAsset As Inventor.Asset In oAssets
		If oAsset.IsUsed Or oAsset.IsReadOnly Then Continue For
		Try
			oAsset.Delete
		Catch
			'Logger.Error("Error deleting Asset named '" & oAsset.Name & "'.")
		End Try
	Next
End Sub

If this solved your problem, or answered your question, please click ACCEPT SOLUTION.
Or, if this helped you, please click (LIKE or KUDOS) :thumbs_up:.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes

Michael.Navara
Advisor
Advisor

Here is a different approach to purge and update styles. As @WCrihfield mentions above, update assets is not easy task.

 

Sub Main()

    Dim doc As Document = ThisDoc.Document

    Select Case doc.DocumentType
        Case DocumentTypeEnum.kAssemblyDocumentObject
            Dim asm As AssemblyDocument = doc
            PurgeStyles(asm.LightingStyles)
            PurgeStyles(asm.TextStyles)

            UpdateStyles(asm.LightingStyles)
            UpdateStyles(asm.TextStyles)

            PurgeAssets(asm.MaterialAssets)
            PurgeAssets(asm.AppearanceAssets)

        Case DocumentTypeEnum.kPartDocumentObject
            Dim prt As PartDocument = doc
            PurgeStyles(prt.LightingStyles)
            PurgeStyles(prt.TextStyles)
            
            UpdateStyles(prt.LightingStyles)
            UpdateStyles(prt.TextStyles)

            PurgeAssets(prt.MaterialAssets)
            PurgeAssets(prt.AppearanceAssets)

            If doc.DocumentSubType.DocumentSubTypeID = "{9C464203-9BAE-11D3-8BAD-0060B0CE6BB4}" Then
                Dim smCompDef As SheetMetalComponentDefinition = prt.ComponentDefinition
                PurgeStyles(smCompDef.SheetMetalStyles)
                PurgeStyles(smCompDef.UnfoldMethods)

                UpdateStyles(smCompDef.SheetMetalStyles)
                UpdateStyles(smCompDef.UnfoldMethods)
            End If

        Case DocumentTypeEnum.kDrawingDocumentObject
            Dim drw As DrawingDocument = doc
            PurgeStyles(drw.StylesManager.Styles)

            UpdateStyles(drw.StylesManager.Styles)

        Case Else
            Logger.Warn("This document can't be purged")
    End Select


End Sub

''' <summary>
''' Purges all styles from stylesCollection
''' </summary>
''' <param name="stylesCollection">Must be collection of objects accesible by index.
''' Each element in collection must provide properties: bool InUse, string Name, StyleLocationEnum StyleLocation, and method Delete()</param>
Sub PurgeStyles(stylesCollection As Object)
    Dim someStyleDeleted As Boolean
    Do
        someStyleDeleted = False
        Dim i As Integer = 1
        Do

            Dim s = stylesCollection(i)
            If s.InUse Or s.StyleLocation = StyleLocationEnum.kLibraryStyleLocation Then
                i += 1
            Else
                Dim msg = s.Name
                Try
                    s.Delete()
                    someStyleDeleted = True
                Catch
                    msg = msg & " Not deleted"
                    i += 1
                End Try
                Logger.Debug(msg)
            End If

        Loop While stylesCollection.Count >= i
    Loop While someStyleDeleted
    Logger.Info("{0} - Done", [Enum].GetName(GetType(ObjectTypeEnum), stylesCollection.Type))

End Sub

Sub PurgeAssets(assetsCollection As AssetsEnumerator)
    Dim i As Integer = 1
    Do
        Dim asset As Asset = assetsCollection(i)
        If asset.IsUsed Then
            i += 1
        Else
            Dim msg = asset.Name
            Try
                asset.Delete()
                i += 1
            Catch
                msg = msg & " Not deleted"
                i += 1
            End Try
            Logger.Debug(msg)
        End If
    Loop While assetsCollection.Count >= i
End Sub

Sub UpdateStyles(stylesCollection As Object)
    For Each s In stylesCollection
        If Not s.UpToDate Then s.UpdateFromGlobal()
    Next
End Sub

 

 

Notes to @WCrihfield's solution.

  • It is potentially dangerous to remove an item from a collection while iterating over that collection using a For Each loop. Here is the situation from real world.
  • Some styles are not cleaned up in the first iteration. Because they are used by another style that is not used but is placed further in the collection. Therefore, it is necessary to iterate the collection several times.

 

0 Likes

WCrihfield
Mentor
Mentor

Hi @Michael.Navara.  I think that last code you posted needs a line fixed.  Within the Sub Main area, right after the Case where you check the DocumentType against a Part type, you are setting the Type of your 'prt' variable as an AssemblyDocument, instead of a PartDocument.  And yes, I know that sometimes when you delete a style that is referencing other styles within it, it can free up those other referenced styles if they are no longer being referenced by any other styles.  Then those other freed up styles can sometimes be deleted in subsequent cycles.  In my own personal use code, which is much longer and divided up, I simply run a similar For Each loop multiple times and use a Boolean variable.  I tend to avoid using Do loops in my own work tools, as a personal preference, due to previous negative experiences with them.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes

Michael.Navara
Advisor
Advisor
0 Likes

Darkforce_the_ilogic_guy
Advisor
Advisor

can you add the fix code in here ? the update part of the code fail on my computer. when run on a part

bt_0-1660826364005.png

 

bt_1-1660826372522.png

 

 

 

 

 

0 Likes

Michael.Navara
Advisor
Advisor
Fixed. I forgot the explicit type of iteration variable 's' in UpdateStyles method

Darkforce_the_ilogic_guy
Advisor
Advisor

well that fix the error.  but i can see it does not total purge and update the files.  but it is the best so far. does you know for fix it so it take it all ?

 

bt_0-1660886157385.png

 

bt_1-1660886174180.png

 

 

0 Likes