Copy iLogic Rules from template dwg to actual dwg in C#

Copy iLogic Rules from template dwg to actual dwg in C#

mowag
Enthusiast Enthusiast
1,110 Views
15 Replies
Message 1 of 16

Copy iLogic Rules from template dwg to actual dwg in C#

mowag
Enthusiast
Enthusiast

Hi all,

 

We have a lot of drawings based on an old template dwg. I've managed to copy all the custom properties from the template dwg to the old drawings.

How can i copy the iLogic rules from the template dwg to the old drawings  in C# ?

 

I've seached already the API help, but i cannot find anything on iLogic, Rules, ......  ??

 

Kind Regards

 

Johan

0 Likes
1,111 Views
15 Replies
Replies (15)
Message 2 of 16

mowag
Enthusiast
Enthusiast

Hi all,

 

Can anyone point me to information about iLogic Rules ?

Where to find them with te Inventor API,how to access them ... ?

 

Kind Regards

 

Johan

0 Likes
Message 3 of 16

dhanna
Enthusiast
Enthusiast

I stumbled upon this code by Jelte de Jong on the website clintbrown.co.uk. Hopefully it can illuminate the path you need to follow:

 

<code>

'Code by Jelte de Jong Originally posted at https://clintbrown.co.uk/one-rule-to-search-them-all---guest-post
Public Class ThisRule
    Private searchText As String
    Private iLogicAddinGuid As String = "{3BDD8D79-2179-4B11-8A5A-257B1C0263AC}"
    Private iLogicAddin As ApplicationAddIn = Nothing
    Private iLogicAutomation = Nothing
    Private outputFile As String = "c:\TEMP\seachedRules.txt"

    Sub Main()
        If (IO.File.Exists(outputFile)) Then
            IO.File.Delete(outputFile)
        End If
        searchText = InputBox("Text to search for", "Search")

        iLogicAddin = ThisApplication.ApplicationAddIns.ItemById(
			"{3bdd8d79-2179-4b11-8a5a-257b1c0263ac}")
        iLogicAutomation = iLogicAddin.Automation
        Dim doc As AssemblyDocument = ThisDoc.Document

        searchDoc(doc)
        For Each refDoc As Document In doc.AllReferencedDocuments
            searchDoc(refDoc)
        Next

        Process.Start("notepad.exe", outputFile)
    End Sub

    Private Sub searchDoc(doc As Document)
        Dim rules = iLogicAutomation.Rules(doc)
        If (rules Is Nothing) Then Return
        For Each rule In rules
            Dim strReader As IO.StringReader = New IO.StringReader(rule.Text)
            Dim i As Integer = 1

            Do While (True)
                Dim line As String
                line = strReader.ReadLine()
                If line Is Nothing Then Exit Do
                If (line.ToUpper().Contains(searchText.ToUpper())) Then
                    Dim nl = System.Environment.NewLine
                    IO.File.AppendAllText(outputFile,
                        "Doc name : " & doc.DisplayName & nl &
                        "Rule name: " & rule.Name & nl &
                        "line " & i & "  : " & line.Trim() & nl & nl)
                End If
                i = i + 1
            Loop
        Next
    End Sub
End Class

</code>

Message 4 of 16

mowag
Enthusiast
Enthusiast

Hi dhanna,

 

Thanks  for the reply, but this is an iLogic ( external rule) in VBA.

I've written a C# dekstop app using the Inventor API, so this is not usible for me!

But thanks anyways  !

 

Johan

0 Likes
Message 5 of 16

dhanna
Enthusiast
Enthusiast

As I am unfamiliar with c#, I know I cannot really help with the coding, though if you are comfortable with c# converting the 

<code>

        iLogicAddin = ThisApplication.ApplicationAddIns.ItemById(
			"{3bdd8d79-2179-4b11-8a5a-257b1c0263ac}")
        iLogicAutomation = iLogicAddin.Automation

</code>

to c# should get you access to the rules, as I understand it. could pop over to that chat gpt and ask it to convert it to a proper c# line(s) of code. either way, good luck

 

0 Likes
Message 6 of 16

WCrihfield
Mentor
Mentor

Hi @mowag & @dhanna.  I am also not super fluent in C#, but I am pretty familiar with vb.net, which is pretty similar.  Here is another very similar example you can look at.  It was simply a utility for copying internal rules from a 'source' document, to another, but I customized it to look for a drawing template as its source.  You may need to change the name of the source drawing template file, but this code worked for me.  It uses the same principles as the example above too.  Basically, once you get that 'Automation' object from the iLogic ApplicationAddIn object, you can use that similar to this phrase in an iLogic rule "iLogicVb.Automation".  So, with that knowledge in hand, you can play around with that idea.

