示例#1
0
        /// <summary>
        /// A function that checks if the provided string contains a Content Center Library path.
        /// </summary>
        /// <param name="path">Path as a string.</param>
        /// <param name="inventorApp">Inventor.Application object.</param>
        /// <returns></returns>
        public static bool IsContentCenterPath(this string path, Application inventorApp)
        {
            if (String.IsNullOrEmpty(path))
            {
                return(false);
            }

            DesignProject designProject      = inventorApp.DesignProjectManager.ActiveDesignProject;
            bool          projectCCPathInUse = designProject.ContentCenterPathOverridden;
            string        ccPath;

            if (projectCCPathInUse)
            {
                ccPath = designProject.ContentCenterPath;
            }
            else
            {
                ccPath = inventorApp.FileOptions.ContentCenterPath;
            }

            ccPath = TrimEndingDirectorySeparator(ccPath);

            if (path.Contains(ccPath))
            {
                return(true);
            }

            return(false);
        }
示例#2
0
        public void Run(Document placeholder)
        {
            // LogTrace("Run called with {0}", doc.DisplayName);

            LogTrace("Running Update BOM...");
            string currDir = Directory.GetCurrentDirectory();


            // For local debugging
            //string inputPath = System.IO.Path.Combine(currDir, @"../../inputFiles", "params.json");
            //Dictionary<string, string> options = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(inputPath));

            Dictionary <string, string> options = JsonConvert.DeserializeObject <Dictionary <string, string> >(System.IO.File.ReadAllText("inputParams.json"));
            string inputFile   = options["inputFile"];
            string projectFile = options["projectFile"];

            string assemblyPath    = Path.GetFullPath(Path.Combine(currDir, inputFile));
            string fullProjectPath = Path.GetFullPath(Path.Combine(currDir, projectFile));

            Console.WriteLine("fullProjectPath = " + fullProjectPath);

            DesignProject dp = inventorApplication.DesignProjectManager.DesignProjects.AddExisting(fullProjectPath);

            dp.Activate();

            Console.WriteLine("assemblyPath = " + assemblyPath);
            Document doc = inventorApplication.Documents.Open(assemblyPath);

            using (new HeartBeat())
            {
                GetBom(doc);
            }
        }
示例#3
0
        public void Run(Document doc)
        {
            LogTrace("Run()");

            if (IsLocalDebug)
            {
                dynamic dynDoc     = doc;
                string  parameters = getParamsAsJson(dynDoc.ComponentDefinition.Parameters.UserParameters);

                System.IO.File.WriteAllText("documentParams.json", parameters);
            }
            else
            {
                string currentDir = System.IO.Directory.GetCurrentDirectory();
                LogTrace("Current Dir = " + currentDir);

                Dictionary <string, string> inputParameters = JsonConvert.DeserializeObject <Dictionary <string, string> >(System.IO.File.ReadAllText("inputParams.json"));
                logInputParameters(inputParameters);

                using (new HeartBeat())
                {
                    if (inputParameters.ContainsKey("projectPath"))
                    {
                        string projectPath     = inputParameters["projectPath"];
                        string fullProjectPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(currentDir, projectPath));
                        LogTrace("fullProjectPath = " + fullProjectPath);
                        DesignProject dp = inventorApplication.DesignProjectManager.DesignProjects.AddExisting(fullProjectPath);
                        dp.Activate();
                    }
                    else
                    {
                        LogTrace("No 'projectPath' property");
                    }

                    if (inputParameters.ContainsKey("documentPath"))
                    {
                        string documentPath = inputParameters["documentPath"];

                        string fullDocumentPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(currentDir, documentPath));
                        LogTrace("fullDocumentPath = " + fullDocumentPath);
                        dynamic invDoc = inventorApplication.Documents.Open(fullDocumentPath);
                        LogTrace("Opened input document file");
                        dynamic compDef = invDoc.ComponentDefinition;

                        string parameters = getParamsAsJson(compDef.Parameters.UserParameters);

                        System.IO.File.WriteAllText("documentParams.json", parameters);
                        LogTrace("Created documentParams.json");
                    }
                    else
                    {
                        LogTrace("No 'documentPath' property");
                    }
                }
            }
        }
示例#4
0
 public GameViewModel(DesignProject project)
 {
     Cells   = new ObservableCollection <PatternCellViewModel>();
     Project = project;
     Project.Design.PropertyChanged += DesignPropertyChanged;
     ((INotifyCollectionChanged)Project.Design.Cells).CollectionChanged += CellsCollectionChanged;
     foreach (var patternCell in Project.Design.Cells)
     {
         Cells.Add(new PatternCellViewModel(patternCell));
     }
 }
示例#5
0
        public void BadInput_Null()
        {
            Inventor.Application app = ApplicationShim.Instance();
            app.Documents.CloseAll();
            DesignProject dp = app.DesignProjectManager.ActiveDesignProject;

            dp.Activate();

            string test = null;

            Assert.IsFalse(PathShim.IsContentCenterPath(test, ref app));
        }
