private Boolean DocCheck() { if (swModel == null) { ExportPDFException e = new ExportPDFException("You must have a drawing document open."); return(false); } else if ((Int32)swModel.GetType() != (Int32)swDocumentTypes_e.swDocDRAWING) { ExportPDFException e = new ExportPDFException("You must have a drawing document open."); return(false); } else if (swModel.GetPathName() == String.Empty) { swModel.Extension.RunCommand((int)swCommands_e.swCommands_SaveAs, swModel.GetTitle()); if (swModel.GetPathName() == string.Empty) { return(false); } return(true); } else { return(true); } }
/// <summary> /// Check for an existing hash. We basically want it to be fresh every time. /// This would be a good place to abuse the Redbrick, if you had a mind to. /// </summary> private void AddHash() { System.IO.FileInfo fi; try { if (!string.IsNullOrWhiteSpace(Document.GetPathName())) { fi = new System.IO.FileInfo(Document.GetPathName()); prop.PartFileInfo = fi; if (!prop.Contains("CRC32")) { prop.Hash = Redbrick.GetHash(string.Format("{0}\\{1}", prop.PartFileInfo.Directory.FullName, prop.PartFileInfo.Name)); SwProperty p = new SwProperty("CRC32", swCustomInfoType_e.swCustomInfoNumber, prop.Hash.ToString(), true); p.Old = false; prop.Add(p); } else { } } else { //this.prop.PartName = "New Document"; // <-- stack overflow? weird } } catch (ArgumentException ae) { prop.PartName = ae.HResult.ToString(); } catch (Exception e) { prop.PartName = e.HResult.ToString(); } }
private Boolean CreerConfigs() { Dictionary <String, ModelDoc2> ListeMdl = new Dictionary <String, ModelDoc2>() { { MdlBase.GetPathName(), MdlBase } }; Dictionary <String, String> ListeMdlDisplayState = new Dictionary <string, string>() { { MdlBase.GetPathName(), MdlBase.eComposantRacine().ReferencedDisplayState } }; foreach (Component2 cp in ListeComposants) { ModelDoc2 mdl = cp.GetModelDoc2(); ListeMdl.AddIfNotExist(mdl.GetPathName(), mdl); ListeMdlDisplayState.AddIfNotExist(mdl.GetPathName(), cp.ReferencedDisplayState); foreach (Component2 cpParent in cp.eListeComposantParent()) { ModelDoc2 mdlParent = cpParent.GetModelDoc2(); ListeMdl.AddIfNotExist(mdlParent.GetPathName(), mdlParent); ListeMdlDisplayState.AddIfNotExist(mdlParent.GetPathName(), cpParent.ReferencedDisplayState); } } int Options = (int)swConfigurationOptions2_e.swConfigOption_InheritProperties; if (SupprimerNvlFonction) { Options += (int)swConfigurationOptions2_e.swConfigOption_SuppressByDefault; } if (SupprimerNvComposant) { Options += (int)swConfigurationOptions2_e.swConfigOption_HideByDefault; } if ((ListeConfig.IsRef()) && (ListeConfig.Count > 0) && !String.IsNullOrWhiteSpace(ListeConfig[0])) { foreach (ModelDoc2 mdl in ListeMdl.Values) { WindowLog.Ecrire(mdl.eNomAvecExt()); WindowLog.Ecrire(" - " + String.Join(" ", ListeConfig)); foreach (String nomConfig in ListeConfig) { String NomCurrentDisplayState = ListeMdlDisplayState[mdl.GetPathName()]; mdl.eAddConfiguration(nomConfig, nomConfig, "", Options); } WindowLog.SautDeLigne(); } return(true); } return(false); }
public static byte[] ModelToBytes(ModelDoc2 model) { try { string fileName = model.GetTitle() + ".SLDPRT"; if (model.GetPathName() == null || model.GetPathName().Length == 0) { MessageBox.Show("Please, save model before adding!", "Search 3d Models", MessageBoxButtons.OK); MessageBox.Show("Model in DB will be with with name, that was in 'Model Name' input box!", "Attention!", MessageBoxButtons.OK); bool boolstatus = model.Save3((int)swSaveAsOptions_e.swSaveAsOptions_SaveReferenced, 0, 0); } string sourcePath = model.GetPathName(); string targetPath; if (GetModelsFolder() == null || GetModelsFolder().Length == 0) { string myDocuments = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments); targetPath = myDocuments + @"\Search3DModels\Temp\"; } else { targetPath = GetModelsFolder() + @"\Temp\"; } string destinationFile = System.IO.Path.Combine(targetPath, fileName); if (!System.IO.Directory.Exists(targetPath)) { System.IO.Directory.CreateDirectory(targetPath); } System.IO.File.Copy(sourcePath, destinationFile, true); FileStream fs = new FileStream(destinationFile, FileMode.Open, FileAccess.Read); byte[] modelInBytes = new byte[fs.Length]; fs.Read(modelInBytes, 0, System.Convert.ToInt32(fs.Length)); fs.Close(); Directory.Delete(targetPath, true); return(modelInBytes); } catch (Exception exp) { MessageBox.Show(exp.StackTrace, "modelToBytes()", MessageBoxButtons.OK); } return(null); }
public void OpenDrawing() { ModelDoc2 swModel = iSwApp.ActiveDoc; //SelectionMgr selMgr = new SelectionMgr(); int iErrors = 0; int iWarnings = 0; Component2 swComponent; String swComponentPath; SelectionMgr selMgr = default(SelectionMgr); selMgr = (SelectionMgr)swModel.SelectionManager; swComponent = selMgr.GetSelectedObjectsComponent4(1, -1); try { swComponentPath = swComponent.GetPathName(); } catch (NullReferenceException) { swComponentPath = swModel.GetPathName(); //swComponentPath = swComponent.GetPathName(); } var swDrawingArr = swComponentPath.Split('.'); String swDrawPath = swDrawingArr[0] + ".SLDDRW"; iSwApp.OpenDoc6(swDrawPath, 3, 1, "", iErrors, iWarnings); //MessageBox.Show(swComponentPath.ToString()); }
private bool Connect() { // Get SolidWorks object if (app is null) { app = (SldWorks)Activator.CreateInstance(Type.GetTypeFromProgID("SldWorks.Application")); if (app is null) { MessageBox.Show("Error: Can't connect to the SolidWorks application!"); return(false); } } // Get SolidWorks document if (doc is null) { doc = (ModelDoc2)app.ActiveDoc; if (doc is null) { MessageBox.Show("Error: Can't get the SolidWorks document!"); return(false); } } // Get path path = System.IO.Path.GetDirectoryName((string)doc.GetPathName()); return(true); }
private void ReplaceBolsaCP(Coletor coletor) { swApp.ActivateDoc(coletor.CodigoColetor + ".SLDASM"); swModel = swApp.ActiveDoc; AssemblyDoc swAssembly = (AssemblyDoc)swModel; Object[] components = swAssembly.GetComponents(true); foreach (var componente in components) { Component2 component = (Component2)componente; swModel = component.GetModelDoc2(); string nomeCompletoDoComponente = swModel.GetPathName(); string nomeComExtensao = Path.GetFileName(nomeCompletoDoComponente); if (String.Equals(nomeComExtensao, "BOLSA SOLDA SUCCAO CP TEMPLATE.SLDPRT")) { component.Select(true); break; } } swAssembly.ReplaceComponents($@"C:\ELETROFRIO\ENGENHARIA SMR\PRODUTOS FINAIS ELETROFRIO\MECÂNICA\RACK PADRAO\COLETOR SUCCAO\{coletor.CodigoBolsaSoldaSuccaoCompressor}.SLDPRT", "", true, true); swModel = swApp.ActiveDoc; swModel.Save(); }
public SwModelWrapper(SwApiWrapper swApi, SldWorks swApp, swDocumentTypes_e swDocType, ModelDoc2 swMainModel, string strConfigName) { this.swApi = swApi; this.swApp = swApp; this.swMainModel = swMainModel; swModelDocExt = (ModelDocExtension)swMainModel.Extension; if (swDocType == swDocumentTypes_e.swDocASSEMBLY) { swMainAssembly = (AssemblyDoc)swMainModel; } if (strConfigName != null) { this.swMainConfig = (Configuration)swMainModel.GetConfigurationByName(strConfigName); } else { this.swMainConfig = (Configuration)swMainModel.GetActiveConfiguration(); } strConfigName = this.swMainConfig.Name; // Write model info to shared variables string[] configsArray = swMainModel.GetConfigurationNames(); this.configNames.AddRange(configsArray); this.configNames.Sort(); this.pathName = swMainModel.GetPathName(); this.modelName = swMainModel.GetTitle(); this.currentConfigName = strConfigName; }
//获取当前文件的Material属性 public static MaterialModel GetMaterialInfo() { //【1】打开指定的SW文件,并获取文件名 ModelDoc2 swDoc = swAppHelper.ActiveDoc(); string fileName = swDoc.GetPathName();//文件名 if (fileName == null || fileName.Length == 0) { Msg.ShowError("无法获取文件名,请保存文件后重试!"); return(null); } //【2】从模型中获取属性并封装到物料实体类中 //2.1-配置特定属性 //string configName = swDoc.ConfigurationManager.ActiveConfiguration.Name;//当前激活配置名 //2.2-自定义属性 string configName = "";//特别说明:获取自定义属性时,只需要将配置名设置为空白""即可 MaterialModel objMaterial = new MaterialModel() { //DrawingCode = swDoc.GetCustomInfoValue(configName, "图号"), //MaterialName = swDoc.GetCustomInfoValue(configName, "名称"), //DrawingCode = swDoc.GetCustomInfoValue(configName, "Identification Nb"), MaterialName = swDoc.GetCustomInfoValue(configName, "Description"), MaterialSpec = swDoc.GetCustomInfoValue(configName, "规格"), MaterialType = swDoc.GetCustomInfoValue(configName, "型号"), Unit = swDoc.GetCustomInfoValue(configName, "单位"), Mquality = swDoc.GetCustomInfoValue(configName, "Material"), Weight = swDoc.GetCustomInfoValue(configName, "Weight"), MachiningPropertyId = swDoc.GetCustomInfoValue(configName, "加工属性"), PaintingColor = swDoc.GetCustomInfoValue(configName, "涂装颜色"), BrandId = swDoc.GetCustomInfoValue(configName, "品牌") }; return(objMaterial); }
private void GetChildren(JSolidworksAsemble _JswDoc) { //this.Parts.Add((JSolidworksAsemble)_JswDoc); //先将此文件加入到子零部件列表中 //如果是装配体 if (_JswDoc.swDoc == null) { _JswDoc.Load(); } Configuration swConf = (Configuration)_JswDoc.swDoc.GetActiveConfiguration(); if (swConf == null) { return; } Component2 swRootComp = (Component2)swConf.GetRootComponent(); if (swRootComp == null) { return; } else { object[] Children_List = swRootComp.GetChildren(); foreach (object _doc in Children_List) { ModelDoc2 t_doc = ((Component2)_doc).GetModelDoc2(); if (t_doc.GetType() == (int)swDocumentTypes_e.swDocPART) { //子件是 string _Path = t_doc.GetPathName(); JSolidworksPart JPart = new JSolidworksPart(t_doc.GetPathName()); JPart.Load(); _JswDoc.Parts.Add(JPart); } else { if (t_doc.GetType() == (int)swDocumentTypes_e.swDocASSEMBLY) { JSolidworksAsemble JPart = new JSolidworksAsemble(t_doc.GetPathName()); JPart.Load(); _JswDoc.Parts.Add(JPart); } } } } return; }
public List <string> get_list_of_open_docs() { ModelDoc2 temp = (ModelDoc2)swApp.GetFirstDocument(); List <string> ml = new List <string>(); temp.GetNext(); while (temp != null) { string temp_string = temp.GetPathName(); if (temp.Visible == true && !ml.Contains(temp_string)) { ml.Add(temp.GetPathName()); } temp = (ModelDoc2)temp.GetNext(); } return(ml); }
public KitchenModule(ModelDoc2 _rootModel, Component2 _swRootComponent, SwAddin _swAddin, ModelDoc2 _swModel) { RootModel = _rootModel; swRootComponent = _swRootComponent; measure = RootModel.Extension.CreateMeasure(); swAddin = _swAddin; swModel = _swModel; rootName = Path.GetFileNameWithoutExtension(RootModel.GetPathName()); }
//获取当前文件的配置名 public static string GetConfigName() { //【1】打开指定的SW文件,并获取文件名 ModelDoc2 swDoc = swAppHelper.ActiveDoc(); string fileName = swDoc.GetPathName(); //文件名 string configName = swDoc.ConfigurationManager.ActiveConfiguration.Name; //当前激活配置名 return(configName); }
private void AjouterInfos(ModelDoc2 Mdl) { try { if (!_ListeComp.Contains(Mdl.GetPathName()) && (ComposantsExterne || Mdl.eEstDansLeDossier(MdlBase))) { _ListeComp.Add(Mdl.GetPathName()); WindowLog.Ecrire(Mdl.eNomAvecExt()); CustomPropertyManager PM = Mdl.Extension.get_CustomPropertyManager(""); foreach (String k in _Dic.Keys) { PM.Add3(k, (int)swCustomInfoType_e.swCustomInfoText, _Dic[k], (int)swCustomPropertyAddOption_e.swCustomPropertyDeleteAndAdd); } } } catch (Exception e) { this.LogMethode(new Object[] { e }); } }
// Este metodo no es necesario ya que esto trabaja con archivos externos a Solidworks // Sin embargo se utiliza para determinar sobre cual numero de caso esta activo y cual es la carpeta de sw con imagenes a utilizar public static void ConnectToSolidworks() { try { ISldWorks swApp = Activator.CreateInstance(Type.GetTypeFromProgID("SldWorks.Application.24"), true) as ISldWorks; ModelDoc2 swModel = swApp.IActiveDoc2; caseNumber = GetAssemblyName(swModel.GetPathName()); swApp = null; swModel = null; } catch (System.NullReferenceException e) { // Parametros necesarios para crear el .txt string username = System.Security.Principal.WindowsIdentity.GetCurrent().Name.Replace("US\\", ""); string desktopPath = "C:\\Users\\" + username + "\\Desktop\\ProphecyCroppinApplication Results.txt"; // Elabora el contenido a mostrar en el .txt string content = "Prophecy Cropping Tool - Microport Orthopedics 2019\n-------------------------------------------\n\n" + "Probable Cause: Solidworks 2016 Instance not found.\n\n" + "Exception Message: " + e.Message + "\n\n" + "Exception trace: " + e + "\n\n" + "--------------------------------------------------------------------------------------------------------------"; // Llama al metodo que crea el txt file y cierra el programa CreateLogFile(desktopPath, content); // mata el proceso ligado a solidworks Process[] localByName = Process.GetProcessesByName("SLDWORKS"); foreach (Process p in localByName) { p.Kill(); } // ciera el programa System.Environment.Exit(0); } catch (Exception) { //Console.WriteLine("No se pudo obtener una instancia de Solidworks 2016"); System.Environment.Exit(0); } }
public void OpenInExplorer() { ModelDoc2 swModel = iSwApp.ActiveDoc; string swModelPath = swModel.GetPathName(); swModelPath = "/select, " + swModelPath; System.Diagnostics.Process Process = new System.Diagnostics.Process(); Process.StartInfo.UseShellExecute = true; Process.StartInfo.FileName = @"explorer"; Process.StartInfo.Arguments = swModelPath; Process.Start(); }
/// <summary> /// 获取当前激活文档的文件名 /// </summary> /// <returns></returns> public static string GetActiveDocName() { StartSW(); ModelDoc2 swDoc = swApp.ActiveDoc; if (swDoc == null) { return("error"); } string fileName = swDoc.GetPathName(); return(fileName); }
public static List <KeyValuePair <string, string> > GetAll(SldWorks swApp, ModelDoc2 childDoc, string configuration) { swApp.ActivateDoc(childDoc.GetTitle()); var swCustProp = childDoc.Extension.CustomPropertyManager[configuration]; var list = new List <KeyValuePair <string, string> >(); foreach (var item in Properties) { list.Add(new KeyValuePair <string, string>(item.Key, GetProperty(swCustProp, item.Key))); } swApp.CloseDoc(Path.GetFileName(childDoc.GetPathName())); return(list); }
private static void LerBOM(BomTableAnnotation swBomTable, ModelDoc2 swModel) { TableAnnotation tabela = (TableAnnotation)swBomTable; long coluna = tabela.ColumnCount; long linha = tabela.RowCount; listaDeCodigos.Add(Path.GetFileNameWithoutExtension(swModel.GetPathName()) + ";"); for (int i = 0; i < linha - 1; i++) { listaDeCodigos.Add((tabela.Text[i, 1] + ";" + tabela.Text[i, 5])); } listaDeCodigos.Add(";"); }
private void CloseAllModel() { do { ModelDoc2 swModel = iSwApp.ActiveDoc as ModelDoc2; if (swModel != null) { iSwApp.CloseDoc(swModel.GetPathName()); } else { break; } } while (true); }
private void SalvarPDF() { string nome = Path.GetFileNameWithoutExtension(swModel.GetPathName()); // Pega o nome sem extensão do full path do nome original com extensão. int Error = 0; int Warnings = 0; bool bRet; bRet = swExt.SaveAs($@"C:\ELETROFRIO\ENGENHARIA SMR\PRODUTOS FINAIS ELETROFRIO\MECÂNICA\RACK PADRAO\COLETOR SUCCAO\{nome}.PDF", (int)swSaveAsVersion_e.swSaveAsCurrentVersion, (int)swSaveAsOptions_e.swSaveAsOptions_Silent, null, ref Error, ref Warnings); // Converte um enum do tipo int para a string do enum deixando mais claro o erro // pois será retornada um msg e não um int. swFileSaveError_e e = (swFileSaveError_e)Error; MessageBox.Show(e.ToString()); }
//获取当前文件的文件名 public static string GetFileName() { string fileName = string.Empty; //【1】打开指定的SW文件,并获取文件名 ModelDoc2 swDoc = swAppHelper.ActiveDoc(); if (swDoc != null) { fileName = swDoc.GetPathName();//文件名 } else { fileName = null; } return(fileName); }
public string CreateNewJoinPart(AssemblyDoc assemblyDoc, Component2 insertComponentSendtoCustomer, Component2 insertComponentLocal, ModelDoc2 swModel, string partname, out Component2 returnpart) { Component2 sendToCustomerBodies = default(Component2); object swFaceOrPlane = default(object); assemblyDoc.InsertNewVirtualPart(swFaceOrPlane, out sendToCustomerBodies); sendToCustomerBodies.Select(true); assemblyDoc.FixComponent(); sendToCustomerBodies.Select(true); assemblyDoc.EditPart(); insertComponentSendtoCustomer.Select(false); insertComponentLocal.Select(true); assemblyDoc.InsertJoin2(false, false); swModel = (ModelDoc2)swApp.ActiveDoc; swModel.BreakAllExternalReferences(); object[] splits = sendToCustomerBodies.Name2.Split('^'); // string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + splits[0]; string compName = System.IO.Directory.GetParent(swModel.GetPathName()) + "\\" + partname; ModelDoc2 compModel = default(ModelDoc2); compModel = (ModelDoc2)sendToCustomerBodies.GetModelDoc(); if (compModel.GetType() == (int)swDocumentTypes_e.swDocPART) { compName = compName + ".sldprt"; } else { compName = compName + ".sldasm"; } bool ret; ret = sendToCustomerBodies.SaveVirtualComponent(compName); returnpart = sendToCustomerBodies; return(sendToCustomerBodies.GetSelectByIDString()); }
public void SetModelDoc() { swModel = swApp.ActiveDoc; if (swModel != null) { string pathName = swModel.GetPathName(); if (string.IsNullOrEmpty(pathName.Trim())) { FileName = swModel.GetTitle(); } else { FileName = System.IO.Path.GetFileNameWithoutExtension(pathName); FilePath = System.IO.Path.GetDirectoryName(pathName); } } }
// Converts the PIDs to actual references to the components and proceeds recursively // through the child nodes public static void LoadSWComponents(ModelDoc2 model, LinkNode node, List <string> problemLinks) { logger.Info("Loading SolidWorks components for " + node.Link.Name + " from " + model.GetPathName()); node.Link.SWComponents = LoadSWComponents(model, node.Link.SWComponentPIDs); if (node.Link.SWComponents.Count != node.Link.SWComponentPIDs.Count) { problemLinks.Add(node.Link.Name); logger.Error("Link " + node.Link.Name + " did not fully load all components"); } logger.Info("Loaded " + node.Link.SWComponents.Count + " components for link " + node.Link.Name); foreach (LinkNode Child in node.Nodes) { LoadSWComponents(model, Child, problemLinks); } }
//获取当前文件的Drawing属性 public static DrawingModel GetDrawingInfo() { DrawingModel objDrawing = new DrawingModel(); //【1】打开指定的SW文件,并获取文件名 ModelDoc2 swDoc = swAppHelper.ActiveDoc(); string fileName = swDoc.GetPathName(); //文件名 string configName = swDoc.ConfigurationManager.ActiveConfiguration.Name; //当前激活配置名 if (fileName == null || fileName.Length == 0) { Msg.ShowError("无法获取文件名,请保存文件后重试!"); return(null); } //【2】从模型中获取主要属性值 string drawingcode = swDoc.GetCustomInfoValue(configName, "图号"); string materialname = swDoc.GetCustomInfoValue(configName, "名称"); string materialspec = swDoc.GetCustomInfoValue(configName, "规格型号"); string weight = swDoc.GetCustomInfoValue(configName, "重量"); string unit = swDoc.GetCustomInfoValue(configName, "单位"); string purchasetypeid = swDoc.GetCustomInfoValue(configName, "采购类型"); string selectiontypeid = swDoc.GetCustomInfoValue(configName, "选型分类"); string surfacetreatment = swDoc.GetCustomInfoValue(configName, "表面处理"); string heattreatment = swDoc.GetCustomInfoValue(configName, "热处理"); string brand = swDoc.GetCustomInfoValue(configName, "品牌"); string remark = swDoc.GetCustomInfoValue(configName, "备注"); //【3】封装图号实体类对象属性 objDrawing.FileName = fileName; objDrawing.ConfigName = configName; objDrawing.DrawingCode = drawingcode; objDrawing.MaterialName = materialname; objDrawing.MaterialSpec = materialspec;//XorG:规格型号 objDrawing.Weight = weight; objDrawing.Unit = unit; objDrawing.PurchaseTypeId = purchasetypeid; objDrawing.SelectionTypeId = selectiontypeid; objDrawing.SurfaceTreatment = surfacetreatment; objDrawing.HeatTreatment = heattreatment; objDrawing.Brand = brand; objDrawing.ReMark = remark; return(objDrawing); }
public string GetPath() { swApp = (SldWorks)Marshal.GetActiveObject("SldWorks.Application"); modelDoc = swApp?.ActiveDoc; if (swApp != null) { if (modelDoc != null) { return(modelDoc.GetPathName()); } else { swApp.SendMsgToUser("Нету открытых документов!"); return(string.Empty); } } return(string.Empty); }
//private Boolean shouldCheck = true; /// <summary> /// Constructor /// </summary> /// <param name="sw">Requires a <see cref="SolidWorks.Interop.sldworks.SldWorks"/> type.</param> /// <param name="ps">Requires a <see cref="ArchivePDF.csproj.PathSet"/></param> public PDFArchiver(ref SldWorks sw, ArchivePDF.csproj.PathSet ps) { swApp = sw; APathSet = ps; swModel = (ModelDoc2)swApp.ActiveDoc; ModelDocExtension ex = (ModelDocExtension)swModel.Extension; string lvl = GetRev(ex); if (DocCheck()) { if (swModel.GetType() != (int)swDocumentTypes_e.swDocDRAWING) { throw new ExportPDFException("You must have a Drawing Document open."); } swDraw = (DrawingDoc)swModel; swFrame = (Frame)swApp.Frame(); swView = GetFirstView(swApp); metal = IsMetal(swView); sourcePath = swView.GetReferencedModelName().ToUpper().Trim(); drawingPath = swModel.GetPathName().ToUpper().Trim(); if (sourcePath.Contains("SLDASM")) { modelType = swDocumentTypes_e.swDocASSEMBLY; } else if (sourcePath.Contains("SLDPRT")) { modelType = swDocumentTypes_e.swDocPART; } else { modelType = swDocumentTypes_e.swDocNONE; } } else { MustSaveException e = new MustSaveException("The drawing has to be saved."); throw e; } }
public void TraverseComponent(Component2 swComp) { string name = swComp.Name2; object[] vChildComp; Component2 swChildComp; vChildComp = (object[])swComp.GetChildren(); for (int i = 0; i < vChildComp.Length; i++) { swChildComp = (Component2)vChildComp[i]; TraverseComponent(swChildComp); } try { ModelDoc2 compMdl = (ModelDoc2)swComp.GetModelDoc2(); if (compMdl != null) { string mdlName = Path.GetFileName(compMdl.GetPathName()); string refCfg = swComp.ReferencedConfiguration; string newConfig = GetNewConfig(mdlName, refCfg); if (!string.IsNullOrEmpty(newConfig)) { ModifyComponent comp = new ModifyComponent(swComp, refCfg, newConfig); comp.Change(); swComp.Select(false); AssemblyDoc assem = (AssemblyDoc)iSwApp.ActiveDoc; assem.CompConfigProperties4(2, 0, true, true, newConfig, false); } } } catch { } }
public void SetSheetMetalProperty(ModelDoc2 swModel, Feature swFeat, double BendRadius, double KFactor) { var sketches = new List <string> { "Листовой металл1", "Листовой металл" }; var dimensions = new List <string> { "D1", "D2" }; var sketchName = ""; foreach (var sketch in sketches.Where(sketch => swModel.Extension.SelectByID2(sketch, "BODYFEATURE", 0, 0, 0, false, 0, null, 0))) { sketchName = sketch; } var swSelMgr = swModel.ISelectionManager; swFeat = (Feature)swSelMgr.GetSelectedObject6(1, -1); foreach ( var dimenison in dimensions.Where( sketch => swModel.Extension.SelectByID2( sketch + "@" + sketchName + "@" + Path.GetFileName(swModel.GetPathName()), "DIMENSION", 0, 0, 0, false, 0, null, 0)). Select(dimension => (DisplayDimension)swSelMgr.GetSelectedObject6(1, 0)). Select(swDisplayDimension => swDisplayDimension.GetDimension2(0). SetSystemValue3(0.1, (int)swSetValueInConfiguration_e.swSetValue_InThisConfiguration, swModel.ConfigurationManager.ActiveConfiguration.Name))) { } SheetMetalFeatureData swSheetMetal = swFeat.GetDefinition(); swSheetMetal.BendRadius = BendRadius; swSheetMetal.KFactor = KFactor; swFeat.ModifyDefinition(swSheetMetal, swModel, null); }
/// <summary> /// 重设 表格格式 /// </summary> private void ResetGridTable() { ModelDoc2 swModel = null; swModel = (ModelDoc2)iswApp.ActiveDoc; if (swModel.GetType() == 2) { labActionModelPath.Text = swModel.GetPathName(); var sheet = ReoGridReport.CurrentWorksheet; sheet.Reset(); sheet["A1"] = "序号"; sheet["B1"] = "名称"; sheet["C1"] = "材料"; sheet["D1"] = "数量"; sheet["E1"] = "备注"; sheet.ColumnCount = 5; sheet.RowCount = 1000; sheet.AutoFitColumnWidth(0, true); sheet.AutoFitColumnWidth(1, true); sheet.AutoFitColumnWidth(2, true); sheet.AutoFitColumnWidth(3, true); sheet.AutoFitColumnWidth(4, true); sheet.SetColumnsWidth(3, 3, 45); } else { //MessageBox.Show("只有装配体才有BOM"); cancel = true; this.Close(); //return; } }
public bool SetAsmUnit(ModelDoc2 model, out LinkedList<Component2> swComps) { bool ret = false; Configuration swConfig; swComps = new LinkedList<Component2>(); try { SetModelProperty(model, "AsmUnit", "", swCustomInfoType_e.swCustomInfoText, model.GetPathName()); swConfig = (Configuration)model.GetActiveConfiguration(); if (swConfig != null) { var swRootComponent = (Component2)swConfig.GetRootComponent(); if (GetComponents(swRootComponent, swComps, true, false)) { foreach (var component2 in swComps) { var mod = component2.IGetModelDoc(); if (mod != null) { bool isIndependent = (!string.IsNullOrEmpty(mod.GetCustomInfoValue("", "IsIndependent") as string) && mod.GetCustomInfoValue("", "IsIndependent") == "Yes"); if (isIndependent) { SetModelProperty(mod, "AsmUnit", "", swCustomInfoType_e.swCustomInfoText, RootModel.GetPathName()); } else { var swParentComp = component2.GetParent(); string val = swParentComp == null ? model.GetPathName() : swParentComp.GetPathName(); SetModelProperty(mod, "AsmUnit", "", swCustomInfoType_e.swCustomInfoText, val); } } } ret = true; } } } catch { } return ret; }
//Events public int OnDocChange() { swmodel=(ModelDoc2)iSwApp.ActiveDoc; currentfilepath=swmodel.GetPathName(); mTaskpaneHost.updatefile(currentfilepath); return 0; }
public bool SetObjectValue(ModelDoc2 inModel, string inName, int inType, double inVal, bool noArtIfSuppressed = false) { object swObj; Dimension swDim; Feature swFeature; Component2 swComp; bool ret = false; if (GetObjectByName(inModel, inName, inType, out swObj)) { double dTestVal; switch (inType) { case 14: swDim = (Dimension)swObj; dTestVal = swDim.GetSystemValue2("") * 1000; if (dTestVal != inVal) { ret = (swDim.SetSystemValue2(inVal / 1000, (int) swSetValueInConfiguration_e.swSetValue_InAllConfigurations) == (int)swSetValueReturnStatus_e.swSetValue_Successful); } else ret = true; break; case 22: swFeature = (Feature)swObj; dTestVal = (swFeature.IsSuppressed() ? 0 : 1); if (dTestVal != inVal) { //ret = swFeature.SetSuppression(inVal == 0 ? (int) swFeatureSuppressionAction_e.swSuppressFeature : (int)swFeatureSuppressionAction_e.swUnSuppressFeature); ret = swFeature.SetSuppression2( inVal == 0 ? (int)swFeatureSuppressionAction_e.swSuppressFeature : (int)swFeatureSuppressionAction_e.swUnSuppressFeature, (int)swInConfigurationOpts_e.swAllConfiguration, inModel.GetConfigurationNames()); #region ������ �������� Component2 newComp = null; var config = inModel.IGetActiveConfiguration(); if (config != null) { swComp = config.IGetRootComponent2(); if (swComp != null) { var outComps = new LinkedList<Component2>(); if (GetComponents(swComp, outComps, false, false)) { foreach (var component2 in outComps) { var mod = component2.IGetModelDoc(); if (mod != null) { var texture = component2.GetTexture(""); if (mod.GetType() == (int)swDocumentTypes_e.swDocPART && texture != null) { newComp = component2; } } } } } } if (newComp != null) { inModel.Save(); if (newComp.Select(false)) ((AssemblyDoc)inModel).ComponentReload(); } #endregion } else ret = true; break; case 20: swComp = (Component2)swObj; try { if ((swComp.IsSuppressed() ? 0 : 1) == inVal) { ret = true; } else { int k = inVal == 0 ? (int)swComponentSuppressionState_e.swComponentSuppressed : (int)swComponentSuppressionState_e.swComponentFullyResolved; bool isCavity = false; if (inVal == 0) { var outC = new LinkedList<Component2>(); if (GetComponents(swComp, outC, true, false)) { isCavity = outC.Select(component2 => component2.IGetModelDoc()).Any( m => m != null && m.get_CustomInfo2("", "swrfIsCut") == "Yes"); } } int tmp = k; if (k == (int)swComponentSuppressionState_e.swComponentFullyResolved) tmp = swComp.SetSuppression2(k); if (noArtIfSuppressed) { //���� ���� ������, �� ������ �����.. //���� ���� ��������- �� �������� ��.. ModelDoc2 outModel; if (GetModelByName(inModel, inName, false, out outModel, true)) { if (k == (int)swComponentSuppressionState_e.swComponentSuppressed) { //������� ������� RenameCustomProperty(outModel, string.Empty, "Articul", "Noarticul"); } else if (k == (int)swComponentSuppressionState_e.swComponentFullyResolved) { //����� ������� RenameCustomProperty(outModel, string.Empty, "Noarticul", "Articul"); } } } if (k == (int)swComponentSuppressionState_e.swComponentSuppressed) tmp = swComp.SetSuppression2(k); k = tmp; #region ��������� ��������� var equMrg = inModel.GetEquationMgr(); if (equMrg != null) { var outList = new LinkedList<Component2>(); if (GetComponents(inModel.IGetActiveConfiguration().IGetRootComponent2(), outList, true, false)) { bool notSuppComp = outList.All( component2 => !swComp.IsSuppressed() || swComp.GetPathName() != component2.GetPathName() || component2.IsSuppressed()); for (int i = 0; i < inModel.GetEquationMgr().GetCount(); i++) { if (equMrg.Equation[i].Contains( Path.GetFileNameWithoutExtension(swComp.GetPathName()))) { if ((equMrg.get_Suppression(i) ? 0 : 1) != inVal) { equMrg.set_Suppression(i, inVal == 0 && notSuppComp); } } } } } #endregion #region ��������� ��������� if (isCavity) { LinkedList<Component2> swComps; List<Feature> list; if (_features.Count == 0 || _comps.Count == 0) list = GetAllCavitiesFeatures(out swComps); else { list = _features; swComps = _comps; } string nameMod = Path.GetFileNameWithoutExtension(inModel.GetPathName()); var delList = (from component2 in swComps where component2.Name.Contains(nameMod) && component2.Name.Contains(swComp.Name) from feature in list where component2.Name == GetSpecialNameFromFeature(feature.IGetFirstSubFeature().Name). Split('/').First() + "/" + GetSpecialNameFromFeature(feature.IGetFirstSubFeature().Name). Split('/').ToArray()[1] select feature).ToList(); SwModel.ClearSelection(); foreach (var feature in delList) { feature.Select(true); } SwModel.DeleteSelection(false); } #endregion ret = (k == (int)swSuppressionError_e.swSuppressionChangeOk); } } catch { } break; } } return ret; }
public static void Actualization(ModelDoc2 model, SwAddin _mSwAddin) { Component2 _swSelectedComponent = model.ConfigurationManager.ActiveConfiguration.GetRootComponent3(true); OleDbCommand cm; OleDbDataReader rd; OleDbConnection oleDb; if (!_mSwAddin.OpenModelDatabase(model, out oleDb)) return; cm = new OleDbCommand("SELECT * FROM faners ORDER BY FanerName ", oleDb); rd = cm.ExecuteReader(); List<Faner> faners = new List<Faner>(); while (rd.Read()) { if (rd["FanerType"] as string != null) { faners.Add(new Faner((string)rd["FanerName"], (string)rd["FanerType"], (string)rd["DecorGroup"])); } else { faners.Add(new Faner((string)rd["FanerName"], string.Empty, (string)rd["DecorGroup"])); } } rd.Close(); Feature feature; foreach (var faner in faners) { string suffix = faner.FanerName.Substring(faner.FanerName.Length - 2, 2); feature = FindEdge(_swSelectedComponent, faner.AxFanerName); if (feature != null) { if (feature.IsSuppressed()) { _mSwAddin.SetModelProperty(model, "Faner" + suffix, "", swCustomInfoType_e.swCustomInfoText, string.Empty, true); _mSwAddin.SetModelProperty(model, "colorFaner" + suffix, "", swCustomInfoType_e.swCustomInfoText, string.Empty, true); } else { string fieldValue = model.GetCustomInfoValue(string.Empty, "Faner" + suffix); if (fieldValue == string.Empty) { string msgText = "Для данной детали: " + model.GetPathName() + " кромка Faner" + suffix + " в модели не соответствует свойствам файла сборки. Данная кромка не будет импортирована в программу Покупки! Чтобы исправить эту ошибку используйте опцию \"MrDoors - Отделка кромки\""; MessageBox.Show(msgText, @"MrDoors", MessageBoxButtons.OK); } } } } }
public static void Create(ISldWorks app, ModelDoc2 mainModel) { string drawingTemplate = app.GetUserPreferenceStringValue((int)swUserPreferenceStringValue_e.swDefaultTemplateDrawing); ModelDoc2 designProject = app.NewDocument(drawingTemplate, (int)swDwgPaperSizes_e.swDwgPaperBsize, 0, 0); DrawingDoc designProjectDrawing = (DrawingDoc)designProject; int errors = 0; app.ActivateDoc2(designProject.GetTitle(), false, ref errors); designProjectDrawing.SetupSheet5("", (int)swDwgPaperSizes_e.swDwgPapersUserDefined, (int)swDwgTemplates_e.swDwgTemplateCustom, 1, 100, false, "a4 - iso.slddrt", 0.297, 0.21, "", true); var h = designProjectDrawing.CreateDrawViewFromModelView3(mainModel.GetPathName(), "*Изометрия", 0.1, 0.2, 0); List<OrderComponentData> orderData = new List<OrderComponentData>(); object[] allComponents = ((AssemblyDoc)mainModel).GetComponents(true); foreach (Component2 component in allComponents) { ModelDoc2 currentModel = component.GetModelDoc2(); string ip = GetCustomPropertyValue(currentModel, "IsProduct"); if (ip == "Yes") { orderData.Add( new OrderComponentData() { Article = GetCustomPropertyValue(currentModel, "Articul"), Name = GetCustomPropertyValue(currentModel, "Part_Name_spec"), Width = GetCustomPropertyValue(currentModel, "Size1_spec"), Depth = GetCustomPropertyValue(currentModel, "Size2_spec"), Height = GetCustomPropertyValue(currentModel, "Size3_spec"), Color1 = GetCustomPropertyValue(currentModel, "Color1"), Color2 = GetCustomPropertyValue(currentModel, "Color2"), Color3 = GetCustomPropertyValue(currentModel, "Color3"), Color4 = GetCustomPropertyValue(currentModel, "Color4"), Color5 = GetCustomPropertyValue(currentModel, "Color5"), Color6 = GetCustomPropertyValue(currentModel, "Color6"), Color7 = GetCustomPropertyValue(currentModel, "Color7") }); } } TableAnnotation table = designProjectDrawing.InsertTableAnnotation(0.01, 0.15, (int)swBOMConfigurationAnchorType_e.swBOMConfigurationAnchor_TopLeft, orderData.Count + 1, 14); table.BorderLineWeight = 0; table.GridLineWeight = 0; #region Заполнение заголовков колонок таблицы table.set_Text(0, 0, "Поз."); table.set_Text(0, 1, "Артикул"); table.set_Text(0, 2, "Наименование изделия"); table.set_Text(0, 3, "Ширина"); table.set_Text(0, 4, "Глубина"); table.set_Text(0, 5, "Высота"); table.set_Text(0, 6, "Цвет 1"); table.set_Text(0, 7, "Цвет 2"); table.set_Text(0, 8, "Цвет 3"); table.set_Text(0, 9, "Цвет 4"); table.set_Text(0, 10, "Цвет 5"); table.set_Text(0, 11, "Цвет 6"); table.set_Text(0, 12, "Цвет 7"); table.set_Text(0, 13, "Кол-во"); #endregion int i = 1; foreach (OrderComponentData productData in orderData) { table.set_Text(i, 0, i.ToString()); table.set_Text(i, 1, productData.Article); table.set_Text(i, 2, productData.Name); table.set_Text(i, 3, productData.Width); table.set_Text(i, 4, productData.Depth); table.set_Text(i, 5, productData.Height); table.set_Text(i, 6, productData.Color1); table.set_Text(i, 7, productData.Color2); table.set_Text(i, 8, productData.Color3); table.set_Text(i, 9, productData.Color4); table.set_Text(i, 10, productData.Color5); table.set_Text(i, 11, productData.Color6); table.set_Text(i, 12, productData.Color7); i++; } table.SetColumnWidth(0, 0.013, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); table.SetColumnWidth(1, 0.025, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); table.SetColumnWidth(2, 0.07, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); for (int j = 3; j < 14; j++) { table.SetColumnWidth(j, 0.02, (int)swTableRowColSizeChangeBehavior_e.swTableRowColChange_TableSizeCanChange); } designProject.ViewZoomtofit2(); }
private bool SetColorProperty(ModelDoc2 inModel, string colorProp, OleDbConnection oleDb, string colorName, string column, OleDbConnection oleDbDecorDef) { bool isColorChanged = false; if (colorProp != "") { var names = (string[])inModel.GetCustomInfoNames2(""); if (names.Contains(colorProp)) { isColorChanged = _mSwAddin.SetModelProperty(inModel, colorProp, "", swCustomInfoType_e.swCustomInfoText, colorName, true); if (oleDbDecorDef != null) { string fullDecorName = string.Empty; string[] restrictionValues = new string[3] { null, null, "decornames" }; DataTable schemaInformation = oleDbDecorDef.GetSchema("Tables", restrictionValues); if (schemaInformation.Rows.Count == 0) fullDecorName = string.Empty; else { string selectStr = @"select * from decornames where FILEJPG = """ + colorName + @""""; var cmDecorDef = new OleDbCommand(selectStr, oleDbDecorDef); var rdDecorDef = cmDecorDef.ExecuteReader(); while (rdDecorDef.Read()) { fullDecorName = rdDecorDef["DecorName"].ToString(); } schemaInformation.Dispose(); cmDecorDef.Dispose(); rdDecorDef.Close(); } int index; if (int.TryParse(colorProp.Substring(colorProp.Length - 1, 1), out index)) _mSwAddin.SetModelProperty(inModel, "ColorName" + index.ToString(), "", swCustomInfoType_e.swCustomInfoText, fullDecorName, true); } } } else { if (column == "Part Color Priority") MessageBox.Show(@"В файле " + Environment.NewLine + oleDb.DataSource + Environment.NewLine + @" в столбце 'Part Color Priority', Element: " + Path.GetFileNameWithoutExtension( _mSwAddin.GetModelNameWithoutSuffix(inModel.GetPathName())) + @" ошибка!", _mSwAddin.MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); else MessageBox.Show(@"В файле " + Environment.NewLine + oleDb.DataSource + Environment.NewLine + @" в столбце '" + column + @"' ошибка!", _mSwAddin.MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); } return isColorChanged; }
private ModelDoc2 GetCurrentAsmModel(ModelDoc2 swModel) { ModelDoc2 swAsmModel = null; LinkedList<ModelDoc2> outModels; if (_swAdd.GetAllUniqueModels(_swAdd.RootModel, out outModels)) { SwDmDocumentOpenError oe; SwDMApplication swDocMgr = SwAddin.GetSwDmApp(); var swDoc = (SwDMDocument8)swDocMgr.GetDocument(swModel.GetPathName(), SwDmDocumentType.swDmDocumentDrawing, true, out oe); if (swDoc != null) { SwDMSearchOption src = swDocMgr.GetSearchOptionObject(); object brokenRefVar; var varRef = (object[])swDoc.GetAllExternalReferences2(src, out brokenRefVar); var name = (string)varRef[0]; swAsmModel = outModels.FirstOrDefault(modelDoc2 => modelDoc2.GetPathName().ToLower() == name.ToLower()); swDoc.CloseDoc(); } } return swAsmModel; }
private bool SomeLogicChanges(ModelDoc2 swModel) { XmlNodeList views = null; XmlNode F1View = null, F6View = null; XmlNodeList list = null; if (this._cxml.ChildNodes[0].Attributes["Name"].Value.Contains("8504F_Панель вкладная 00AA") && Properties.Settings.Default.DeleteDraftIfStandart) { foreach (XmlNode node3 in this._cxml.ChildNodes[0].ChildNodes) { list = node3.SelectNodes("View"); if (list.Count > 0) { foreach (XmlNode node4 in list) { if (node4.Attributes["Name"].Value == "F1") { double result = 0.0; double num2 = 0.0; if ((double.TryParse(node4.ChildNodes[0].Attributes["Y"].Value, out result) && double.TryParse(node4.ChildNodes[1].Attributes["Y"].Value, out num2)) && ((((result >= 140.0) && (result < 601.0)) && (result == (num2 + 50.0))) || (((result > 69.0) && (result < 140.0)) && (result == (num2 * 2.0))))) { bool flag2 = true; if (MessageBox.Show("Данная деталь совпадает со стандртной типологией, на которую существует программа на обработку, поэтому чертеж на нее является излишним.Удалить чертеж на данную деталь ?", "MrDoors", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) != DialogResult.Yes) { break; } try { string pathName = swModel.GetPathName(); string path = string.Format("{0}{1}", pathName.Substring(0, pathName.Length - 6), "SLDASM"); if (File.Exists(path)) { int errors = 0; int warnings = 0; ModelDoc2 model = this._swApp.OpenDoc6(path, 2, 1, "", ref errors, ref warnings); this._swAdd.SetModelProperty(model, "Required Draft", "", swCustomInfoType_e.swCustomInfoText, "No", true); model.Save2(true); } if (File.Exists(pathName)) { this._swApp.CloseDoc(pathName); File.Delete(pathName); } this.DrawRenumering(); flag2 = false; } catch (Exception) { } return flag2; } } } } } } List<XmlNode> allViews = new List<XmlNode>(); foreach (XmlNode sheet in _cxml.ChildNodes[0].ChildNodes) { views = sheet.SelectNodes("View"); if (views.Count > 0) { foreach (XmlNode view in views) { allViews.Add(view); if (view.Attributes["Name"].Value == "F1") F1View = view; if (view.Attributes["Name"].Value == "F6") F6View = view; } } } if (F1View != null) { double currentDepth = 0; try { double.TryParse(F1View.ChildNodes[0].Attributes["Z"].Value, out currentDepth); } catch { } foreach (XmlNode node in F1View.ChildNodes) { string X = node.Attributes["X"].Value; string Y = node.Attributes["Y"].Value; //string xPath = string.Format("*[@X={0} and @Y={1}]", X, Y); List<XmlNode> correlateNodes = new List<XmlNode>(); foreach (XmlNode child in F1View.ChildNodes) { if (child.Attributes["Depth"] == null) continue; if (child.Attributes["X"].Value == X && child.Attributes["Y"].Value == Y) correlateNodes.Add(child); } //var correlateNodes = F1View.SelectNodes(xPath); XmlNode sequentiallyNode = null; if (correlateNodes.Count > 1) { //тут мы определили что есть минимум 2 присадки с одинаковыми координатами //проверить что хотябы одна из них сквозная foreach (XmlNode corrNode in correlateNodes) { if (corrNode.Attributes["Depth"].Value == "0") { sequentiallyNode = corrNode; break; } } if (sequentiallyNode == null) goto second; // есть более одной присадки с совпадающими координатами, но ниодна из них не сквозная. Выходим из цикла if (F6View == null) // если нет F6 то ее придется создать F6View = CreateF("F6", _cxml, F1View); MoveToOppositePlane("F6", sequentiallyNode, F1View, F6View, _cxml); } second: if (currentDepth == 0 || node.Name == "id0" || F6View == null) continue; correlateNodes = new List<XmlNode>(); foreach (XmlNode child in F6View.ChildNodes) { if (child.Attributes["X"].Value == X && child.Attributes["Y"].Value == Y) correlateNodes.Add(child); } //correlateNodes = F6View.SelectNodes(xPath); XmlNode unSequentiallyNode = null; if (node.Attributes["Depth"].Value == "0") sequentiallyNode = node; else unSequentiallyNode = node; if (correlateNodes.Count > 0) { foreach (XmlNode corrNode in correlateNodes) { if (corrNode.Attributes["Depth"].Value == "0") sequentiallyNode = corrNode; else unSequentiallyNode = corrNode; } if (sequentiallyNode == null) continue; // есть более одной присадки с совпадающими координатами, но ниодна из них не сквозная. Выходим из цикла double unSequentiallyNodeDepth; if (currentDepth != 0 && unSequentiallyNode!=null && double.TryParse(unSequentiallyNode.Attributes["Depth"].Value, out unSequentiallyNodeDepth)) { sequentiallyNode.Attributes["Depth"].Value = ((int)(currentDepth - unSequentiallyNodeDepth + 5)).ToString(); } } } } if (F6View != null) { double currentDepth = 0; try { double.TryParse(F6View.ChildNodes[0].Attributes["Z"].Value, out currentDepth); } catch { } foreach (XmlNode node in F6View.ChildNodes) { string X = node.Attributes["X"].Value; string Y = node.Attributes["Y"].Value; //string xPath = string.Format("*[@X={0} and @Y={1}]", X, Y); List<XmlNode> correlateNodes = new List<XmlNode>(); foreach (XmlNode child in F6View.ChildNodes) { if (child.Attributes["Depth"] == null) continue; if (child.Attributes["X"].Value == X && child.Attributes["Y"].Value == Y) correlateNodes.Add(child); } //var correlateNodes = F6View.SelectNodes(xPath); XmlNode sequentiallyNode = null; if (correlateNodes.Count > 1) { //тут мы определили что есть минимум 2 присадки с одинаковыми координатами //проверить что хотябы одна из них сквозная foreach (XmlNode corrNode in correlateNodes) { if (corrNode.Attributes["Depth"].Value == "0") { sequentiallyNode = corrNode; continue; } } if (sequentiallyNode == null) goto third; // есть более одной присадки с совпадающими координатами, но ниодна из них не сквозная. Выходим из цикла if (F1View == null) // если нет F6 то ее придется создать F1View = CreateF("F1", _cxml, F6View); MoveToOppositePlane("F1", sequentiallyNode, F1View, F6View, _cxml); } third: if (currentDepth == 0 || node.Name == "id0" || F1View == null) continue; correlateNodes = new List<XmlNode>(); foreach (XmlNode child in F1View.ChildNodes) { if (child.Attributes["X"].Value == X && child.Attributes["Y"].Value == Y) correlateNodes.Add(child); } //correlateNodes = F1View.SelectNodes(xPath); XmlNode unSequentiallyNode = null; if (node.Attributes["Depth"].Value == "0") sequentiallyNode = node; else unSequentiallyNode = node; if (correlateNodes.Count > 0) { foreach (XmlNode corrNode in correlateNodes) { if (corrNode.Attributes["Depth"].Value == "0") sequentiallyNode = corrNode; else unSequentiallyNode = corrNode; } if (sequentiallyNode == null) continue; // есть более одной присадки с совпадающими координатами, но ниодна из них не сквозная. Выходим из цикла double unSequentiallyNodeDepth; if (currentDepth != 0 && unSequentiallyNode!=null && double.TryParse(unSequentiallyNode.Attributes["Depth"].Value, out unSequentiallyNodeDepth)) { sequentiallyNode.Attributes["Depth"].Value = ((int)(currentDepth - unSequentiallyNodeDepth + 5)).ToString(); } } } } foreach (XmlNode view in allViews) { if (view != null && view.ChildNodes.Count > 1) { XmlNode newView; List<Tuple<double, double, XmlNode>> nodeList = new List<Tuple<double, double, XmlNode>>(); newView = view.CloneNode(false); foreach (XmlNode node in view.ChildNodes) { nodeList.Add(new Tuple<double, double, XmlNode>(double.Parse(node.Attributes["Y"].Value), double.Parse(node.Attributes["X"].Value), node)); } if (newView != null && newView.Attributes != null && view != null && view.Attributes != null && view.Attributes["Name"]!=null) { view.RemoveAll(); foreach (XmlAttribute attribute in newView.Attributes) { XmlAttribute xKey = _cxml.CreateAttribute(attribute.Name); xKey.Value = attribute.Value; view.Attributes.Append(xKey); } if (view.Attributes["Name"].Value == "F1" || view.Attributes["Name"].Value == "F6") nodeList =nodeList.OrderBy(x => x.Item3.Name != "id0").ThenBy(x => x.Item1).ThenBy(x => x.Item2).ToList(); else nodeList =nodeList.OrderBy(x => x.Item3.Name != "id0").ThenBy(x => x.Item2).ThenBy(x => x.Item1).ToList(); int i = 0; foreach (var tuple in nodeList) { //tuple.Item3.InnerXml = tuple.Item3.InnerXml.Replace(tuple.Item3.Name, string.Format("id{0}", i)); XmlNode newNode = _cxml.CreateElement(string.Format("id{0}", i)); if (tuple.Item3 != null && tuple.Item3.Attributes != null && newNode.Attributes!=null) { foreach (XmlAttribute attribute in tuple.Item3.Attributes) { XmlAttribute xKey = _cxml.CreateAttribute(attribute.Name); xKey.Value = attribute.Value; newNode.Attributes.Append(xKey); } } i++; view.AppendChild(newNode); } } } } return true; }
private string WriteXmlFile(ModelDoc2 swModel, bool isValidXml, string targetModelPath = null) { string ret = ""; if (_createProgramm) { var path = Path.GetDirectoryName(_swAdd.RootModel.GetPathName()); path = path + @"\Программы\"; if (!Directory.Exists(path)) Directory.CreateDirectory(path); string modelName = Path.GetFileName(swModel.GetPathName()); ret = path + modelName + ".xml"; string fnameWithoutExt = Path.GetFileNameWithoutExtension(swModel.GetPathName()); fnameWithoutExt = fnameWithoutExt.Substring(fnameWithoutExt.Length - 4, 4); string underlyingModelFileName; if (fnameWithoutExt[0] == '#' && (fnameWithoutExt[3] == 'P' || fnameWithoutExt[3] == 'p')) { underlyingModelFileName = targetModelPath;//@"D:\_SWLIB_BACKUP\ШКАФЫ-КУПЕ\Каркасные детали\ДСП 16 мм\8504F_Панель вкладная 000A#17P.SLDASM"; } else underlyingModelFileName = swModel.GetPathName().Replace("SLDDRW", "SLDASM"); ModelDoc2 underlyingModel =(ModelDoc2) _swApp.OpenDoc(underlyingModelFileName, (int) swDocumentTypes_e.swDocASSEMBLY); string sketchNumber = underlyingModel.GetCustomInfoValue("", "Sketch Number"); string orderNumber = underlyingModel.GetCustomInfoValue("", "Order Number"); _swApp.CloseDoc(underlyingModelFileName); if (!(string.IsNullOrEmpty(sketchNumber) || string.IsNullOrEmpty(orderNumber))) ret = Path.Combine(path, orderNumber + "_" + sketchNumber + ".xml"); if (File.Exists(ret)) { File.Delete(ret); } try { _cxml = new XmlDocument(); var element = _cxml.CreateElement("Model"); //modelName = Encoding.UTF8.GetString(Encoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.UTF8.GetBytes(modelName))); element.SetAttribute("Name", modelName); element.SetAttribute("CNCValid", isValidXml.ToString()); element.SetAttribute("vAddInn", Assembly.GetExecutingAssembly().GetName().Version.ToString()); element.SetAttribute("vLib", Properties.Settings.Default.PatchVersion); _node = _cxml.AppendChild(element); } catch (Exception ex) { MessageBox.Show(@"Ошибка: " + ex.Message); } } return ret; }
private bool GetComponentModel(ModelDoc2 swModel, Component2 inComp, out ModelDoc2 swCompModel, out string modelFileName) { int i = 0; modelFileName = ""; do { var compState = (swComponentSuppressionState_e)inComp.GetSuppression(); if (compState.ToString() == "swComponentSuppressed") inComp.SetSuppression2((int)swComponentSuppressionState_e.swComponentFullyResolved); swCompModel = (ModelDoc2)inComp.GetModelDoc(); if (swCompModel == null) { string newModelPath = CheckIsCompInOurLib(inComp.GetPathName()); if (inComp.Select(false)) { ((AssemblyDoc)swModel).ReplaceComponents(newModelPath, "", true, true); //((AssemblyDoc) swModel).ComponentReload(); swCompModel = inComp.IGetModelDoc(); //((AssemblyDoc) swModel).OpenCompFile(); //��� �������������� ��������� ���������� OpenCompFile �� ��������! if (((ModelDoc2)_iSwApp.ActiveDoc).GetPathName() != swModel.GetPathName()) swCompModel = (ModelDoc2)_iSwApp.ActiveDoc; } } i++; } while (swCompModel == null && i < 10); if (swCompModel != null) modelFileName = swCompModel.GetPathName(); else { MessageBox.Show(@"��������� " + inComp.Name + @"�� ���������!", MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } return true; }
private static string GetRootFolder(ModelDoc2 inRootModel) { return Path.GetDirectoryName(inRootModel.GetPathName()); }
/// <summary> /// Задает материал для детали из сборки (если задан componentId) либо по имени детали /// </summary> /// <param name="materialName">Материал (код или наименование по базе)</param> /// <param name="swDoc">Деталь</param> /// <param name="componentId">The component identifier.</param> private static void SetMeterial(string materialName, ModelDoc2 swDoc, string componentId) { if (componentId != "") { try { //"ВНС-901.43.230-1@ВНС-901.43.200/ВНС-901.43.231-1@ВНС-901.43.230" swDoc.Extension.SelectByID2(componentId, "COMPONENT", 0, 0, 0, false, 0, null, 0); var comp = swDoc.ISelectionManager.GetSelectedObject3(1); var matChangingModel = comp.GetModelDoc(); const string configName = ""; const string databaseName = "materialsXML.sldmat"; matChangingModel.SetMaterialPropertyName2(configName, databaseName, AddMaterialtoXml(materialName)); Логгер.Информация(string.Format("Для компонента {1} применен материал {0} ", AddMaterialtoXml(materialName), componentId), null, "", "SetMeterial"); } catch (Exception ex) { Логгер.Ошибка($"Не удалось применить материал {AddMaterialtoXml(materialName)} для компонента {componentId}. {ex.Message}", ex.StackTrace, null, "SetMeterial"); } } if (componentId == "") { try { var swPart = ((PartDoc) (swDoc)); const string configName = ""; const string databaseName = "materialsXML.sldmat"; swPart.SetMaterialPropertyName2(configName, databaseName, AddMaterialtoXml(materialName)); Логгер.Информация( string.Format("Для детали {1} применен материал {0} ", AddMaterialtoXml(materialName), swDoc.GetPathName()), null, "", "SetMeterial"); } catch (Exception ex) { Логгер.Ошибка($"Не удалось применить материал {AddMaterialtoXml(materialName)} для детали {componentId}. {ex.Message}", ex.StackTrace, null, "SetMeterial"); } } File.Delete(@"C:\Program Files\SW-Complex\materialsXML.sldmat"); }
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(); } }
private void getPriceForComponent(ModelDoc2 model, bool ParentCalcStruct, Action<decimal> nextPrice, Action<Exception, string> nextError) { string currentConfig = model.IGetActiveConfiguration().Name; if (currentConfig.ToLower().Contains("по умолчани") || currentConfig.ToLower().Contains("default")) currentConfig = string.Empty; string isProduct = model.GetCustomInfoValue(currentConfig, "IsProduct"); if (string.IsNullOrEmpty(isProduct)) { isProduct = model.GetCustomInfoValue(string.Empty, "IsProduct"); if (string.IsNullOrEmpty(isProduct)) isProduct = "No"; } if (isProduct == "Yes") { //изделие //Проверка существования артикула для компонента в случает отсутствия, расчет цены на сам компонент не производится string articul = model.GetCustomInfoValue(string.Empty, "Articul"); if (string.IsNullOrEmpty(articul)) articul = model.GetCustomInfoValue(currentConfig, "Articul"); if (!string.IsNullOrEmpty(articul)) { try { nextPrice(сalculatePriceForModel(model)); } catch (Exception e) { if (checkError(e)) nextError(e, Path.GetFileName(model.GetPathName())); } } string s = model.GetPathName(); AssemblyDoc model_assembly = model as AssemblyDoc; if (model_assembly != null) { bool calcStruct = true; if (!string.IsNullOrEmpty(articul)) { string calcStructStr = model.get_CustomInfo2(string.Empty, "CalcStruct"); if (calcStructStr.ToLower() == "no") calcStruct = false; } var components = (object[])((AssemblyDoc)model).GetComponents(true); foreach (var component in components) { var comp = (Component2)component; ModelDoc2 _model = comp.IGetModelDoc(); if (_model != null) { getPriceForComponent(_model, calcStruct, nextPrice, nextError); } } } } else { //не изделие string articul = model.GetCustomInfoValue(string.Empty, "Articul"); if (string.IsNullOrEmpty(articul)) articul = model.GetCustomInfoValue(currentConfig, "Articul"); string isIndependentStr = model.get_CustomInfo2(string.Empty, "IsIndependent"); bool isIndependent = true; if (string.IsNullOrEmpty(isIndependentStr) || isIndependentStr.ToLower() == "no") isIndependent = false; if (isIndependent) { bool calcStruct = true; if (!string.IsNullOrEmpty(articul)) { //независимый и с артикулом try { nextPrice(сalculatePriceForModel(model)); } catch (Exception e) { if (checkError(e)) nextError(e, Path.GetFileName(model.GetPathName())); } string calcStructStr = model.get_CustomInfo2(string.Empty, "CalcStruct"); if (calcStructStr.ToLower() == "no") calcStruct = false; } if (calcStruct) { AssemblyDoc model_assembly = model as AssemblyDoc; if (model_assembly != null) { var components = (object[])((AssemblyDoc)model).GetComponents(true); foreach (var component in components) { var comp = (Component2)component; ModelDoc2 _model = comp.IGetModelDoc(); if (_model != null) { getPriceForComponent(_model, calcStruct, nextPrice, nextError); } } } } } else { //компонент входит в состав изделия if (ParentCalcStruct) { //нужно получить цену bool calcStruct = true; if (!string.IsNullOrEmpty(articul)) { try { nextPrice(сalculatePriceForModel(model)); } catch (Exception e) { if (checkError(e)) nextError(e, Path.GetFileName(model.GetPathName())); } string calcStructStr = model.get_CustomInfo2(string.Empty, "CalcStruct"); if (calcStructStr.ToLower() == "no") calcStruct = false; } AssemblyDoc model_assembly = model as AssemblyDoc; if (model_assembly != null) { var components = (object[])((AssemblyDoc)model).GetComponents(true); foreach (var component in components) { var comp = (Component2)component; ModelDoc2 _model = comp.IGetModelDoc(); if (_model != null) { getPriceForComponent(_model, calcStruct, nextPrice, nextError); } } } } else { if (model as AssemblyDoc != null) { var components = (object[])((AssemblyDoc)model).GetComponents(true); foreach (var component in components) { var comp = (Component2)component; ModelDoc2 _model = comp.IGetModelDoc(); if (_model != null) { getPriceForComponent(_model, false, nextPrice, nextError); } } } } } } }
public string GetModelDatabaseFileName(ModelDoc2 inModel) { string ret = ""; string strDbName = inModel.GetPathName(); if (strDbName != "") { if (strDbName.Contains("_SWLIB_BACKUP")) // ���� ����� �� ����, �� �� ��������� ��������� 3 ������� ����� ����������� { string fileName = Path.GetFileNameWithoutExtension(strDbName); fileName = string.Format("{0}{1}", fileName.Substring(0, fileName.Length - 4), Path.GetExtension(strDbName)); strDbName = Path.Combine(Path.GetDirectoryName(strDbName), fileName); } strDbName = GetModelNameWithoutSuffix(strDbName); if (Path.GetExtension(strDbName).ToLower() == ".slddrw") strDbName = Path.GetFileNameWithoutExtension(strDbName) + ".sldasm"; string DBPathResult = Furniture.Helpers.SaveLoadSettings.ReadAppSettings("DBPath") == string.Empty ? Properties.Settings.Default.DBPath : Furniture.Helpers.SaveLoadSettings.ReadAppSettings("DBPath"); var dir = new DirectoryInfo(DBPathResult); //var dir = new DirectoryInfo(Properties.Settings.Default.DBPath); // ������ ������� foreach (FileInfo file in dir.GetFiles(Path.GetFileName(strDbName) + ".mdb", SearchOption.AllDirectories)) { strDbName = file.FullName; ret = strDbName; break; } } return ret; }
private void AutoDimensionDrawing2(ModelDoc2 swModel, bool many ) { bool del3List = false; var thrdList = new List<string>(); int shi = 0; isValidXml = true; var swDrawing = (DrawingDoc)swModel; if (swModel.GetCustomInfoValue("", "AutoDim") == "No") { if (many) { MessageBox.Show(@"Если хотите образмерить чертеж, смените No на Yes в поле 'AutoDim' свойств данного чертежа", @"MrDoors", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } isValidXml = false; } if (swModel.GetCustomInfoValue("", "MakeCNCprog") == "Yes") { _createProgramm = true; } if (!isValidXml && !_createProgramm) // если не надо создавать программу и авто дим = но, то образмеривать просто не нужно. return; swModel.Extension.SetUserPreferenceDouble((int)swUserPreferenceDoubleValue_e.swDetailingDimToDimOffset, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, 0.006); swModel.Extension.SetUserPreferenceDouble((int)swUserPreferenceDoubleValue_e.swDetailingObjectToDimOffset, (int)swUserPreferenceOption_e.swDetailingNoOptionSpecified, 0.010); Dictionary<string, bool> listSide; string targetModelPath = null; if (!File.Exists(Path.Combine(Path.GetDirectoryName(_swAdd.RootModel.GetPathName()), "fpTime.txt"))) { //MessageBox.Show("Образмеривание детали может пройти некорректно! Для корректного образмеривания детали необходимо произвести Окончательную обработку заказа."); throw new Exception("Образмеривание детали может пройти некорректно! Для корректного образмеривания детали необходимо произвести Окончательную обработку заказа."); } else { //просто взять Sketch Number string fnameWithoutExt = Path.GetFileNameWithoutExtension(swModel.GetPathName()); fnameWithoutExt = fnameWithoutExt.Substring(fnameWithoutExt.Length - 4, 4); SwDMDocument8 swDoc = null; SwDMApplication swDocMgr = SwAddin.GetSwDmApp(); SwDmDocumentOpenError oe; SwDmCustomInfoType type; if (!(fnameWithoutExt[0] == '#' && (fnameWithoutExt[3] == 'P' || fnameWithoutExt[3] == 'p'))) { swDoc = (SwDMDocument8) swDocMgr.GetDocument(Path.ChangeExtension(swModel.GetPathName(), "SLDASM"),SwDmDocumentType.swDmDocumentAssembly, true, out oe); } else { object brokenRefVar; SwDMSearchOption src = swDocMgr.GetSearchOptionObject(); var swDocDraw = (SwDMDocument8)swDocMgr.GetDocument(swModel.GetPathName(), SwDmDocumentType.swDmDocumentDrawing, true, out oe); var varRef = (object[])swDocDraw.GetAllExternalReferences2(src, out brokenRefVar); swDocDraw.CloseDoc(); targetModelPath = (string)varRef[0]; swDoc = (SwDMDocument8)swDocMgr.GetDocument(targetModelPath, SwDmDocumentType.swDmDocumentAssembly, true, out oe); } if (swDoc != null) { var prop = swDoc.GetCustomProperty("Sketch Number", out type); if (string.IsNullOrEmpty(prop) || prop == "0") throw new Exception("Образмеривание детали прервано, т.к. может пройти некорректно ! Для корректного образмеривания детали необходимо произвести Окончательную обработку заказа."); swDoc.CloseDoc(); } _swAdd.SetModelProperty(swModel, "WasMesure", string.Empty, swCustomInfoType_e.swCustomInfoYesOrNo, "Yes", true); } string pathXml = WriteXmlFile(swModel, isValidXml, targetModelPath); bool isNeededSheetNumber = PrepareDrawingDoc(swModel, out listSide); bool dimOnlyNew = false; if (swModel.GetCustomInfoValue("", "DimOnlyNew") == "Yes") dimOnlyNew = true; var vSheetNames = (string[])swDrawing.GetSheetNames(); var rootNode = _node; bool atLeastOneF1View = false; foreach (var vSheetName in vSheetNames) { bool iftherewasAhole = false; XmlElement element = null; XmlElement sheetNode = null; KeyValuePair<string,string> tableNameAttribute = new KeyValuePair<string, string>(); if (_createProgramm && !string.IsNullOrEmpty(pathXml)) { element = _cxml.CreateElement("Sheet"); element.SetAttribute("Name", vSheetName); _node = rootNode.AppendChild(element); sheetNode = element; } double vScale = 0; var type = new List<string>(); var listSize = new List<SizeForDim>(); swDrawing.ActivateSheet(vSheetName); swModel.Extension.SelectByID2(vSheetName, "SHEET", 0, 0, 0, true, (int)swSelectionMarkAction_e.swSelectionMarkAppend, null, 0); swModel.ViewZoomToSelection(); swModel.ClearSelection(); var swSheet = (Sheet)swDrawing.GetCurrentSheet(); var swViews = (object[])swSheet.GetViews(); bool side = shi == 1; if (isNeededSheetNumber && listSide.ContainsKey(vSheetName.Substring(vSheetName.Length - 1))) side = listSide[vSheetName.Substring(vSheetName.Length - 1)]; if (vSheetName.ToUpper().Contains("FACE")) side = true; if (vSheetName.ToUpper().Contains("BACK")) side = false; if (swViews != null) { var rootViewElement = _node; if (Properties.Settings.Default.ViewsBeforeDimen) ReplaceViews(swViews, swDrawing); foreach (var t in swViews) { #region Образмеривание вида var swView = (View) t; swModel.ClearSelection2(true); const string expr = "^F[1-6]$"; Match isMatch = Regex.Match(swView.Name, expr, RegexOptions.IgnoreCase); if (_createProgramm && swView.Name.ToLower().Contains("const")) { //Logging.Log.Instance.Fatal(@"На данный чертеж программа не будет создана! " + swModel.GetPathName() + "swView.Name = " + swView.Name); //MessageBox.Show(@"На данный чертеж программа не будет создана!", @"MrDoors",MessageBoxButtons.OK,MessageBoxIcon.Exclamation); } if (!(isMatch.Success || swView.Name.Contains("Чертежный вид")) || swView.Name.ToLower().Contains("const") || swView.Type == (int)swDrawingViewTypes_e.swDrawingDetailView) continue; if (_createProgramm && !isMatch.Success) { _createProgramm = false; //Logging.Log.Instance.Fatal(@"На данный чертеж программа не будет создана! " + swModel.GetPathName() + "swView.Name = " + swView.Name); //MessageBox.Show(@"На данный чертеж программа не будет создана!", @"MrDoors", // MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } swDrawing.ActivateView(swView.GetName2()); swView.UseSheetScale = 0; var list = HideUnusedComponents(swView, dimOnlyNew); try { vScale = ((double[]) swView.ScaleRatio)[1]; swView.SetDisplayMode3(false, (int) swDisplayMode_e.swFACETED_HIDDEN, true, true); #region Процесс образмеривания using (var d = new DimensionView(_swApp, BlockPositionExtension.FromBool(side), dimOnlyNew)) { d.DimView(side); if (!iftherewasAhole) iftherewasAhole = d.IsHole; if (!isNeededSheetNumber && !side && !iftherewasAhole) del3List = true; else { if (isNeededSheetNumber && !iftherewasAhole) { del3List = true; thrdList.Add(vSheetName); } } foreach (var tp in d.List) { if (!type.Contains(tp)) type.Add(tp); } listSize.Add(d.AddSize); #region Запись данных в xml файл if (element != null) { element = _cxml.CreateElement("View"); element.SetAttribute("Name", swView.Name); if (swView.Name == "F1") { atLeastOneF1View = true; SwDmDocumentOpenError oe; SwDMApplication swDocMgr = SwAddin.GetSwDmApp(); var swDoc = (SwDMDocument8)swDocMgr.GetDocument(Path.ChangeExtension(swModel.GetPathName(), "SLDASM"), SwDmDocumentType.swDmDocumentAssembly, true, out oe); if (swDoc != null) { var cit = new SwDmCustomInfoType(); string[] names = swDoc.GetCustomPropertyNames(); string extFeats = null,faner11 = null,faner12 = null,faner21 = null,faner22 = null; if (names.Contains("ExtFanerFeats")) extFeats = swDoc.GetCustomProperty("ExtFanerFeats", out cit); double angle = 57.29577951308232*swView.Angle; //(180/П) if (Math.Abs(angle) < 0.000001 || Math.Abs(angle + 90) < 0.000001 || Math.Abs(angle - 270) < 0.000001 || Math.Abs(angle - 180) < 0.000001 || Math.Abs(angle - 90) < 0.000001) //!string.IsNullOrEmpty(extFeats) && extFeats == "Yes" && { if (names.Contains("Faner11")) faner11 = swDoc.GetCustomProperty("Faner11", out cit); if (names.Contains("Faner12")) faner12 = swDoc.GetCustomProperty("Faner12", out cit); if (names.Contains("Faner21")) faner21 = swDoc.GetCustomProperty("Faner21", out cit); if (names.Contains("Faner22")) faner22 = swDoc.GetCustomProperty("Faner22", out cit); var tmpElem = _cxml.CreateElement("Comment"); string comment = FrmEdge.GetCommentFromProperties(faner11,faner12,faner21,faner22, angle, _swAdd,swModel); double angle2 = angle + 90; double angle4 = angle + 180; double angle3 = angle + 270; if (angle2 > 270) angle2 = angle2%360; if (angle3 > 270) angle3 = angle3 % 360; if (angle4 > 270) angle4 = angle4 % 360; string comment2 = FrmEdge.GetCommentFromProperties(faner11, faner12, faner21, faner22, angle2, _swAdd, swModel); string comment3 = FrmEdge.GetCommentFromProperties(faner11, faner12, faner21, faner22, angle3, _swAdd, swModel); string comment4 = FrmEdge.GetCommentFromProperties(faner11, faner12, faner21, faner22, angle4, _swAdd, swModel); tmpElem.SetAttribute("Rot270",comment3); tmpElem.SetAttribute("Rot180",comment4); tmpElem.SetAttribute("Rot90", comment2); tmpElem.SetAttribute("Rot0", comment); rootNode.PrependChild(tmpElem); } } //swDoc.CloseDoc(); //int warnings = 0; //int errors = 0; //var swModelDoc = _swApp.OpenDoc6(Path.ChangeExtension(swModel.GetPathName(), "SLDASM"), (int)swDocumentTypes_e.swDocASSEMBLY, // (int)swOpenDocOptions_e.swOpenDocOptions_Silent, "", errors, // warnings); //if (!string.IsNullOrEmpty(swModelDoc.CustomInfo2["", "ExtFanerFeats"]) && swModelDoc.CustomInfo2["", "ExtFanerFeats"] == "Yes") //{ // var tmpElem = _cxml.CreateElement("Comment"); // string comment = FrmEdge.GetComment(swModelDoc, swView.Angle, _swAdd); // tmpElem.SetAttribute("Rot270", string.Empty); // tmpElem.SetAttribute("Rot90", string.Empty); // tmpElem.SetAttribute("Rot0", comment); // rootNode.PrependChild(tmpElem); //} } if (_node != null) { _node = rootViewElement.AppendChild(element); switch (d.Side) { case BlockPosition.LeftTopToRightBottom: if (swView.Name == "F1") tableNameAttribute = new KeyValuePair<string, string>("F1","J"); if (swView.Name == "F6") { if (tableNameAttribute.Key!="F1") // F1 - приоритетнее tableNameAttribute = new KeyValuePair<string, string>("F6", "B"); } if (string.IsNullOrEmpty(tableNameAttribute.Key)) { tableNameAttribute = new KeyValuePair<string, string>("none","J"); } break; case BlockPosition.RightTopToLeftBottom: if (swView.Name == "F1") tableNameAttribute = new KeyValuePair<string, string>("F1","B"); if (swView.Name == "F6") { if (tableNameAttribute.Key!="F1") // F1 - приоритетнее tableNameAttribute = new KeyValuePair<string, string>("F6", "J"); } if (string.IsNullOrEmpty(tableNameAttribute.Key)) { tableNameAttribute = new KeyValuePair<string, string>("none", "B"); } break; case BlockPosition.LeftBottomToRightTop: case BlockPosition.RigthBottomToLeftTop: //MessageBox.Show( // "В этом чертеже начало координат находится внизу. Программа может быть создана некорректно!", // @"MrDoors", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // element = _cxml.CreateElement("Table"); // element.SetAttribute("Name", "Не удалось определить наименование стола!"); //_node=_node.AppendChild(element); break; } } int i = 0; string id = "id" + i; element = _cxml.CreateElement(id); element.SetAttribute("X", Math.Round(d.X).ToString(CultureInfo.CreateSpecificCulture("ru-RU"))); element.SetAttribute("Y", Math.Round(d.Y).ToString(CultureInfo.CreateSpecificCulture("ru-RU"))); if (swView.Name == "F1" || swView.Name == "F6") element.SetAttribute("Z", _z.ToString(CultureInfo.CreateSpecificCulture("ru-RU"))); if (_node != null) _node.AppendChild(element); foreach (var ls in d.ListSize) { i++; id = "id" + i; element = _cxml.CreateElement(id); element.SetAttribute("X", ls.X.ToString(CultureInfo.CreateSpecificCulture("ru-RU"))); element.SetAttribute("Y", ls.Y.ToString(CultureInfo.CreateSpecificCulture("ru-RU"))); element.SetAttribute("Diameter", ls.Diameter.ToString(CultureInfo.CreateSpecificCulture("ru-RU"))); element.SetAttribute("Depth",ls.Depth.ToString(CultureInfo.CreateSpecificCulture("ru-RU"))); if (_node != null) _node.AppendChild(element); } _node = _node.ParentNode; } #endregion } #endregion swView.SetDisplayMode3(false, (int) swDisplayMode_e.swFACETED_HIDDEN_GREYED, true, true); swDrawing.ActivateSheet(vSheetName); } catch (Exception e) { MessageBox.Show(@"Ошибка при образмеривании! " + e.Message, @"MrDoors", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (dimOnlyNew) ShowHiddenComponents(list); } #endregion } } if (type.Count != 0) LegendMaker(swModel, swDrawing, type, vScale); if (!string.IsNullOrEmpty(tableNameAttribute.Value)) sheetNode.SetAttribute("TableName", tableNameAttribute.Value); if (Properties.Settings.Default.ScaleWhenDimen && !del3List && shi != 0) AutoScaleSheet(listSize, swSheet, vScale, side); shi++; if(_node!=null) _node = _node.ParentNode; AutoArrangeDimentions(vSheetName,dimOnlyNew); } swModel.EditRebuild3(); if (shi == 3) { if (del3List) { if (isNeededSheetNumber && thrdList.Count > 0) foreach (var sh in thrdList) swModel.Extension.SelectByID2(sh, "SHEET", 0, 0, 0, true, 0, null, 0); else { if (!swModel.Extension.SelectByID2("Лист3", "SHEET", 0, 0, 0, false, 0, null, 0)) { swModel.Extension.SelectByID2("Back3", "SHEET", 0, 0, 0, false, 0, null, 0); } } swModel.DeleteSelection(true); } else SheetNumering(swModel, swDrawing); } swModel.ForceRebuild3(false); bool writeXml = true; if (atLeastOneF1View) { try { writeXml=SomeLogicChanges(swModel); } catch(Exception e) { if (swModel.GetPathName() != null) Logging.Log.Instance.Fatal(e, "Ошибка при применении логики к XML. " + swModel.GetPathName()); else Logging.Log.Instance.Fatal(e, "Ошибка при применении логики к XML. "); } if (writeXml) StopWriteXml(pathXml); } return; }
private bool CopyDrawing(ModelDoc2 inModel, bool askIfExist, string whereToSearchDirectory) { bool ret = false; try { string strModelName = inModel.GetPathName(); if (strModelName != "") { string strDrwNewName; // ��� ���� ��������... string strDrwName = string.Empty; var dir = new DirectoryInfo(DrwPathResult); if (strModelName.ToUpper().Contains("_SWLIB_BACKUP")) { strDrwNewName = Path.GetDirectoryName(RootModel.GetPathName()) + "\\�������\\" + Path.GetFileNameWithoutExtension(strModelName) + ".SLDDRW"; string modelNameWithoutExtension = Path.GetFileNameWithoutExtension(strModelName); strDrwName = modelNameWithoutExtension.Substring(0, modelNameWithoutExtension.Length - 4); foreach (FileInfo file in dir.GetFiles(strDrwName + ".SLDDRW", SearchOption.AllDirectories)) { strDrwName = file.FullName; break; } if (!Directory.Exists(Path.GetDirectoryName(RootModel.GetPathName()) + "\\�������")) Directory.CreateDirectory(Path.GetDirectoryName(RootModel.GetPathName()) + "\\�������"); } else { strDrwNewName = Path.GetDirectoryName(strModelName) + "\\" + Path.GetFileNameWithoutExtension(strModelName) + ".SLDDRW"; //string strDrwNewMyName = GetRootFolder(inRootModel) + "\\������� " + GetOrderName(inRootModel) + "\\" + Path.GetFileName(strDrwNewName); strDrwName = GetModelNameWithoutSuffix(strModelName); if (!string.IsNullOrEmpty(whereToSearchDirectory)) { string[] postfixArr = Path.GetFileNameWithoutExtension(strModelName).Split('-'); string postfix = string.Empty; if (postfixArr.Length > 1) postfix = "*" + postfixArr.Last() + ".SLDDRW"; else postfix = "*.SLDDRW"; dir = new DirectoryInfo(whereToSearchDirectory); foreach ( FileInfo file in dir.GetFiles(Path.GetFileNameWithoutExtension(strDrwName) + postfix, SearchOption.AllDirectories)) { strDrwName = file.FullName; break; } } else { foreach ( FileInfo file in dir.GetFiles(Path.GetFileNameWithoutExtension(strDrwName) + ".SLDDRW", SearchOption.AllDirectories)) { strDrwName = file.FullName; break; } } if (!File.Exists(strDrwName) && !string.IsNullOrEmpty(whereToSearchDirectory)) { // �������� �� ���������� strDrwName = GetModelNameWithoutSuffix(strModelName); dir = new DirectoryInfo(DrwPathResult); foreach ( FileInfo file in dir.GetFiles(Path.GetFileNameWithoutExtension(strDrwName) + ".SLDDRW", SearchOption.AllDirectories)) { strDrwName = file.FullName; break; } } } if (File.Exists(strDrwName)) { bool isOverwriteExistingFile = true; if (File.Exists(strDrwNewName)) { if (askIfExist) isOverwriteExistingFile = (MessageBox.Show(@"���� " + strDrwNewName + @" ����������. �� ������ ������������ ���?", MyTitle, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes); else isOverwriteExistingFile = false; } if (isOverwriteExistingFile) { File.Copy(strDrwName, strDrwNewName, true); File.SetAttributes(strDrwNewName, FileAttributes.Normal); SwDmDocumentOpenError oe; object brokenRefVar; SwDMApplication swDocMgr = GetSwDmApp(); var swDoc = (SwDMDocument8)swDocMgr.GetDocument(strDrwNewName, SwDmDocumentType.swDmDocumentDrawing, false, out oe); SwDMSearchOption src = swDocMgr.GetSearchOptionObject(); var varRef = (object[])swDoc.GetAllExternalReferences2(src, out brokenRefVar); if (varRef.Count() > 1) { foreach (var o in varRef) { ModelDoc2 mod; if (GetModelByName(inModel, (new FileInfo((string)o)).Name, false, out mod)) { swDoc.ReplaceReference((string)o, mod.GetPathName()); } else { MessageBox.Show("������ �������� ����� � ��������! ��������� �������� � ������ �� ������� ���������� �� �����."); } } } else swDoc.ReplaceReference((string)varRef[0], strModelName); SwDmDocumentSaveError lngSaveRes = swDoc.Save(); swDoc.CloseDoc(); ret = true; } // ���� ������� ret = true, �.�. ���� ������� ��� ����� ����������, ������ �� �������� else ret = true; } } } catch (Exception e) { MessageBox.Show(e.Message, MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } return ret; }
private void ReloadAllSetParameters(Component2 swTestSelComp) { #region Очистить все словари местные переменные int downPos = 0; //закоменчено, т.к. этот код вызывает ошибку внутри солида и его закрытие. //замена на похожие методы (ClearSelection2 и т.п.) не помогает /*/ if (!_isMate) { _swAsmDoc.NewSelectionNotify -= NewSelection; _swModel.ClearSelection(); _swAsmDoc.NewSelectionNotify += NewSelection; } /*/ _dictHeightPage.Clear(); _dictPathPict.Clear(); _dictionary.Clear(); _dictConfig.Clear(); _commonList.Clear(); _objListChanged.Clear(); _setNewListForComboBox = true; _butPlusTxt.Clear(); _dimensionConfig.Clear(); _textBoxListForRedraw.Clear(); _numbAndTextBoxes.Clear(); _comboBoxListForRedraw.Clear(); _namesOfColumnNameFromDimLimits.Clear(); refobj = null; #endregion if (swTestSelComp != null) { if (_mSwAddin.GetParentLibraryComponent(swTestSelComp, out _swSelComp)) { ModelDoc2 specModel; _swSelComp = _mSwAddin.GetMdbComponentTopLevel(_swSelComp, out specModel); _swSelModel = _swSelComp.IGetModelDoc(); #region ссылочный эскиз //bool draft = (specModel.CustomInfo2["", "Required Draft"] == "Yes" || // specModel.CustomInfo2[specModel.IGetActiveConfiguration().Name, "Required Draft"] == "Yes"); //if (draft) //{ // tabMain.Location = new Point(8, 70); // var dir = new DirectoryInfo(Path.GetDirectoryName(_mSwAddin.SwModel.GetPathName())); // var paths = // dir.GetFiles( // Path.GetFileNameWithoutExtension(specModel.GetPathName()) + ".SLDDRW", // SearchOption.AllDirectories); // string path=null; // if (paths.Any()) // path = paths[0].FullName; // else // { // if (SwAddin.needWait) // { // path = Path.Combine(Path.GetDirectoryName(specModel.GetPathName()), // Path.GetFileNameWithoutExtension(specModel.GetPathName()) + // ".SLDDRW"); // ThreadPool.QueueUserWorkItem(CheckDWRexistAfterCopy, path); // } // } // if (!string.IsNullOrEmpty(path)) // { // linkLabel1.Name = path; // linkLabel1.Click += LinkLabel1Click; // string textInfo = specModel.CustomInfo2["", "Sketch Number"]; // if (textInfo == "" || textInfo == "0" || textInfo == "Sketch Number") // linkLabel1.Text = @"ЭСКИЗ № н/о"; // else // linkLabel1.Text = @"ЭСКИЗ № " + textInfo; // } // else // tabMain.Location = new Point(8, 40); //} //else //{ // tabMain.Location = new Point(8, 40); // linkLabel1.Text = ""; //} #endregion _lblPrm.Clear(); _btnPrm.Clear(); tbpParams.Controls.Clear(); tbpPos.Controls.Clear(); lblCompName.Text = _swSelComp.Name2; OleDbConnection oleDb; int i; if (_mSwAddin.OpenModelDatabase(_swSelModel, out oleDb)) { using (oleDb) { #region Обработка файла *.mdb if (!tabMain.Controls.Contains(tbpParams)) { tabMain.Controls.Remove(tbpPos); tabMain.Controls.Add(tbpParams); tabMain.Controls.Add(tbpPos); } if (Properties.Settings.Default.KitchenModeOn) { tabMain.SelectTab(tbpPos); } else { if (tabMain.SelectedTab != tbpParams) { tabMain.SelectTab(tbpParams); } } var oleSchem = oleDb.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); OleDbCommand cm; OleDbDataReader rd; listForDimensions = new List<DimensionConfForList>(); #region Если есть objects if (oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "objects")) { _chkMeasure = new CheckBox { Appearance = Appearance.Button, Location = new Point(133, 12), Name = @"chkMeasure", Size = new Size(80, 24), Text = @"Измерить", TextAlign = ContentAlignment.MiddleCenter, UseVisualStyleBackColor = true }; tbpParams.Controls.Add(_chkMeasure); _chkMeasure.CheckedChanged += StartMeasure; i = 0; bool isNumber = false, isIdSlave = false, isAsmConfig = false, isFixedValues = false; #region Dimension Configuration if ( oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "dimension_conf")) { cm = new OleDbCommand("SELECT * FROM dimension_conf ORDER BY id", oleDb); rd = cm.ExecuteReader(); var outComps = new LinkedList<Component2>(); if (_mSwAddin.GetComponents( _swSelModel.IGetActiveConfiguration().IGetRootComponent2(), outComps, true, false)) { _dimensionConfig = Decors.GetListComponentForDimension(_mSwAddin, rd, outComps); _dimensionConfig.Sort((x, y) => x.Number.CompareTo(y.Number)); rd.Close(); } } #endregion var thisDataSet = new DataSet(); var testAdapter = new OleDbDataAdapter("SELECT * FROM objects", oleDb); testAdapter.Fill(thisDataSet, "objects"); testAdapter.Dispose(); bool captConfigBool = thisDataSet.Tables["objects"].Columns.Contains("captConf"); foreach (var v in thisDataSet.Tables["objects"].Columns) { var vc = (DataColumn)v; if (vc.ColumnName == "number") isNumber = true; if (vc.ColumnName == "idslave") { if (vc.DataType.Name != "String") MessageBox.Show( @"Неверно указан тип данных в столбце 'ismaster'", _mSwAddin.MyTitle, MessageBoxButtons.OK, MessageBoxIcon.Information); isIdSlave = true; } if (vc.ColumnName == "mainasmconf" && _swSelModel.GetConfigurationCount() > 1) isAsmConfig = true; if (vc.ColumnName == "fixedvalues") isFixedValues = true; } thisDataSet.Clear(); if (Properties.Settings.Default.CheckParamLimits && oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "dimlimits")) { testAdapter = new OleDbDataAdapter("SELECT * FROM dimlimits", oleDb); testAdapter.Fill(thisDataSet, "dimlimits"); testAdapter.Dispose(); foreach (var v in thisDataSet.Tables["dimlimits"].Columns) { var vc = (DataColumn)v; _namesOfColumnNameFromDimLimits.Add(vc.ColumnName); } thisDataSet.Clear(); } string currentConf = _swSelComp.ReferencedConfiguration; cm = isNumber ? new OleDbCommand( "SELECT * FROM objects WHERE number>0 ORDER BY number", oleDb) : new OleDbCommand("SELECT * FROM objects ORDER BY id", oleDb); rd = cm.ExecuteReader(); #region Размеры #region Считывание данных из objects int k = 1; var dictWithDiscretValues = new Dictionary<string, List<int>>(); while (rd.Read()) { if (captConfigBool && rd["captConf"] != null && rd["captConf"].ToString() != "all" && rd["captConf"].ToString() != currentConf && !string.IsNullOrEmpty(rd["captConf"].ToString())) continue; if (rd["caption"].ToString() == null || rd["caption"].ToString() == "" || rd["caption"].ToString().Trim() == "") continue; #region Обработка поля mainasmconf if (isAsmConfig) { var neededConf = rd["mainasmconf"].ToString(); bool isNeededConf = neededConf.Split('+').Select(v => v.Trim()).Any( f => f == currentConf); if (neededConf == "all") isNeededConf = true; if (!isNeededConf) continue; } #endregion string strObjName = rd["name"].ToString(); double strObjVal; if (_swSelModel.GetPathName().Contains("_SWLIB_BACKUP")) { string pn = Path.GetFileNameWithoutExtension(_swSelModel.GetPathName()); string last3 = pn.Substring(pn.Length - 4, 4); string[] arr = strObjName.Split('@'); if (arr.Length != 3) throw new Exception("что-то не так"); arr[2] = Path.GetFileNameWithoutExtension(arr[2]) + last3 + Path.GetExtension(arr[2]); strObjName = string.Format("{0}@{1}@{2}", arr[0], arr[1], arr[2]); } if (_mSwAddin.GetObjectValue(_swSelModel, strObjName, (int)rd["type"], out strObjVal)) { int val = GetCorrectIntValue(strObjVal); int number = isNumber ? (int)rd["number"] : (int)rd["id"]; while (number != k && _dimensionConfig.Count != 0) { listForDimensions.AddRange( from dimensionConfiguration in _dimensionConfig where dimensionConfiguration.Number == k select new DimensionConfForList(dimensionConfiguration.Number, dimensionConfiguration.Caption, "", -1, GetListIntFromString( dimensionConfiguration. IdSlave), dimensionConfiguration. Component, false, dimensionConfiguration.Id)); //Logging.Log.Instance.Debug("listForDimensions1:" + listForDimensions.Count.ToString()); k++; } var listId = new List<int>(); try { if (isIdSlave) listId = GetListIntFromString((string)rd["idslave"]); } catch { listId = null; } string labelName; try { labelName = rd["caption"].ToString(); } catch { string[] strObjNameParts = strObjName.Split('@'); labelName = strObjNameParts[0]; } if (isFixedValues) { try { var arr = (string)rd["fixedvalues"]; string[] arrs = arr.Split(','); var list = arrs.Select(s => Convert.ToInt32(s)).ToList(); if (!dictWithDiscretValues.ContainsKey(strObjName)) dictWithDiscretValues.Add(strObjName, list); } catch { } } listForDimensions.Add(new DimensionConfForList(number, labelName, strObjName, val, listId, null, (bool)rd["ismaster"], (int)rd["id"])); //Logging.Log.Instance.Debug("listForDimensions2:" + listForDimensions.Count.ToString()); k++; } } rd.Close(); #endregion listForDimensions.AddRange( _dimensionConfig.Where(x => x.Number >= k).Select( b => new DimensionConfForList(b.Number, b.Caption, "", -1, GetListIntFromString(b.IdSlave), b.Component, false, b.Id))); listForDimensions.Sort((x, y) => x.Number.CompareTo(y.Number)); //Logging.Log.Instance.Debug("listForDimensions3:" + listForDimensions.Count.ToString()); foreach (var dimensionConfForList in listForDimensions) { var lblNew = new Label { Size = new Size(125, 24) }; lblNew.Location = new Point(0, 48 + i * (lblNew.Size.Height + 6)); lblNew.Name = "lblPrm" + i; lblNew.TextAlign = ContentAlignment.MiddleRight; lblNew.Text = dimensionConfForList.LabelName; lblNew.Tag = dimensionConfForList.StrObjName; tbpParams.Controls.Add(lblNew); _lblPrm.AddLast(lblNew); downPos = lblNew.Location.Y + lblNew.Size.Height; if (dimensionConfForList.StrObjName != "") { #region TextBox с размерами if (dictWithDiscretValues.ContainsKey(dimensionConfForList.StrObjName)) { #region Если дискретные значения var comboBoxWithDiscretValues = new ComboBox { Size = new Size(53, 24), Location = new Point( lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), Tag = dimensionConfForList.StrObjName, TabIndex = i }; int val = dimensionConfForList.ObjVal; foreach (int vals in dictWithDiscretValues[dimensionConfForList.StrObjName]) { int ordNumb = comboBoxWithDiscretValues.Items.Add(vals); if (vals == val) comboBoxWithDiscretValues.SelectedIndex = ordNumb; } tbpParams.Controls.Add(comboBoxWithDiscretValues); _comboBoxListForRedraw.Add(comboBoxWithDiscretValues, dimensionConfForList.IdSlave); comboBoxWithDiscretValues.SelectedIndexChanged += ComboBoxWithDiscretValuesSelectedIndexChanged; #endregion } else { #region Если обычные значения int val = GetCorrectIntValue(dimensionConfForList.ObjVal); var txtNew = new TextBox { Size = new Size(35, 24), Location = new Point( lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), Name = lblNew.Text + "@" + dimensionConfForList.ObjVal, Text = val.ToString(), TextAlign = HorizontalAlignment.Right, Tag = dimensionConfForList.StrObjName, TabIndex = i }; _numbAndTextBoxes.Add(dimensionConfForList.Id, txtNew); if (!dimensionConfForList.IsGrey) txtNew.ReadOnly = true; else { _textBoxListForRedraw.Add(txtNew, dimensionConfForList.IdSlave); txtNew.KeyDown += TxtPrmKeyDown; txtNew.TextChanged += TxtNewTextChanged; var btnNew = new Button { ImageKey = @"Units1.ico", ImageList = imageList1, Size = new Size(24, 24), Location = new Point( txtNew.Location.X + txtNew.Size.Width + 4, lblNew.Location.Y), Name = dimensionConfForList.ObjVal. ToString(), Text = "", Tag = txtNew.Name, Enabled = false }; if (!_butPlusTxt.ContainsKey(btnNew)) _butPlusTxt.Add(btnNew, txtNew); tbpParams.Controls.Add(btnNew); _btnPrm.AddLast(btnNew); btnNew.Click += MeasureLength; #region если есть таблица ref_objects и в ней есть хоть одна строка с соотв-щем id if (refobj == null) { refobj = new List<ref_object>(); if (oleSchem.Rows.Cast<DataRow>().Any(row => (string)row["TABLE_NAME"] == "ref_objects_axe")) { cm = new OleDbCommand("SELECT * FROM ref_objects LEFT JOIN ref_objects_axe ON ref_objects_axe.id=ref_objects.objectsId", oleDb); rd = cm.ExecuteReader(); while (rd.Read()) { refobj.Add(new ref_object((string)rd["componentName"], (int)rd["objectsId"], (string)rd["axe"], (float)rd["correctionLeft_Up"], (float)rd["correctionRight_Down"])); } rd.Close(); } } ref_object[] currentrefs = refobj.Where(d => d.ObjectId == dimensionConfForList.Id).ToArray(); if (currentrefs.Length > 0) { //добавить кнопку //выбрать из refobj только dimensionConfigForList.Id var btnRef = new Button { ImageKey = @"expand.gif", ImageList = imageList1, Size = new Size(24, 24), Location = new Point( txtNew.Location.X + txtNew.Size.Width + btnNew.Size.Width + 8, lblNew.Location.Y), Name = dimensionConfForList.ObjVal. ToString(), Text = "", Tag = currentrefs, Enabled = true }; tbpParams.Controls.Add(btnRef); //_btnPrm.AddLast(btnNew); btnRef.Click += ExpandBtn; if (!_butPlusTxt.ContainsKey(btnRef)) _butPlusTxt.Add(btnRef, txtNew); } #endregion } tbpParams.Controls.Add(txtNew); _commonList.Add(txtNew); #endregion } #endregion } else { #region ComboBox с конфигурациями var cmp = dimensionConfForList.Component; var comboBoxConfForDimTab = new ComboBox { Size = new Size(56, 24), Location = new Point( lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), Tag = cmp, TabIndex = i }; var confNames = (string[])cmp.IGetModelDoc().GetConfigurationNames(); foreach (var confName in confNames) { int lonhName = confName.Length * 6; if (comboBoxConfForDimTab.DropDownWidth < lonhName) comboBoxConfForDimTab.DropDownWidth = lonhName; comboBoxConfForDimTab.Items.Add(confName); } comboBoxConfForDimTab.SelectedItem = cmp.ReferencedConfiguration; tbpParams.Controls.Add(comboBoxConfForDimTab); _comboBoxListForRedraw.Add(comboBoxConfForDimTab, dimensionConfForList.IdSlave); comboBoxConfForDimTab.SelectedIndexChanged += ComboBoxConfForDimTabSelectedIndexChanged; #endregion } i++; } #region Добавить выбор конфигурации try { if (_swSelModel.GetConfigurationCount() > 1) { var lblNew = new Label { Size = new Size(125, 24) }; lblNew.Location = new Point(0, 48 + i * (lblNew.Size.Height + 6)); lblNew.Name = "lblPrm" + i; lblNew.TextAlign = ContentAlignment.MiddleRight; lblNew.Text = "Конфигурации:"; tbpParams.Controls.Add(lblNew); //lblNew.Tag = dimensionConfForList.StrObjName; downPos = lblNew.Location.Y + lblNew.Size.Height; string[] configurations = _swSelModel.GetConfigurationNames(); var comboBoxConfig = new ComboBox { Size = new Size(56, 24), Location = new Point(lblNew.Location.X + lblNew.Size.Width + 4, lblNew.Location.Y), }; string activeConf = _swSelComp.ReferencedConfiguration;//_swSelModel.IGetActiveConfiguration().Name; foreach (var configuration in configurations) { int currentIndex = comboBoxConfig.Items.Add(configuration); if (configuration == activeConf) comboBoxConfig.SelectedIndex = currentIndex; } Size size = TextRenderer.MeasureText(activeConf, comboBoxConfig.Font); int lonhName = size.Width; //nameOfConfiguration.Length * 5; if (comboBoxConfig.DropDownWidth < lonhName) comboBoxConfig.DropDownWidth = lonhName; tbpParams.Controls.Add(comboBoxConfig); comboBoxConfig.SelectedIndexChanged += ConfigurationChanged; } } catch { } #endregion #endregion _dictHeightPage.Add(tbpParams, downPos); } #endregion #region Если есть comments if (oleSchem.Rows.Cast<DataRow>().Any( row => (string)row["TABLE_NAME"] == "comments")) { cm = new OleDbCommand("SELECT * FROM comments ORDER BY id", oleDb); rd = cm.ExecuteReader(); if (rd.Read()) { try { CommentLayout.Visible = true; WarningPB.Visible = (bool)rd["showSimbol"]; commentsTb.Text = (string)rd["comment"]; Size size = TextRenderer.MeasureText(commentsTb.Text, commentsTb.Font); commentsTb.Height = (size.Width / (commentsTb.Width - 10)) * 30; } catch { CommentLayout.Visible = false; } } rd.Close(); } else { CommentLayout.Visible = false; } #endregion #region Decors if (!ReloadDecorTab(oleDb, oleSchem)) return; #endregion oleDb.Close(); #endregion } } else if (_tabDec != null) tabMain.Controls.Remove(_tabDec); var swFeat = (Feature)_swSelModel.FirstFeature(); i = 0; #region Position var mates = _swSelComp.GetMates(); Dictionary<string, Mate2> existingMates = new Dictionary<string, Mate2>(); if (mates != null) { foreach (var mate in mates) { if (mate is Mate2) { var spec = (Mate2)mate; int mec = spec.GetMateEntityCount(); if (mec > 1) { for (int ik = 0; ik < mec; ik++) { MateEntity2 me = spec.MateEntity(ik); if (me.ReferenceComponent.Name.Contains(_swSelComp.Name)) { Entity tt = me.Reference; var tt2 = tt as Feature; if (tt is RefPlane && tt2 != null) { if (!existingMates.ContainsKey(tt2.Name)) existingMates.Add(tt2.Name, spec); } } } } } } } int downPosPosition = 0; int tabIndex = 0; while (swFeat != null) { if (swFeat.GetTypeName2() == "RefPlane") { string strPlaneName = swFeat.Name; if (strPlaneName.Length > 1) { if (strPlaneName.Substring(0, 1) == "#") { var btnNew = new Button { Size = new Size(120, 20) }; btnNew.Location = new Point(62, 24 + i * (btnNew.Size.Height + 6)); //if (Properties.Settings.Default.KitchenModeOn) // btnNew.Name = strPlaneName;//"btnPos" + i; //else btnNew.Name = "btnPos" + i; btnNew.Text = strPlaneName.Substring(5); btnNew.Tag = strPlaneName; btnNew.TabIndex = tabIndex; tabIndex++; tbpPos.Controls.Add(btnNew); btnNew.Click += AddMate; downPosPosition = btnNew.Location.Y + btnNew.Size.Height; if (existingMates.ContainsKey(strPlaneName)) { //добавить кнопку для отвязки var btnDeattach = new Button { Size = new Size(20, 20) }; btnDeattach.Location = new Point(62 + btnNew.Size.Width + 10, 24 + i * (btnNew.Size.Height + 6)); btnDeattach.Name = strPlaneName; btnDeattach.Text = "X"; btnDeattach.Tag = existingMates[strPlaneName]; tbpPos.Controls.Add(btnDeattach); btnDeattach.Click += DeleteMate; } i++; } } } swFeat = (Feature)swFeat.GetNextFeature(); } _dictHeightPage.Add(tbpPos, downPosPosition); #endregion if (_lblPrm.Count == 0) { tabMain.SelectTab(tbpPos); downPos = downPosPosition; SetSizeForTab(downPos); if (tabMain.Controls.Contains(tbpParams)) { tabMain.Controls.Remove(tbpParams); //Logging.Log.Instance.Fatal("Вкладка на РПД не показана.Смотреть listForDimensions"); } } if (rbMode1 != null && rbMode2 != null) { if (controlsToHideWhenChangeMode == null || controlsToHideWhenChangeMode.Count == 0) pnlMode.Visible = false; if (Properties.Settings.Default.DefaultRPDView) { rbMode1.CheckedChanged += new EventHandler(ModeCheckedChanged); rbMode1.Checked = true; } else { rbMode2.Checked = true; rbMode1.CheckedChanged += new EventHandler(ModeCheckedChanged); } } SetSizeForTab(_dictHeightPage[tabMain.SelectedTab]); } } }