Quantcast
Channel: Dotnet/C# – Xinyustudio
Viewing all 204 articles
Browse latest View live

Using Matlab functions in C# (2009 a)

$
0
0

1. Create a m-file function which encapsulate your subroutine, and save it to a folder:

WriteMFunction.png

2. Add this folder to Matlab path: in Matlab, File > SetPath

3. In MATLAB command window, type “deploytool”

4. In MATLAB window, click the File new icon to create a New Deployment Project.

  • In the New Deployment Project dialog box, select MATLAB Builder NE and .NET Component.
  • In the name textbox, type whatever meaningful titles, and then click OK.

5. Select “Generate Verbose Output” and Add the source *.m file to the project, and then save the project.

6. Build the component by clicking the “Build “button in the Deployment Tool toolbar. The build process begins, and a log of the build appears in the Output pane of the Deployment Tool. The files that are needed for the component are copied to two newly created subdirectories, src and distrib. A copy of the build log is placed in the src directory. The building process may take quite a few seconds…, have a cup of coffee now…

Now the output folders and files may like this:

7. Now, almost done! Let us try and test it in VisualStudio.net, write source code for a C# application that accesses the component, for instance:

NDimVoronoiDiagram vg=new NDimVoronoiDiagram ( );

MWArray [] Results=new MWArray[2];
Results = (MWArray [])vg.CalVoronoiDiagram(2, (MWNumericArray)X, (MWNumericArray)Y);

double [,] VoronoiVertices =(double [,]) Results[0].ToArray();
object[,] VoronoiEdgeIndice = (object[,])Results[1].ToArray();
8. Add two references, \toolbox\dotnetbuilder\bin\win64\v2.0\MWArray.dll and the generated dll, in our case, NDimVoronoiDiagram.dll, build the solution, and that is it.

Note that a ” Runtime Error R6034, An application has made an attempt to load ” occurs one when initializing the NDimVoronoiDiagram object, and I am running Matlab on Vista x64, and I cannot figure out the reason, and if any one has solutions, please let me know.

*****************************************

Extra note I: I put the matlab project inside my VS project folder, and compile it, it results in the failure of reflecting the output dll using ObjectBrowser in VS, and this directly leads to unknown namespace which contains the Matlab class.Very weird.

Extra note II: The namespace, class name and the method name follows the rules as dipicted in the figure below.

Note1.png


Posted in Dotnet/C#, Maths

Create Splines using SolidWorks

$
0
0

SolidWorks generally has two sets of spline functions:

  1. The spline curve passes through the given points, i.e. spline fitting, (the curve S1 in the below figure)
  2. The given points are the control points of the spline curve, i.e. spline interpolation (the curve S2 in the below figure)

Accordingly, there are two functions which does the jobs:

  1. IModelDoc2.CreateSpline
  2. SketchManager.CreateSplinesByEqnParams

The below data are used in the experiments:

int nOrder = 4;
int nPoints = 5;
double[] Pt = new double[3 * nPoints];
Pt[0] = -0.1; Pt[1] = -0.1; Pt[2] = 0;
Pt[3] = 0.1; Pt[4] = -0.1; Pt[5] = 0;
Pt[6] = 0.1; Pt[7] = 0.1; Pt[8] = 0;
Pt[9] = -0.1; Pt[10] = 0.1; Pt[11] = 0;
Pt[12] = -0.15; Pt[13] = 0; Pt[14] = 0;

For the 1st spline fitting problem, another point which is coincident to the 1st point should be appended, to indicate that this curve is closed:

double[] Pt2 = new double[Pt.Length + 3];
Pt.CopyTo(Pt2, 0);
Pt2[Pt.Length] = -0.1;
Pt2[Pt.Length + 1] = -0.1;
Pt2[Pt.Length + 2] = 0;

modDoc.CreateSpline(Pt2);

For the 2nd interpolation problem, the function call is a bit of cumbersome and the help manual is also less clear. After experimenting for a few times, here comes the solution.

  • Prepare a kont vector, it could be uniform ones or whatever valid vector