示例#6
0
        /// <summary>
        /// Activate Inventor Project
        /// </summary>
        /// <param name="projectName"></param>
        /// <returns></returns>
        public bool ActivateInventorProject(string projectName)
        {
            try
            {
                //string currentDirectory = Directory.GetCurrentDirectory();
                string        fullProjectPath = Path.GetFullPath(Path.Combine(currentDirectory, projectName));
                DesignProject project         = inventorApplication.DesignProjectManager.DesignProjects.AddExisting(fullProjectPath);
                project.Activate();
            }
            catch (Exception ex)
            {
                LogTrace(ex.ToString());
                return(false);
            }

            return(true);
        }
示例#7
0
        public void Run(Document placeholder)
        {
            LogTrace("Creating Drawing from iLogic rule...");
            string currDir = Directory.GetCurrentDirectory();

            LogTrace("currDir: " + currDir);
            // For local debugging
            //string inputPath = System.IO.Path.Combine(currDir, @"../../inputFiles", "params.json");
            //Dictionary<string, string> options = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(inputPath));

            Dictionary <string, string> options = JsonConvert.DeserializeObject <Dictionary <string, string> >(System.IO.File.ReadAllText("inputParams.json"));
            string inputFile      = options["inputFile"];
            string projectFile    = options["projectFile"];
            string rule           = options["runRule"];
            string drawingDocName = "result";

            string assemblyPath = Path.GetFullPath(Path.Combine(currDir, inputFile));

            string fullProjectPath = Path.GetFullPath(Path.Combine(currDir, projectFile));


            Console.WriteLine("fullProjectPath = " + fullProjectPath);

            DesignProject dp = inventorApplication.DesignProjectManager.DesignProjects.AddExisting(fullProjectPath);

            dp.Activate();

            Console.WriteLine("assemblyPath = " + assemblyPath);
            Document doc = inventorApplication.Documents.Open(assemblyPath);

            //RunRule(doc, rule);
            CreateDrawing(doc);

            // Drawing will be the last one created
            int      docCount = inventorApplication.Documents.Count;
            Document lastDoc  = inventorApplication.Documents[docCount];

            LogTrace("lastDoc: " + lastDoc.DisplayName);

            string drawingPath = Directory.GetCurrentDirectory() + "/result.idw";

            LogTrace("saving drawing: " + drawingPath);
            lastDoc.SaveAs(drawingPath, false);
            LogTrace("saving as pdf: " + drawingDocName);
            SaveAsPdf(lastDoc, drawingDocName);
        }
示例#8
0
 private void ApplicationEvents_OnActiveProjectChanged(DesignProject ProjectObject, EventTimingEnum BeforeOrAfter,
                                                       NameValueMap Context, out HandlingCodeEnum HandlingCode)
 {
     if (_activeProjectType != ProjectObject.ProjectType)
     {
         if (ProjectObject.ProjectType == MultiUserModeEnum.kVaultMode)
         {
             TryLoadVaultAddin();
         }
         else
         {
             UnSubscribeEvents();
         }
         _activeProjectType = ProjectObject.ProjectType;
     }
     HandlingCode = HandlingCodeEnum.kEventNotHandled;
 }
示例#9
0
        /// <summary>
        /// A function that checks if the provided string contains an Inventor library path.
        /// </summary>
        /// <param name="path">Path as a string.</param>
        /// <param name="inventorApp">Inventor.Application object.</param>
        /// <returns></returns>
        public static bool IsLibraryPath(this string path, Application inventorApp)
        {
            if (String.IsNullOrEmpty(path))
            {
                return(false);
            }

            DesignProject designProject = inventorApp.DesignProjectManager.ActiveDesignProject;
            ProjectPaths  libraryPaths  = designProject.LibraryPaths;

            //ProjectPath libraryPath;

            foreach (ProjectPath libraryPath in libraryPaths)
            {
                if (path.Contains(TrimEndingDirectorySeparator(libraryPath.Path)))
                {
                    return(true);
                }
            }

            return(false);
        }
示例#10
0
        private void ActivateDefaultProject(string dir)
        {
            var defaultProjectName = "FDADefault";

            var projectFullFileName = System.IO.Path.Combine(dir, defaultProjectName + ".ipj");

            DesignProject project = null;

            if (System.IO.File.Exists(projectFullFileName))
            {
                project = inventorApplication.DesignProjectManager.DesignProjects.AddExisting(projectFullFileName);
                Trace.TraceInformation("Adding existing default project file: {0}", projectFullFileName);
            }
            else
            {
                project = inventorApplication.DesignProjectManager.DesignProjects.Add(MultiUserModeEnum.kSingleUserMode, defaultProjectName, dir);
                Trace.TraceInformation("Creating default project file with name: {0} at {1}", defaultProjectName, dir);
            }

            Trace.TraceInformation("Activating default project {0}", project.FullFileName);
            project.Activate(true);
        }
