Example #1
0
        public static void RecopyHeare(SwAddin swAddin, ISldWorks swApp,ModelDoc2 swModelDoc)
        {
            try
            {
            SwAddin.IsEventsEnabled = false;
            swModelDoc.Save();
            ModelDocExtension swModelDocExt = default(ModelDocExtension);
            PackAndGo swPackAndGo = default(PackAndGo);
            Dictionary<string,string> filesToHideAndShow = new Dictionary<string, string>();
            WaitTime.Instance.ShowWait();
            WaitTime.Instance.SetLabel("Отрыв сборки от библиотеки.");
            int warnings = 0;
            int errors = 0;
            string _openFile = swModelDoc.GetPathName();

            swAddin.currentPath = string.Empty;
            swApp.CloseAllDocuments(true);
            if (!Directory.Exists("C:\\Temp"))
                Directory.CreateDirectory("C:\\Temp");
            string tempDir = Path.Combine("C:\\Temp", Path.GetFileNameWithoutExtension(_openFile));
            if (Directory.Exists(tempDir))
            {
                Directory.Delete(tempDir, true);
            }
            Directory.CreateDirectory(tempDir);
            string fileToOpenTemp = Path.Combine(tempDir, Path.GetFileName(_openFile));
            //File.Copy(_openFile, fileToOpenTemp);
            Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory(Path.GetDirectoryName(_openFile), tempDir);
            if (!File.Exists(fileToOpenTemp))
            {
                throw new Exception("Ошибка. Не найден файл: " + fileToOpenTemp);
            }
            swAddin.DetachEventHandlers();
            swModelDoc = (ModelDoc2)swApp.OpenDoc6(fileToOpenTemp, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                    (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors,
                                                    warnings);
            swAddin.AttachEventHandlers();
            try
            {
                foreach (var file in Directory.GetFiles(Path.GetDirectoryName(_openFile)))
                {
                    File.Delete(file);
                }
                foreach (var directory in Directory.GetDirectories(Path.GetDirectoryName(_openFile)))
                {
                    Microsoft.VisualBasic.FileIO.FileSystem.DeleteDirectory(directory, Microsoft.VisualBasic.FileIO.UIOption.OnlyErrorDialogs, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin);
                    //Directory.Delete(directory, true);
                }
            }
            catch (Exception e)
            {
                Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory( tempDir,Path.GetDirectoryName(_openFile),true);
                swAddin.DetachEventHandlers();
                swApp.CloseAllDocuments(true);
                swModelDoc = (ModelDoc2)swApp.OpenDoc6(_openFile, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                        (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors,
                                                        warnings);
                swAddin.AttachEventHandlers();
                MessageBox.Show(@"Из-за ошибки: """ + e.Message + @""" не удалось оторвать проект. Перезапустите SW и попробуйте еще раз.");
                return;
            }

            //File.Delete(_openFile);
            swModelDocExt = (ModelDocExtension)swModelDoc.Extension;

            swPackAndGo = (PackAndGo)swModelDocExt.GetPackAndGo();

            //swModelDoc = (ModelDoc2)swApp.OpenDoc6(openFile, (int)swDocumentTypes_e.swDocASSEMBLY, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", ref errors, ref warnings);
            //swModelDocExt = (ModelDocExtension)swModelDoc.Extension;

            int namesCount = swPackAndGo.GetDocumentNamesCount();

            object fileNames;
            object[] pgFileNames = new object[namesCount - 1];
            bool status = swPackAndGo.GetDocumentNames(out fileNames);
            string[] newFileNames = new string[namesCount];
            string[] rFileNames1 = fileNames as string[];
            if (rFileNames1 == null)
                throw new Exception("Не удалось оторвать заказ.");
            string[] rFileNames = new string[rFileNames1.Length];

            for (int ii = 0; ii < rFileNames1.Length;ii++ )
            {
                var tt1 = Microsoft.VisualBasic.FileSystem.Dir(rFileNames1[ii]);
                if (tt1==null)
                    tt1 = Microsoft.VisualBasic.FileSystem.Dir(rFileNames1[ii], Microsoft.VisualBasic.FileAttribute.Hidden);
                rFileNames[ii] = Path.Combine(Path.GetDirectoryName(rFileNames1[ii]),tt1);
            }
            //удалить неактуальные программы..
            DeleteXmlFiles(tempDir, rFileNames,_openFile);
            //bool isAuxiliary = (swCompModel.get_CustomInfo2("", "Auxiliary") == "Yes");
            //bool isAccessory = (swCompModel.get_CustomInfo2("", "Accessories") == "Yes");

            //string strSubCompNewFileName;
            //if (GetComponentNewFileName(swModel, isAuxiliary, isAccessory,
            //                            isFirstLevel, strSubCompOldFileNameFromModel,
            //                            out strSubCompNewFileName))
            //{
            //}

            string xName = swAddin.GetXNameForAssembly(false, Path.GetFileNameWithoutExtension(_openFile));
            string furnDir = Path.Combine(Path.GetDirectoryName(_openFile), "ФУРНИТУРА");
            string furnHelpDir = Path.Combine(Path.GetDirectoryName(_openFile), "ФУРНИТУРА", "Модели фурнитуры");
            string partDir = Path.Combine(Path.GetDirectoryName(_openFile), "ДЕТАЛИ");
            string partDirHelp = Path.Combine(Path.GetDirectoryName(_openFile), "ДЕТАЛИ", "Вспомогательные детали");
            string partForAssDir = Path.Combine(Path.GetDirectoryName(_openFile), "ДЕТАЛИ", "Детали для сборок");

            //DSOFile.OleDocumentProperties m_oDocument = null;
            //m_oDocument = new DSOFile.OleDocumentPropertiesClass();
            for (int i = 0; i<namesCount;i++)
            {

                //вот пример как выглядит массив элементов в fileNames. Переделать их в newFileNames и все...
            //                [0]	"c:\\temp\\2222\\2222.sldasm"	string
            //[1]	"d:\\_swlib_backup\\крепежная фурнитура\\вспомогательные\\3090_штифт для эксцентрика пластикового 20 мм.sldprt"	string
            //[2]	"d:\\_swlib_backup\\крепежная фурнитура\\вспомогательные\\3093_эксцентрик пластиковый для дсп 16 мм 20 мм.sldprt"	string
            //[3]	"d:\\_swlib_backup\\крепежная фурнитура\\вспомогательные\\отв для арт. 3090.sldprt"	string
            //[4]	"d:\\_swlib_backup\\крепежная фурнитура\\3093+3090_(эксцентрик пластиковый 20 мм для дсп 16 мм+штифт для эксцентрика пластикового 20 мм).sldasm"	string
            //[5]	"d:\\_swlib_backup\\шкафы-купе\\каркасные детали\\дсп 16 мм\\вспомогательные\\8504_панель вкладная 000a01p.sldprt"	string
            //[6]	"d:\\_swlib_backup\\шкафы-купе\\каркасные детали\\дсп 16 мм\\8504f_панель вкладная 000a01p.sldasm"	string

                //в rFileNames[i] вот что:
                //d:\_swlib_backup\шкафы-купе\каркасы шкафов-купе\вспомогательные\детали для сборок\Панель боковая правая_K02214P.SLDPRT
                //если содержит _swlib_backup и на конце 2 цифры + "P" = заменяем эти 2 цифры на 01 и помещаем оба файлика в список
                //потом пробегусь по списку. 01 - убрать скрытие, для старого - скрыть

                string fileName = Path.GetFileName(rFileNames[i]);
                string tmprFileName = rFileNames[i];
                if (!Directory.Exists(partDir))
                    Directory.CreateDirectory(partDir);
                if (fileName.ToLower().Contains(Path.GetFileName(_openFile.ToLower())))
                {
                    newFileNames[i] = _openFile;
                    continue;
                }
                if (rFileNames[i].ToLower().Contains(tempDir.ToLower()))
                {
                    newFileNames[i] = rFileNames[i].Replace(tempDir.ToLower(), Path.GetDirectoryName(_openFile));
                    continue;
                }
                string idCopyTo = rFileNames[i].Substring(rFileNames[i].Length - 10, 2);
                  int newNumber;
                char lastChar = Path.GetFileNameWithoutExtension(rFileNames[i]).Last();
                if ((lastChar != 'p' && lastChar!='P') || !int.TryParse(idCopyTo, out newNumber))//(rFileNames[i].ToLower().Contains("крепежная фурнитура") || rFileNames[i].ToLower().Contains("фурнитура для каркасов"))
                {
                    if (!Directory.Exists(furnDir))
                        Directory.CreateDirectory(furnDir);

                    if (rFileNames[i].ToLower().Contains("вспомогательные"))
                    {
                        //2222//ФУРНИТУРА//Модели фурнитуры
                        if (!Directory.Exists(furnHelpDir))
                            Directory.CreateDirectory(furnHelpDir);
                        newFileNames[i] = Path.Combine(furnHelpDir, Path.GetFileNameWithoutExtension(rFileNames[i]) + " #" + xName+"-1" + Path.GetExtension(rFileNames[i]));
                        continue;
                    }
                    else
                    {
                        //2222//ФУРНИТУРА//
                        newFileNames[i] = Path.Combine(furnDir, Path.GetFileNameWithoutExtension(rFileNames[i]) + " #" + xName +"-1"+ Path.GetExtension(rFileNames[i]));
                        continue;
                    }
                }
                else
                {
                    tmprFileName = GetFileNameWithoutSuff(rFileNames[i]);
                }
                string fnext = Path.GetFileNameWithoutExtension(tmprFileName);
                string[] arr = fnext.Split('-').ToArray();
                if (arr.Length != 2)
                {
                    //учитывать только последний "-"
                    string[] tmp = new string[2];
                    for (int j = 0; j < arr.Length-1; j++)
                    {
                        tmp[0] = string.Format("{0}-{1}", tmp[0], arr[j]);
                    }
                    tmp[0] = tmp[0].Remove(0, 1);
                    tmp[1] = arr.Last();
                    arr = tmp;
                }
                string newName = arr[0] + " #" + xName+"-" + arr[1] + Path.GetExtension(tmprFileName);
                if (tmprFileName.ToLower().Contains("вспомогательные"))
                {
                    //if (true)//(tmprFileName.ToLower().Contains("детали для сборок"))//|| Path.GetExtension(tmprFileName).ToLower()==".sldprt" )
                    //{
                        if (!Directory.Exists(partForAssDir))
                            Directory.CreateDirectory(partForAssDir);
                        newFileNames[i] = Path.Combine(partForAssDir, newName);
                        continue;
                    //}
                    ////2222\ДЕТАЛИ\Вспомогательные детали
                    //if (!Directory.Exists(partDirHelp))
                    //    Directory.CreateDirectory(partDirHelp);

                    //newFileNames[i] = Path.Combine(partDirHelp, newName);
                    //continue;
                }
                newFileNames[i] = Path.Combine(partDir, newName);
            }
            BStrWrapper[] pgSetFileNames;
            //тут надо немного поправить newFileNames так, чтобы не было одинаковых..
            string[] tmpFileNames = new string[newFileNames.Length];
            int jj = 0;
            foreach (var tmpFileName in newFileNames)
            {
                int same = tmpFileNames.Count(f => f!=null ? f.ToLower() == tmpFileName.ToLower() : false);
                if (same > 0 && !tmpFileName.Contains("фурнитура") && !tmpFileName.Contains("ФУРНИТУРА"))
                {
                    string tmp = Path.GetFileNameWithoutExtension(tmpFileName).Split('-').LastOrDefault();
                    if (string.IsNullOrEmpty(tmp))
                        continue;
                    int tmpNumb;
                    if (!int.TryParse(tmp, out tmpNumb))
                        continue;

                    int index = Path.GetFileNameWithoutExtension(tmpFileName).IndexOf('-');
                    string substr = Path.GetFileNameWithoutExtension(tmpFileName).Substring(0, index)+"-"+(tmpNumb+1).ToString() + Path.GetExtension(tmpFileName);
                    string res = Path.Combine(Path.GetDirectoryName(tmpFileName), substr);
                next:
                    same = tmpFileNames.Count(f => f != null ? f.ToLower() == res.ToLower() : false);
                    if (same > 0)
                    {
                        tmp = Path.GetFileNameWithoutExtension(res).Split('-').LastOrDefault();
                        if (string.IsNullOrEmpty(tmp))
                            continue;
                        if (!int.TryParse(tmp, out tmpNumb))
                            continue;
                        index = Path.GetFileNameWithoutExtension(res).IndexOf('-');
                        substr = Path.GetFileNameWithoutExtension(res).Substring(0, index) + "-" + (tmpNumb + 1).ToString() + Path.GetExtension(tmpFileName);
                        res = Path.Combine(Path.GetDirectoryName(res), substr);
                        goto next;
                    }
                    tmpFileNames[jj] = res;
                }
                else
                {
                    tmpFileNames[jj] = tmpFileName;
                }
                jj++;
            }
            newFileNames = tmpFileNames;
            pgSetFileNames = ObjectArrayToBStrWrapperArray(newFileNames);
            //var documentsToRemove = ObjectArrayToBStrWrapperArray(newFileNames.Where(x => x == "C:\\temp").ToArray());
            //swPackAndGo.RemoveExternalDocuments(documentsToRemove);
            status = swPackAndGo.SetDocumentSaveToNames(pgSetFileNames);

            var statuses = (int[])swModelDocExt.SavePackAndGo(swPackAndGo);
            //перед открытием создать файлик dictionary
            string dictFile= Path.Combine(Path.GetDirectoryName(_openFile), Path.GetFileNameWithoutExtension(_openFile) + "_dictionary.txt");
            if (File.Exists(dictFile))
                File.Delete(dictFile);
            using (File.CreateText(dictFile)) { }; //File.Create(dictFile);
            List<string> strArr = new List<string>();
            foreach (string file in Directory.GetFiles(partDir, "*.SLDASM", SearchOption.TopDirectoryOnly))
            {
                strArr.Add(file);
            }
            File.SetAttributes(dictFile, FileAttributes.Normal);
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(dictFile, true))
            {
                foreach (var line in strArr)
                {
                    file.WriteLine(line);
                }
                file.Close();
            }
            //File.WriteAllLines(dictFile, strArr);
            File.SetAttributes(dictFile, FileAttributes.Hidden);

            //тут проверить что все оторвалось. Если что, поправить ссылки
            SwDMApplication swDocMgr = SwAddin.GetSwDmApp();
            SwDmDocumentOpenError oe;
            SwDMSearchOption src = swDocMgr.GetSearchOptionObject();
            object brokenRefVar;
            string[] files = Directory.GetFiles(Path.GetDirectoryName(_openFile),"*.*",SearchOption.AllDirectories);
            foreach (string fileName in files)
            {
                SwDMDocument8 swDoc = null;
                if (fileName.ToLower().Contains("sldasm"))
                    swDoc = (SwDMDocument8) swDocMgr.GetDocument(fileName,
                                                                 SwDmDocumentType.swDmDocumentAssembly,
                                                                 false, out oe);
                if (swDoc != null)
                {

                    var varRef = (string[]) swDoc.GetAllExternalReferences2(src, out brokenRefVar);
                    if (varRef != null && varRef.Length != 0)
                    {
                        foreach (string o in varRef)
                        {
                            if (o.ToUpper().Contains("_SWLIB_BACKUP"))
                            {
                                string tt = Path.GetFileNameWithoutExtension(o);
                                string newRef = null;
                                foreach (var fn in files)
                                {
                                    if (fn.Contains(tt))
                                    {
                                        newRef = fn;
                                        break;
                                    }
                                }
                                if (newRef != null)
                                {
                                    swDoc.ReplaceReference(o, newRef);
                                    swDoc.Save();
                                }

                            }
                        }
                    }
                    else
                    {
                        swDoc.CloseDoc();
                        continue;
                    }
                    swDoc.CloseDoc();
                }
            }
            swApp.CloseAllDocuments(true);
            if (!File.Exists(_openFile))
                throw new Exception("Ошибка. Не найден файл: " + _openFile);
            foreach (var file in newFileNames)
            {
                File.SetAttributes(file,FileAttributes.Normal);
            }
            //Logging.Log.Instance.Debug("SetAttributes ");
            SwAddin.IsEventsEnabled = true;
            swModelDoc = (ModelDoc2)swApp.OpenDoc6(_openFile, (int)swDocumentTypes_e.swDocASSEMBLY,
                                                    (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors,
                                                    warnings);
            SwAddin.IsEventsEnabled = false;
            //Logging.Log.Instance.Debug("OpenDoc6");
            swModelDoc.EditRebuild3();
            swAddin.AttachModelDocEventHandler(swModelDoc);
            //теперь тут пробежатся по всем файлам в filesToHideAndShow. key -хайдить , value - показывать
            //foreach (var files in filesToHideAndShow)
            //{
            //    if (File.Exists(files.Key) && File.Exists(files.Value))
            //    {
            //        File.SetAttributes(files.Value, FileAttributes.Normal);
            //        File.SetAttributes(files.Key, FileAttributes.Hidden);
            //        string nextFile,sourceFile = files.Key;
            //        while (SwAddin.IfNextExist(sourceFile, out nextFile))
            //        {
            //            sourceFile = nextFile;
            //            File.SetAttributes(nextFile, FileAttributes.Hidden);
            //        }
            //    }
            //}
            SwDmCustomInfoType swDmCstInfoType;
            if (Directory.Exists(furnDir))
            {
                foreach (string path in Directory.GetFiles(furnDir, "*.sldasm", SearchOption.TopDirectoryOnly))
                {
                    if (!File.Exists(path))
                        continue;
                    var swDoc = swDocMgr.GetDocument(path, SwDmDocumentType.swDmDocumentAssembly, true, out oe);
                    if (Path.GetFileNameWithoutExtension(path).First() == '~' || swDoc == null)
                        continue;
                    string valueOfName = swDoc.GetCustomProperty("Accessories", out swDmCstInfoType);
                    swDoc.CloseDoc();
                    if (valueOfName != null && (valueOfName == "No" || valueOfName == "no"))
                    {
                        File.Delete(path);
                    }
                }
            }
            var oComps = (object[])((AssemblyDoc)swModelDoc).GetComponents(true);
            if (oComps != null)
            {

                foreach (var oComp in oComps)
                {
                    var comp = (Component2)oComp;
                    var model = (ModelDoc2)comp.GetModelDoc();
                    if (model != null)
                    {
                        File.SetAttributes(model.GetPathName(), FileAttributes.Normal);
                        var swDoc = swDocMgr.GetDocument(model.GetPathName(), SwDmDocumentType.swDmDocumentUnknown, true, out oe);
                        if (swDoc != null)
                        {
                            var names = (string[])swDoc.GetCustomPropertyNames();
                            try
                            {
                                foreach (var name in names)
                                {

                                    string valueOfName = swDoc.GetCustomProperty(name, out swDmCstInfoType);
                                    string lowValOfName = valueOfName.ToLower();

                                    if (lowValOfName.Contains("@") &&
                                        lowValOfName.Contains("#") &&
                                        (lowValOfName.Contains(".sld")))
                                    {
                                        var split = valueOfName.Split('.');
                                        string tmp = split.First();
                                        string ext = split.Last();
                                        if (lowValOfName.Contains("#" + xName) || tmp.ToUpper().Last()!='P')
                                            continue;
                                        string sid = tmp.Substring(tmp.Length - 3, 2);
                                        int id;
                                        if (!int.TryParse(sid,out id))
                                            continue;
                                        tmp = tmp.Substring(0, tmp.Length - 4);
                                        tmp = tmp +" #" +xName+"-"+id +"."+ext;

                                        swAddin.SetModelProperty(model, name, "",
                                                                swCustomInfoType_e.
                                                                    swCustomInfoText,
                                                                tmp);
                                        model.Save();

                                        //swDoc.SetCustomProperty(name, tmp);
                                    }
                                }
                            }
                            catch (Exception)
                            {
                                Logging.Log.Instance.Debug("Ошибка при попытке обратится к св-ву. Деталь: " + swDoc.FullName);
                            }
                            finally
                            {
                                swDoc.CloseDoc();
                            }
                        }

                    }
                }
            }

            Cash.ActualizaAllCash();
            SwAddin.IsEventsEnabled = true;
            linksToCash.Remove(_openFile);
            //скопировать fpTime.txt
            string fpTime = Path.Combine(tempDir, "fpTime.txt");
            if (File.Exists(fpTime))
                File.Copy(fpTime, Path.Combine(Path.GetDirectoryName(_openFile), "fpTime.txt"));
            CopyDrawings(rFileNames, newFileNames, tempDir, _openFile);
            CopyProgramms(rFileNames, newFileNames,tempDir, _openFile);

            }
            catch(Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
            finally
            {
                WaitTime.Instance.HideWait();

            }
        }