double[] pKnotsArray = new double[nOrder + nPoints];
for (int i = 0; i < pKnotsArray.Length; i++)
pKnotsArray[i]=i;
  • According to the manual, prepare a property array, note that althought the parameters are integers, however
    you must use a double array to hold the data, and later, this double array will be merged into one bigger double array:
#region Property Array
double[] PropertyArray = new double[4];
PropertyArray[0] = 3; //Dimension, 2 is not OK!
PropertyArray[1] = nOrder; //Order
PropertyArray[2] = nPoints; //Number of control Points
PropertyArray[3] = 1; //Periodicity=true
#endregion
  • Merge all the double array into a single double []:

int n1 = PropertyArray.Length;
int n2 = pKnotsArray.Length;
int n3 = Pt.Length;

double [] Parameters=new double[n1+n2+n3];
PropertyArray.CopyTo(Parameters,0);
pKnotsArray.CopyTo(Parameters, n1);
Pt.CopyTo(Parameters, n1+n2);

modDoc.SketchManager.CreateSplinesByEqnParams(Parameters);

There are several notes to be mentioned:

  • Even though the sketch is on a 2D plane, experiments show that the Z coordinates cannot be omitted;
  • Even the spline curve is closed, it is no need to add another point (coincident with the 1st control point) to the control point list!
    Otherwise, a sharp corner will result, as shown in the figure below.
  • I have also tried to use below codes, however in vein.
    List<double []> Parameters=new List<double []>;
    Parameter.Add(PropertyArray);
    Parameter.Add(pKnotArray);
    Parameter.Add(Pt);
    modDoc.SketchManager.CreateSplinesByEqnParams(Parameters.ToArray());
  • The other function with the same name but different signature does not work in C# COM based programming, 
    since there is still no way to marshal an "int []" to a "ref int".
    virtual SketchSegment ICreateSplineByEqnParams(ref int PropArray,
    ref double KnotsArray,ref double CntrlPntCoordArray );
  • By adding another array W into the control point coordiate, the function CreateSplinesByEqnParams
    can actually be used to model NURBS curve.

Spline2.png Spline3.png


Posted in CAD, Dotnet/C#

SolidWorks API: Loading/getting Simulation (CosmosWorks) object, failure?

$
0
0

As the SolidWorks 2009 Simulation API help states, the typical use of Cosmos Works begins by creating an instance of the ICosmosWorks class:

private object iCosWorks = null;
iCosWorks = (ICosmosWorks) SwApp.GetAddInObject(“CosmosWorks.CosmosWorks”);

However if you try the code above, you will find that the iCosWorks object is always null .

Where does the string (“CosmosWorks.CosmosWorks”) come from, and how is it named? It is not very clear in the documentation: The help manual tells us that the signature of this function is:

virtual object GetAddInObject(
   string clsid          
)
"This method also accepts the ProgID, both version independent and version dependent, for clsid."
So I wonder, the ProgID has updated in the new 2009 API, while the documentation falls behind and remain intact. What lazy engineers! It costs me much time...

So I tried to get the string by myself. In SolidWorks 2009, the Simulation DLL is ‘cosworks.dll’,

  • Search the registry with this dll as the keyword
  • The ProgID as well as VerionIndependentProgID can be found.

Now, retry the following code:

iCosWorks = (ICosmosWorks) SwApp.GetAddInObject(“SldWorks.Simulation.2“); or
iCosWorks = (ICosmosWorks) SwApp.GetAddInObject(“SldWorks.Simulation“);
Debug.Assert(iCosWorks != null);

It works now!


Posted in CAD, Dotnet/C# Tagged: 2009, CosmosWorks, error, failure, GetAddInObject, how to, null, SolidWorks Simulation

Using C# to program CosmosWorks (Simulation)

$
0
0

Thanks go to Mahir Abrahim at General Atomics for his VB code, and I have converted it to equivalent C# code, with some additions of code from Simulation Manual.

private CwAddincallback pCWAddin = null;
private CosmosWorks pCWApp = null;
private CWModelDoc pCWDoc = null;
private CWStudyManager pStudyManager = null;
private CWStudy pStudy=null;
private CWMesh pMesh = null;

