/// <summary> /// 以不可见模式打开文档 Open a document invisibly. It will not be shown to the user but you will be /// able to interact with it through the API as if it is loaded. /// </summary> /// <param name="sldWorks"></param> /// <param name="toolFile"></param> /// <returns></returns> public static ModelDoc2 OpenInvisibleReadOnly(this ISldWorks sldWorks, string toolFile, bool visible = false, swDocumentTypes_e type = swDocumentTypes_e.swDocPART) { try { if (!visible) { sldWorks.DocumentVisible(false, (int)type); } var spec = (IDocumentSpecification)sldWorks.GetOpenDocSpec(toolFile); if (!visible) { spec.Silent = true; spec.ReadOnly = true; } var doc = sldWorks.OpenDoc7(spec); doc.Visible = visible; return(doc); } finally { if (!visible) { sldWorks.DocumentVisible (true, (int) type); } } }
protected IDisposable OpenDataDocument(string name, bool readOnly = true, Action <IDocumentSpecification> specEditor = null) { var filePath = GetFilePath(name); var spec = (IDocumentSpecification)m_SwApp.GetOpenDocSpec(filePath); spec.ReadOnly = readOnly; spec.LightWeight = false; specEditor?.Invoke(spec); var model = m_SwApp.OpenDoc7(spec); if (model != null) { if (model is IAssemblyDoc) { (model as IAssemblyDoc).ResolveAllLightWeightComponents(false); } var docWrapper = new DocumentWrapper(m_SwApp, model); m_Disposables.Add(docWrapper); return(docWrapper); } else { throw new NullReferenceException($"Failed to open the the data document at '{filePath}'"); } }
public ModelDoc2 OpenSwAssembly(string path) { ModelDoc2 swModel = default(ModelDoc2); DocumentSpecification swDocSpecification = default(DocumentSpecification); string[] componentsArray = new string[1]; object[] components = null; string name = null; int errors = 0; int warnings = 0; //Set the specifications swDocSpecification = (DocumentSpecification)app.GetOpenDocSpec(path); componentsArray[0] = "food bowl-1@bowl and chute"; components = (object[])componentsArray; swDocSpecification.ComponentList = components; swDocSpecification.Selective = true; name = swDocSpecification.FileName; swDocSpecification.DocumentType = (int)swDocumentTypes_e.swDocASSEMBLY; swDocSpecification.DisplayState = "Default_Display State-1"; swDocSpecification.UseLightWeightDefault = false; swDocSpecification.LightWeight = true; swDocSpecification.Silent = true; swDocSpecification.IgnoreHiddenComponents = true; //Open the assembly document as per the specifications swModel = (ModelDoc2)app.OpenDoc7(swDocSpecification); errors = swDocSpecification.Error; warnings = swDocSpecification.Warning; Debugger.Break(); if (errors > 0) { throw new Exception("Error while opening Solidworks assembly"); } if (warnings > 0) { System.Diagnostics.Debug.WriteLine("Warning while opening Soliworks assembly"); } activeModel = swModel; return(swModel); }
private void UpdateCachedBodyIfNeeded(LinkFileMacroFeatureParameters parameters) { LastError = null; IModelDoc2 refDoc = null; bool isRefDocLoaded = false; try { if (File.Exists(parameters.LinkedFilePath)) { LastUpdateStamp = File.GetLastWriteTimeUtc(parameters.LinkedFilePath).Ticks; refDoc = m_App.GetOpenDocumentByName(parameters.LinkedFilePath) as IModelDoc2; isRefDocLoaded = refDoc != null; if (LastUpdateStamp != parameters.FileLastUpdateTimeStamp || (isRefDocLoaded && refDoc.GetSaveFlag()) || CachedBodies == null) { if (!isRefDocLoaded) { m_App.DocumentVisible(false, (int)swDocumentTypes_e.swDocPART); var docSpec = m_App.GetOpenDocSpec(parameters.LinkedFilePath) as IDocumentSpecification; docSpec.Silent = true; docSpec.ReadOnly = true; refDoc = m_App.OpenDoc7(docSpec); if (refDoc == null) { throw new InvalidOperationException($"Failed to load the referenced file ${docSpec.FileName} with error: {(swFileLoadError_e)docSpec.Error}"); } } if (refDoc is IPartDoc) { var bodies = (refDoc as IPartDoc).GetBodies2((int)swBodyType_e.swAllBodies, true) as object[]; if (bodies != null && bodies.Any()) { var resBodies = bodies.Cast <IBody2>().Select(b => b.ICopy()).ToArray(); CachedBodies = resBodies; } else { throw new InvalidOperationException("No bodies in the referenced document"); } } else { throw new InvalidOperationException("Referenced document is not a part"); } } } else { throw new FileNotFoundException($"Linked file '${parameters.LinkedFilePath}' is not found"); } } catch (Exception ex) { LastError = ex; } finally { m_App.DocumentVisible(true, (int)swDocumentTypes_e.swDocPART); if (!isRefDocLoaded && refDoc != null) { m_App.CloseDoc(refDoc.GetTitle()); } } }
public void OpenModel() { //if (Path.GetFileName(modelName) == "SW_24505210.SLDPRT") //{ // string hying = "Test"; //} try { IDocumentSpecification spec = GetSpec(); string config = Const.DEFAULTCONFIG; if (!string.IsNullOrEmpty(refConfig)) { if (refConfig.ToLower() != "default") { config = refConfig; spec.ConfigurationName = config; } else { config = Const.DEFAULTCONFIG; spec.ConfigurationName = config; } } if (!File.Exists(modelName)) { WriteLog(string.Format("零部件不存在:{0}", modelName), 2); return; } model2 = (ModelDoc2)iSwApp.OpenDoc7(spec); if (model2 == null) { WriteLog(string.Format("零部件没打开:{0}!", modelName), 2); } else { WriteLog(string.Format("变化零部件:{0}", Path.GetFileName(modelName)), 1); } } catch (Exception ex) { WriteLog(string.Format("打开模型:{0}出错,请确认模型是否存在 {1}", modelName, ex.ToString()), 2); } //try //{ // int longstatus = 0, longwarnings = 0; // model2 = (ModelDoc2)iSwApp.OpenDoc6(modelName, 2, 0, "", ref longstatus, ref longwarnings); // model2 = (ModelDoc2)iSwApp.ActivateDoc2(Path.GetFileName(modelName).Split('.')[0], false, ref longstatus); // WriteLog(string.Format("变化零部件:{0}!", Path.GetFileName(modelName)), 1); //} //catch (Exception) //{ // WriteLog(string.Format("打开模型:{0}出错,请确认模型是否处在!", Path.GetFileName(modelName)), 2); //} WriteLog("ActivateConfig", 1); ActivateConfig(); WriteLog("binReadmodelInfo", 1); binReadmodelInfo(); AddConfig(); }
public static void Start(string installDirectory, string programStatePath, string GUIconfigPath, string DDTOpath) { /* * This program listens for a 'call to action bool' * - the second character in a string from the * - run state config file for this MS * On TRUE it reads the DDTO, which the GUI MS * will have sent the current set of expressions to * evaluate, then set the GUI's call to action state * to false - meaning it cannot write to the DDTO, * though it will store the command and do it asap, * then this daemon will read the DDTO and implement * the expressions in it, after it resets its own * and the GUI's call to action, turning itself off * and the GUI's write ability on */ RunState programState; Console.WriteLine(" -- Daemon - Start --"); try { do { programState = RunState.GetProgramState(programStatePath); if (programState.GetActionState()) { CloseGUIsemaphore(GUIconfigPath); var PROG_ID = "SldWorks.Application.24"; var swType = Type.GetTypeFromProgID(PROG_ID); ValidateSWtype(swType); swApp = (ISldWorks)Activator.CreateInstance(swType); CreateSWAppInstance(swApp); var blobName = programState.GetBlobName(); var blobPath = installDirectory + "blob\\" + blobName; DocumentSpecification documentSpecification = SWDocSpecification.GetDocumentSpecification(swApp, blobPath); if (documentSpecification == null) { Console.WriteLine("Could not Get Document Specification for - " + blobPath); return; } Console.WriteLine(" - Obtained Document Specification for - " + blobPath); var model = swApp.OpenDoc7( documentSpecification); if (model == null) { Console.WriteLine(" - ERROR - Could not Open Document - " + blobPath); return; } Console.WriteLine(" - Opened SolidWorks Document - " + blobPath); EquationMgr equationManager = model.GetEquationMgr(); if (equationManager == null) { Console.WriteLine("Could Not Get Equation Manager Instance"); Console.WriteLine(" - Closing All Open SolidWorks Documents"); swApp.CloseAllDocuments(true); return; } Console.WriteLine(" - Created Equation Manager Instance"); var rawBlempString = Blemp.LoadDDTO(DDTOpath); var writeSuccess = false; var timeOut = 5; if (rawBlempString != null) { var equationSegments = Blemp.GetDDTOequationSegments(rawBlempString); if (equationSegments != null) { Console.WriteLine(" - Valid Equations Found - Processing"); try { for (var i = 0; i < equationSegments.Length; ++i) { SWEquation.AddEquation( equationManager, equationSegments[i] ); SWEquation.Build( model ); SWEquation.DeleteEquation( equationManager, 0); } } catch (ArgumentOutOfRangeException exception) { Console.WriteLine(exception); } } else { Console.WriteLine(" - WARNING - No Valid Equations for Processing Found"); } } else { Console.WriteLine("No Equations Found in DDTO"); } do { Console.WriteLine(" - Closing Call to Action Semaphore"); writeSuccess = FileWrite.WriteStringToFileFalseOnFail( programStatePath, "011!" ); FileWrite.WriteStringToFileFalseOnFail(DDTOpath, ""); Thread.Sleep(300); } while (!writeSuccess && timeOut-- > 0); if (timeOut > 0) { Console.WriteLine(" - Call to Action Semaphore - Successfuly Closed"); } else { Console.WriteLine(" - ERROR - Could Not Write Call to Action Close Command"); Console.WriteLine(" - Exiting Daemon -"); Console.WriteLine(" -- Daemon - Exit --"); return; } timeOut = 5; do { Console.WriteLine(" - Opening GUI Call to Action Semaphore"); writeSuccess = FileWrite.WriteStringToFileFalseOnFail( GUIconfigPath, "00" ); Thread.Sleep(300); } while (!writeSuccess && timeOut-- > 0); } if (programState.GetCloseBlob()) { CloseGUIsemaphore(GUIconfigPath); if (swApp != null) { swApp.CloseAllDocuments(true); } FileWrite.WriteStringToFileFalseOnFail(programStatePath, "011!"); Console.WriteLine(" - Opening GUI Call to Action Semaphore"); FileWrite.WriteStringToFileFalseOnFail( GUIconfigPath, "00"); } Thread.Sleep(300); } while (programState.GetRunState()); } catch (Exception exception) { Console.WriteLine(exception); } if (swApp != null) { swApp.CloseAllDocuments(true); } Console.WriteLine(" -- Daemon - Exit --"); }
static void Main(string[] args) { // LiveUpdateTest(); var swType = SWType.GetFromProgID(PROG_ID); if (swType == null) { logger.Error("\n ERROR: GetFromProgID returned null\n" + " - Exiting Program"); promptToExitProgram(); return; } ISldWorks swApp = CreateSWInstance.Create(swType); if (swApp == null) { logger.Error("\n ERROR: Could not get reference to " + "SolidWorks App\n - Exiting Program"); promptToExitProgram(); return; } var path = "C:\\Users\\bolinger\\Desktop\\test install\\toppAppDBdaemon\\blob\\C-HSSX.blob.SLDPRT"; DocumentSpecification documentSpecification = SWDocSpecification.GetDocumentSpecification(swApp, path); if (documentSpecification == null) { logger.Error("\n ERROR: Could not Get Document Specification for file: " + path + "\n - Exiting Program"); promptToExitProgram(); return; } logger.Debug("\n Getting Model from Document Specification"); ModelDoc2 model = (ModelDoc2)swApp.OpenDoc7( documentSpecification); if (model == null) { logger.Error("\n ERROR: Could not get Model from " + "Document Specification\n - Exiting Program"); promptToExitProgram(); return; } Config.model = model; logger.Debug("\n Getting Equation Manager from Model"); EquationMgr equationManager = model.GetEquationMgr(); if (equationManager == null) { logger.Error("\n ERROR: Could not get Equation Manager from Model\n" + " - Exiting Program"); promptToExitProgram(); return; } Config.equationManager = equationManager; logger.Debug("\n SolidWorks App Instance Initialized - Starting Microservice Daemon"); Daemon.Start(); promptToExitProgram(); logger.Debug("\n Closing Open SolidWorks Documents" + "\n - Exiting Microservice"); swApp.CloseAllDocuments(true); }