Sub CopyInternalRulesFromTemplate()
	Dim InvApp As Inventor.Application = GetObject(, "Inventor.Application")
	Dim sTPath As String = InvApp.DesignProjectManager.ActiveDesignProject.TemplatesPath
	Dim sTemplateName As String = "A-Size Standard Drawing.idw"
	Dim sTemplateFile As String = sTPath & "\" & sTemplateName
	Dim oTemplateDoc As Inventor.Document = Nothing
	If System.IO.File.Exists(sTemplateFile) Then
		oTemplateDoc = InvApp.Documents.Open(sTemplateFile, False)
	End If
	If oTemplateDoc Is Nothing Then Exit Sub
	Dim oDoc As Inventor.Document = InvApp.ActiveDocument
	Dim iLogicID As String = "{3BDD8D79-2179-4B11-8A5A-257B1C0263AC}"
	Dim iLogic As Inventor.ApplicationAddIn = Nothing
	Try : iLogic = InvApp.ApplicationAddIns.ItemById(iLogicID) : Catch : End Try
	If IsNothing(iLogic) Then Exit Sub
	iLogic.Activate
	Dim iLogicAuto As Object = iLogic.Automation
	Dim oTemplateRules = iLogicAuto.Rules(oTemplateDoc)
	If oTemplateRules Is Nothing Then Exit Sub
	For Each oTRule In oTemplateRules
		Dim oDRule = Nothing
		oDRule = iLogicAuto.GetRule(oDoc, oTRule.Name)
		If oDRule Is Nothing Then
			oDRule = iLogicAuto.AddRule(oDoc, oTRule.Name, "")
		End If
		If oDRule.Text <> oTRule.Text Then
			oDRule.Text = oTRule.Text
		End If
	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) 👍.

 

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 7 of 16

WCrihfield
Mentor
Mentor

You may notice that I am not directly copying the 'text' of the rule, when it is initially created.  That is because it would cause the rule to run instantly.  So, I set the text of the rule as a secondary action, to avoid that automatic running of the rule when it is created.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 8 of 16

mowag
Enthusiast
Enthusiast

Hi WCrihfield,

 

Thanks for the code !

But got stuck on the Rules property of the iLogicAddIn.Automation !

i'll have to figure out how to find the Rules in the object !

 

Regards

 

Johan

0 Likes
Message 9 of 16

WCrihfield
Mentor
Mentor

Hi @mowag.  There will not be any Intellisense or other helpful pop-up suggestions available after that 'iLogicAuto' variable, since it is declared as an Object.  In iLogic, it represents the IiLogicAutomation Interface.  Then Rules is a Property of that Interface, which works similarly to a Function.  If you follow that Rules link, you will see a VB example, and a C# example.  Since I am not fluent in C#, I would assume from that example, that you may need to use the word 'This', instead of 'Rules', but I'm not sure.  Then it should return an IEnumerable, if there were some rules in that document.  In iLogic or vb.net, it will simply be Nothing if there were no rules found, but I'm not sure if C# will be the same.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

0 Likes
Message 10 of 16

mowag
Enthusiast
Enthusiast

Hi @WCrihfield ,

 

Thanks very much for pointing me into the right direction !!

 

Indeed, no Intellisense because of type Object.

Now i've made a reference to Autodesk.iLogic.Interfaces .

 

string iLogicID = "{3BDD8D79-2179-4B11-8A5A-257B1C0263AC}";
iLogicAddIn = _inventordataService.invApp.ApplicationAddIns.ItemById[iLogicID];

iLogicAddIn.Activate();

IiLogicAutomation iLogicAuto = (IiLogicAutomation)iLogicAddIn.Automation;

Inventor.Document TemplateDoc;

string TemplateFile = @"Z:\InventorToolsData\DrawingTemplates\HorA4 - Astra-NEW.dwg";
if (System.IO.File.Exists(TemplateFile))
{
   TemplateDoc = _inventordataService.invApp.Documents.Open(TemplateFile, false);

   IEnumerable TemplateRules = iLogicAuto.get_Rules(TemplateDoc);
}

 

Since the Automation property of the ApplicationAddIn returns an automation interface, i thought i could cast it to an IilogicAutomation interface.

 

But it gives an error : unable to cast.

I checed that the AddIn was activated !

 

 

0 Likes
Message 11 of 16

dhanna
Enthusiast
Enthusiast

wish I could help, but at the risk of being obnoxious, I would try something like

declare the variable as object

check if variable is not nothing

debug/messagebox variable is of type...

 

then edit declaration to the type passed 

and hope for the best

 

0 Likes
Message 12 of 16

WCrihfield
Mentor
Mentor

In vb.net, it has been my experience so far, that you generally do not need to instantiate a variable that represents one of the Autodesk.iLogic.Interface.... Interface objects, you just need to fully declare that Type of variable ahead of time.  Then you can simply use that variable similarly to how you would in an iLogic rule.  For example:

