static List<string[]> GetDependencies(string[] strParentNames, SwDMApplication swDocMgr) { SwDMDocument19 swDoc = default(SwDMDocument19); SwDMSearchOption swSearchOpt = default(SwDMSearchOption); // returns list of string arrays // 0: parent file name // 1: child file name List<string[]> listDepends = new List<string[]>(); foreach (string ParentName in strParentNames) { // get doc type SwDmDocumentType swDocType = GetTypeFromString(ParentName); if (swDocType == SwDmDocumentType.swDmDocumentUnknown) { Console.WriteLine("Skipping unknown file: " + ParentName); continue; } // get the document SwDmDocumentOpenError nRetVal = 0; swDoc = (SwDMDocument19)swDocMgr.GetDocument(ParentName, swDocType, true, out nRetVal); if (SwDmDocumentOpenError.swDmDocumentOpenErrorNone != nRetVal) { Console.WriteLine("Failed to open solidworks file: " + ParentName); continue; } // get arrays of dependency info (one-dimensional) object oBrokenRefVar; object oIsVirtual; object oTimeStamp; swSearchOpt = swDocMgr.GetSearchOptionObject(); // swSearchOpt.SearchFilters = 16; string[] varDepends = (string[])swDoc.GetAllExternalReferences4(swSearchOpt, out oBrokenRefVar, out oIsVirtual, out oTimeStamp); if (varDepends == null) continue; Boolean[] blnIsVirtual = (Boolean[])oIsVirtual; for (int i = 0; i < varDepends.Length; i++) { // file name with absolute path string ChildName = varDepends[i]; // only return non-virtual components if ((bool)blnIsVirtual[i] != true) { string[] strDepend = new string[2] { ParentName, ChildName }; listDepends.Add(strDepend); } } swDoc.CloseDoc(); } return listDepends; }
void OpenDoc() { _swDocMgr = _swClassFact.GetApplication(SLicenseKey); _nDocType = SwDocMgrDocType(); _swDocument10 = (SwDMDocument10)_swDocMgr.GetDocument(SDocFileName, _nDocType, false, out _nRetVal); _swDocument13 = (SwDMDocument13)_swDocument10; }
public override void release() { if (app != null) { System.Runtime.InteropServices.Marshal.FinalReleaseComObject(app); app = null; } }
private static void ProcessFile(SwDMApplication app, string filePath, StreamWriter csvFileWriter) { var docType = SwDmDocumentType.swDmDocumentUnknown; switch (Path.GetExtension(filePath).ToLower()) { case ".sldprt": docType = SwDmDocumentType.swDmDocumentPart; break; case ".sldasm": docType = SwDmDocumentType.swDmDocumentAssembly; break; case ".slddrw": docType = SwDmDocumentType.swDmDocumentDrawing; break; } SwDmDocumentOpenError err; var doc = app.GetDocument(filePath, docType, true, out err); if (doc != null) { var confNames = (string[])doc.ConfigurationManager.GetConfigurationNames(); if (confNames?.Any() == true) { foreach (var confName in confNames) { try { ProcessConfiguration(doc, confName, csvFileWriter); } catch (Exception ex) { csvFileWriter.WriteLine($"\"{filePath}\",\"{confName}\",{ex.Message}"); } } } else { throw new Exception("No configurations found"); } } else { throw new Exception($"Failed to open the document: {err}"); } }
static void Main(string[] args) { SwDMClassFactory classFactory = Activator.CreateInstance( Type.GetTypeFromProgID("SwDocumentMgr.SwDMClassFactory")) as SwDMClassFactory; if (classFactory != null) { SwDMApplication dmApp = classFactory.GetApplication(SW_DM_KEY); Console.WriteLine(dmApp.GetLatestSupportedFileVersion()); } else { throw new NullReferenceException("Document Manager SDK is not installed"); } }
public override Boolean connect() { try { // replace licenseKey with your license key SwDMClassFactory swClassFact = default(SwDMClassFactory); String licenseKey = "<Your License Key>"; swClassFact = new SwDMClassFactory(); app = (SwDMApplication)swClassFact.GetApplication(licenseKey); } catch { app = null; } return (app != null); }
// constructor public SWDocMgr(string strLicenseKey) { SwDMClassFactory swClassFact; swClassFact = new SwDMClassFactory(); try { swDocMgr = swClassFact.GetApplication(strLicenseKey); } catch (Exception ex) { DialogResult dr = MessageBox.Show("Failed to get an instance of the SolidWorks Document Manager API: " + ex.Message, "Loading SW", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1); } }
private static void DeleteIfNonAccessory(string file, SwDMSearchOption src, SwDMApplication swDocMgr, SwDmDocumentOpenError oe, SwDmCustomInfoType type) { //удалить все связанные, кроме аксесуаров.. if (!File.Exists(file)) return; if (!file.ToLower().Contains("_swlib_backup") || Path.GetFileNameWithoutExtension(file).First() == '~') return; var swDoc = swDocMgr.GetDocument(file, SwDmDocumentType.swDmDocumentAssembly, true, out oe); if (swDoc == null) { Logging.Log.Instance.Debug("Не удалось сделать GetDocument в " + file); return; } bool isAccessory; try { string[] tmp = swDoc.GetCustomPropertyNames(); if (tmp != null && tmp.Contains("Accessories")) isAccessory = swDoc.GetCustomProperty("Accessories", out type) == "Yes"; else isAccessory = false; } catch (Exception) { Logging.Log.Instance.Debug("Ошибка при попытке обратится к св-ву Accessories. Деталь: " + swDoc.FullName); swDoc.CloseDoc(); return; } if (isAccessory) // если это аксесуар, то ничего не делаем. { swDoc.CloseDoc(); return; } if (Path.GetExtension(file) == ".SLDASM") { string[] extReferences = swDoc.GetAllExternalReferences(src); swDoc.CloseDoc(); foreach (var extReference in extReferences) { DeleteIfNonAccessory(extReference, src, swDocMgr, oe, type); } } else swDoc.CloseDoc(); if (Path.GetExtension(file) == ".SLDASM" || Path.GetExtension(file) == ".SLDPRT") File.Delete(file); }
public static string CopyToCash(string sourcePath, string idCopyTo, bool isAccessory = false, SwDMSearchOption src = null, SwDMApplication swDocMgr = null, Dictionary<string, string> deleteDict = null) { if (!sourcePath.Contains("_SWLIB_") && !sourcePath.Contains("_SWLIB_BACKUP") || !File.Exists(sourcePath)) //|| sourcePath.Contains(Path.Combine(Properties.Settings.Default.ModelPath, "Крепежная фурнитура"))) { Logging.Log.Instance.Debug("НЕ КОПИРУЕМ В КЭШ! " + sourcePath); return "01"; } //Logging.Log.Instance.Debug("Копирование в кэш:" + sourcePath); if (string.IsNullOrEmpty(idCopyTo) || idCopyTo == "99") { //тут надо найти idCopyTo string destPath = sourcePath.Replace("_SWLIB_", "_SWLIB_BACKUP").Replace("_swlib_", "_swlib_backup"); string destFolderPath = Path.GetDirectoryName(destPath); string sourceFolderPath = Path.GetDirectoryName(sourcePath); if (!Directory.Exists(destFolderPath)) { Directory.CreateDirectory(destFolderPath); if (Directory.Exists(sourceFolderPath)) { if ((File.GetAttributes(sourceFolderPath) & FileAttributes.Hidden) == FileAttributes.Hidden) File.SetAttributes(destFolderPath, FileAttributes.Hidden); } } var files = Directory.GetFiles(Path.GetDirectoryName(destPath)).Where(f => f.ToUpper().Contains(Path.GetFileNameWithoutExtension(sourcePath).ToUpper()) && f.First() != '~' && (Path.GetFileName(f).Length == Path.GetFileName(sourcePath).Length + 4 || Path.GetFileName(f).Length == Path.GetFileName(sourcePath).Length + 5)); idCopyTo = files.Max(f => f.Substring(f.Length - 10, 2)); int newNumber; if (int.TryParse(idCopyTo, out newNumber)) { newNumber = newNumber + 1; if (newNumber >= 99) idCopyTo = "01"; else { if (newNumber >= 10 && newNumber < 99) idCopyTo = newNumber.ToString(); else idCopyTo = "0" + newNumber.ToString(); } } else { //throw new Exception("Ошибка при копировании в кэш. Обратитесь к разработчикам."); idCopyTo = "01"; } } File.SetAttributes(sourcePath, FileAttributes.Normal); if (swDocMgr == null) swDocMgr = SwAddin.GetSwDmApp(); SwDmDocumentOpenError oe; if (src == null) src = swDocMgr.GetSearchOptionObject(); var swDoc = swDocMgr.GetDocument(sourcePath, SwDmDocumentType.swDmDocumentAssembly, true, out oe); if (swDoc == null) { Logging.Log.Instance.Debug("Не удалось сделать GetDocument в " + sourcePath); return idCopyTo; } SwDmCustomInfoType type; if (!isAccessory) { try { string[] tmp = swDoc.GetCustomPropertyNames(); if (tmp!=null && tmp.Contains("Accessories")) isAccessory = swDoc.GetCustomProperty("Accessories", out type) == "Yes"; else isAccessory = false; } catch (Exception) { Logging.Log.Instance.Debug("Ошибка при попытке обратится к св-ву Accessories. Деталь: " + swDoc.FullName); } } string[] extReferences = swDoc.GetAllExternalReferences(src); File.SetAttributes(sourcePath, FileAttributes.ReadOnly); string newPath; if (!isAccessory) { newPath =Path.Combine(Path.GetDirectoryName(sourcePath).Replace("_SWLIB_", "_SWLIB_BACKUP").Replace("_swlib_","_swlib_backup"),Path.GetFileNameWithoutExtension(sourcePath) +"#"+ idCopyTo + "P" + Path.GetExtension(sourcePath)); if (deleteDict != null && deleteDict.ContainsKey(sourcePath)) newPath = deleteDict[sourcePath]; } else { if (!File.Exists(sourcePath) || sourcePath.ToUpper().Contains("_SWLIB_BACKUP")) return idCopyTo; if (!File.Exists(sourcePath.ToUpper().Replace("_SWLIB_", "_SWLIB_BACKUP"))) { newPath = sourcePath.Replace("_SWLIB_", "_SWLIB_BACKUP").Replace("_swlib_", "_swlib_backup"); if (deleteDict != null && deleteDict.ContainsKey(sourcePath)) newPath = deleteDict[sourcePath]; if (!Directory.Exists(Path.GetDirectoryName(newPath))) Directory.CreateDirectory(Path.GetDirectoryName(newPath)); File.Copy(sourcePath,newPath, false); File.SetAttributes(newPath, FileAttributes.Normal); if (extReferences != null) { foreach (string reference in extReferences) { CopyToCash(reference, idCopyTo, true, src, swDocMgr, deleteDict); } } } return idCopyTo; //newPath = sourcePath.Replace("_SWLIB_", "_SWLIB_BACKUP"); } if (!File.Exists(newPath)) { //создать путь если надо if (!Directory.Exists(Path.GetDirectoryName(newPath))) Directory.CreateDirectory(Path.GetDirectoryName(newPath)); File.Copy(sourcePath, newPath); } string firstLvlId = idCopyTo; File.SetAttributes(newPath, FileAttributes.Normal); swDoc.CloseDoc(); swDoc = swDocMgr.GetDocument(newPath, SwDmDocumentType.swDmDocumentAssembly, false, out oe); if (swDoc == null) return idCopyTo; string[] extReferences2 = swDoc.GetAllExternalReferences(src); if (extReferences2 == null) return idCopyTo; //тут какая то фигня что полученные референсы могут иметь не свсем правильные значения string[] tmpExtReference = new string[extReferences2.Length]; bool isChenge = false; for (int j = 0; j < extReferences2.Length;j++ ) { if (!File.Exists(extReferences2[j])) { isChenge = true; tmpExtReference[j] = extReferences[j]; continue; } string[] spl = extReferences2[j].Split('\\'); if (spl.Length < 2) continue; if (spl[1] != "_SWLIB_" && spl[1] != "_SWLIB_BACKUP" && spl[1].Contains("_SWLIB_")) //&& spl[1].Length>15) { StringBuilder sb = new StringBuilder(); isChenge = true; for (int i = 0; i < spl.Length; i++) { if (i != 1) sb.Append(spl[i]); else sb.Append("_SWLIB_"); if (i < spl.Length-1) sb.Append(Path.DirectorySeparatorChar); } tmpExtReference[j] = sb.ToString(); } } if (isChenge) { for (int i = 0; i < tmpExtReference.Length; i++) { if (tmpExtReference[i] != null) swDoc.ReplaceReference(extReferences2[i], tmpExtReference[i]); else tmpExtReference[i] = extReferences2[i]; } swDoc.Save(); extReferences2 = swDoc.GetAllExternalReferences(src); } //конец обработки той фигни for (int i = 0; i < extReferences.Length; i++) { string extReference = extReferences[i]; //проверить правильная ли ссылка if (Path.GetExtension(extReferences2[i]).ToLower() == ".sldasm" && Path.GetExtension(sourcePath).ToLower() == ".sldprt") //&& !extReferences2[i].ToUpper().Contains("_SWLIB_")) { //Logging.Log.Instance.Debug("циклическая ссылка :" + extReferences2[i] + "в моделе: " + sourcePath); //так быть не должно! от этого все проблемы! continue; } if (!File.Exists(extReference)) { Logging.Log.Instance.Debug("Не правильная ссылка в " + sourcePath + " сама ссылка: " + extReference); continue; } if (extReference.ToUpper().Contains("_SWLIB_BACKUP")) continue; var swDocR = swDocMgr.GetDocument(extReference, SwDmDocumentType.swDmDocumentAssembly, true, out oe); if (swDocR == null) { Logging.Log.Instance.Debug("Не удалось сделать GetDocument в " + sourcePath); return idCopyTo; } //if (!isAccessory) //{ try { string[] tmp = swDocR.GetCustomPropertyNames(); if (tmp != null && tmp.Contains("Accessories")) isAccessory = swDocR.GetCustomProperty("Accessories", out type) == "Yes"; else isAccessory = false; } catch (Exception) { Logging.Log.Instance.Debug("Ошибка при попытке обратится к св-ву Accessories. Деталь: " + swDoc.FullName); } //} if (isAccessory) { if (!File.Exists(extReferences2[i]) || extReferences2[i].ToUpper().Contains("_SWLIB_BACKUP") && Path.GetExtension(extReferences2[i]).ToUpper() == ".SLDPRT") { continue; } //string newPath2; //if (!extReferences2[i].Contains("_SWLIB_BACKUP")) // newPath2 = extReferences2[i].Replace("_SWLIB_", "_SWLIB_BACKUP").Replace("_swlib_", "_swlib_backup"); //else // newPath2 = extReferences2[i]; //if (!File.Exists(newPath2))//(!File.Exists(extReferences2[i].ToUpper().Replace("_SWLIB_", "_SWLIB_BACKUP"))) //{ // if (deleteDict != null && deleteDict.ContainsKey(sourcePath)) // newPath2 = deleteDict[sourcePath]; // if (!Directory.Exists(Path.GetDirectoryName(newPath2))) // Directory.CreateDirectory(Path.GetDirectoryName(newPath2)); // File.Copy(extReferences2[i], newPath2, false); // File.SetAttributes(newPath2, FileAttributes.Normal); //} //swDoc.ReplaceReference(extReferences2[i], newPath2); //if (Path.GetExtension(extReferences2[i]) == ".SLDASM") //{ // var swDoc2 = swDocMgr.GetDocument(newPath2, SwDmDocumentType.swDmDocumentAssembly, false, out oe); // if (swDoc2 == null) // continue; // string[] extReferences3 = swDoc2.GetAllExternalReferences(src); // if (extReferences3 == null) // return idCopyTo; // foreach (var reference in extReferences3) // { // if (!File.Exists(reference) || reference.ToUpper().Contains("_SWLIB_BACKUP")) // continue; // string ttt = reference.Replace("_SWLIB_", "_SWLIB_BACKUP").Replace("_swlib_","_swlib_backup"); // if (!Directory.Exists(Path.GetDirectoryName(ttt))) // Directory.CreateDirectory(Path.GetDirectoryName(ttt)); // if (!File.Exists(ttt)) // File.Copy(reference,ttt , false); // File.SetAttributes(ttt, FileAttributes.Normal); // swDoc2.ReplaceReference(reference, ttt); // } // swDoc2.Save(); //} //continue; } //if (Path.GetExtension(extReference).ToUpper() == ".SLDASM") //{ idCopyTo = CopyToCash(extReference, null, isAccessory, src, swDocMgr); //} string destPath = extReference.Replace("_SWLIB_", "_SWLIB_BACKUP").Replace("_swlib_", "_swlib_backup"); if (!isAccessory) { //CheckHidden(extReference, sourcePath); destPath = Path.Combine(Path.GetDirectoryName(destPath),Path.GetFileNameWithoutExtension(destPath) +"#"+ idCopyTo + "P" +Path.GetExtension(destPath)); if (deleteDict != null && deleteDict.ContainsKey(destPath)) destPath = deleteDict[sourcePath]; } if (!File.Exists(destPath)) { if (!Directory.Exists(Path.GetDirectoryName(destPath))) Directory.CreateDirectory(Path.GetDirectoryName(destPath)); File.Copy(extReference, destPath); File.SetAttributes(destPath, FileAttributes.Normal); File.SetAttributes(destPath, FileAttributes.Hidden); } swDoc.ReplaceReference(extReferences2[i], destPath); //Logging.Log.Instance.Debug("ReplaceReference " + swDoc.FullName + "from " + extReferences2[i] + "to " + destPath); swDocR.CloseDoc(); } //переписать свойства! try { string[] tmp = swDoc.GetCustomPropertyNames(); string[] relatedFiles=null; if (tmp != null) { foreach (string name in tmp) { SwDmCustomInfoType swDmCstInfoType; string valueOfName = swDoc.GetCustomProperty(name, out swDmCstInfoType); string lowValOfName = valueOfName.ToLower(); if (lowValOfName.Contains("@") && !lowValOfName.Contains("#") && (lowValOfName.Contains(".sld"))) { var search = valueOfName.Split('.').First().Split('@').Last(); if (relatedFiles == null) relatedFiles = swDoc.GetAllExternalReferences(src); foreach (var file in relatedFiles) { if (Path.GetFileNameWithoutExtension(file).Contains(search)) { string newValue = valueOfName.Replace(search, Path.GetFileNameWithoutExtension(file)); swDoc.SetCustomProperty(name, newValue); } } } } } } catch (Exception) { Logging.Log.Instance.Debug("Ошибка при попытке обратится к св-ву. Деталь: " + swDoc.FullName); } swDoc.Save(); //Logging.Log.Instance.Debug("SAVE "+swDoc.FullName); swDoc.CloseDoc(); return firstLvlId;//idCopyTo; }
protected bool TraverseCore(string assemblyPath, string configurationName) { if (string.IsNullOrEmpty(assemblyPath)) { return(false); } if (!File.Exists(assemblyPath)) { return(false); } string originalExt; SwDmDocumentType docType = SldFileExtentionChecker.CheckDM(assemblyPath, out originalExt); if (docType != SwDmDocumentType.swDmDocumentAssembly && docType != SwDmDocumentType.swDmDocumentPart) { return(false); } SwDMClassFactory swDMClassFactory = new SwDMClassFactory(); //this.AllComObjects.Enqueue(swDMClassFactory); SwDMApplication swDMApp = swDMClassFactory.GetApplication(GetDocumentPropertiesViaDM.LinktronLicenseKey); this.GlobalSearchOption = swDMApp.GetSearchOptionObject(); //this.AllComObjects.Enqueue(swDMApp); SwDmDocumentOpenError returnValue = 0; SwDMDocument17 swDoc = (SwDMDocument17)swDMApp.GetDocument(assemblyPath, docType, true, out returnValue); if (swDoc == null || returnValue != SwDmDocumentOpenError.swDmDocumentOpenErrorNone) { return(false); } //this.AllComObjects.Enqueue(swDoc); SwDMConfigurationMgr dmConfigMgr = swDoc.ConfigurationManager; //this.AllComObjects.Enqueue(dmConfigMgr); string[] configurationNames = (string[])dmConfigMgr.GetConfigurationNames(); if (configurationNames == null || configurationNames.Length <= 0) { return(false); } string configNameToOpen = null; if (string.IsNullOrEmpty(configurationName)) { configNameToOpen = dmConfigMgr.GetActiveConfigurationName(); } else { configNameToOpen = configurationName; } SwDMConfiguration14 activeCfg = (SwDMConfiguration14)dmConfigMgr.GetConfigurationByName(configNameToOpen); if (activeCfg == null) { return(false); } //this.AllComObjects.Enqueue(activeCfg); int topId = this.GetTopDocumentInfo(assemblyPath, swDoc, activeCfg); if (topId <= 0) { return(false); } if (docType == SwDmDocumentType.swDmDocumentAssembly) { try { object[] allComponents = activeCfg.GetComponents(); if (allComponents != null) { foreach (object o in allComponents) { SwDMComponent9 subComponent = o as SwDMComponent9; this.TraverseRecursively(subComponent, 1, topId); } } } catch (Exception ex) { Trace.WriteLine(string.Format("TraverseCore:exception:{0}", ex.Message)); } } return(true); }