public AddFeature(ISldWorks _swApp) { swApp = _swApp; Doc = swApp.ActiveDoc; BitmapHandler iBmp = new BitmapHandler(); Assembly thisAssembly; thisAssembly = System.Reflection.Assembly.GetAssembly(this.GetType()); var sbm = iBmp.CreateFileFromResourceBitmap("qwe.ToolbarSmall.bmp", thisAssembly); var lbm = iBmp.CreateFileFromResourceBitmap("qwe.ToolbarLarge.bmp", thisAssembly); Doc.InsertLibraryFeature("Dave's LibFeatPartNameIn"); var tpv = swApp.CreateTaskpaneView2(lbm, "DoesIt"); tpv.AddStandardButton(0, "HERE!"); swApp.ActivateTaskPane(1); //tpv.AddStandardButton(1, "tooltip!"); //var toolbar = swApp.AddToolbar4( //var SelMan = Doc.SelectionManager; //string[] Methods = new string[9]; //int Names = 0; //int Types = 0; //int Values = 0; //int vEditBodies = 0; //long options = 0; //int dimTypes = 0; //int dimValue = 0; //string[] icons = new string[3]; //var ThisFile = "C:/Analytics"; //Methods[0] = ThisFile; //Methods[1] = "FeatureModule"; //Methods[2] = "swmRebuild"; //Methods[3] = ThisFile; //Methods[4] = "FeatureModule"; //Methods[5] = "swmEditDefinition"; //Methods[6] = ""; //Methods[7] = ""; //Methods[8] = ""; //A security routine is optional; //var pathname = ThisFile; //icons[0] = pathname + "/FeatureIcon.bmp"; //icons[1] = pathname + "/FeatureIcon.bmp"; //icons[2] = pathname + "/FeatureIcon.bmp"; //options = (long)swMacroFeatureOptions_e.swMacroFeatureByDefault; //Feature selFeat = SelMan.GetSelectedObject6(1, -1); //IFeatureManager swFeatMgr = Doc.FeatureManager; //swFeatMgr.InsertMacroFeature3("EmptyFeature", "", (object)Methods, (object)Names, (object)Types, (object)Values, (object)dimTypes, (object)dimValue, (object)vEditBodies, (object)icons, (int)options); //var boolstatus = feat.MakeSubFeature(selFeat); }
public bool ConnectToSW(object ThisSW, int cookie) { iSwApp = (ISldWorks)ThisSW; addinID = cookie; //Setup callbacks iSwApp.SetAddinCallbackInfo(0, this, addinID); iSwApp.AddMenuItem4((int)swDocumentTypes_e.swDocPART, addinID, "Export STLs", -1, "ExportPartSTLs", "", "", ""); return true; }
public CustomPropertiesEventsHandler(ISldWorks app, IModelDoc2 model) { m_App = app; m_Model = model; (m_App as SldWorks).CommandCloseNotify += OnCommandCloseNotify; (m_App as SldWorks).OnIdleNotify += OnIdleNotify; if (model is PartDoc) { (model as PartDoc).AddCustomPropertyNotify += OnAddCustomPropertyNotify; (model as PartDoc).DeleteCustomPropertyNotify += OnDeleteCustomPropertyNotify; (model as PartDoc).ChangeCustomPropertyNotify += OnChangeCustomPropertyNotify; } else if (model is AssemblyDoc) { (model as AssemblyDoc).AddCustomPropertyNotify += OnAddCustomPropertyNotify; (model as AssemblyDoc).DeleteCustomPropertyNotify += OnDeleteCustomPropertyNotify; (model as AssemblyDoc).ChangeCustomPropertyNotify += OnChangeCustomPropertyNotify; } else if (model is DrawingDoc) { (model as DrawingDoc).AddCustomPropertyNotify += OnAddCustomPropertyNotify; (model as DrawingDoc).DeleteCustomPropertyNotify += OnDeleteCustomPropertyNotify; (model as DrawingDoc).ChangeCustomPropertyNotify += OnChangeCustomPropertyNotify; } else { throw new NotSupportedException(); } CaptureCurrentProperties(); }
protected override bool OnEditDefinition(ISldWorks app, IModelDoc2 model, IFeature feature) { var featData = feature.GetDefinition() as IMacroFeatureData; featData.AccessSelections(model, (feature as IEntity).GetComponent()); var parameters = GetParameters(feature, featData, model); var addHeight = parameters.AddHeight; var newAddHeight = app.SendMsgToUser2("Add extra height (Yes) or remove extra height (No)?", (int)swMessageBoxIcon_e.swMbQuestion, (int)swMessageBoxBtn_e.swMbYesNo) == (int)swMessageBoxResult_e.swMbHitYes; if (newAddHeight != addHeight) { parameters.AddHeight = newAddHeight; SetParameters(model, feature, featData, parameters); feature.ModifyDefinition(featData, model, (feature as IEntity).GetComponent()); } else { featData.ReleaseSelectionAccess(); } return(true); }
/// <summary> /// Checks if the version of the SOLIDWORKS is newer or equal to the specified parameters /// </summary> /// <param name="app">Current SOLIDWORKS application</param> /// <param name="version">Target minimum supported version of SOLIDWORKS</param> /// <param name="servicePack">Target minimum service pack version or null to ignore</param> /// <param name="servicePackRev">Target minimum revision of service pack version or null to ignore</param> /// <returns>True of version of the SOLIDWORKS is the same or newer</returns> internal static bool IsVersionNewerOrEqual(this ISldWorks app, SwVersion_e version, int?servicePack = null, int?servicePackRev = null) { if (!servicePack.HasValue && servicePackRev.HasValue) { throw new ArgumentException($"{nameof(servicePack)} must be specified when {nameof(servicePackRev)} is specified"); } int curSp; int curSpRev; var curVers = GetVersion(app, out curSp, out curSpRev); if (curVers >= version) { if (servicePack.HasValue && curVers == version) { if (curSp >= servicePack.Value) { if (servicePackRev.HasValue) { return(curSpRev >= servicePackRev.Value); } else { return(true); } } } else { return(true); } } return(false); }
// Constructor for SW2URDF Exporter class public URDFExporter(ISldWorks iSldWorksApp) { constructExporter(iSldWorksApp); iSwApp.GetUserProgressBar(out progressBar); mSavePath = System.Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%"); mPackageName = ActiveSWModel.GetTitle(); }
/// <inheritdoc cref="GetVersion(ISldWorks, out int, out int)"/> public static SwVersion_e GetVersion(this ISldWorks app) { int sp; int spRev; return(app.GetVersion(out sp, out spRev)); }
internal THandler EnsureFeatureRegistered(ISldWorks app, IModelDoc2 model, IFeature feat, out bool isNew) { isNew = false; MacroFeatureDictionary featsDict; if (!m_Register.TryGetValue(model, out featsDict)) { m_Logger.Log($"{model?.GetTitle()} model is not registered in the register"); featsDict = new MacroFeatureDictionary(); m_Register.Add(model, featsDict); var lcm = new MacroFeatureLifecycleManager(model, m_BaseName, m_Logger); lcm.ModelDisposed += OnModelDisposed; lcm.FeatureDeleted += OnFeatureDeleted; m_LifecycleManagers.Add(model, lcm); } THandler handler = null; if (!featsDict.TryGetValue(feat, out handler)) { m_Logger.Log($"{feat?.Name} feature in {model?.GetTitle()} model is not registered in the register"); handler = new THandler(); featsDict.Add(feat, handler); handler.Init(app, model, feat); isNew = true; } return(handler); }
void AddMacroFeature(ISldWorks app) { var moddoc = (IModelDoc2)app.ActiveDoc; var macroFeature = new MultiWireBodies(); macroFeature.Edit(app, moddoc, null); }
protected override IBody2[] CreateGeometry(ISldWorks app, SplitBodyByFacesDataModel parameters) { if (parameters.Bodies != null && parameters.Bodies.Any()) { var modeler = app.IGetModeler(); var resBodies = new List <IBody2>(); foreach (var body in parameters.Bodies) { var faces = (body.GetFaces() as object[]).Cast <IFace2>().ToArray(); foreach (var face in faces) { var sheetBody = modeler.CreateSheetFromFaces(new IFace2[] { face }); resBodies.Add(sheetBody); } } return(resBodies.ToArray()); } else { throw new UserErrorException("No input bodies selected"); } }
public static void SetManipulatorPositionToBodyCenter(ISldWorks sldWorks, TriadManipulatorTs manipulator, IBody2 body, IModelDoc2 model) { var box = body.GetBodyBoxTs(); manipulator.Origin = (MathPoint)((IMathUtility)sldWorks.GetMathUtility()).CreatePoint(box.Center.ToDoubles()); manipulator.UpdatePosition(); }
internal MacroFeatureParametersParser(ISldWorks app) { MathUtils = app.IGetMathUtility(); //TODO: pass logger as parameter m_Logger = new TraceLogger("xCAD.MacroFeature"); }
public DocumentEventHandler(ModelDoc2 modDoc, CAM_Setup_Sheets_Addin addin) { document = modDoc; userAddin = addin; iSwApp = (ISldWorks)userAddin.SwApp; openModelViews = new Hashtable(); }
public void Setup() { if (SW_PRC_ID < 0) { List <string> m_DisabledStartupAddIns; SwApplicationFactory.DisableAllAddInsStartup(out m_DisabledStartupAddIns); m_App = SwApplicationFactory.Create(null, ApplicationState_e.Background | ApplicationState_e.Safe | ApplicationState_e.Silent); if (m_DisabledStartupAddIns?.Any() == true) { SwApplicationFactory.EnableAddInsStartup(m_DisabledStartupAddIns); } m_CloseSw = true; } else if (SW_PRC_ID == 0) { var prc = Process.GetProcessesByName("SLDWORKS").First(); m_App = SwApplicationFactory.FromProcess(prc); } else { var prc = Process.GetProcessById(SW_PRC_ID); m_App = SwApplicationFactory.FromProcess(prc); } m_SwApp = m_App.Sw; m_Disposables = new List <IDisposable>(); }
public bool ConnectToSW(object ThisSW, int cookie) { solidworks = (ISldWorks)ThisSW; addinCookie = cookie; //Setup callbacks solidworks.SetAddinCallbackInfo(0, this, addinCookie); #region Setup the Command Manager _commandManager = solidworks.GetCommandManager(cookie); AddCommandMgr(); #endregion #region Setup the Event Handlers addin = (SolidWorks.Interop.sldworks.SldWorks)solidworks; documentsEventsRepo = new Hashtable(); //this will be called only the first time the addin is loaded //this method will attached events to all documents that open after the addin is loaded. AttachSwEvents(); //Listen for events on all currently open docs //we need to call this method here because sometimes user fires the addin while he has some documents open already //there are events that will attach event handlers to all documents but until those events are fired this call to the method will suffice AttachEventsToAllDocuments(); #endregion #region Setup Sample Property Manager AddPMP(); #endregion return(true); }
public DocumentEventHandler(ModelDoc2 modDoc, SwAddin addin) { document = modDoc; userAddin = addin; iSwApp = userAddin.SwApp; openModelViews = new Hashtable(); }
public DocumentEventHandler(ModelDoc2 modDoc, SwAddin addin) { Document = modDoc; UserAddin = addin; SwApp = UserAddin.SwApp; OpenModelViews = new Hashtable(); }
public DocumentEventHandler(ModelDoc2 modDoc, SwAddin addin) { document = modDoc; userAddin = addin; iSwApp = (ISldWorks)userAddin.SwApp; openModelViews = new Hashtable(); }
//private const string FILE_PATH = @"D:\body.dat"; public static void ExportBodyToFile(string FILE_PATH) { ISldWorks app = PStandAlone.GetSolidWorks(); app.Visible = true; IModelDoc2 swModel; swModel = app.IActiveDoc2; if (swModel != null) { IBody2 body = (Body2)swModel.ISelectionManager.GetSelectedObject6(1, -1); if (body != null) { SaveBodyToFile(body, FILE_PATH); } else { throw new Exception("Please select body to export"); } } else { throw new Exception("Please open the model"); } }
protected PropertyManagerPageBaseControlConstructor(ISldWorks app, swPropertyManagerPageControlType_e type, IconsConverter iconsConv) { m_App = app; m_IconConv = iconsConv; m_Type = type; }
public void Insert(ISldWorks app, IModelDoc2 modelDoc, TData data) { Init(app, modelDoc, null); LoadSelections(); Database = data; Commit(); }
public bool ConnectToSW(object ThisSW, int cookie) { iSwApp = (ISldWorks)ThisSW; addinID = cookie; //Setup callbacks iSwApp.SetAddinCallbackInfo(0, this, addinID); #region Setup the Command Manager iCmdMgr = iSwApp.GetCommandManager(cookie); AddCommandMgr(); #endregion #region Setup the Event Handlers SwEventPtr = (SolidWorks.Interop.sldworks.SldWorks)iSwApp; openDocs = new Hashtable(); AttachEventHandlers(); #endregion #region Setup Sample Property Manager AddPMP(); #endregion return(true); }
//this method crashes SOLIDWORKS - need to research private void UpdateIconsIfRequired(ISldWorks app, IModelDoc2 model, IFeature feat) { var data = (feat as IFeature).GetDefinition() as IMacroFeatureData; data.AccessSelections(model, null); var icons = data.IconFiles as string[]; if (icons != null) { if (icons.Any(i => { string iconPath = ""; if (Path.IsPathRooted(i)) { iconPath = i; } else { iconPath = Path.Combine( Path.GetDirectoryName(this.GetType().Assembly.Location), i); } return(!File.Exists(iconPath)); })) { data.IconFiles = MacroFeatureIconInfo.GetIcons(this.GetType(), app.SupportsHighResIcons()); feat.ModifyDefinition(data, model, null); } } }
public Model(ISldWorks sw, string file, string MID) { iSwApp = sw; ModelID = MID; modelName = file; CreateDXF = false; }
public static void AddMacroFeature(ISldWorks app) { var moddoc = (IModelDoc2)app.ActiveDoc; var macroFeature = new SampleMacroFeature(); macroFeature.Edit(app, moddoc, null); }
protected override MacroFeatureRebuildResult OnRebuild(ISldWorks app, IModelDoc2 model, IFeature feature, RoundStockFeatureParameters parameters) { var cylParams = GetCylinderParams(model, parameters); //temp SetProperties(model, parameters, cylParams); // parameters.Height = cylParams.Height; parameters.Radius = cylParams.Radius; var featData = feature.GetDefinition() as IMacroFeatureData; MacroFeatureOutdateState_e state; SetParameters(model, feature, featData, parameters, out state); if (state != MacroFeatureOutdateState_e.UpToDate) { app.ShowBubbleTooltip("Stock Master", $"'{feature.Name}' feature is outdated. Edit definition of the feature to update", BubbleTooltipPosition_e.TopLeft, Resources.warning_icon); } if (parameters.CreateSolidBody) { var body = m_StockModel.CreateCylindricalStock(cylParams); return(MacroFeatureRebuildResult.FromBody(body, feature.GetDefinition() as IMacroFeatureData)); } else { return(MacroFeatureRebuildResult.FromStatus(true)); } }
public DocView(CAM_Setup_Sheets_Addin addin, IModelView mv, DocumentEventHandler doc) { userAddin = addin; mView = (ModelView)mv; iSwApp = (ISldWorks)userAddin.SwApp; parent = doc; }
public bool DisconnectFromSW() { foreach (var grpId in m_CommandGroupIds) { m_CmdMgr.RemoveCommandGroup(0); } var res = OnDisconnect(); if (Marshal.IsComObject(m_CmdMgr)) { Marshal.ReleaseComObject(m_CmdMgr); } m_CmdMgr = null; if (Marshal.IsComObject(m_App)) { Marshal.ReleaseComObject(m_App); } m_App = null; GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); return(res); }
public RoundStockController(ISldWorks app, RoundStockModel model, IUserSettingsService opts) { m_App = app; m_Model = model; m_UserSetts = opts; }
internal PropertyManagerPageGroupBase(int id, object tag, SwPropertyManagerPageHandler handler, ISldWorks app, PropertyManagerPagePage parentPage, IMetadata[] metadata) : base(id, tag, metadata) { Handler = handler; App = app; ParentPage = parentPage; }
public static Task <bool> RunCommandAsync(this ISldWorks app, swCommands_e cmd) { return(Task.Run(() => { if (app.RunCommand((int)cmd, "")) { var isCmdCompleted = false; var res = false; (app as SldWorks).CommandCloseNotify += (int Command, int reason) => { res = reason == (int)swCommands_e.swCommands_PmOK; isCmdCompleted = true; return 0; }; while (!isCmdCompleted) { Task.Delay(10); } return res; } return false; })); }
protected override bool OnEditDefinition(ISldWorks app, IModelDoc2 model, IFeature feature) { var featData = feature.GetDefinition() as IMacroFeatureData; //rollback feature featData.AccessSelections(model, null); //read current parameters var parameters = GetParameters(feature, featData, model); var res = ShowPage(parameters); if (res) { //set parameters and update feature data SetParameters(model, feature, featData, parameters); feature.ModifyDefinition(featData, model, null); } else { //cancel modifications featData.ReleaseSelectionAccess(); } return(true); }
/// <summary> /// Open a document invisibly. It will not be shown to the user but you will be /// able to interact with it through the API as if it is loaded. /// </summary> /// <param name="sldWorks"></param> /// <param name="toolFile"></param> /// <returns></returns> public static ModelDoc2 OpenInvisibleReadOnly(this ISldWorks sldWorks, string toolFile, bool visible = false, swDocumentTypes_e type = swDocumentTypes_e.swDocPART) { try { if (!visible) { sldWorks.DocumentVisible(false, (int)type); } var spec = (IDocumentSpecification)sldWorks.GetOpenDocSpec(toolFile); if (!visible) { spec.Silent = true; spec.ReadOnly = true; } var doc = SwAddinBase.Active.SwApp.OpenDoc7(spec); doc.Visible = visible; return(doc); } finally { if (!visible) { sldWorks.DocumentVisible (true, (int) type); } } }
/// <summary> /// Tries to load an iges file invisibly. Throws an exception if it doesn't work. /// </summary> /// <param name="sldWorks"></param> /// <param name="igesFile"></param> /// <param name="visible"></param> /// <returns></returns> public static ModelDoc2 LoadIgesInvisible(this ISldWorks sldWorks, string igesFile, bool visible = false) { var swDocPart = (int)swDocumentTypes_e.swDocPART; try { if (!visible) { sldWorks.DocumentVisible(false, swDocPart); } ImportIgesData swImportData = (ImportIgesData)SwAddinBase.Active.SwApp.GetImportFileData(igesFile); int err = 0; var newDoc = SwAddinBase.Active.SwApp.LoadFile4(igesFile, "r", swImportData, ref err); if (err != 0) { throw new Exception(@"Unable to load file {igesFile"); } return(newDoc); } finally { if (!visible) { sldWorks.DocumentVisible (true, swDocPart); } } }
public Vis(ISldWorks _swApp, IModelDoc2 _myModel) { myModel = _myModel; swApp = _swApp; myModel = (ModelDoc2)swApp.ActiveDoc; myPart = (PartDoc)myModel; myMatVisProps = myPart.GetMaterialVisualProperties(); }
public frmCopyProject(SwAddin swAdd,ISldWorks iswApp,ModelDoc2 rootModel,string openFile) { _swAdd = swAdd; _iswApp = iswApp; _swModelDoc = rootModel; _openFile = openFile; InitializeComponent(); WarningLabel.Text = string.Empty; }
public static Loader Initialize(ISldWorks solidWorks, IAssemblyDoc assembly) { if (Instance == null) { Instance = new Loader(solidWorks, assembly); } return Instance; }
public FrmOptions(SwAddin swAdd, ISldWorks iswApp, int cook) { _swAdd = swAdd; _iswApp = iswApp; _cook = cook; InitializeComponent(); Closing += FrmOptionsClosing; FormClosed += FrmOptionsClosed; }
public frmPurchaseExport(ISldWorks _iSwApp) { InitializeComponent(); iSwApp = _iSwApp; this.FormClosing += ((s, a) => { if (worker != null && worker.IsAlive) worker.Abort(); }); }
public UserPMPage(SwAddin addin) { userAddin = addin; if (userAddin != null) { iSwApp = (ISldWorks)userAddin.SwApp; CreatePropertyManagerPage(); } else { System.Windows.Forms.MessageBox.Show("SwAddin not set."); } }
public void createpack(ISldWorks iswapplication) { ModelDoc2 swModel = default(ModelDoc2); ModelDocExtension swModelDocExt = default(ModelDocExtension); PackAndGo swPackAndGo = default(PackAndGo); int namesCount = 0; bool status = false; string myPath = null; object statuses = null; string completefilename; string currentfilename; string completezipfile; // Open assembly document swModel = (ModelDoc2)iswapplication.ActiveDoc; swModelDocExt = (ModelDocExtension)swModel.Extension; completefilename = swModel.GetPathName(); // Get Pack and Go object swPackAndGo = (PackAndGo)swModelDocExt.GetPackAndGo(); // Get number of documents in assembly namesCount = swPackAndGo.GetDocumentNamesCount(); // Get current paths and filenames of the assembly's documents object fileNames; object[] pgFileNames = new object[namesCount - 1]; status = swPackAndGo.GetDocumentNames(out fileNames); pgFileNames = (object[])fileNames; // Set document paths and names for Pack and Go status = swPackAndGo.SetDocumentSaveToNames(pgFileNames); // Override path where to save documents currentfilename = getfilename(completefilename); myPath = Properties.Settings.Default.savepath; completezipfile = myPath + "\\" + currentfilename + ".zip"; status = swPackAndGo.SetSaveToName(true, completezipfile); // Pack and Go both SolidWorks and non-SolidWorks files statuses = swModelDocExt.SavePackAndGo(swPackAndGo); FileSecurity fSecurity = File.GetAccessControl(completezipfile); FileSystemRights fmodify = FileSystemRights.Modify; AccessControlType fallow = AccessControlType.Allow; //IdentityReference fid= IdentityReference fSecurity.AddAccessRule(new FileSystemAccessRule(@"Authenticated Users",fmodify,fallow)); File.SetAccessControl(completezipfile, fSecurity); }
public AssemblyExportForm(ISldWorks iSwApp, LinkNode node) { InitializeComponent(); swApp = iSwApp; BaseNode = node; ActiveSWModel = swApp.ActiveDoc; Exporter = new URDFExporter(iSwApp); AutoUpdatingForm = false; jointBoxes = new Control[] { textBox_joint_name, comboBox_axis, comboBox_joint_type, textBox_axis_x, textBox_axis_y, textBox_axis_z, textBox_joint_x, textBox_joint_y, textBox_joint_z, textBox_joint_pitch, textBox_joint_roll, textBox_joint_yaw, textBox_limit_lower, textBox_limit_upper, textBox_limit_effort, textBox_limit_velocity, textBox_damping, textBox_friction, textBox_calibration_falling, textBox_calibration_rising, textBox_soft_lower, textBox_soft_upper, textBox_k_position, textBox_k_velocity }; linkBoxes = new Control[] { textBox_inertial_origin_x, textBox_inertial_origin_y, textBox_inertial_origin_z, textBox_inertial_origin_roll, textBox_inertial_origin_pitch, textBox_inertial_origin_yaw, textBox_visual_origin_x, textBox_visual_origin_y, textBox_visual_origin_z, textBox_visual_origin_roll, textBox_visual_origin_pitch, textBox_visual_origin_yaw, textBox_collision_origin_x, textBox_collision_origin_y, textBox_collision_origin_z, textBox_collision_origin_roll, textBox_collision_origin_pitch, textBox_collision_origin_yaw, textBox_ixx, textBox_ixy, textBox_ixz, textBox_iyy, textBox_iyz, textBox_izz, textBox_mass, domainUpDown_red, domainUpDown_green, domainUpDown_blue, domainUpDown_alpha, comboBox_materials, textBox_texture }; saveConfigurationAttributeDef = iSwApp.DefineAttribute("URDF Export Configuration"); int Options = 0; saveConfigurationAttributeDef.AddParameter("data", (int)swParamType_e.swParamTypeString, 0, Options); saveConfigurationAttributeDef.AddParameter("name", (int)swParamType_e.swParamTypeString, 0, Options); saveConfigurationAttributeDef.AddParameter("date", (int)swParamType_e.swParamTypeString, 0, Options); saveConfigurationAttributeDef.AddParameter("exporterVersion", (int)swParamType_e.swParamTypeDouble, 1.0, Options); saveConfigurationAttributeDef.Register(); }
public DocView(SwAddin addin, IModelView mv, DocumentEventHandler doc) { userAddin = addin; mView = (ModelView)mv; iSwApp = (ISldWorks)userAddin.SwApp; parent = doc; }
public MouseEventHandler(SwAddin addin, IModelView mv, DocumentEventHandler doc) { userAddin = addin; mView = (ModelView)mv; mMouse = mView.GetMouse(); iSwApp = (ISldWorks)userAddin.SwApp; parent = doc; }
public UserPMPage(SwAddin addin) { userAddin = addin; iSwApp = (ISldWorks)userAddin.SwApp; CreatePropertyManagerPage(); }
public void getSwApp(ISldWorks swAppIn) { swApp = swAppIn; }
public void ExportSketches(ISldWorks swApp) { string projectFolderPath = Path.GetDirectoryName(((ModelDoc2)swApp.ActiveDoc).GetPathName()); OracleConnection connection; using (connection = new OracleConnection(ConnectionString)) { using (OracleCommand cmd = new OracleCommand()) { cmd.Connection = connection; connection.Open(); cmd.CommandText = "GENERAL.SWR_FILEDATA_SKETCHES_PRE_SW"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("P_NUMAGREE", OracleDbType.Varchar2).Value = OrderNumber; cmd.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T'; cmd.ExecuteNonQuery(); } using (OracleCommand cmd = new OracleCommand()) { cmd.Connection = connection; string commandText = @"SELECT SWRFDS.IT, SWRFDS.ITAGREEMENT, SWRFDS.FILEPATH, SWRFDS.FILENAME, SWRFDS.IDSKETCH, SWRFDS.FILENAME_DRW, SWRFDS.FILENAME_DWG, SWRFDS.FILENAME_PDF, SWRFDS.FILENAME_XML, SWRFDS.DWG_SKETCH, SWRFDS.PDF_SKETCH, SWRFDS.XML_SKETCH, SWRFDS.CODEFILETYPE FROM GENERAL.VW_SWR_FILEDATA_SKETCHES SWRFDS WHERE SWRFDS.ITAGREEMENT = SCENTRE.AGR_GETITAGREE(:P_NUMAGREE)"; cmd.CommandText = commandText; cmd.CommandType = CommandType.Text; cmd.Parameters.Add("P_NUMAGREE", OracleDbType.Varchar2).Value = OrderNumber; OracleDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { int it = (int)reader["IT"]; string filePath = reader["FILEPATH"].ToString(); string fileName = reader["FILENAME"].ToString(); string fileName_DRW = reader["FILENAME_DRW"].ToString(); string fileName_DWG = reader["FILENAME_DWG"].ToString(); string fileNamePDF = reader["FILENAME_PDF"].ToString(); string fileName_XML = reader["FILENAME_XML"].ToString(); if (File.Exists(filePath + fileName_DRW)) { //открываем файл в солиде int errors = 0; int warnings = 0; ModelDoc2 drwModel = swApp.OpenDoc6(filePath + fileName_DRW, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_Silent, string.Empty, errors, warnings); //сохраняем в dwg object exportData = null; string dwgFilePath = filePath + fileName_DWG; drwModel.Extension.SaveAs(dwgFilePath, 0, 0, exportData, errors, warnings); //сохраняем в pdf /*/ exportData = swApp.GetExportFileData(1); string pdfFilePath = projectFolderPath + @"\\ЧЕРТЕЖИ_PDF\\" + fileNamePDF; if (!Directory.Exists(projectFolderPath + @"\\ЧЕРТЕЖИ_PDF\\")) Directory.CreateDirectory(projectFolderPath + @"\\ЧЕРТЕЖИ_PDF\\"); drwModel.Extension.SaveAs(pdfFilePath, 0, 0, exportData, errors, warnings); /*/ //закрываем файл в солиде swApp.QuitDoc(drwModel.GetTitle()); //архивируем dwg и pdf string dwgZipFilePath = fileToZip(dwgFilePath); //string pdfZipFilePath = fileToZip(pdfFilePath); //отправляем dwg.zip в базу byte[] dwgZipFile = File.ReadAllBytes(dwgZipFilePath); using (OracleCommand cmdSendDwg = new OracleCommand()) { cmdSendDwg.Connection = connection; cmdSendDwg.CommandText = "GENERAL.SWR_FILEDATA_SKTDWG_UPD"; cmdSendDwg.CommandType = CommandType.StoredProcedure; cmdSendDwg.Parameters.Add("P_IT", OracleDbType.Int32).Value = it; cmdSendDwg.Parameters.Add("P_FILENAME_DWG", OracleDbType.Varchar2).Value = Path.GetFileName(dwgZipFilePath); cmdSendDwg.Parameters.Add("P_DWG_SKETCH", OracleDbType.Blob).Value = dwgZipFile; cmdSendDwg.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T'; cmdSendDwg.ExecuteNonQuery(); } //отправляем pdf.zip в базу /*/ byte[] pdfZipFile = File.ReadAllBytes(pdfZipFilePath); using (OracleCommand cmdSendPdf = new OracleCommand()) { cmdSendPdf.Connection = connection; cmdSendPdf.CommandText = "GENERAL.SWR_FILEDATA_SKTPDF_UPD"; cmdSendPdf.CommandType = CommandType.StoredProcedure; cmdSendPdf.Parameters.Add("P_IT", OracleDbType.Int32).Value = it; cmdSendPdf.Parameters.Add("P_FILENAME_PDF", OracleDbType.Varchar2).Value = Path.GetFileName(pdfZipFilePath); cmdSendPdf.Parameters.Add("P_PDF_SKETCH", OracleDbType.Blob).Value = pdfZipFile; cmdSendPdf.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T'; cmdSendPdf.ExecuteNonQuery(); } /*/ //отправляем xml в базу string xmlFilePath = projectFolderPath + @"\Программы\" + fileName_XML; if (File.Exists(xmlFilePath)) { byte[] xmlFile = File.ReadAllBytes(xmlFilePath); using (OracleCommand cmdSendXml = new OracleCommand()) { cmdSendXml.Connection = connection; cmdSendXml.CommandText = "GENERAL.SWR_FILEDATA_SKTXML_UPD"; cmdSendXml.CommandType = CommandType.StoredProcedure; cmdSendXml.Parameters.Add("P_IT", OracleDbType.Int32).Value = it; cmdSendXml.Parameters.Add("P_FILENAME_XML", OracleDbType.Varchar2).Value = Path.GetFileName(xmlFilePath); cmdSendXml.Parameters.Add("P_XML_SKETCH", OracleDbType.Blob).Value = xmlFile; cmdSendXml.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T'; cmdSendXml.ExecuteNonQuery(); } } //удаляем архив dwg.zip и сами файлы dwg File.Delete(dwgFilePath); File.Delete(dwgZipFilePath); //удаляем архив pdf.zip //File.Delete(pdfZipFilePath); } else throw new FileNotFoundException("Не найден файл чертежа " + filePath + fileName_DRW); } //удаляем папку ЧЕРТЕЖИ_PDF //Directory.Delete(projectFolderPath + @"\\ЧЕРТЕЖИ_PDF\\"); } } }
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(); }
public string CreateBlock(ISldWorks swApp, int type, out MathPoint instancePosition, double x = 0, double y = 0 ) { var objPoint1 = new double[3]; objPoint1[0] = 0; objPoint1[1] = 0; objPoint1[2] = 0; var swMathUtil1 = swApp.IGetMathUtility(); instancePosition = (MathPoint)swMathUtil1.CreatePoint(objPoint1); int i = 0; switch (type) { case 0: i = 4; break; case 1: i = 6; break; case 2: i = 2; break; case 3: i = 3; break; case 4: i = 6; break; } double blScale = 0.05; var swModel = (ModelDoc2)swApp.ActiveDoc; var swSkSeg = new ISketchSegment[i]; swModel.SetAddToDB(true); switch (type) { case 0: // 5 through swSkSeg[0] = (SketchSegment)swModel.CreateLine2(-0.04, 0.0, 0.0, 0.0, 0.04, 0.0); swSkSeg[1] = (SketchSegment)swModel.CreateLine2(0.0, 0.04, 0.0, 0.04, 0.0, 0.0); swSkSeg[2] = (SketchSegment)swModel.CreateLine2(0.04, 0.0, 0.0, 0.0, -0.04, 0.0); swSkSeg[3] = (SketchSegment)swModel.CreateLine2(0.0, -0.04, 0.0, -0.04, 0.0, 0.0); break; case 1: // 5 H 12 swSkSeg[0] = (SketchSegment)swModel.CreateCircle2(0.0, 0.0, 0.0, 0.003, 0.0, 0.0); swSkSeg[2] = (SketchSegment)swModel.CreateCircle2(0.0, 0.0, 0.0, 0.0045, 0.0, 0.0); swSkSeg[3] = (SketchSegment)swModel.CreateCircle2(0.0, 0.0, 0.0, 0.006, 0.0, 0.0); swSkSeg[4] = (SketchSegment)swModel.CreateCircle2(0.0, 0.0, 0.0, 0.0075, 0.0, 0.0); swSkSeg[5] = (SketchSegment)swModel.CreateCircle2(0.0, 0.0, 0.0, 0.009, 0.0, 0.0); blScale = 0.075; break; case 2: // 8 swSkSeg[0] = (SketchSegment)swModel.CreateLine2(-0.04, -0.04, 0.0, 0.04, 0.04, 0.0); swSkSeg[1] = (SketchSegment)swModel.CreateLine2(-0.04, 0.04, 0.0, 0.04, -0.04, 0.0); blScale = 0.06; break; case 3: //8 through swSkSeg[0] = (SketchSegment)swModel.CreateLine2(-0.04, -0.0293, 0.0, 0.0, 0.04, 0.0); swSkSeg[1] = (SketchSegment)swModel.CreateLine2(0.0, 0.04, 0.0, 0.04, -0.0293, 0.0); swSkSeg[2] = (SketchSegment)swModel.CreateLine2(0.04, -0.0293, 0.0, -0.04, -0.0293, 0.0); break; case 4: //811 swSkSeg[0] = (SketchSegment)swModel.CreateLine2(-0.04, -0.04, 0.0, -0.04, 0.04, 0.0); swSkSeg[1] = (SketchSegment)swModel.CreateLine2(-0.04, 0.04, 0.0, 0.04, 0.04, 0.0); swSkSeg[2] = (SketchSegment)swModel.CreateLine2(0.04, 0.04, 0.0, 0.04, -0.04, 0.0); swSkSeg[3] = (SketchSegment)swModel.CreateLine2(0.04, -0.04, 0.0, -0.04, -0.04, 0.0); swSkSeg[4] = (SketchSegment)swModel.CreateLine2(-0.04, -0.04, 0.0, 0.04, 0.04, 0.0); swSkSeg[5] = (SketchSegment)swModel.CreateLine2(-0.04, 0.04, 0.0, 0.04, -0.04, 0.0); blScale = 0.03; break; } object vSkSeg = swSkSeg; swModel.Extension.MultiSelect(vSkSeg, true, null); SketchBlockDefinition swSketchBlockDef = swModel.SketchManager.MakeSketchBlockFromSelected(null); var swInst = swSketchBlockDef.IGetInstances(1); swInst.Scale = blScale; if (x != 0 && y != 0) { var objPoint = new double[3]; objPoint[0] = x+0.01; objPoint[1] = y; objPoint[2] = 0; var swMathUtil = swApp.IGetMathUtility(); var swMathPoint = (MathPoint)swMathUtil.CreatePoint(objPoint); swInst.InstancePosition = swMathPoint; instancePosition = swMathPoint; } swModel.SetAddToDB(false); swModel.GraphicsRedraw2(); swModel.ClearSelection(); return swInst.Name; }
/// <summary> /// Определяет наличие состава заказа в БД /// </summary> public bool IsOrderEmpty(ISldWorks swApp) { string orderPath = (((ModelDoc2)swApp.ActiveDoc)).GetPathName(); string orderNum = Path.GetFileName(Path.GetDirectoryName(orderPath)); OracleConnection connection; using (connection = new OracleConnection(ConnectionString)) { using (OracleCommand cmd = new OracleCommand()) { cmd.Connection = connection; connection.Open(); cmd.CommandText = "SELECT GENERAL.SWR_ISEMPTYAGREE(:P_NUMAGREE) ISEMP FROM DUAL"; cmd.CommandType = CommandType.Text; cmd.BindByName = true; cmd.Parameters.Add("P_NUMAGREE", OracleDbType.Varchar2).Value = orderNum; OracleDataReader reader = cmd.ExecuteReader(); if (reader.Read()) { var result = reader["ISEMP"]; if (result.ToString() == "0") return false; else return true; } else throw new Exception("Ошибка соединения с БД."); } } }
public DimensionView(ISldWorks swApp, BlockPosition side, bool dimOnlyNew) { _swApp = swApp; _swModel = swApp.IActiveDoc2; _side = side; _dimOnlyNew = dimOnlyNew; ListSize = new List<CoordAndDepth>(); }
public FoundCoordinate(ISldWorks swApp, Entity ent, Ordinate vertex, double[] dimLineH, double[] dimLineV, BlockPosition side,View swView,bool doThroughHoles) { _swApp = swApp; _swModel = swApp.IActiveDoc2; _side = side; _ent = ent; _vertex = vertex; _doThroughHoles = doThroughHoles; _swSelData = _swModel.ISelectionManager.CreateSelectData(); _swView = swView; _coordinate = FindCoord(dimLineH, dimLineV); }
public DimensionDraft(SwAddin swAddin) { _swAdd = swAddin; _swApp = swAddin.SwApp; }
public SolidWorksMacro(ISldWorks solidWorks, IDictionary<Property, string> configuration) { this.solidWorks = solidWorks; this.configuration = configuration; }
private void constructExporter(ISldWorks iSldWorksApp) { iSwApp = iSldWorksApp; ActiveSWModel = (ModelDoc2)iSwApp.ActiveDoc; swMath = iSwApp.GetMathUtility(); }
/// <summary> /// Экспорт свойств компонентов в базу данных /// </summary> public void AttributesExport(ISldWorks swApp) { try { Connection = new OracleConnection(ConnectionString); Connection.Open(); string orderPath = (((ModelDoc2)swApp.ActiveDoc)).GetPathName(); string orderNum = Path.GetFileName(Path.GetDirectoryName(orderPath)); //очистка данных по заказу using (OracleCommand cmd = new OracleCommand()) { cmd.Connection = Connection; cmd.CommandText = "GENERAL.SWR_FILEDATA_CLEAR_SW"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("P_NUMAGREE", OracleDbType.Varchar2).Value = orderNum; cmd.Parameters.Add("P_COMMIT", OracleDbType.Char).Value = 'T'; cmd.ExecuteNonQuery(); } //Коллекция уникальных сочетаний компонент-свойство //Dictionary<KeyValuePair<string, string>, string> componentsAttributesDictionary = new Dictionary<KeyValuePair<string, string>, string>(); Collection<AttributeInfo> componentsAttributesCollection = new Collection<AttributeInfo>(); Action<ModelDoc2> action = new Action<ModelDoc2>((model) => { string path = model.GetPathName(); DocumentSpecification swDocSpecification = (DocumentSpecification)swApp.GetOpenDocSpec(path); int fileType = swDocSpecification.DocumentType; string filePath = path.Substring(0, path.LastIndexOf(@"\") + 1); string fileName = Path.GetFileName(Path.GetFileName(path)); string configuration = string.Empty; sendAttributes(model, componentsAttributesCollection, path, orderNum, fileType, filePath, fileName, configuration); configuration = model.IGetActiveConfiguration().Name; sendAttributes(model, componentsAttributesCollection, path, orderNum, fileType, filePath, fileName, configuration); }); SolidWorksInterop.DoSmthForEachComponent((AssemblyDoc)swApp.ActiveDoc, action); } finally { Connection.Close(); } }
public InsertDimension(ISldWorks swApp, Entity entity, Ordinate vertex, SelectData swSelData) { _swModel = swApp.IActiveDoc2; _ent = entity; _vertex = vertex; _swSelData = swSelData; }
public bool DisconnectFromSW() { System.Runtime.InteropServices.Marshal.ReleaseComObject(iSwApp); iSwApp = null; //The addin _must_ call GC.Collect() here in order to retrieve all managed code pointers GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); GC.WaitForPendingFinalizers(); return true; }
public PMPHandler(SwAddin addin) { userAddin = addin; iSwApp = (ISldWorks)userAddin.SwApp; }