Dim iLogicAuto As Autodesk.iLogic.Interfaces.IiLogicAutomation

...then do not set a value to that 'iLogicAuto' variable, just use it to access its 'Rules' property as you would normally.

I do something similar in my 'extension' external iLogic rules that are set to 'Straight VB Code', so that I can use the 'iLogic Logger'.

Private Logger As Autodesk.iLogic.Interfaces.IRuleLogger

...(above is the normal way, then below is an alternate way)

Private Logger As Autodesk.iLogic.Interfaces.LogControl

...then, to use it, I use a line similar to this:

Logger.Log(LogLevel.Error, "XXXX method encountered an Error")

 Some of these types of things that seem native to iLogic can be found at this Link.  Those are basically just variables that have created for us in the background, within the ThisRule Class (that is also automatically created for us in the background for our rules).  Some of those are just direct references to these Interface type tools.

Wesley Crihfield

EESignature

(Not an Autodesk Employee)

Message 13 of 16

dave.cutting
Advocate
Advocate

Hi,

 

Could you use the code injector app from the Autodesk App Store?

 

https://apps.autodesk.com/INVNTOR/en/Detail/Index?id=7381718697722491251

Dave Cutting
Message 14 of 16

SebastienOuellet
Participant
Participant

Maybe this will help, not exactly what you want to achieve but it will show you how you need to cast

 

 

{
    // RETRIEVE THE ACTIVE INVENTOR APPLICATION INSTANCE
    Inventor.Application oApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Inventor.Application") as Inventor.Application;

    // DEFINE THE GUID OF THE ILOGIC ADD-IN
    string iLogicAddinGuid = "{3BDD8D79-2179-4B11-8A5A-257B1C0263AC}";

    Inventor.ApplicationAddIn addin = null;

    try
    {
        // ATTEMPT TO RETRIEVE THE ILOGIC ADD-IN
        addin = oApp.ApplicationAddIns.get_ItemById(iLogicAddinGuid);
    }
    catch
    {
        // HANDLE ANY ERRORS HERE...
    }

    if (addin != null)
    {
        // ACTIVATE THE ADD-IN IF IT IS NOT ALREADY ACTIVE
        if (!addin.Activated)
            addin.Activate();
        
        // GET THE ILOGIC AUTOMATION INTERFACE
        dynamic _iLogicAutomation = addin.Automation;
        Document oCurrentDoc = oApp.ActiveDocument;
        dynamic myRule = null;

        // ITERATE THROUGH ALL RULES
        foreach (dynamic eachRule in _iLogicAutomation.Rules(oCurrentDoc))
        {
            if (eachRule.Name == "MyRule")
            {
                myRule = eachRule;
                
                // DISPLAY THE CODE OF THE RULE
                MessageBox.Show(myRule.Text);
                break;
            }
        }

        // IF THE RULE IS FOUND, RUN THE RULE
        if (myRule != null)
            _iLogicAutomation.RunRule(oCurrentDoc, "MyRule");
    }
}

 

 



Logo MCMCAD
https://mcmcad.com/
0 Likes
Message 15 of 16

mowag
Enthusiast
Enthusiast

@SebastienOuellet ,

 

Thanks for the code, it solved my problem !!!

Now i'm able  to get to the rules !

Now i can start trying to copy the rules from the template to the actual drawingdocument.

 

Johan

0 Likes
Message 16 of 16

JelteDeJong
Mentor
Mentor

try this method:

public void CopyRule(Document docSource, string ruleName, Document docTarget)
{
    string iLogicAddinGuid = "{3BDD8D79-2179-4B11-8A5A-257B1C0263AC}";
    Inventor.Application app = (Inventor.Application)docSource.Parent;
    Inventor.ApplicationAddIn addin = app.ApplicationAddIns.get_ItemById(iLogicAddinGuid);

    if (addin == null) return;
    if (!addin.Activated) addin.Activate();

    //IiLogicAutomation iLogicAutomation = addin.Automation as IiLogicAutomation;
    dynamic iLogicAutomation = addin.Automation;

    //iLogicRule ruleOrg = iLogicAutomation.GetRule(docSource, ruleName); 
    dynamic ruleOrg = iLogicAutomation.GetRule(docSource, ruleName);

    // When you add the rule it will be executed 
    // to prevent that I did not add code to the rule directly
    // iLogicRule newRule = iLogicAutomation.AddRule(docTarget, ruleName, string.Empty);
    dynamic newRule = iLogicAutomation.AddRule(docTarget, ruleName, string.Empty);
    newRule.Text = ruleOrg.Text;
}

 (I left the lines with the real interfaces instead of the dynamic object. I use those to make the intellisense work 😉

Jelte de Jong
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.

EESignature


Blog: hjalte.nl - github.com