pCWAddin = (CwAddincallback)SwApp.GetAddInObject(“SldWorks.Simulation”);
Debug.Assert(pCWAddin != null);

pCWApp = pCWAddin.CosmosWorks;
pCWDoc = pCWApp.ActiveDoc;
pStudyManager = pCWDoc.StudyManager;
int nStudies = pStudyManager.StudyCount;
int errCode;
if(nStudies<1)
{
const int cwStaticAnalysis = 0; //const int cwSolidElementMesh = 0;
pStudy = pStudyManager.CreateNewStudy2(“Static_solid”, cwStaticAnalysis, out errCode);
}

pStudyManager.ActiveStudy = 0;
pStudy = pStudyManager.GetStudy(0);
CWSolidManager pSolidMgr = pStudy.SolidManager;
CWSolidComponent pSolidComponent=pSolidMgr.GetComponentAt(0, out errCode);
CWSolidBody pSolidBody = pSolidComponent.GetSolidBodyAt(0, out errCode);
pMesh = pStudy.Mesh;
const int cwMeshState_SUCCEEDED=1;

int rtn = -100;
if (pMesh.MeshState != cwMeshState_SUCCEEDED)
{
pMesh.Quality = 1;
double el, tl;
pMesh.GetDefaultElementSizeAndTolerance(0, out el, out tl);
rtn=pStudy.CreateMesh(0, el,tl);

string info=string.Format(“{0} elements created”, pMesh.ElementCount.ToString());
MessageBox.Show(info);
}


Posted in CAD, Dotnet/C#

Bind class object instances using PropertyGrid

$
0
0

1. Design a class with public field

2. Add attributes to the class and class members

3. Add a PropertyGrid control to a form, and set the “SelectedObject” Property to an instance of an object, that is it. A nice thing is that it is automatically data bound to the object instance if you edit the value through the grid.

4. Some commonly used attributes:

  • Category
  • DisplayName
  • Description
  • DefaultValue
  • PasswordPropertyText
  • Browsable
  • ReadOnly
  • DefaultProperty

More details, refer to MSDN here.

5. In case some class members are other class instances embedded, for instance

class ParentClass
{
public SomeChildClass AnotherChild
{get; set;}
}

Now if you want to display the detailed info of SomeChildClass in the grid as well, add the following attributes:

[TypeConverter(typeof(ExpandableObjectConverter))]
class ParentClass
{
public SomeChildClass AnotherChild
{get; set;}
}


Posted in Dotnet/C#

DriveBar control for C#

$
0
0

List All the drives on your machine using C# DriveBar control:

DriveBar_R1.png

DriveBar_R2.png

1. Drag a DriveBar control to the form, and it appeas like below:

2. Set the images for these drives:

DriveBar_B.png

3. Now the drive bar looks-just cool!

DriveBar_C.png

4. To add event handler for these toolbar items:

driveBar1.DriveBarItemClick +=new DriveBar.DriveButtonClickEvent(OnDriveBtnClick);

DriveBar_C2.png

Click the “C:” button, Wow, it starts the explorer and browse there!

DriveBar_D.png

p/s: when the USB devices is plugged or unplugged, a nice thing is that the control automatically updates!


Posted in Dotnet/C#

VisualStudio 2010 Resources

Using Matlab functions in C# (2009b)

$
0
0

Matlab has changed a bit of the command “deploytool” in 2009a and 2009b. To see how to use matlab functions in 2009a, see my previous post here.

