Beispiel #1
0
        public void RunWithArguments(Document doc, NameValueMap map)
        {
            LogTrace("Processing " + doc.FullFileName);

            try
            {
                //string dirPath = System.IO.Path.GetDirectoryName(doc.FullDocumentName);
                string currentDirPath = System.IO.Directory.GetCurrentDirectory();

                #region ExportSAT file

                Trace.TraceInformation("Export SAT file.");
                TranslatorAddIn oSAT = null;

                foreach (ApplicationAddIn item in inventorApplication.ApplicationAddIns)
                {
                    if (item.ClassIdString == "{89162634-02B6-11D5-8E80-0010B541CD80}")
                    {
                        Trace.TraceInformation("Finded the PDF addin.");
                        oSAT = (TranslatorAddIn)item;
                        break;
                    }
                    else
                    {
                    }
                }

                if (oSAT != null)
                {
                    TranslationContext oContext = inventorApplication.TransientObjects.CreateTranslationContext();
                    NameValueMap       oIgesMap = inventorApplication.TransientObjects.CreateNameValueMap();

                    if (oSAT.get_HasSaveCopyAsOptions(doc, oContext, oIgesMap))
                    {
                        Trace.TraceInformation("SAT can be exported.");

                        Trace.TraceInformation("SAT: Set context type");
                        oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                        Trace.TraceInformation("SAT: create data medium");
                        DataMedium oData = inventorApplication.TransientObjects.CreateDataMedium();

                        Trace.TraceInformation("SAT save to: " + currentDirPath + "\\export.sat");
                        oData.FileName = currentDirPath + "\\export.sat";

                        oIgesMap.set_Value("GeometryType", 1);

                        oSAT.SaveCopyAs(doc, oContext, oIgesMap, oData);
                        Trace.TraceInformation("SAT exported.");
                    }

                    #endregion
                    GetListOfDirectory(System.IO.Directory.GetCurrentDirectory());
                }
            }
            catch (Exception e)
            {
                LogError("Processing failed. " + e.ToString());
            }
        }
Beispiel #2
0
        public void ExportSAT(Document doc)
        {
            string currentDirectory = System.IO.Directory.GetCurrentDirectory();

            LogTrace("Export SAT file.");
            TranslatorAddIn SAT_AddIn = (TranslatorAddIn)_inventorApplication.ApplicationAddIns.ItemById["{89162634-02B6-11D5-8E80-0010B541CD80}"];

            if (SAT_AddIn == null)
            {
                LogTrace("Could not access to SAT translator ...");
                return;
            }

            TranslationContext oContext = _inventorApplication.TransientObjects.CreateTranslationContext();
            NameValueMap       map      = _inventorApplication.TransientObjects.CreateNameValueMap();

            if (SAT_AddIn.get_HasSaveCopyAsOptions(doc, oContext, map))
            {
                LogTrace("SAT: Set context type");
                oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                LogTrace("SAT: create data medium");
                DataMedium oData = _inventorApplication.TransientObjects.CreateDataMedium();

                LogTrace("SAT save to: " + currentDirectory + "\\export.sat");
                oData.FileName = currentDirectory + "\\export.sat";

                map.set_Value("GeometryType", 1);

                SAT_AddIn.SaveCopyAs(doc, oContext, map, oData);
                LogTrace("SAT exported.");
            }
        }