示例#11
0
        static void Main(string[] args)
        {
            Console.BufferWidth = 300;
            Console.WindowWidth = 140;
            string msg = String.Format("coolOrange bcpMaker v{0}", System.Reflection.Assembly.GetExecutingAssembly().GetName().Version);

            Console.WriteLine(msg);
            Console.WriteLine("".PadRight(msg.Length, '*'));
            if (System.IO.File.Exists("bcpMaker.log"))
            {
                System.IO.File.Delete("bcpMaker.log");
            }
            System.IO.File.AppendAllLines("bcpMaker.log", new string[] { msg });
            if (!System.IO.File.Exists("config.xml"))
            {
                Console.WriteLine("config.xml file could not be found nearby the bcpMaker.exe");
                Console.ReadKey();
                return;
            }
            XmlDocument config = new XmlDocument();

            try
            {
                config.Load("config.xml");
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("Error loading config.xml: {0}", ex));
                Console.ReadKey();
                return;
            }

            var    parameters    = config.SelectSingleNode("//PARAMETERS");
            string sourceFolder  = parameters.Attributes["SourceFilesFolder"].Value;
            string targetFolder  = parameters.Attributes["TargetBCPFolder"].Value;
            var    ignore        = config.SelectSingleNode("//IGNORE");
            string ignoreFolder  = ignore.Attributes["Folders"].Value;
            string ignoreFiles   = ignore.Attributes["FileExtensions"].Value;
            var    categoryRules = config.SelectNodes("//CATEGORYRULE");

            System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("Source folder: {0} ", sourceFolder) });
            System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("target folder: {0} ", sourceFolder) });
            System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("ignore file extensions: {0} ", ignoreFiles) });
            System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("ignore folder: {0} ", ignoreFolder) });
            if (!System.IO.Directory.Exists(sourceFolder))
            {
                Console.WriteLine(String.Format("source folder '{0}' does not exist", sourceFolder));
                Console.ReadKey();
                return;
            }
            try
            {
                System.IO.Directory.CreateDirectory(targetFolder);
            }
            catch
            {
                Console.WriteLine(String.Format("target folder '{0}' could not be created", targetFolder));
                Console.ReadKey();
                return;
            }

            #region apprentice server initialization
            ApprenticeServerComponent _invApp         = new ApprenticeServerComponent();
            DesignProject             InventorProject = _invApp.DesignProjectManager.ActiveDesignProject;
            List <string>             libraryFolders  = new List <string>();
            string ccPath = InventorProject.ContentCenterPath;
            libraryFolders.Add(ccPath.Replace(sourceFolder, ""));
            string workSpace = InventorProject.WorkspacePath;
            workSpace = workSpace.Replace(sourceFolder, "");
            var libraryPaths = InventorProject.LibraryPaths;
            msg = String.Format("Using Inventor Project File '{0}'", InventorProject.FullFileName);
            Console.WriteLine(msg);
            System.IO.File.AppendAllLines("bcpMaker.log", new string[] { msg });
            ProjectPaths libPaths = InventorProject.LibraryPaths;
            foreach (ProjectPath libpath in libPaths)
            {
                libraryFolders.Add(libpath.Path.TrimStart('.').Replace("\\", "/"));
            }
            #endregion

            List <string> files = new List <string>();
            Console.WriteLine("Scanning folders...");
            GetAllFilesFromFolderRecursively(sourceFolder, files, ignoreFiles, ignoreFolder);
            Console.WriteLine(String.Format("\rCollected files {0}", files.Count).PadRight(Console.BufferWidth, ' '));

            #region adding files to BCP package
            Console.WriteLine("Adding files to BCP package...");
            var bcpSvcBuilder = new BcpServiceBuilder {
                Version = BcpVersion._2016
            };
            bcpSvcBuilder.SetPackageLocation(targetFolder);
            var bcpSvc = bcpSvcBuilder.Build();

            int counter = 1;
            Dictionary <string, FileObject> bcpInventorFiles = new Dictionary <string, FileObject>(StringComparer.OrdinalIgnoreCase);

            foreach (string file in files)
            {
                string vaultTarget = file.Replace(sourceFolder, "$").Replace("\\", "/");
                bool   isLibrary   = libraryFolders.Any(lf => vaultTarget.Contains(lf.Replace("\\", "/")));
                var    bcpFile     = bcpSvc.FileService.AddFile(vaultTarget, file, isLibrary);
                string extension   = System.IO.Path.GetExtension(file);
                foreach (XmlNode categoryRule in categoryRules)
                {
                    var fileExtensions      = categoryRule.SelectSingleNode("//FILEEXTENSION");
                    var category            = categoryRule.SelectSingleNode("//CATEGORY");
                    var lifecycleDefinition = categoryRule.SelectSingleNode("//LIFECYCLEDEFINITON");
                    var state              = categoryRule.SelectSingleNode("//STATE");
                    var revision           = categoryRule.SelectSingleNode("//REVISION");
                    var revisionDefinition = categoryRule.SelectSingleNode("//REVISIONDEFINITION");
                    if (fileExtensions != null && (fileExtensions.InnerText == "" || fileExtensions.InnerText.Split(',').Contains(extension)))
                    {
                        if (category != null && category.InnerText != "")
                        {
                            bcpFile.Category = category.InnerText;
                        }
                        string stateName = state != null ? state.InnerText : "";
                        if (lifecycleDefinition != null && lifecycleDefinition.InnerText != "")
                        {
                            bcpFile.LatestIteration.Setstate(lifecycleDefinition.InnerText, stateName);
                        }
                        bcpFile.LatestRevision.SetRevisionDefinition(revisionDefinition != null ? revisionDefinition.InnerText : "", revision != null ? revision.InnerText : "");
                        break;
                    }
                }
                if (file.ToLower().EndsWith("iam") || file.ToLower().EndsWith("ipt") || file.ToLower().EndsWith("idw") || file.ToLower().EndsWith("ipn") || file.ToLower().EndsWith("dwg"))
                {
                    bcpInventorFiles.Add(file, bcpFile);
                    System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("Adding to reference check list: {0}", file) });
                }
                msg = String.Format("\rAdding file {0} of {1} to BCP package", counter++, files.Count());
                Console.Write(msg);
            }
            Console.WriteLine(String.Format("\rAdded files {0}", bcpSvc.EntitiesTable.Vault.Statistics.Totfiles).PadRight(Console.BufferWidth, ' '));
            #endregion


            var inventorFiles = files.Where(file => file.ToLower().EndsWith("iam") || file.ToLower().EndsWith("ipt") || file.ToLower().EndsWith("idw") || file.ToLower().EndsWith("ipn") || file.ToLower().EndsWith("dwg")).ToList();
            Console.WriteLine("Building references for Inventor files...");
            counter = 0;
            foreach (string iFile in inventorFiles)
            {
                msg = String.Format("\r{1}/{2}: Building references and properties for {0}", iFile, counter++, inventorFiles.Count);
                Console.Write(msg.PadRight(Console.BufferWidth, ' '));
                ApprenticeServerDocument doc = null;
                try
                {
                    doc = _invApp.Open(iFile);
                }
                catch (Exception ex)
                {
                    msg = String.Format("\r\nOpen ERROR!File {0} could not be opened", iFile);
                    Console.WriteLine(msg);
                    System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("{0}\r\n{1}", msg, ex) });
                    continue;
                }
                var    bcpParent          = bcpInventorFiles[iFile];
                string databaseRevisionID = "";
                string lastSavedLocation  = "";
                object indices            = null;
                object oldPaths           = null;
                object currentPaths       = null;
                try {
                    doc._GetReferenceInfo(out databaseRevisionID, out lastSavedLocation, out indices, out oldPaths, out currentPaths, true);
                }
                catch (Exception ex)
                {
                    msg = String.Format("\r\nRead ERROR!References for file {0} could not retrieved", iFile);
                    Console.WriteLine(msg);
                    System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("{0}\r\n{1}", msg, ex) });
                    continue;
                }

                string[] refs = currentPaths as string[];
                int[]    idx  = indices as int[];
                for (int i = 0; i < refs.Count(); i++)
                {
                    string child = refs[i];
                    if (child == null)
                    {
                        msg = String.Format("\r\nReference Warning!Reference {0} not found for assembly {1}", (oldPaths as string[])[i], iFile);
                        Console.WriteLine(msg);
                        System.IO.File.AppendAllLines("bcpMaker.log", new string[] { msg });
                        continue;
                    }
                    System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("Reference {0}", child) });

                    if (bcpInventorFiles.ContainsKey(child))
                    {
                        var bcpChild = bcpInventorFiles[child];
                        var assoc    = bcpParent.LatestIteration.AddAssociation(bcpChild.LatestIteration, AssociationObject.AssocType.Dependency);
                        assoc.refId           = idx[i].ToString();
                        assoc.needsresolution = true;
                    }
                    else
                    {
                        msg = String.Format("\rPackage ERROR!Child {0} not in bcp package for assembly {1}", (oldPaths as string[])[i], iFile);
                        Console.WriteLine(msg);
                        System.IO.File.AppendAllLines("bcpMaker.log", new string[] { msg });
                    }
                }
                string propName = "";
                try
                {
                    foreach (PropertySet propSet in doc.PropertySets)
                    {
                        foreach (Property prop in propSet)
                        {
                            propName = prop.Name;
                            if (!propName.Equals("Thumbnail") && !propName.Equals("Part Icon") && prop.Value != null)
                            {
                                bcpParent.LatestIteration.AddProperty(prop.DisplayName, prop.Value.ToString());
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    msg = String.Format("\r\nProperty ERROR!Property {1} for file {0} could not be retrieved", iFile, propName);
                    Console.WriteLine(msg);
                    System.IO.File.AppendAllLines("bcpMaker.log", new string[] { String.Format("{0}\r\n{1}", msg, ex) });
                }
                doc.Close();
            }
            _invApp.Close();

            bcpSvc.Flush();
            System.Diagnostics.Process.Start(targetFolder);
        }
示例#12
0
 public RibbonViewModel(DesignProject project)
 {
     Project = project;
 }
示例#13
0
        //public void SetExternalRulesDirectory(string externalRuleDirName)
        //{
        //    LogTrace(" ************ Start Processing Adding External Rules Directory *********");
        //    string ClientId = "{3BDD8D79-2179-4B11-8A5A-257B1C0263AC}";
        //    ApplicationAddIn iLogicAddIn = inventorApplication.ApplicationAddIns.ItemById[(ClientId)];
        //    dynamic iLogicAuto = iLogicAddIn.Automation;
        //    if (iLogicAuto == null)
        //    {
        //        LogError("Error: No iLogicAuto Atuomation set!");
        //    }
        //    else
        //    {
        //        List<string> externalRuleDirectories = new List<string>();
        //        foreach (string path in iLogicAuto.FileOptions.ExternalRuleDirectories)
        //        {
        //            externalRuleDirectories.Add(path);
        //            LogTrace("Existing Extrenal Rule Directory:" + path);
        //        }
        //        if (!externalRuleDirectories.Contains(externalRuleDirName))
        //        {
        //            LogTrace("Add a new Extrenal Directory:" + externalRuleDirName);
        //            externalRuleDirectories.Add(externalRuleDirName);
        //            iLogicAuto.FileOptions.ExternalRuleDirectories = externalRuleDirectories.ToArray();
        //        }
        //    }
        //    LogTrace(" ************ End Processing Adding External Rules Directory *********");
        //}

        public void Run(Document doc)
        {
            LogTrace("Run()");

            string currentDir = System.IO.Directory.GetCurrentDirectory();

            LogTrace("Current Dir = " + currentDir);

            var map = CreateEnumMap();

            JObject parameters = JObject.Parse(System.IO.File.ReadAllText("params.json"));

            string assemblyPath = parameters.GetValue("assemblyPath").Value <string>();

            using (new HeartBeat())
            {
                CheckPerformance();
                if (parameters.ContainsKey("projectPath"))
                {
                    string projectPath     = parameters.GetValue("projectPath").Value <string>();
                    string fullProjectPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(currentDir, projectPath));
                    LogTrace("fullProjectPath = " + fullProjectPath);

                    if (System.IO.File.Exists(fullProjectPath))
                    {
                        LogTrace("Loading and activating project");
                        DesignProject dp = inventorApplication.DesignProjectManager.DesignProjects.AddExisting(fullProjectPath);
                        dp.Activate();
                    }
                    else
                    {
                        LogTrace("Project file not found");
                    }
                }

                string fullAssemblyPath = System.IO.Path.GetFullPath(System.IO.Path.Combine(currentDir, assemblyPath));
                LogTrace("fullAssemblyPath = " + fullAssemblyPath);
                if (!System.IO.File.Exists(fullAssemblyPath))
                {
                    LogTrace("Did not find assembly");
                    return;
                }

                string           ext = System.IO.Path.GetExtension(fullAssemblyPath);
                AssemblyDocument asmDoc;
                if (ext == ".iam")
                {
                    if (parameters.ContainsKey("LOD"))
                    {
                        fullAssemblyPath += "<" + parameters.GetValue("LOD").Value <string>() + ">";
                    }
                    asmDoc = inventorApplication.Documents.Open(fullAssemblyPath, true) as AssemblyDocument;
                }
                else
                {
                    asmDoc           = AnyCADImport(fullAssemblyPath);
                    fullAssemblyPath = System.IO.Path.ChangeExtension(fullAssemblyPath, ".iam");
                }

                LogTrace("fullAssemblyPath = " + fullAssemblyPath);
                LogTrace("Opened input assembly file");
                AssemblyComponentDefinition compDef = asmDoc.ComponentDefinition;

                LogTrace("Before Update2");
                asmDoc.Update2(true);
                LogTrace("After Update2");

                PartDocument partDoc = inventorApplication.Documents.Add(DocumentTypeEnum.kPartDocumentObject, "", true) as PartDocument;
                LogTrace("Created part document");
                PartComponentDefinition partCompDef = partDoc.ComponentDefinition;

                ShrinkwrapDefinition SWD = null;
                try
                {
                    LogTrace("asmDoc.FullDocumentName = " + asmDoc.FullDocumentName);
                    LogTrace("LOD = " + asmDoc.LevelOfDetailName);
                    SWD = partCompDef.ReferenceComponents.ShrinkwrapComponents.CreateDefinition(asmDoc.FullDocumentName);
                    LogTrace("After ShrinkwrapComponents.CreateDefinition");
                    if (parameters.ContainsKey("CreateIndependentBodiesOnFailedBoolean"))
                    {
                        SWD.CreateIndependentBodiesOnFailedBoolean =
                            GetValue <bool>(parameters, "CreateIndependentBodiesOnFailedBoolean");
                    }
                    if (parameters.ContainsKey("DeriveStyle"))
                    {
                        // e.g. DerivedComponentStyleEnum.kDeriveAsSingleBodyNoSeams
                        SWD.DeriveStyle = map[GetValue <string>(parameters, "DeriveStyle")];
                    }
                    if (parameters.ContainsKey("RemoveInternalParts"))
                    {
                        SWD.RemoveInternalParts = GetValue <bool>(parameters, "RemoveInternalParts");
                    }
                    if (parameters.ContainsKey("RemoveAllInternalVoids"))
                    {
                        SWD.RemoveAllInternalVoids = GetValue <bool>(parameters, "RemoveAllInternalVoids");
                    }
                    if (parameters.ContainsKey("RemoveHolesDiameterRange"))
                    {
                        SWD.RemoveHolesDiameterRange = GetValue <double>(parameters, "RemoveHolesDiameterRange"); // in cm
                    }
                    if (parameters.ContainsKey("RemoveHolesStyle"))
                    {
                        SWD.RemoveHolesStyle = map[GetValue <string>(parameters, "RemoveHolesStyle")];
                    }
                    if (parameters.ContainsKey("RemoveFilletsRadiusRange"))
                    {
                        SWD.RemoveFilletsRadiusRange = GetValue <double>(parameters, "RemoveFilletsRadiusRange"); // in cm
                    }
                    if (parameters.ContainsKey("RemoveFilletsStyle"))
                    {
                        SWD.RemoveFilletsStyle = map[GetValue <string>(parameters, "RemoveFilletsStyle")];
                    }
                    if (parameters.ContainsKey("RemoveChamfersDistanceRange"))
                    {
                        SWD.RemoveChamfersDistanceRange = GetValue <double>(parameters, "RemoveChamfersDistanceRange");
                    }
                    if (parameters.ContainsKey("RemoveChamfersStyle"))
                    {
                        SWD.RemoveChamfersStyle = map[GetValue <string>(parameters, "RemoveChamfersStyle")];
                    }
                    if (parameters.ContainsKey("RemovePartsBySize"))
                    {
                        SWD.RemovePartsBySize = GetValue <bool>(parameters, "RemovePartsBySize");
                    }
                    if (parameters.ContainsKey("RemovePartsSize"))
                    {
                        SWD.RemovePartsSize = GetValue <double>(parameters, "RemovePartsSize"); // in cm
                    }
                    if (parameters.ContainsKey("RemovePocketsStyle"))
                    {
                        SWD.RemovePocketsStyle = map[GetValue <string>(parameters, "RemovePocketsStyle")];
                    }
                    if (parameters.ContainsKey("RemovePocketsMaxFaceLoopRange"))
                    {
                        SWD.RemovePocketsMaxFaceLoopRange = GetValue <double>(parameters, "RemovePocketsMaxFaceLoopRange"); // in cm
                    }

                    LogTrace("Before ShrinkwrapComponents.Add");
                    ShrinkwrapComponent SWComp = null;
                    try
                    {
                        SWComp = partCompDef.ReferenceComponents.ShrinkwrapComponents.Add(SWD);
                    }
                    catch (Exception ex)
                    {
                        LogTrace(ex.Message);
                        SWComp = partCompDef.ReferenceComponents.ShrinkwrapComponents[1];
                    }
                    LogTrace("After ShrinkwrapComponents.Add");

                    LogTrace("Before SuppressLinkToFile = true");
                    try
                    {
                        if (parameters.ContainsKey("SuppressLinkToFile"))
                        {
                            SWComp.SuppressLinkToFile = parameters.GetValue("SuppressLinkToFile").Value <bool>();
                        }
                    }
                    catch (Exception ex)
                    {
                        LogTrace(ex.Message);
                    }
                    LogTrace("After SuppressLinkToFile = true");

                    LogTrace("Saving part document");
                    partDoc.SaveAs(System.IO.Path.Combine(currentDir, "output.ipt"), false);
                    LogTrace("Saved part document to output.ipt");

                    //LogTrace("Saving to OBJ");
                    //partDoc.SaveAs(System.IO.Path.Combine(currentDir, "outputObjZip", "output.obj"), true);
                    //LogTrace("Saved to OBJ named output.obj");
                }
                catch (Exception ex)
                {
                    LogTrace("Error: " + ex.Message);
                }

                LogTrace("Finished");
            }
        }
        public void Run(Document placeholder /*not used*/)
        {
            LogTrace("Running v16 - open active LOD with logging - openVisible = false");
            try
            {
                // !AA! Get project path and assembly from json passed in
                // !AA! Pass in output type, assembly or SVF
                using (new HeartBeat())
                {
                    string currDir = Directory.GetCurrentDirectory();

                    // Uncomment out for local debug
                    //string inputPath = System.IO.Path.Combine(currDir, @"../../inputFiles", "params.json");
                    //Dictionary<string, string> options = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(inputPath));

                    Dictionary <string, string> options = JsonConvert.DeserializeObject <Dictionary <string, string> >(System.IO.File.ReadAllText("inputParams.json"));
                    string outputType   = options["outputType"];
                    string inputFile    = options["inputFile"];
                    string assemblyPath = Path.GetFullPath(Path.Combine(currDir, inputFile));

                    if (options.ContainsKey("verboseLogs"))
                    {
                        isVerbose = true;
                    }

                    if (options.ContainsKey("projectFile"))
                    {
                        string projectFile     = options["projectFile"];
                        string fullProjectPath = Path.GetFullPath(Path.Combine(currDir, projectFile));

                        // For debug of input data set
                        //DirPrint(currDir);
                        Console.WriteLine("fullProjectPath = " + fullProjectPath);

                        DesignProject dp = inventorApplication.DesignProjectManager.DesignProjects.AddExisting(fullProjectPath);
                        dp.Activate();
                    }

                    Console.WriteLine("assemblyPath = " + assemblyPath);

                    Document doc = null;
                    if (assemblyPath.ToUpper().EndsWith(".IAM"))
                    {
                        FileManager fm       = inventorApplication.FileManager;
                        string[]    dvReps   = fm.GetDesignViewRepresentations(assemblyPath);
                        string      dvActRep = fm.GetLastActiveDesignViewRepresentation(assemblyPath);
                        LogTrace($"LastActiveDesignViewRepresentation: {dvActRep}");

                        string[] lodReps   = fm.GetLevelOfDetailRepresentations(assemblyPath);
                        string   lodActRep = fm.GetLastActiveLevelOfDetailRepresentation(assemblyPath);
                        LogTrace($"LastActiveLevelOfDetailRepresentation: {lodActRep}");

                        //string[] posReps = fm.GetPositionalRepresentations(assemblyPath);
                        //string posActRep = fm.get

                        NameValueMap openOptions = inventorApplication.TransientObjects.CreateNameValueMap();
                        openOptions.Add("LevelOfDetailRepresentation", lodActRep);
                        openOptions.Add("DesignViewRepresentation", dvActRep);

                        doc = inventorApplication.Documents.OpenWithOptions(assemblyPath, openOptions, false);
                    }
                    else
                    {
                        doc = inventorApplication.Documents.Open(assemblyPath);
                    }
                    LogTrace($"Full document name: {doc.FullDocumentName}");

                    // Uncomment out for local debug
                    //string paramInputPath = System.IO.Path.Combine(currDir, @"../../inputFiles", "parameters.json");
                    //Dictionary<string, string> parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(paramInputPath));

                    Dictionary <string, string> parameters = JsonConvert.DeserializeObject <Dictionary <string, string> >(System.IO.File.ReadAllText("documentParams.json"));
                    foreach (KeyValuePair <string, string> entry in parameters)
                    {
                        var paramName  = entry.Key;
                        var paramValue = entry.Value;
                        LogTrace($" params: {paramName}, {paramValue}");
                        ChangeParam(doc, paramName, paramValue);
                    }

                    LogTrace($"Getting full file name of assembly");
                    var docDir   = Path.GetDirectoryName(doc.FullFileName);
                    var pathName = doc.FullFileName;
                    doc.Update2(true);

                    // Save both svf and iam for now. To optimize check output type to only save one or the other

                    // Save Forge Viewer format (SVF)
                    string viewableDir = SaveForgeViewable(doc);
                    //string viewableZip = Path.Combine(Directory.GetCurrentDirectory(), "viewable.zip");
                    //ZipOutput(viewableDir, viewableZip);

                    if (isVerbose)
                    {
                        LogTrace(">> Start of listing folder contents (before flatten)");
                        listFolderContents(currDir);
                        LogTrace(">> End of listing folder contents (before flatten)");
                    }

                    if (!options.ContainsKey("dontFlattenFolder"))
                    {
                        LogTrace($"Flattening SvfOutput folder");
                        flattenFolder(viewableDir, viewableDir, "");
                    }

                    if (isVerbose)
                    {
                        LogTrace(">> Start of listing folder contents (after flatten)");
                        listFolderContents(currDir);
                        LogTrace(">> End of listing folder contents (after flatten)");
                    }

                    LogTrace($"Code finished");

                    doc.Save2(true);
                    doc.Close(true);

                    // Zip up the output assembly
                    //
                    // assembly lives in own folder under WorkingDir. Get the WorkingDir. We want to zip up the original zip to include things like project
                    // files and libraries
                    //var zipInputDir = Path.GetDirectoryName(Path.GetDirectoryName(pathName) + "/../");
                    //var fileName = Path.Combine(Directory.GetCurrentDirectory(), "result.zip"); // the name must be in sync with OutputIam localName in Activity
                    //ZipOutput(zipInputDir, fileName);
                }
            }
            catch (Exception e)
            {
                LogError("Processing failed. " + e.ToString());
            }
        }
        public void Run(Document placeholder /*not used*/)
        {
            //LogTrace("Run called with {0}", doc.DisplayName);
            try
            {
                // !AA! Get project path and assembly from json passed in
                // !AA! Pass in output type, assembly or SVF
                using (new HeartBeat())
                {
                    string currDir = Directory.GetCurrentDirectory();

                    // Uncomment out for local debug
                    //string inputPath = System.IO.Path.Combine(currDir, @"../../inputFiles", "params.json");
                    //Dictionary<string, string> options = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(inputPath));

                    Dictionary <string, string> options = JsonConvert.DeserializeObject <Dictionary <string, string> >(System.IO.File.ReadAllText("inputParams.json"));
                    string outputType  = options["outputType"];
                    string inputFile   = options["inputFile"];
                    string projectFile = options["projectFile"];

                    string assemblyPath    = Path.GetFullPath(Path.Combine(currDir, inputFile));
                    string fullProjectPath = Path.GetFullPath(Path.Combine(currDir, projectFile));

                    if (options.ContainsKey("projectPath"))
                    {
                        // For debug of input data set
                        //DirPrint(currDir);
                        Console.WriteLine("fullProjectPath = " + fullProjectPath);

                        DesignProject dp = inventorApplication.DesignProjectManager.DesignProjects.AddExisting(fullProjectPath);
                        dp.Activate();
                    }

                    Console.WriteLine("documentPath = " + assemblyPath);
                    Document doc = inventorApplication.Documents.Open(assemblyPath);

                    // Uncomment out for local debug
                    //string paramInputPath = System.IO.Path.Combine(currDir, @"../../inputFiles", "documentParams.json");
                    //Dictionary<string, string> parameters = JsonConvert.DeserializeObject<Dictionary<string, string>>(System.IO.File.ReadAllText(paramInputPath));

                    Dictionary <string, string> parameters = JsonConvert.DeserializeObject <Dictionary <string, string> >(System.IO.File.ReadAllText("documentParams.json"));
                    foreach (KeyValuePair <string, string> entry in parameters)
                    {
                        var paramName  = entry.Key;
                        var paramValue = entry.Value;
                        LogTrace($" params: {paramName}, {paramValue}");
                        ChangeParam(doc, paramName, paramValue);
                    }


                    LogTrace($"Getting full file name of assembly");
                    var docDir   = Path.GetDirectoryName(doc.FullFileName);
                    var pathName = doc.FullFileName;
                    doc.Update2(true);

                    // Save Forge Viewer format (SVF)
                    string viewableDir = SaveForgeViewable(doc);
                    string viewableZip = Path.Combine(Directory.GetCurrentDirectory(), "viewable.zip");
                    ZipOutput(viewableDir, viewableZip);

                    // Save both svf and iam for now. To optimize check output type to only save one or the other
                    LogTrace($"Saving updated assembly");
                    doc.Save2(true);
                    doc.Close(true);

                    // Zip up the output assembly
                    //
                    // assembly lives in own folder under WorkingDir. Get the WorkingDir. We want to zip up the original zip to include things like project
                    // files and libraries. For parts make sure they are also in a subdirectory
                    LogTrace("Zipping up path: " + Path.GetDirectoryName(pathName));
                    var zipInputDir = Path.GetDirectoryName(Path.GetDirectoryName(pathName) + "/../");
                    var fileName    = Path.Combine(Directory.GetCurrentDirectory(), "result.zip"); // the name must be in sync with OutputIam localName in Activity
                    ZipOutput(zipInputDir, fileName);
                }
            }
            catch (Exception e)
            {
                LogError("Processing failed. " + e.ToString());
            }
        }
 public MainWindowViewModel()
 {
     Project         = new DesignProject();
     RibbonViewModel = new RibbonViewModel(Project);
     GameViewModel   = new GameViewModel(Project);
 }
 private void ApplicationEvents_OnActiveProjectChanged(DesignProject ProjectObject, EventTimingEnum BeforeOrAfter,
     NameValueMap Context, out HandlingCodeEnum HandlingCode)
 {
     if (_activeProjectType != ProjectObject.ProjectType)
     {
         if (ProjectObject.ProjectType == MultiUserModeEnum.kVaultMode)
         {
             TryLoadVaultAddin();
         }
         else
         {
             UnSubscribeEvents();
         }
         _activeProjectType = ProjectObject.ProjectType;
     }
     HandlingCode = HandlingCodeEnum.kEventNotHandled;
 }