In 2009b, this has changed a bit and this post will show you how to accomplish the same task in Matlab 2009b.

  1. Start Matlab and key in “DeployTools”, Select “.NET assembly”, and the project location and name

     M2009b_A

  2. After clicking the OK button…

    M2009b_B 
    M2009b_C

  3. In the “Build” Tab, Add a class which corresponds to the .Net Class Name, and matlab .m files, each .m file (i.e. a matlab function) corresponds to a method of the .Net Class.

     M2009b_D

  4. click the Build button.

    M2009b_E M2009b_F
    Particular note that your project folder structure should be supposedly SIMPLE, and better avoid spaces or less frequently used chars, otherwize, it is very likely to fail in the build process.

  5. Now start a C# Winform project, add a reference to the output built by Matlab

    M2009b_G 
    In the object brower, you can see that the class “VoronoiCell” appears, and it has two important functions, as expected, with different overloadded prototypes!

    M2009b_H M2009b_I
    What a cool feature!

  6. Now, add another assembly called “Mwarray.dll”, located in \toolbox\dotnetbuilder\bin\win64\v2.0 folder.
  7. Create a C# project, and test with some code, for instance:
       1: MyVoronoiCell vgc= new MyVoronoiCell();

       2: double[] X = { 0.5, 0, -0.5, -0.2, -0.1, 0.1, 0.1 };

       3: double[] Y = { 0, 0.5, -0.5, -0.1, 0.1, -0.1, 0.1 };   

       4: MWArray[] Results = (MWArray[])vgc.GetVoronoiEdge  

       5:                     (2,    

       6:                     MWNumericArray)X,    

       7:                     MWNumericArray)Y);   

       8: double[,] EdgeX = (double[,])Results[0].ToArray();   

       9: double[,] EdgeY = (double[,])Results[1].ToArray();

  8. Now, problem comes. If you run the program, exception will be thrown at Line 1, and there are a few possible cases
    1. {"Could not load file or assembly ‘MWArray, Version=2.9.1.0, Culture=neutral, PublicKeyToken=e1d84a0da19db86f’ or one of its dependencies. An attempt was made to load a program with an incorrect format."}

      This is mostly due to the absense of MWArray.DLL in GAC, and the simplest solution is to add it to GAC by typing

      gacutil /i MWarray.dll

    2. {"The type initializer for ‘MathWorks.MATLAB.NET.Utility.MWMCR’ threw an exception."}, {"Trouble initializing libraries required by Builder NE.\n"}, "   at MathWorks.MATLAB.NET.Utility.MWMCR..cctor()", or {"Trouble initializing libraries required by Builder NE.\n"}  or

      {Unable to load DLL ‘mclmcrrtXXX.dll’} or

      MathWorks.MATLAB.NET.Utility.MWMCR.mclmcrInitialize(); at MathWorks.MATLAB.NET.Utility.MWMCR..cctor()

      For these kind of applications in x86 platform, the solution is to run MCRInstaller.exe to install the Matlab Compiler Runtime, it should work once MCR is installed. Restart OS after MCRInstaller.exe is installed!!! Restart VisualStudio, Matlab!!!

Now rebuild the project, all is fine.


Posted in Dotnet/C#, Maths

P/Invoke “DllNotFoundException” Exception

$
0
0

When calling C functions with InterOp Invoke, although the C DLL is already in the same folder as the target assembly, however, it is common to see the “DllNotFoundException” Exception. One of the most possible reason is that the C DLL depends on other legacy DLLs, and such dependents are not in the same directory as the assembly. For instance, for the below Motor.DLL, it depends on four DLLs:

PInvokeDLL_A

Copy all the depended DLLs to the assembly output folder, and rebuild, all will be fine.


Posted in Dotnet/C#

SerialPort (Com1,2…) Communication in C#

$
0
0

Traditional programming Com1 and Com2 is generally tedious. With DotNet, this becomes trivial. In the toolbox, component tab, drag a SerialPort object onto the form:

SerialPort

   1: static SerialPort ComPort = new SerialPort();

   2: //configuring the serial port

   3: ComPort.PortName = "COM" + iPort.ToString();

   4: ComPort.BaudRate = 9600;

   5: ComPort.DataBits = 8;

   6: ComPort.Parity = Parity.None;

   7: ComPort.StopBits = StopBits.One;

   8:  

   9: //opening the serial port

  10: try

  11: {

  12:     ComPort.Open();

  13:     if (ComPort.IsOpen)     return true;

  14:     else                    return false;

  15: }

  16: catch (System.Exception ex)

  17: {

  18: }

