Example #1
0
        static void GetRefs(ref SwDMDocument15 dmDoc)
        {
            //Prerequisites for getting references
            SwDMSearchOption dmSearchOptions = dmDocManager.GetSearchOptionObject();
            object           oBrokenRefVar;
            object           oIsVirtual;
            object           oTimeStamp;

            string[] references;

            //Get the references!
            references = dmDoc.GetAllExternalReferences4(dmSearchOptions, out oBrokenRefVar, out oIsVirtual, out oTimeStamp);

            if (references == null || references.Length == 0)
            {
                Console.WriteLine("\"" + dmDoc.FullName + "\"\t");
                return;
            }

            //Output references to console along with virtual and broken references
            string IsVirtual;
            string IsReferenceBroken;

            foreach (string reference in references)
            {
                //check if virtual
                if (reference.ToUpper().Contains(@"\TEMP\") && reference.Contains("^"))
                {
                    IsVirtual         = "Virtual";
                    IsReferenceBroken = "Not Broken";
                }
                else
                {
                    IsVirtual = "Not Virtual";

                    //check if the reference exists
                    if (File.Exists(reference))
                    {
                        IsReferenceBroken = "Not Broken";
                    }
                    else
                    {
                        IsReferenceBroken = "Broken";
                    }
                }
                Console.WriteLine("\"" + dmDoc.FullName + "\"\t\t\"" + reference + "\"\t\"" + IsVirtual + "\"\t\"" + IsReferenceBroken + "\"");
            }
        }
Example #2
0
        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;
        }
Example #3
0
        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);
        }
Example #4
0
        public List <string[]> GetDependencies(string FileName, bool Deep = false)
        {
            // external references for assembly files (GetAllExternalReferences4)
            // external references for part files (GetExternalFeatureReferences)
            SwDMDocument19   swDoc       = default(SwDMDocument19);
            SwDMSearchOption swSearchOpt = default(SwDMSearchOption);

            // returns list of string arrays
            // 0: short file name
            // 1: long file name
            List <string[]> listDepends = new List <string[]>();

            // get doc type
            SwDmDocumentType swDocType = GetTypeFromString(FileName);

            if (swDocType == SwDmDocumentType.swDmDocumentUnknown)
            {
                return(null);
            }

            // get the document
            SwDmDocumentOpenError nRetVal = 0;

            swDoc = (SwDMDocument19)swDocMgr.GetDocument(FileName, swDocType, true, out nRetVal);
            if (SwDmDocumentOpenError.swDmDocumentOpenErrorNone != nRetVal)
            {
                DialogResult dr = MessageBox.Show("Failed to open solidworks file: " + FileName,
                                                  "Loading SW File",
                                                  MessageBoxButtons.OK,
                                                  MessageBoxIcon.Exclamation,
                                                  MessageBoxDefaultButton.Button1);
                return(null);
            }

            // get arrays of dependency info (one-dimensional)
            object oBrokenRefVar;
            object oIsVirtual;
            object oTimeStamp;

            swSearchOpt = swDocMgr.GetSearchOptionObject();
            string[] varDepends = (string[])swDoc.GetAllExternalReferences4(swSearchOpt, out oBrokenRefVar, out oIsVirtual, out oTimeStamp);
            if (varDepends == null)
            {
                return(null);
            }

            Boolean[] blnIsVirtual = (Boolean[])oIsVirtual;
            for (int i = 0; i < varDepends.Length; i++)
            {
                // file name with absolute path
                string strFullName = varDepends[i];

                // short file name with extension
                string strName = strFullName.Substring(strFullName.LastIndexOf("\\") + 1);

                // only return non-virtual components
                if ((bool)blnIsVirtual[i] != true)
                {
                    string[] strDepend = new string[2] {
                        strName, strFullName
                    };
                    listDepends.Add(strDepend);
                }
            }

            swDoc.CloseDoc();
            return(listDepends);
        }