Beispiel #3
0
        private void TranslatorSave(Inventor.Application application, object saveDataIn, string name)
        {
            try
            {
                //translator object does all the complicated saving
                TranslatorAddIn tAddIn = (TranslatorAddIn)application.ApplicationAddIns.ItemById["{81CA7D27-2DBE-4058-8188-9136F85FC859}"];

                //the document that we are saving
                object saveData = saveDataIn;

                //translator context holds the IOMechanism, don't worry about it
                TranslationContext context = application.TransientObjects.CreateTranslationContext();
                context.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                //options hold all the options of the save, like quality and file structure
                NameValueMap options = application.TransientObjects.CreateNameValueMap();

                //these options are needed in case the inventor defaults change
                options.Value["ExportFileStructure"] = 0;    //make sure all parts are saved as seperate files
                options.Value["Resolution"]          = 20;   //low resolution save (0 for high, 1 for medium)
                options.Value["ExportColor"]         = true; //makes sure color is exported

                //the data medium holds the destination
                DataMedium dataMed = application.TransientObjects.CreateDataMedium();
                dataMed.FileName = path + name + ".stl";
                //calls the save
                tAddIn.SaveCopyAs(saveData, context, options, dataMed);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }
        public static bool saveDwg(string pathToSave, DrawingDocument oDoc)
        {
            TranslatorAddIn DWGAddIn = (TranslatorAddIn)iApp.ApplicationAddIns.ItemById["{C24E3AC2-122E-11D5-8E91-0010B541CD80}"];

            TranslationContext oContext = iApp.TransientObjects.CreateTranslationContext();

            oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

            NameValueMap oOptions = iApp.TransientObjects.CreateNameValueMap();

            DataMedium oDataMedium = iApp.TransientObjects.CreateDataMedium();

            if (DWGAddIn.HasSaveCopyAsOptions[oDoc, oContext, oOptions])
            {
                string strIniFile = "C:\\Users\\edgesuser\\Desktop\\DWG-DXF\\test.ini";
                oOptions.Value["Export_Acad_IniFile"] = strIniFile;
                oOptions.Value["Sheet_Range"]         = PrintRangeEnum.kPrintAllSheets;
            }

            string[] oldName = System.Text.RegularExpressions.Regex.Split(oDoc.DisplayName, "\\.");


            oDataMedium.FileName = "C:\\Users\\edgesuser\\Desktop\\DWG-DXF\\" + oldName[0] + ".dwg";


            DWGAddIn.SaveCopyAs(oDoc, oContext, oOptions, oDataMedium);

            return(true);
        }
Beispiel #5
0
        public void WriteSTLFiles(string outputfolder)
        {
            Inventor.Application _invApp    = Links[0].Application;
            TranslatorAddIn      stptrans   = (TranslatorAddIn)_invApp.ApplicationAddIns.ItemById["{533E9A98-FC3B-11D4-8E7E-0010B541CD80}"];
            TranslationContext   stpcontext = _invApp.TransientObjects.CreateTranslationContext();

            NameValueMap stpoptions = _invApp.TransientObjects.CreateNameValueMap();

            Links.Reverse();

            foreach (Link oAsmComp in Links.Skip(1))
            {
                dynamic test = oAsmComp.ReferencedDocumentDescriptor.ReferencedDocument;

                if (stptrans.HasSaveCopyAsOptions[test, stpcontext, stpoptions])
                {
                    stpoptions.Value["ExportUnits"] = 6;
                    stpoptions.Value["Resolution"]  = 2;
                    stpcontext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                    DataMedium stpdata = _invApp.TransientObjects.CreateDataMedium();
                    stpdata.FileName = outputfolder + "\\" + oAsmComp.Name + ".stl";
                    stptrans.SaveCopyAs(test, stpcontext, stpoptions, stpdata);
                }
            }
        }
Beispiel #6
0
        public override void ExecWithArguments(Document doc, NameValueMap map)
        {
            try
            {
                LogTrace("Processing " + doc.FullFileName);

                using (new HeartBeat())
                {
                    if (doc.DocumentType == DocumentTypeEnum.kPartDocumentObject ||
                        doc.DocumentType == DocumentTypeEnum.kAssemblyDocumentObject) // Assembly.
                    {
                        ApplicationAddIn objExportAddin = _inventorApplication
                                                          .ApplicationAddIns
                                                          .Cast <ApplicationAddIn>()
                                                          .FirstOrDefault(item => item.ClassIdString.Equals("{f539fb09-fc01-4260-a429-1818b14d6bac}", StringComparison.OrdinalIgnoreCase));

                        var translator = (TranslatorAddIn)objExportAddin;

                        if (translator != null)
                        {
                            Trace.TraceInformation("OBJ Export translator is available. Preparing options.");

                            TranslationContext context = _inventorApplication.TransientObjects.CreateTranslationContext();
                            context.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                            // Set translation options
                            NameValueMap options = _inventorApplication.TransientObjects.CreateNameValueMap();
                            if (translator.get_HasSaveCopyAsOptions(doc, context, options))
                            {
                                options.set_Value("ExportFileStructure", 0); // one file
                                options.set_Value("RemoveInternalFacets", true);
                                options.set_Value("ExportUnits", 6);         // meters... to match default Unity units
                                options.set_Value("Resolution", 2);          // low
                            }

                            DataMedium data      = _inventorApplication.TransientObjects.CreateDataMedium();
                            var        outputDir = Path.Combine(Directory.GetCurrentDirectory(), "OBJ");
                            Directory.CreateDirectory(outputDir);
                            data.FileName = Path.Combine(outputDir, "result.obj");

                            translator.SaveCopyAs(doc, context, options, data);
                            LogTrace($"Export OBJ to '{data.FileName}'");
                        }
                        else
                        {
                            LogError("Cannot find OBJ Export translator");
                        }
                    }
                    else
                    {
                        LogError("Document type is not supported");
                    }
                }
            }
            catch (Exception e)
            {
                LogError("Processing failed. " + e.ToString());
            }
        }
Beispiel #7
0
        private void SaveAsSVF(Document Doc)
        {
            using (new HeartBeat())
            {
                LogTrace("** Saving SVF");

                try
                {
                    ApplicationAddIn svfAddin = _inventorApplication
                                                .ApplicationAddIns
                                                .Cast <ApplicationAddIn>()
                                                .FirstOrDefault(item => item.ClassIdString == "{C200B99B-B7DD-4114-A5E9-6557AB5ED8EC}");

                    var oAddin = (TranslatorAddIn)svfAddin;

                    if (oAddin != null)
                    {
                        Trace.TraceInformation("SVF Translator addin is available");
                        TranslationContext oContext = _inventorApplication.TransientObjects.CreateTranslationContext();
                        // Setting context type
                        oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                        NameValueMap oOptions = _inventorApplication.TransientObjects.CreateNameValueMap();
                        // Create data medium;
                        DataMedium oData = _inventorApplication.TransientObjects.CreateDataMedium();

                        Trace.TraceInformation("SVF save");
                        var sessionDir = Path.Combine(Directory.GetCurrentDirectory(), "SvfOutput");
                        oData.FileName = Path.Combine(sessionDir, "result.collaboration");
                        var outputDir          = Path.Combine(sessionDir, "output");
                        var bubbleFileOriginal = Path.Combine(outputDir, "bubble.json");
                        var bubbleFileNew      = Path.Combine(sessionDir, "bubble.json");

                        // Setup SVF options
                        if (oAddin.get_HasSaveCopyAsOptions(Doc, oContext, oOptions))
                        {
                            oOptions.set_Value("GeometryType", 1);
                            oOptions.set_Value("EnableExpressTranslation", false);
                            oOptions.set_Value("SVFFileOutputDir", sessionDir);
                            oOptions.set_Value("ExportFileProperties", true);
                            oOptions.set_Value("ObfuscateLabels", false);
                        }

                        LogTrace($"SVF files are output to: {oOptions.get_Value("SVFFileOutputDir")}");

                        oAddin.SaveCopyAs(Doc, oContext, oOptions, oData);
                        Trace.TraceInformation("SVF can be exported.");
                        LogTrace($"** Saved SVF as {oData.FileName}");
                        File.Move(bubbleFileOriginal, bubbleFileNew);
                    }
                }
                catch (Exception e)
                {
                    LogError($"********Export to format SVF failed: {e.Message}");
                }
            }
        }
        static PdfDocument InventorStitchDocuments(string toSavePath)
        {
            Process[] aInventor = Process.GetProcessesByName("Inventor");
            if (aInventor.Length == 0)
            {
                Console.WriteLine("Inventor application is not currently running.");
                return(null);
            }
            Application InvApp = (Application)Marshal.GetActiveObject("Inventor.Application");

            TranslatorAddIn PDFAddin = InvApp.ApplicationAddIns.ItemById["{0AC6FD96-2F4D-42CE-8BE0-8AEA580399E4}"] as Inventor.TranslatorAddIn;

            TranslationContext oContext = InvApp.TransientObjects.CreateTranslationContext();

            oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

            NameValueMap oOptions    = InvApp.TransientObjects.CreateNameValueMap();
            DataMedium   oDataMedium = InvApp.TransientObjects.CreateDataMedium();



            int           i     = 0;
            int           j     = 1;
            int           count = InvApp.Documents.VisibleDocuments.Count;
            List <string> files = new List <string>();

            foreach (var document in InvApp.Documents.VisibleDocuments)
            {
                if (PDFAddin.HasSaveCopyAsOptions[document, oContext, oOptions])
                {
                    // Options for drawings...
                    oOptions.Value["All_Color_AS_Black"]  = 1;
                    oOptions.Value["Remove_Line_Weights"] = 1;
                    oOptions.Value["Vector_Resolution"]   = 400;
                    oOptions.Value["Sheet_Range"]         = PrintRangeEnum.kPrintSheetRange;
                    oOptions.Value["Custom_Begin_Sheet"]  = 2;
                    oOptions.Value["Custom_End_Sheet"]    = 4;
                }

                files.Add(@toSavePath + "\\" + (i++).ToString() + ".pdf");
                oDataMedium.FileName = files.Last();

                PDFAddin.SaveCopyAs(document, oContext, oOptions, oDataMedium);
                Console.Write("\rExporting Inventor PDFs {0} of {1}", j++, count);
            }
            Console.Write("\n");

            PdfDocument pdfDocument = PdfStitchDocuments(@toSavePath, files.Select(s => s.Substring((s.LastIndexOf('\\')) + 1)).ToArray());

            return(pdfDocument);
        }
Beispiel #9
0
        public string Translate(string substitutePathVal)
        {
            string strFilePath = substitutePathVal.Substring(4);
            string strFileName = strFilePath.Substring(strFilePath.Length - int.Parse(substitutePathVal.Substring(0, 4), System.Globalization.NumberStyles.HexNumber));

            strFileName = strFileName.Substring(0, strFileName.Length - 5);
            System.Diagnostics.Debug.WriteLine(strFileName + "///" + strFilePath);
            ApplicationAddIns oAddIns     = _stAddIn.m_invApp.ApplicationAddIns;
            TranslatorAddIn   oTransAddIn = (TranslatorAddIn)oAddIns.ItemById[translatorID];

            oTransAddIn.Activate();

            TransientObjects transObj = _stAddIn.m_invApp.TransientObjects;

            DataMedium file = transObj.CreateDataMedium();

            file.FileName = strFilePath;

            TranslationContext context = transObj.CreateTranslationContext();

            context.Type = IOMechanismEnum.kFileBrowseIOMechanism;

            NameValueMap options = transObj.CreateNameValueMap();

            bool oHasOpt = oTransAddIn.HasOpenOptions[file, context, options];

            oTransAddIn.Open(file, context, options, out object oDoc);

            Document doc = (Document)oDoc;

            _stAddIn.m_invApp.SilentOperation = true;
            string savingDirectory = Properties.Settings.Default.projectFolder;

            if (savingDirectory == "")
            {
                savingDirectory =
                    _stAddIn.m_invApp.DesignProjectManager
                    .ActiveDesignProject.WorkspacePath
                    + "\\MCMASTER_REPOSITORY\\";
            }
            doc.SaveAs(savingDirectory + strFileName + ".ipt", false);
            if (System.IO.File.Exists(strFilePath))
            {
                System.IO.File.Delete(strFilePath);
            }
            _stAddIn.m_invApp.SilentOperation = false;
            doc.Close();
            return(savingDirectory + strFileName + ".ipt");
        }
Beispiel #10
0
        private void SaveAsPdf(Document doc, string fileName)
        {
            string          dirPath = Directory.GetCurrentDirectory();
            TranslatorAddIn oPDF    = null;

            foreach (ApplicationAddIn item in inventorApplication.ApplicationAddIns)
            {
                if (item.ClassIdString == "{0AC6FD96-2F4D-42CE-8BE0-8AEA580399E4}")
                {
                    Trace.TraceInformation("Found the PDF addin.");
                    oPDF = (TranslatorAddIn)item;
                    break;
                }
                else
                {
                }
            }

            if (oPDF != null)
            {
                TranslationContext oContext = inventorApplication.TransientObjects.CreateTranslationContext();
                NameValueMap       oPdfMap  = inventorApplication.TransientObjects.CreateNameValueMap();

                if (oPDF.get_HasSaveCopyAsOptions(doc, oContext, oPdfMap))
                {
                    Trace.TraceInformation("PDF: can be exported.");

                    Trace.TraceInformation("PDF: Set context type");
                    oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                    Trace.TraceInformation("PDF: create data medium");
                    DataMedium oData = inventorApplication.TransientObjects.CreateDataMedium();

                    string pdfFileName = dirPath + "/" + fileName + ".pdf";
                    Trace.TraceInformation("PDF save to: " + pdfFileName);
                    oData.FileName = pdfFileName;

                    oPdfMap.set_Value("All_Color_AS_Black", 0);

                    oPDF.SaveCopyAs(doc, oContext, oPdfMap, oData);
                    Trace.TraceInformation("PDF exported.");
                }
            }
        }
        private static void importaFromAutocad(string v)
        {
            TranslatorAddIn oDWGTranslator = (TranslatorAddIn)iApp.ApplicationAddIns.ItemById["{C24E3AC2-122E-11D5-8E91-0010B541CD80}"];

            DataMedium oDataMedium = iApp.TransientObjects.CreateDataMedium();

            oDataMedium.FileName = @"X:\Commesse\Focchi\200000 40L\99 Service\Matrici full\" + v + "_def.dwg";

            TranslationContext oTranslationContext = iApp.TransientObjects.CreateTranslationContext();

            oTranslationContext.Type = Inventor.IOMechanismEnum.kFileBrowseIOMechanism;


            PartDocument oDoc = (PartDocument)iApp.Documents.Add(DocumentTypeEnum.kPartDocumentObject);

            PartComponentDefinition oPartCompDef = oDoc.ComponentDefinition;

            PlanarSketch oSketchC = oPartCompDef.Sketches.Add(oPartCompDef.WorkPlanes[2], true);

            oSketchC.Name = "testtttttt";

            Sketch oSketch = (Sketch)oPartCompDef.Sketches["testtttttt"];

            oSketch.Edit();

            oTranslationContext.OpenIntoExisting = oSketch;

            NameValueMap oOptions = iApp.TransientObjects.CreateNameValueMap();

            oOptions.Add("SelectedLayers", "0");

            oOptions.Add("InvertLayersSelection", false);
            oOptions.Add("ConstrainEndPoints", true);

            object boh;

            oDWGTranslator.Open(oDataMedium, oTranslationContext, oOptions, out boh);
            oSketch.ExitEdit();
            // RegisterAutoCADDefault()
        }
Beispiel #12
0
        public void Open(DataMedium SourceData, TranslationContext Context, NameValueMap Options, ref object TargetObject)
        {
            InvAddIn.InventorSol S = new InvAddIn.InventorSol();


            using (var reader = new Pdf3DReaderService())
            {
                List <Element3D> allElements = null;
                List <string>    Olist       = new List <string>();
                reader.ReadPdf3D(SourceData.FileName, out allElements);
                S.Draw3D((Part)allElements[0], "test");
            }



            //// InvAddIn.InventorSol.Start(Pdf_File);

            //InvAddIn.InventorSol S = new InvAddIn.InventorSol();
            //S.Start(SourceData.FileName);

            ////InvAddIn.InventorSol.StandartTest();
        }
        ///<summary>Initializes a new instance of <see cref="TranslatorData"/></summary>
        internal TranslatorData(string addinGUID, string fullFileName, Document doc = null, Inventor.Application app = null)
        {
            if (app == null)
            {
                app = (Application)doc.Parent;
            }

            oAppAddIn = app.ApplicationAddIns.ItemById[addinGUID];

            TransientObjects oTo = app.TransientObjects;

            if (oAppAddIn is TranslatorAddIn)
            {
                oContext      = oTo.CreateTranslationContext();
                oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                oDataMedium = oTo.CreateDataMedium();

                oDataMedium.FileName = fullFileName;
            }
            oOptions = oTo.CreateNameValueMap();
        }
        //private void TriggerDrawingRules(Document doc)
        //{
        //    Parameters parameters = ((DrawingDocument)doc).Parameters;

        //    try
        //    {
        //        dynamic trigger = parameters["iTrigger0"];

        //        // Just inccrement the trigger value, right now only supporting numeric triggers
        //        trigger.Value++;
        //        LogTrace("Fired trigger for drawing rules");
        //    }
        //    catch (Exception)
        //    {
        //        LogTrace("No drawing rules to trigger");
        //    }

        // }

        // Export Drawing file to PDF format
        // In case that the Drawing has more sheets -> it will export PDF with pages
        // Each PDF page represet one Drawing sheet
        public void ExportIDWToPDF(Document doc, string exportFileName)
        {
            if (doc == null)
            {
                LogError("Document is null!");
                return;
            }

            LogTrace("PDF file full path : " + exportFileName);

            LogTrace("Create PDF Translator Addin");
            TranslatorAddIn PDFAddIn = (TranslatorAddIn)inventorApplication.ApplicationAddIns.ItemById["{0AC6FD96-2F4D-42CE-8BE0-8AEA580399E4}"];

            if (PDFAddIn == null)
            {
                LogError("Error: PDF Translator Addin is null!");
                return;
            }

            TranslationContext context = inventorApplication.TransientObjects.CreateTranslationContext();
            NameValueMap       options = inventorApplication.TransientObjects.CreateNameValueMap();

            if (PDFAddIn.HasSaveCopyAsOptions[doc, context, options])
            {
                context.Type = IOMechanismEnum.kFileBrowseIOMechanism;
                DataMedium dataMedium = inventorApplication.TransientObjects.CreateDataMedium();

                options.Value["Sheet_Range"]       = PrintRangeEnum.kPrintAllSheets;
                options.Value["Vector_Resolution"] = 300;

                options.Value["All_Color_AS_Black"] = false;
                options.Value["Sheets"]             = GetSheetOptions(doc);

                dataMedium.FileName = exportFileName;
                LogTrace("Processing PDF export ...");
                PDFAddIn.SaveCopyAs(doc, context, options, dataMedium);
                LogTrace("Finish processing PDF export ...");
            }
        }
    public bool GetTranslatorOpenOptions(string TranslatorClsId, ref NameValueMap options)
    {
        bool functionReturnValue = false;

        TranslatorAddIn oTranslator = (TranslatorAddIn)mApp.ApplicationAddIns.ItemById[TranslatorClsId];

        if (oTranslator == null)
        {
            functionReturnValue = false;
            return(functionReturnValue);
        }

        oTranslator.Activate();

        if ((oTranslator.AddInType != ApplicationAddInTypeEnum.kTranslationApplicationAddIn))
        {
            //Not a translator addin...
            functionReturnValue = false;
            return(functionReturnValue);
        }

        DataMedium Medium = mApp.TransientObjects.CreateDataMedium();

        Medium.FileName   = "C:\\Temp\\File.xxx";
        Medium.MediumType = MediumTypeEnum.kFileNameMedium;

        TranslationContext Context = mApp.TransientObjects.CreateTranslationContext();

        options = mApp.TransientObjects.CreateNameValueMap();

        try {
            functionReturnValue = oTranslator.get_HasOpenOptions(Medium, Context, options);
        } catch {
            functionReturnValue = false;
        }
        return(functionReturnValue);
    }
        private string SaveForgeViewable(Document doc)
        {
            string viewableOutputDir = null;

            //using (new HeartBeat())
            {
                LogTrace($"** Saving SVF");
                try
                {
                    TranslatorAddIn oAddin = null;


                    foreach (ApplicationAddIn item in inventorApplication.ApplicationAddIns)
                    {
                        if (item.ClassIdString == "{C200B99B-B7DD-4114-A5E9-6557AB5ED8EC}")
                        {
                            Trace.TraceInformation("SVF Translator addin is available");
                            oAddin = (TranslatorAddIn)item;
                            break;
                        }
                        else
                        {
                        }
                    }

                    if (oAddin != null)
                    {
                        Trace.TraceInformation("SVF Translator addin is available");
                        TranslationContext oContext = inventorApplication.TransientObjects.CreateTranslationContext();
                        // Setting context type
                        oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                        NameValueMap oOptions = inventorApplication.TransientObjects.CreateNameValueMap();
                        // Create data medium;
                        DataMedium oData = inventorApplication.TransientObjects.CreateDataMedium();

                        Trace.TraceInformation("SVF save");
                        var workingDir = Directory.GetCurrentDirectory(); //Path.GetDirectoryName(doc.FullFileName);
                        var sessionDir = Path.Combine(workingDir, "SvfOutput");

                        // Make sure we delete any old contents that may be in the output directory first,
                        // this is for local debugging. In DA4I the working directory is always clean
                        if (Directory.Exists(sessionDir))
                        {
                            Directory.Delete(sessionDir, true);
                        }

                        oData.FileName = Path.Combine(sessionDir, "result.collaboration");
                        var outputDir          = Path.Combine(sessionDir, "output");
                        var bubbleFileOriginal = Path.Combine(outputDir, "bubble.json");
                        var bubbleFileNew      = Path.Combine(sessionDir, "bubble.json");

                        // Setup SVF options
                        if (oAddin.get_HasSaveCopyAsOptions(doc, oContext, oOptions))
                        {
                            oOptions.set_Value("EnableExpressTranslation", false);
                            oOptions.set_Value("SVFFileOutputDir", sessionDir);
                            oOptions.set_Value("ExportFileProperties", true);
                            oOptions.set_Value("ObfuscateLabels", false);
                        }

                        LogTrace($"SVF files are oputput to: {oOptions.get_Value("SVFFileOutputDir")}");

                        oAddin.SaveCopyAs(doc, oContext, oOptions, oData);
                        Trace.TraceInformation("SVF can be exported.");
                        LogTrace($"Moving bubble file");
                        File.Move(bubbleFileOriginal, bubbleFileNew);
                        LogTrace($"Deleting result.collaboration");
                        File.Delete(oData.FileName);

                        viewableOutputDir = sessionDir;

                        LogTrace($"Finished SVF generation");
                    }
                }
                catch (Exception e)
                {
                    LogError($"********Export to format SVF failed: {e.Message}");
                    return(null);
                }
            }
            return(viewableOutputDir);
        }
Beispiel #17
0
 public bool get_HasOpenOptions(DataMedium SourceData, TranslationContext Context, NameValueMap DefaultOptions)
 {
     return(false);
 }
Beispiel #18
0
 public object GetThumbnail(DataMedium SourceData)
 {
     return(null);
 }
Beispiel #19
0
 public void SaveCopyAs(object SourceObject, TranslationContext Context, NameValueMap Options, DataMedium TargetData)
 {
 }
Beispiel #20
0
 public void ShowOpenOptions(DataMedium SourceData, TranslationContext Context, NameValueMap ChosenOptions)
 {
 }
        private void mCreateExport(IJobProcessorServices context, IJob job)
        {
            List <string> mExpFrmts    = new List <string>();
            List <string> mUploadFiles = new List <string>();

            // read target export formats from settings file
            Settings settings = Settings.Load();

            #region validate execution rules

            mTrace.IndentLevel += 1;
            mTrace.WriteLine("Translator Job started...");

            //pick up this job's context
            Connection connection = context.Connection;
            Autodesk.Connectivity.WebServicesTools.WebServiceManager mWsMgr = connection.WebServiceManager;
            long   mEntId    = Convert.ToInt64(job.Params["EntityId"]);
            string mEntClsId = job.Params["EntityClassId"];

            // only run the job for files
            if (mEntClsId != "FILE")
            {
                return;
            }

            // only run the job for ipt and iam file types,
            List <string> mFileExtensions = new List <string> {
                ".ipt", ".iam"
            };
            ACW.File mFile = mWsMgr.DocumentService.GetFileById(mEntId);
            if (!mFileExtensions.Any(n => mFile.Name.Contains(n)))
            {
                return;
            }

            // apply execution filters, e.g., exclude files of classification "substitute" etc.
            List <string> mFileClassific = new List <string> {
                "ConfigurationFactory", "DesignSubstitute"
            };                                                                                             //add "DesignDocumentation" for 3D Exporters only
            if (mFileClassific.Any(n => mFile.FileClass.ToString().Contains(n)))
            {
                return;
            }

            // you may add addtional execution filters, e.g., category name == "Sheet Metal Part"

            if (settings.ExportFomats == null)
            {
                throw new Exception("Settings expect to list at least one export format!");
            }
            if (settings.ExportFomats.Contains(","))
            {
                mExpFrmts = settings.ExportFomats.Split(',').ToList();
            }
            else
            {
                mExpFrmts.Add(settings.ExportFomats);
            }

            //remove SM formats, if source isn't sheet metal
            if (mFile.Cat.CatName != settings.SmCatDispName)
            {
                if (mExpFrmts.Contains("SMDXF"))
                {
                    mExpFrmts.Remove("SMDXF");
                }
                if (mExpFrmts.Contains("SMSAT"))
                {
                    mExpFrmts.Remove("SMSAT");
                }
            }

            mTrace.WriteLine("Job execution rules validated.");

            #endregion validate execution rules

            #region VaultInventorServer IPJ activation
            //establish InventorServer environment including translator addins; differentiate her in case full Inventor.exe is used
            Inventor.InventorServer mInv          = context.InventorObject as InventorServer;
            ApplicationAddIns       mInvSrvAddIns = mInv.ApplicationAddIns;

            //override InventorServer default project settings by your Vault specific ones
            Inventor.DesignProjectManager projectManager;
            Inventor.DesignProject        mSaveProject, mProject;
            String   mIpjPath      = "";
            String   mWfPath       = "";
            String   mIpjLocalPath = "";
            ACW.File mProjFile;
            VDF.Vault.Currency.Entities.FileIteration mIpjFileIter = null;

            //download and activate the Inventor Project file in VaultInventorServer
            mTrace.IndentLevel += 1;
            mTrace.WriteLine("Job tries activating Inventor project file as enforced in Vault behavior configurations.");
            try
            {
                //Download enforced ipj file
                if (mWsMgr.DocumentService.GetEnforceWorkingFolder() && mWsMgr.DocumentService.GetEnforceInventorProjectFile())
                {
                    mIpjPath = mWsMgr.DocumentService.GetInventorProjectFileLocation();
                    mWfPath  = mWsMgr.DocumentService.GetRequiredWorkingFolderLocation();
                }
                else
                {
                    throw new Exception("Job requires both settings enabled: 'Enforce Workingfolder' and 'Enforce Inventor Project'.");
                }

                String[] mIpjFullFileName = mIpjPath.Split(new string[] { "/" }, StringSplitOptions.None);
                String   mIpjFileName     = mIpjFullFileName.LastOrDefault();

                //get the projects file object for download
                ACW.PropDef[] filePropDefs = mWsMgr.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE");
                ACW.PropDef   mNamePropDef = filePropDefs.Single(n => n.SysName == "ClientFileName");
                ACW.SrchCond  mSrchCond    = new ACW.SrchCond()
                {
                    PropDefId = mNamePropDef.Id,
                    PropTyp   = ACW.PropertySearchType.SingleProperty,
                    SrchOper  = 3, // is equal
                    SrchRule  = ACW.SearchRuleType.Must,
                    SrchTxt   = mIpjFileName
                };
                string          bookmark     = string.Empty;
                ACW.SrchStatus  status       = null;
                List <ACW.File> totalResults = new List <ACW.File>();
                while (status == null || totalResults.Count < status.TotalHits)
                {
                    ACW.File[] results = mWsMgr.DocumentService.FindFilesBySearchConditions(new ACW.SrchCond[] { mSrchCond },
                                                                                            null, null, false, true, ref bookmark, out status);
                    if (results != null)
                    {
                        totalResults.AddRange(results);
                    }
                    else
                    {
                        break;
                    }
                }
                if (totalResults.Count == 1)
                {
                    mProjFile = totalResults[0];
                }
                else
                {
                    throw new Exception("Job execution stopped due to ambigous project file definitions; single project file per Vault expected");
                }

                //define download settings for the project file
                VDF.Vault.Settings.AcquireFilesSettings mDownloadSettings = new VDF.Vault.Settings.AcquireFilesSettings(connection);
                mDownloadSettings.LocalPath = new VDF.Currency.FolderPathAbsolute(mWfPath);
                mIpjFileIter = new VDF.Vault.Currency.Entities.FileIteration(connection, mProjFile);
                mDownloadSettings.AddFileToAcquire(mIpjFileIter, VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Download);

                //download project file and get local path
                VDF.Vault.Results.AcquireFilesResults   mDownLoadResult;
                VDF.Vault.Results.FileAcquisitionResult fileAcquisitionResult;
                mDownLoadResult       = connection.FileManager.AcquireFiles(mDownloadSettings);
                fileAcquisitionResult = mDownLoadResult.FileResults.FirstOrDefault();
                mIpjLocalPath         = fileAcquisitionResult.LocalPath.FullPath;

                //activate this Vault's ipj temporarily
                projectManager = mInv.DesignProjectManager;
                mSaveProject   = projectManager.ActiveDesignProject;
                mProject       = projectManager.DesignProjects.AddExisting(mIpjLocalPath);
                mProject.Activate();

                //[Optionally:] get Inventor Design Data settings and download all related files ---------

                mTrace.WriteLine("Job successfully activated Inventor IPJ.");
            }
            catch (Exception ex)
            {
                throw new Exception("Job was not able to activate Inventor project file. - Note: The ipj must not be checked out by another user.", ex.InnerException);
            }
            #endregion VaultInventorServer IPJ activation

            #region download source file(s)
            mTrace.IndentLevel += 1;
            mTrace.WriteLine("Job downloads source file(s) for translation.");
            //download the source file iteration, enforcing overwrite if local files exist
            VDF.Vault.Settings.AcquireFilesSettings   mDownloadSettings2 = new VDF.Vault.Settings.AcquireFilesSettings(connection);
            VDF.Vault.Currency.Entities.FileIteration mFileIteration     = new VDF.Vault.Currency.Entities.FileIteration(connection, mFile);
            mDownloadSettings2.AddFileToAcquire(mFileIteration, VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Download);
            mDownloadSettings2.OrganizeFilesRelativeToCommonVaultRoot = true;
            mDownloadSettings2.OptionsRelationshipGathering.FileRelationshipSettings.IncludeChildren        = true;
            mDownloadSettings2.OptionsRelationshipGathering.FileRelationshipSettings.IncludeLibraryContents = true;
            mDownloadSettings2.OptionsRelationshipGathering.FileRelationshipSettings.ReleaseBiased          = true;
            VDF.Vault.Settings.AcquireFilesSettings.AcquireFileResolutionOptions mResOpt = new VDF.Vault.Settings.AcquireFilesSettings.AcquireFileResolutionOptions();
            mResOpt.OverwriteOption           = VDF.Vault.Settings.AcquireFilesSettings.AcquireFileResolutionOptions.OverwriteOptions.ForceOverwriteAll;
            mResOpt.SyncWithRemoteSiteSetting = VDF.Vault.Settings.AcquireFilesSettings.SyncWithRemoteSite.Always;

            //execute download
            VDF.Vault.Results.AcquireFilesResults mDownLoadResult2 = connection.FileManager.AcquireFiles(mDownloadSettings2);
            //pickup result details
            VDF.Vault.Results.FileAcquisitionResult fileAcquisitionResult2 = mDownLoadResult2.FileResults.Where(n => n.File.EntityName == mFileIteration.EntityName).FirstOrDefault();

            if (fileAcquisitionResult2 == null)
            {
                mSaveProject.Activate();
                throw new Exception("Job stopped execution as the source file to translate did not download");
            }
            string mDocPath = fileAcquisitionResult2.LocalPath.FullPath;
            string mExt     = System.IO.Path.GetExtension(mDocPath); //mDocPath.Split('.').Last();
            mTrace.WriteLine("Job successfully downloaded source file(s) for translation.");
            #endregion download source file(s)

            #region VaultInventorServer CAD Export

            mTrace.WriteLine("Job opens source file.");
            Document mDoc = null;
            mDoc = mInv.Documents.Open(mDocPath);

            foreach (string item in mExpFrmts)
            {
                switch (item)
                {
                case ("STP"):
                    //activate STEP Translator environment,
                    try
                    {
                        TranslatorAddIn mStepTrans = mInvSrvAddIns.ItemById["{90AF7F40-0C01-11D5-8E83-0010B541CD80}"] as TranslatorAddIn;
                        if (mStepTrans == null)
                        {
                            //switch temporarily used project file back to original one
                            mSaveProject.Activate();
                            throw new Exception("Job stopped execution, because indicated translator addin is not available.");
                        }
                        TranslationContext mTransContext = mInv.TransientObjects.CreateTranslationContext();
                        NameValueMap       mTransOptions = mInv.TransientObjects.CreateNameValueMap();
                        if (mStepTrans.HasSaveCopyAsOptions[mDoc, mTransContext, mTransOptions] == true)
                        {
                            //open, and translate the source file
                            mTrace.IndentLevel += 1;
                            mTrace.WriteLine("Job opens source file.");
                            mTransOptions.Value["ApplicationProtocolType"] = 3;     //AP 2014, Automotive Design
                            mTransOptions.Value["Description"]             = "Sample-Job Step Translator using VaultInventorServer";
                            mTransContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;
                            //delete local file if exists, as the export wouldn't overwrite
                            if (System.IO.File.Exists(mDocPath.Replace(mExt, ".stp")))
                            {
                                System.IO.File.SetAttributes(mDocPath.Replace(mExt, ".stp"), System.IO.FileAttributes.Normal);
                                System.IO.File.Delete(mDocPath.Replace(mExt, ".stp"));
                            }
                            ;
                            DataMedium mData = mInv.TransientObjects.CreateDataMedium();
                            mData.FileName = mDocPath.Replace(mExt, ".stp");
                            mStepTrans.SaveCopyAs(mDoc, mTransContext, mTransOptions, mData);
                            //collect all export files for later upload
                            mUploadFiles.Add(mDocPath.Replace(mExt, ".stp"));
                            mTrace.WriteLine("STEP Translator created file: " + mUploadFiles.LastOrDefault());
                            mTrace.IndentLevel -= 1;
                        }
                    }
                    catch (Exception ex)
                    {
                        mTrace.WriteLine("STEP Export Failed: " + ex.Message);
                    }
                    break;

                case "JT":
                    //activate JT Translator environment,
                    try
                    {
                        TranslatorAddIn mJtTrans = mInvSrvAddIns.ItemById["{16625A0E-F58C-4488-A969-E7EC4F99CACD}"] as TranslatorAddIn;
                        if (mJtTrans == null)
                        {
                            //switch temporarily used project file back to original one
                            mTrace.WriteLine("JT Translator not found.");
                            break;
                        }
                        TranslationContext mTransContext = mInv.TransientObjects.CreateTranslationContext();
                        NameValueMap       mTransOptions = mInv.TransientObjects.CreateNameValueMap();
                        if (mJtTrans.HasSaveCopyAsOptions[mDoc, mTransContext, mTransOptions] == true)
                        {
                            //open, and translate the source file
                            mTrace.IndentLevel += 1;

                            mTransOptions.Value["Version"] = 102;     //default
                            mTransContext.Type             = IOMechanismEnum.kFileBrowseIOMechanism;
                            //delete local file if exists, as the export wouldn't overwrite
                            if (System.IO.File.Exists(mDocPath.Replace(mExt, ".jt")))
                            {
                                System.IO.File.SetAttributes(mDocPath.Replace(mExt, ".jt"), System.IO.FileAttributes.Normal);
                                System.IO.File.Delete(mDocPath.Replace(mExt, ".jt"));
                            }
                            ;
                            DataMedium mData = mInv.TransientObjects.CreateDataMedium();
                            mData.FileName = mDocPath.Replace(mExt, ".jt");
                            mJtTrans.SaveCopyAs(mDoc, mTransContext, mTransOptions, mData);
                            //collect all export files for later upload
                            mUploadFiles.Add(mDocPath.Replace(mExt, ".jt"));
                            mTrace.WriteLine("JT Translator created file: " + mUploadFiles.LastOrDefault());
                            mTrace.IndentLevel -= 1;
                        }
                    }
                    catch (Exception ex)
                    {
                        mTrace.WriteLine("JT Export Failed: " + ex.Message);
                    }
                    break;

                case "SMDXF":
                    try
                    {
                        TranslatorAddIn mDXFTrans = mInvSrvAddIns.ItemById["{C24E3AC4-122E-11D5-8E91-0010B541CD80}"] as TranslatorAddIn;
                        mDXFTrans.Activate();
                        if (mDXFTrans == null)
                        {
                            mTrace.WriteLine("DXF Translator not found.");
                            break;
                        }

                        if (System.IO.File.Exists(mDocPath.Replace(mExt, ".dxf")))
                        {
                            System.IO.FileInfo fileInfo = new FileInfo(mDocPath.Replace(mExt, ".dxf"));
                            fileInfo.IsReadOnly = false;
                            fileInfo.Delete();
                        }

                        PartDocument mPartDoc = (PartDocument)mDoc;
                        DataIO       mDataIO  = mPartDoc.ComponentDefinition.DataIO;
                        String       mOut     = "FLAT PATTERN DXF?AcadVersion=R12&OuterProfileLayer=Outer";
                        mDataIO.WriteDataToFile(mOut, mDocPath.Replace(mExt, ".dxf"));
                        //collect all export files for later upload
                        mUploadFiles.Add(mDocPath.Replace(mExt, ".dxf"));
                        mTrace.WriteLine("SheetMetal DXF Translator created file: " + mUploadFiles.LastOrDefault());
                        mTrace.IndentLevel -= 1;
                    }
                    catch (Exception ex)
                    {
                        mTrace.WriteLine("SMDXF Export Failed: " + ex.Message);
                    }
                    break;

                default:
                    break;
                }
            }
            mDoc.Close(true);
            mTrace.WriteLine("Source file closed");

            //switch temporarily used project file back to original one
            mSaveProject.Activate();

            mTrace.WriteLine("Job exported file(s); continues uploading.");
            mTrace.IndentLevel -= 1;

            #endregion VaultInventorServer CAD Export

            #region Vault File Management

            foreach (string file in mUploadFiles)
            {
                ACW.File           mExpFile        = null;
                System.IO.FileInfo mExportFileInfo = new System.IO.FileInfo(file);
                if (mExportFileInfo.Exists)
                {
                    //copy file to output location
                    if (settings.OutPutPath != "")
                    {
                        System.IO.FileInfo fileInfo = new FileInfo(settings.OutPutPath + "\\" + mExportFileInfo.Name);
                        if (fileInfo.Exists)
                        {
                            fileInfo.IsReadOnly = false;
                            fileInfo.Delete();
                        }
                        System.IO.File.Copy(mExportFileInfo.FullName, settings.OutPutPath + "\\" + mExportFileInfo.Name, true);
                    }

                    //add resulting export file to Vault if it doesn't exist, otherwise update the existing one

                    ACW.Folder mFolder       = mWsMgr.DocumentService.FindFoldersByIds(new long[] { mFile.FolderId }).FirstOrDefault();
                    string     vaultFilePath = System.IO.Path.Combine(mFolder.FullName, mExportFileInfo.Name).Replace("\\", "/");

                    ACW.File wsFile = mWsMgr.DocumentService.FindLatestFilesByPaths(new string[] { vaultFilePath }).First();
                    VDF.Currency.FilePathAbsolute             vdfPath       = new VDF.Currency.FilePathAbsolute(mExportFileInfo.FullName);
                    VDF.Vault.Currency.Entities.FileIteration vdfFile       = null;
                    VDF.Vault.Currency.Entities.FileIteration addedFile     = null;
                    VDF.Vault.Currency.Entities.FileIteration mUploadedFile = null;
                    if (wsFile == null || wsFile.Id < 0)
                    {
                        // add new file to Vault
                        mTrace.WriteLine("Job adds " + mExportFileInfo.Name + " as new file.");

                        if (mFolder == null || mFolder.Id == -1)
                        {
                            throw new Exception("Vault folder " + mFolder.FullName + " not found");
                        }

                        var folderEntity = new Autodesk.DataManagement.Client.Framework.Vault.Currency.Entities.Folder(connection, mFolder);
                        try
                        {
                            addedFile = connection.FileManager.AddFile(folderEntity, "Created by Job Processor", null, null, ACW.FileClassification.DesignRepresentation, false, vdfPath);
                            mExpFile  = addedFile;
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Job could not add export file " + vdfPath + "Exception: ", ex);
                        }
                    }
                    else
                    {
                        // checkin new file version
                        mTrace.WriteLine("Job uploads " + mExportFileInfo.Name + " as new file version.");

                        VDF.Vault.Settings.AcquireFilesSettings aqSettings = new VDF.Vault.Settings.AcquireFilesSettings(connection)
                        {
                            DefaultAcquisitionOption = VDF.Vault.Settings.AcquireFilesSettings.AcquisitionOption.Checkout
                        };
                        vdfFile = new VDF.Vault.Currency.Entities.FileIteration(connection, wsFile);
                        aqSettings.AddEntityToAcquire(vdfFile);
                        var results = connection.FileManager.AcquireFiles(aqSettings);
                        try
                        {
                            mUploadedFile = connection.FileManager.CheckinFile(results.FileResults.First().File, "Created by Job Processor", false, null, null, false, null, ACW.FileClassification.DesignRepresentation, false, vdfPath);
                            mExpFile      = mUploadedFile;
                        }
                        catch (Exception ex)
                        {
                            throw new Exception("Job could not update existing export file " + vdfFile + "Exception: ", ex);
                        }
                    }
                }
                else
                {
                    throw new Exception("Job could not find the export result file: " + mDocPath.Replace(mExt, ".stp"));
                }

                mTrace.IndentLevel += 1;

                //update the new file's revision
                try
                {
                    mTrace.WriteLine("Job tries synchronizing " + mExpFile.Name + "'s revision in Vault.");
                    mWsMgr.DocumentServiceExtensions.UpdateFileRevisionNumbers(new long[] { mExpFile.Id }, new string[] { mFile.FileRev.Label }, "Rev Index synchronized by Job Processor");
                }
                catch (Exception)
                {
                    //the job will not stop execution in this sample, if revision labels don't synchronize
                }

                //synchronize source file properties to export file properties for UDPs assigned to both
                try
                {
                    mTrace.WriteLine(mExpFile.Name + ": Job tries synchronizing properties in Vault.");
                    //get the design rep category's user properties
                    ACET.IExplorerUtil mExplUtil = Autodesk.Connectivity.Explorer.ExtensibilityTools.ExplorerLoader.LoadExplorerUtil(
                        connection.Server, connection.Vault, connection.UserID, connection.Ticket);
                    Dictionary <ACW.PropDef, object> mPropDictonary = new Dictionary <ACW.PropDef, object>();

                    //get property definitions filtered to UDPs
                    VDF.Vault.Currency.Properties.PropertyDefinitionDictionary mPropDefDic = connection.PropertyManager.GetPropertyDefinitions(
                        VDF.Vault.Currency.Entities.EntityClassIds.Files, null, VDF.Vault.Currency.Properties.PropertyDefinitionFilter.IncludeUserDefined);

                    VDF.Vault.Currency.Properties.PropertyDefinition mPropDef = new PropertyDefinition();
                    ACW.PropInst[] mSourcePropInsts = mWsMgr.PropertyService.GetProperties("FILE", new long[] { mFile.Id }, new long[] { mPropDef.Id });

                    //get property definitions assigned to Design Representation category
                    ACW.CatCfg  catCfg1       = mWsMgr.CategoryService.GetCategoryConfigurationById(mExpFile.Cat.CatId, new string[] { "UserDefinedProperty" });
                    List <long> mFilePropDefs = new List <long>();
                    foreach (ACW.Bhv bhv in catCfg1.BhvCfgArray.First().BhvArray)
                    {
                        mFilePropDefs.Add(bhv.Id);
                    }

                    //get properties assigned to source file and add definition/value pair to dictionary
                    mSourcePropInsts = mWsMgr.PropertyService.GetProperties("FILE", new long[] { mFile.Id }, mFilePropDefs.ToArray());
                    ACW.PropDef[] propDefs = connection.WebServiceManager.PropertyService.GetPropertyDefinitionsByEntityClassId("FILE");
                    foreach (ACW.PropInst item in mSourcePropInsts)
                    {
                        mPropDef = connection.PropertyManager.GetPropertyDefinitionById(item.PropDefId);
                        ACW.PropDef propDef = propDefs.SingleOrDefault(n => n.Id == item.PropDefId);
                        mPropDictonary.Add(propDef, item.Val);
                    }

                    //update export file using the property dictionary; note this the IExplorerUtil method bumps file iteration and requires no check out
                    mExplUtil.UpdateFileProperties(mExpFile, mPropDictonary);
                }
                catch (Exception ex)
                {
                    mTrace.WriteLine("Job failed copying properties from source file " + mFile.Name + " to export file: " + mExpFile.Name + " . Exception details: " + ex);
                    //you may uncomment the action below if the job should abort executing due to failures copying property values
                    //throw new Exception("Job failed copying properties from source file " + mFile.Name + " to export file: " + mExpFile.Name + " . Exception details: " + ex.ToString() + " ");
                }

                //align lifecycle states of export to source file's state name
                try
                {
                    mTrace.WriteLine(mExpFile.Name + ": Job tries synchronizing lifecycle state in Vault.");
                    Dictionary <string, long> mTargetStateNames = new Dictionary <string, long>();
                    ACW.LfCycDef mTargetLfcDef = (mWsMgr.LifeCycleService.GetLifeCycleDefinitionsByIds(new long[] { mExpFile.FileLfCyc.LfCycDefId })).FirstOrDefault();
                    foreach (var item in mTargetLfcDef.StateArray)
                    {
                        mTargetStateNames.Add(item.DispName, item.Id);
                    }
                    mTargetStateNames.TryGetValue(mFile.FileLfCyc.LfCycStateName, out long mTargetLfcStateId);
                    mWsMgr.DocumentServiceExtensions.UpdateFileLifeCycleStates(new long[] { mExpFile.MasterId }, new long[] { mTargetLfcStateId }, "Lifecycle state synchronized by Job Processor");
                }
                catch (Exception)
                { }

                //attach export file to source file leveraging design representation attachment type
                try
                {
                    mTrace.WriteLine(mExpFile.Name + ": Job tries to attach to its source in Vault.");
                    ACW.FileAssocParam mAssocParam = new ACW.FileAssocParam();
                    mAssocParam.CldFileId         = mExpFile.Id;
                    mAssocParam.ExpectedVaultPath = mWsMgr.DocumentService.FindFoldersByIds(new long[] { mFile.FolderId }).First().FullName;
                    mAssocParam.RefId             = null;
                    mAssocParam.Source            = null;
                    mAssocParam.Typ = ACW.AssociationType.Attachment;
                    mWsMgr.DocumentService.AddDesignRepresentationFileAttachment(mFile.Id, mAssocParam);
                }
                catch (Exception)
                { }

                mTrace.IndentLevel -= 1;
            }

            #endregion Vault File Management

            mTrace.IndentLevel = 1;
            mTrace.WriteLine("Job finished all steps.");
            mTrace.Flush();
            mTrace.Close();
        }
Beispiel #22
0
        public void RunWithArguments(Document doc, NameValueMap map)
        {
            StringBuilder traceInfo = new StringBuilder("RunWithArguments called with ");

            traceInfo.Append(doc.DisplayName);
            Trace.TraceInformation(map.Count.ToString());

            // values in map are keyed on _1, _2, etc
            for (int i = 0; i < map.Count; i++)
            {
                traceInfo.Append(" and ");
                traceInfo.Append(map.Value["_" + (i + 1)]);
            }

            Trace.TraceInformation(traceInfo.ToString());

            string dirPath = System.IO.Path.GetDirectoryName(doc.FullDocumentName);


            #region ExportSAT file

            Trace.TraceInformation("Export SAT file.");
            TranslatorAddIn oSAT = null;

            foreach (ApplicationAddIn item in m_inventorServer.ApplicationAddIns)
            {
                if (item.ClassIdString == "{89162634-02B6-11D5-8E80-0010B541CD80}")
                {
                    Trace.TraceInformation("Finded the PDF addin.");
                    oSAT = (TranslatorAddIn)item;
                    break;
                }
                else
                {
                }
            }

            if (oSAT != null)
            {
                TranslationContext oContext = m_inventorServer.TransientObjects.CreateTranslationContext();
                NameValueMap       oIgesMap = m_inventorServer.TransientObjects.CreateNameValueMap();

                if (oSAT.get_HasSaveCopyAsOptions(doc, oContext, oIgesMap))
                {
                    Trace.TraceInformation("SAT can be exported.");

                    Trace.TraceInformation("SAT: Set context type");
                    oContext.Type = IOMechanismEnum.kFileBrowseIOMechanism;

                    Trace.TraceInformation("SAT: create data medium");
                    DataMedium oData = m_inventorServer.TransientObjects.CreateDataMedium();

                    Trace.TraceInformation("SAT save to: " + dirPath + "\\export.sat");
                    oData.FileName = dirPath + "\\export.sat";

                    oIgesMap.set_Value("GeometryType", 1);

                    oSAT.SaveCopyAs(doc, oContext, oIgesMap, oData);
                    Trace.TraceInformation("SAT exported.");
                }

                #endregion
            }
        }