To send the command to the port, use Write(byte [] ,… ) function

   1: static public void StopItNow()

   2: {

   3:             byte [] info=new byte[5];

   4:             info[0] = 64; //@

   5:             info[1] = 48; //0

   6:             info[2] = 255; // '\xff';

   7:             info[3] = 0x0D; //CR;

   8:             info[4] = 0x0A; // LF;

   9:             if (ComPort.IsOpen)

  10:                 ComPort.Write(info,0,5);

  11: }

Or use the Write(string str) method

   1: static public void SetCurPosAsZero(int axis)

   2: {

   3:             Buff = string.Empty;

   4:             SelectAxis(axis);

   5:             Buff += "@0n";

   6:             Buff += axis.ToString() + CR + LF;

   7:             if(ComPort.IsOpen) ComPort.Write(Buff);

   8: }


Posted in CAD, Dotnet/C#

SolidWorks SN Editor

$
0
0

In case you have multiple SolidWorks serial number, say, some belong to the Educational License, and others are commercial keys. Or when you have multiple versions of SolidWorks installed sinutaneously, you can you this program to quickly set the active serial number to make it take effect.

SolidWorks_SN_Editor_A

SolidWorks_SN_Editor 

If you would like to have a copy, leave your request comments below.


Posted in CAD, Dotnet/C#

LING operation (union, intersect, except) and IEquatable

$
0
0

Consider you want to use the union, intersect or except methods using the LINQ feature:

   1: public static VoronoiCell operator +(VoronoiCell A, VoronoiCell B)

   2: {

   3:    VoronoiCell CombinedCell=new VoronoiCell();

   4:    var MuturalPts = A.BoundingPolygonVertices.Intersect(B.BoundingPolygonVertices);

   5:    if(MuturalPts==null) return null;

   6:    var UniqueA = A.BoundingPolygonVertices.Except(MuturalPts);

   7:    var UniqueB = B.BoundingPolygonVertices.Except(MuturalPts);

   8:    CombinedCell.BoundingPolygonVertices = UniqueA.Union(UniqueB).ToList();

   9:    return CombinedCell;

  10: }

In order to make sure the above code works, you should indicate or define in what terms can two objects (in this case, the element of BoundingPolygonVertices, i.e. a Pt2D object). To do so, the Pt2D class should derive from IEquatable:

   1: public class Pt2D : IEquatable<Pt2D>

   2:    {

   3:        public double X

   4:        { get; set;}

   5:        public double Y

   6:        { get; set;}

   7:  

   8:        public Pt2D(double a, double b)

   9:        {

  10:            X = a;

  11:            Y = b;

  12:        }

  13:  

  14:        public override bool Equals(System.Object obj)

  15:        {

  16:            if (ReferenceEquals(null, obj)) return false;

  17:            if (ReferenceEquals(this, obj)) return true;

  18:            if (obj.GetType() != typeof (Pt2D)) return false;

  19:            return Equals((Pt2D) obj);

  20:        }

  21:  

  22:        public bool Equals(Pt2D p)

  23:        {

  24:            if (ReferenceEquals(null, p)) return false;

  25:            if (ReferenceEquals(this, p)) return true;

  26:            return p.X.Equals(X) && p.Y.Equals(Y);

  27:        }

  28:  

  29:        public override int GetHashCode()

  30:        {

  31:            unchecked

  32:            {

  33:                return (X.GetHashCode()*397) ^ Y.GetHashCode();

  34:            }

  35:        }

  36:    }

Done.


Posted in Dotnet/C#

Kill a process inside VisualStudio.net

$
0
0

In developing some addin projects, the output assembly is hosed by another process, and sometimes, after code editing, you wish to recomplile the code and run it again. Unfortunately, you are not always lucky enough.

You may see such errors like below shown:

Error    64    Unable to copy file "xxxAddin.dll" to "xxxAddin.dll". The process cannot access the file ‘xxxAddin.dll’ because it is being used by another process.  

You can then turn to Task Manager, find the process, and then kill it, and then recompile in Visual Studio.

An easy way is to automate this is to use “External Tools” in Visual Studio:

KillProcess_A

The one labelled with A are the build-in external tools facilitated with VS. and the one with B is developed by ourselves. We can also put this custom tools inside a toolbar.

In VS, Tools>Customize, drag the external tools “N” to an existing toolbar.

KillProcess_B 

