Design Patterns Applied to Autodesk® Inventor® API Philippe Leefsma Senior Developer Consultant, Autodesk Developer Network © 2012 Autodesk Class Summary This class focuses on developing .Net based add-ins for Autodesk Inventor® using best practices gained from direct hands-on experience of Autodesk software engineers. It exposes design patterns specifically studied for the Inventor® API. The class may benefit any programmer developing applications on top of Autodesk Inventor®. © 2012 Autodesk About the Presenter Philippe Leefsma Developer Technical Services EMEA (Neuchatel, Switzerland) Philippe has a master's degree in Computer Sciences. He carried his studies in Paris at I.S.E.P and in USA, at Colorado School of Mines. He joined Autodesk 6 years ago where he works as developer consultant for Autodesk Developer Network. He supports various products APIs such as AutoCAD®, AutoCAD Mechanical®, and Autodesk® Inventor®. He likes to travel, meet developers from around the world to work with them around challenging programming, CAD and manufacturing topics. © 2012 Autodesk Learning Objectives At the end of this class, you will be able to: Boost your add-in development with useful functionalities Strengthen stability and efficiency of your application by using well established software architectures Save time and effort by taking advantage of design patterns turned into templates We do not discuss and assume knowledge of How to program in C# or VB.NET The basics of the Inventor API Inventor product usage © 2012 Autodesk I - Creating Custom Project and Item templates © 2012 Autodesk Custom Add-In Template Custom add-in template can be used to enforce design pattern use Let you save time and efforts by automating repetitive tasks Helps standardize development process across company Provides an efficient framework to developers © 2012 Autodesk Creating Custom Templates Creating your own custom add-in template is straightforward from Visual Studio interface: Web references dealing with more advanced functionalities: http://msdn.microsoft.com/en-us/magazine/cc188697.aspx http://blogs.microsoft.co.il/blogs/oshvartz/archive/2008/07/26/creating-visual-studio-items-template-withcustom-wizard.aspx © 2012 Autodesk Custom template - Parameters Template parameters are declared in the format $parameter$ Some useful parameters used in the ADN template: destinationdirectory GUID [1-10] itemname projectname safeitemname safeprojectname time © 2012 Autodesk Custom Template - Parameters Example /////////////////////////////////////////////////////////////////////////////////// // $safeitemname$ Inventor Add-in Command // // Author: $username$ // Creation date: $time$ /////////////////////////////////////////////////////////////////////////////////// namespace $rootnamespace$ { class $safeitemname$: AdnButtonCommandBase { public $safeitemname$(Inventor.Application Application): base(Application) { //... Your code goes here ... } } } © 2012 Autodesk Adding Custom Steps Post-Build: call "%VS90COMNTOOLS%vsvars32" mt.exe -manifest "$(ProjectDir)$projectname$.X.manifest" -outputresource:"$(TargetPath)";#2 xcopy /y "$(ProjectDir)Autodesk.$projectname$.Inventor.addin" "$(AppData)\Autodesk\Inventor Addins\" AfterClean: <Target Name="AfterClean"> <Delete Files="$(AppData)\Autodesk\Inventor Addins\Autodesk.$projectname$.Inventor.addin" /> </Target> © 2012 Autodesk Template Installation On Windows XP: C:\Documents and Settings\<user>\My Documents\Visual Studio <version> \Templates\ProjectTemplates\ C:\ Documents and Settings \<user>\My Documents\Visual Studio <version> \Templates\ItemTemplates\ On Windows Vista/7: C:\Users\<user>\My Documents\Visual Studio <version> \Templates\ProjectTemplates\ C:\Users\<user>\My Documents\Visual Studio <version> \Templates\ItemTemplates\ © 2012 Autodesk Templates in Visual Studio Express Visual Studio Express Edition has a few limitations: Post-Build step not available > Perform manually or use .bat file AfterClean step not available New project created on TEMP folder > Call ‘Save All’, select folder and change .addin and post-build accordingly © 2012 Autodesk Template Demo © 2012 Autodesk II - Add-In Utilities © 2012 Autodesk XML Ribbon Builder Common task for add-ins: create user interface elements XML-based Ribbon builder presents several advantages: Fast and easy definition of Ribbon elements Generate the Ribbon items dynamically at loading Use external XML > Can be replaced / updated by user / application Ribbon Builder © 2012 Autodesk XML Ribbon Builder - Tags Ribbon builder interprets following XML tags: RibbonTab RibbonPanel QAT Button Separator ComboBox Macro Gallery SplitButton SplitButtonMRU ButtonPopup Popup TogglePopup © 2012 Autodesk Ribbon items persistence Ribbon builder implements custom items persistence mechanism: Ribbons.xml <Ribbon> <…> <Ribbon/> Add-in loaded Ribbon Builder Add-in unloaded User.Ribbons. xml <Ribbon> <…> <Ribbon/> Add-in loaded Ribbon Builder © 2012 Autodesk XML Ribbon Builder - Example <?xml version="1.0" encoding="utf-8"?> <Ribbon> <RibbonTab ribbons="ZeroDoc|Part|Assembly|Drawing" internalName="id_TabTools" displayName="Tools" targetTabBefore="" targetTabAfter=""> <RibbonPanel internalName="MyCompany.MyAddin.MyPanel" displayName="My Panel" targetPanelBefore="" targetPanelAfter=""> <Button internalName="MyCompany.MyAddin.MyCommand" useLargeIcon="true" isInSlideout="false" targetControlBefore="TargetControlInternalName" targetControlAfter="" isPersistent="true"/> </RibbonPanel> </RibbonTab> </Ribbon> © 2012 Autodesk XML Ribbon Builder - Use // Create Ribbon items based on a Stream generated // from an XML description file public void CreateRibbonFromStream(Stream stream); // Create Ribbon items based on a Stream name // typically an embedded resource xml file public void CreateRibbonFromResource( Assembly resourceAssembly, string resourcename); // Create Ribbon items based on an existing // xml file on the disk public void CreateRibbonFromFile(string xmlfile); © 2012 Autodesk XML Ribbon Builder - Use public void Activate(Inventor.ApplicationAddInSite addInSiteObject, bool firstTime) { // Add-in Inititialization... Assembly asm = Assembly.GetExecutingAssembly(); string asmName = asm.GetName().Name; if (System.IO.File.Exists(asmName + ".ribbons.override.xml")) { AdnRibbonBuilder.CreateRibbonFromFile(asmName + ".ribbons.override.xml"); } else { AdnRibbonBuilder.CreateRibbonFromResource(asm, “Namespace.resources.ribbons.xml"); } } © 2012 Autodesk Add-in Installer – Registry Free Utilities can be extended also to installer class: Inventor registry-free add-in mechanism based on “.addin” copied at specific location on the machine. Add-in dll can be placed anywhere on the directory structure To handle this feature from classic installer, a custom post install step can be used © 2012 Autodesk Add-in Installer – Registry Free public string InstallRegistryFree(IDictionary stateSaver){ // Get addin dll location Assembly Asm = Assembly.GetExecutingAssembly(); FileInfo asmFile = new FileInfo(Asm.Location); FileInfo addinFile = null; foreach (FileInfo fileInfo in asmFile.Directory.GetFiles()) if (fileInfo.Extension.ToLower() == ".addin"){ addinFile = fileInfo; break; } XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(addinFile.FullName); XmlNode node = xmldoc.GetElementsByTagName("Assembly")[0]; node.InnerText = asmFile.FullName; xmldoc.Save(addinFilenameDest); © 2012 Autodesk Inventor Utilities – Manager Classes class AdnAttributeManager class AdnRefKeyManager class AdnInteractionManager class AdnClientGraphicsManager class AdnDrawingViewManager © 2012 Autodesk III - Design Patterns © 2012 Autodesk Add-In Command Pattern An Inventor command is different for user and programmer User = single concept | Programmer = Multiple API objects Control Definition AdnCommand design pattern gathers all API concepts in a single object: Easily instantiated and extended Helps structure your code Handles Form / InteractionEvents workflow Icons Adn Command Form Interaction Interaction Events © 2012 Autodesk Add-In Command Pattern abstract public class AdnCommandBase { protected AdnCommandBase(Inventor.Application Application) // Static method to add new command public static void AddCommand(AdnCommandBase command) // Implements ControlDefinition creation in derived classes abstract protected void CreateControl() // Public Command Properties public ControlDefinition ControlDefinition public Application Application public abstract string ClientId } © 2012 Autodesk Add-In Command - Use AdnCommandBase is designed to be derived in custom command: AdnCommandBase AdnButtonCommand Base MyButtonCommand AdnCollection CommandBase MySplitCommand MyPopUpCommand © 2012 Autodesk Dockable Window Pattern Provides an easy to use pattern to handle custom Dockable Windows in Inventor Use: create a UserControl and place it inside the Dockable Window Form A static method allows to create or refresh display for the dockable window protected override void OnExecute(NameValueMap context) { MyDockableWnd.MakeVisible( _addInSiteObject, DockingStateEnum.kDockLeft); } © 2012 Autodesk ClientFeature Factory Pattern public abstract class AdnClientFeatureFactoryBase { public abstract string ClientFeatureName; public abstract Bitmap ClientFeatureIcon; public abstract bool IsCustomSolved; public abstract bool HighlightClientGraphicsWithFeature; protected string ClientFeatureId; public abstract bool Edit(ClientFeature feature); public abstract void ExitEdit(); protected ClientFeature CreateClientFeature( Document document, object startElement, object endElement, object inputs) public event OnFeatureDoubleClickEvent; } public event OnClientFeatureSolveEvent; © 2012 Autodesk Wrap up Custom Template Add-in Utilities Project and item templates are powerful time and effort saver Using custom tools on top of API can be very advantageous and lighten coding process Design Patterns Rely on design patterns helps structure code and enforce good practices © 2012 Autodesk Material Presentation Template Samples CP2675 - Design Patterns Applied to the Autodesk® Inventor® API.pptx CP2675 - Design Patterns Applied to the Autodesk® Inventor® API.docx Inventor AddIn Template AdnButtonCommand AdnCollectionCommand AdnClientFeatureFactory DockableWindow - C# | VB.Net - C# | VB.Net - C# | VB.Net - C# | VB.Net - C# Add-In Samples ClientGraphics, DogBone, FxDimensions, Material Profiler, Thread Modeler © 2012 Autodesk Resources for Inventor developers Online Help, Developer's Guide and SDK Samples Inventor Developer Center http://www.autodesk.com/developinventor Webcasts and Trainings on Inventor Programming and News http://www.adskconsulting.com/adn/cs/api_course_sched.php Discussion Group http://discussion.autodesk.com > Inventor API Training Classes http://www.autodesk.com/apitraining ADN, The Autodesk Developer Network http://www.autodesk.com/joinadn Manufacturing DevBlog http://adndevblog.typepad.com/manufacturing © 2012 Autodesk © 2012 Autodesk