KillProcess_C

You can customize the icon image as well by right clicking the toolbar item.

KillProcess_D

Now, let us finally program a console application:

KillProcess_E

Enjoy!


Posted in Dotnet/C#

Protected: Step-bystep C# Rhinocerous Tutorial

$
0
0

This post is password protected. You must visit the website and enter the password to continue reading.


Posted in CAD, Dotnet/C#

Developing AutoCAD addin/plugin using C#

$
0
0
  • In Visual Studio .NET, create a class library solution and project.

NewProject 

  • Add Reference from the Project menu or Solution Explorer, browse to the \inc or \incx64 directory of the ObjectARX SDK and select acdbmgd.dll and acmgd.dll.
  • Create a new class or rename the auto-created class

RenameClass 

  • In the main class file, add the namespaces you will use.

    using Autodesk.AutoCAD.ApplicationServices;
    using Autodesk.AutoCAD.DatabaseServices;
    using Autodesk.AutoCAD.Runtime;

  • Add a C# function

HelloWorld

Note the attributes are important and must be used, otherwise the command will not be fired.

  • In AutoCAD command prompt, type “netload”, then browse to the C# Library assembly, and click OK.
  • In AutoCAD command prompt, type the function name, in our case, it is  “CreateIt”

RunIt

 

Now add some more meaningful code:

public static void CreatePorousObject() 
{
      Point3d center=new Point3d(9.0, 3.0, 0.0);
      Vector3d normal=new Vector3d(0.0, 0.0, 1.0);
      Circle pCirc = new Circle(center, normal, 2.0);

      Database acadDB = HostApplicationServices.WorkingDatabase;
      Autodesk.AutoCAD.DatabaseServices.TransactionManager acadTransMgr =acadDB.TransactionManager;
      Transaction acadTrans = acadTransMgr.StartTransaction();
      BlockTableRecord acadBTR = (BlockTableRecord)acadTrans.GetObject(acadDB.CurrentSpaceId,OpenMode.ForWrite);
      acadBTR.AppendEntity(pCirc);
      acadTrans.AddNewlyCreatedDBObject(pCirc, true);
      acadTrans.Commit();
}
Now re-compile and run, you will see a circle drawn in AutoCAD. 

Posted in CAD, Dotnet/C#

Extending Unigraphics NX using C# (I) Manual approach

$
0
0
  • Create a library project in C#;
  • Add a class with 2 methods like below:
  class TestAtt
    {
        public static void Main()
        {
            Session theSession = Session.GetSession();
            theSession.ListingWindow.Open();
            theSession.ListingWindow.WriteLine("Running the Sample Application");
            MessageBox.Show("Good");
        }

        public static int UnloadLibrary()
        {
            return (int)Session.LibraryUnloadOption.Explicitly;

        }
    }

  • Add reference dll in UGDir\UGII\managed\ to the project
  • Add “using NXOpen; using NXOpen.UF;” in the class file
  • Add the NXSigningResource.res to the project, configure the Build Action as “Embedded Resource”

AddRes

  • In the post-build event, type “SignLibrary -verify $(TargetPath)” to sign the dll.

PostBuild

Note that the last 2 steps are not necessary if you only run the extension plugin/addin on your local computer, however they are required if you want to run on other computers. For more details, refer to NX Open Programmer’s Guide  at UGDir/UGDOC/html_files/nxopen_prog_guide/index.html

  • Compile and build, a dll will be generated.
  • Open UGNx, press Ctrl +U, browse to the folder where the DLL resides, click the DLL, and the DLL will be loaded.

That is it. Happy coding!


Posted in CAD, Dotnet/C#

Extending Unigraphics NX using C# (II) Using the Wizard

$
0
0

UgNX provides app wizard for developers to program the extension addins or plugins. The problem is that these wizards are not always successfully installed to the system. For instance, on my Windows 7 professional system, I failed to see them at the expected places.

To use the NX Open C# wizard:

Step 1.

Choose File→New→Project menu item to activate the New dialog box.

Step 2.

Under Project Types, select Visual C#.

Step 3.

From the Templates list. Select NX5_VCS  wizard or NX7 Open C# Wizard.

Step 4.

In Project Name, enter a project name. By default this becomes the name portion of the program being built. For example, a project named MyNXOpenApp produces either a MyNXOpenApp.dll or MyNXOpenApp.exe. You can override this later, if necessary.

Step 5.

Click OK and follow the on-screen instructions to create your C# project.

Compile and run. That is it.

if you fail to find the wizard in your VisualStudio.net,

  • Copy all files from the NX kit to the corresponding directories of the local Visual Studio installation.  The kit is located in:

    %UGII_BASE_DIR%\ugopen\vs_files\

To determine the correct location of the Visual Studio installation, look at the productdir registry key for each language. The key for C and C++ is HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\version#\Setup\VC/productdir (where version# would be 7.1, 8.0, etc). For other languages replace the VC with either VB or VC#.

  • For each wizard, copy any files and/or folders under each subdirectory from the kit to the Visual Studio installation. This example is for the C language so substitute VB or VC# and the appropriate subdirectory for the other languages. Copy:

    %UGII_BASE_DIR%\UGOPEN\vs_files\VC\VCWizards\ to C:/program Files\Microsoft Visual Studio 8\VC\VCWizards\

    and %UGII_BASE_DIR%\UGOPEN\vs_files\VC\vcprojects\  to C:/program Files\Microsoft Visual Studio 8\VC\vcprojects\

Repeat for each language.


Posted in CAD, Dotnet/C#

Extending Unigraphics NX using C# (III) Accessing entities

$
0
0

In Unigraphics, there are two files which are especially for programmers.

  1. The .net reference, in the folder %UGDir\UGDOC\html_files\nxopen_net_ref.chm, which contains all the class references;
  2. The .net programming guide, in the folder %UGDir\UGDOC\html_files\nxopen_net_ref\index.htm .

The 2nd is esp. useful at the initial programming stages.

For instance, in the programming guide, it is clearlly noted the methods of retrieving the entities:

 

  • NX session → list of parts

  • part → list of solid bodies

  • solid body → list of faces

    solid body → list of edges

  • face → list of associated edges

    face → solid body

  • edge → list of associated faces

    edge → solid body

Using this, it is very easy to access the entities:

            theSession = Session.GetSession();
            FeatureTree.Nodes.Clear();
            PartCollection sessionParts = theSession.Parts;
            foreach (Part p in sessionParts)
            {
                if (p.IsFullyLoaded)
                {
                    TreeNode PartNode =new TreeNode(p.Leaf);
                    FeatureTree.Nodes.Add(PartNode);
                    foreach (Body body in p.Bodies)
                    {
                        TreeNode BodyNode=new TreeNode(body.JournalIdentifier);
                        BodyNode.Tag = body;
                        PartNode.Nodes.Add(BodyNode);
                    }
                }
            }


Filed under: CAD, Dotnet/C#

VS2010: “Type or namespace name could not be found”, problem & solution

$
0
0

I recently converted a VS2008 project to VS2010. An interesting probelm is that the project compiles and runs well in VS2008, however, when compiling in VS2010, errors occur:

“The type or namespace name  could not be found (are you missing an assembly reference?)… ”

Wow, what does this mean?

A search in Google shows that there are a lot of different explanations, but it seems there is no one that works, at least for my case.

Finally, I got the trick:

In the project properties, change the Dotnet framework from 2.0,3.0 or 3.5 to 4, compile and run!

Net40

Happy coding!


Filed under: CAD, Dotnet/C# Tagged: Type or namespace name could not be found

Extending Unigraphics NX using C# (IV) : Recording journals

$
0
0

The concept of journaling is similar as the recording macros in SolidWorks. Before clicking the record journal button on the Jorunal Toolbar:

UG_Record_Macro_3

Do the following:

UG_Record_Macro  UG_Record_Macro_2

Then start recording journals, click the desired buttons or menu items to perform the expected actions, and then stop recording, edit the journal:

and you can get the scripts easily then:

UG_Record_Macro_4

Enjoy coding!


Filed under: CAD, Dotnet/C#
Viewing all 204 articles
Browse latest View live