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

Using .Net object in Matlab

$
0
0

Matlab ’s function is power, but not enough. Sometimes, you need some functionality from .net. One example is the Bezier curve class, which is absent in Matlab.

In this example, I created a C# class called BezierCurve:

Use.Net_A

I would like to use this class in Matlab, and below are the procedures:

  1. Created a new .Net class library, I call this BezierLib;
  2. Add the class into the assembly;
  3. Compile and get the “BezierLib.dll” ;
  4. In Matlab Command or script file:
  5. BezierLibInfo = NET.addAssembly(‘C:\Temp\BezierLib.dll’);
    B=BezierLib.BezierCurve([0,1,2,3,4,5],[0,1,2,3,4,5]);  % Constructor
    B.EvalVaueAt(3);  % Call functions;

That is it.


Filed under: Dotnet/C#, Maths

How to get SolidWork exe path programmatically

$
0
0

For some reasons, I need to get the path where SolidWorks are installed. Note that:

  • Uses may not always installl SolidWorks to the default locations.
  • Multiple SolidWorks versions may coexist;

In order to do this programmatically, one can refer to the registry for details.

SolidWorksPath_A

SolidWorksPath_B 

In this case, I have installed SolidWorks 2008 and SolidWorks 2010, and these infiormation can be accessed at “HKEY_LOCAL_MACHINE\SOFTWARE\SolidWorks\SolidWorks <xxxx> \Setup”, where <xxxx>=2010, 2009 or whatever the version installed.

So the trick is to search all the registry keys and subkeys under the path “HKEY_LOCAL_MACHINE\SOFTWARE\SolidWorks\”, and get all the values whose value name is

The psedo code might be:

——————————————————————————-
string ValueToFind=“SolidWorks Folder”;
List<RegistryKey> AllKeys= GetRegistryKeysWithValueNames(ValueToFind);
foreach(rKey in AllKeys)
       Output.Add(rKey.GetValue(ValueToFind));
——————————————————————————-

Unforturenately, such code does NOT work!

The reason is that the value name displayed in the Regedit.exe is not the actual name returned by code, and if you call SomeKey.GetValueNames(), you will see the value name of interest is actually "SolidWorks Location", instead of “SolidWorks Folder”!

I therefore created a snippet to troubleshoot this, and the code is like this:

SolidWorksPath_D0 SolidWorksPath_D

Download VisualStudio 2010 Project here.


Filed under: CAD, Dotnet/C#

Conditional postbuild in C#

$
0
0

Some Examples:

if “$(ConfigurationName)”==”Debug” “C:\Program Files (x86)\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe” /i $(TargetPath)

  • Do not put the “if clause” and the “action clause“  in seperate two lines
  • Use “”  if the command contains spaces, and if the command does not contain spaces, e.g. “SomeCommand” (not the “Some Command”, the quotation mark can be omitted;
  • This is the same as above
    if $(ConfigurationName)==”Debug”  “C:\Program Files (x86)\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe” /i $(TargetPath)

if “$(PlatformName)”==”x86″ “C:\Program Files (x86)\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil.exe” /i $(TargetPath)

Other variables:

Public property

  • $(Collection) Returns the collection containing the Configuration object supporting this property.
  • Public property$(ConfigurationName) Gets the project configuration to be built.
  • Public property$(DTE) Gets the top-level extensibility object.
  • Public property$(Extender) Returns the requested Extender if it is available for this object.
  • Public property$(ExtenderCATID) Gets the Extender category ID (CATID) for the object.
  • Public property$(ExtenderNames) Gets a list of available Extenders for the object.
  • Public property$(IsBuildable) Gets whether the project or project item configuration can be built.
  • Public property$(IsDeployable) Gets whether the project or project item configuration can be deployed.
  • Public property$(IsRunable) Returns whether the project or project item configuration can be run.
  • Public property$(Object) Gets an object that can be accessed by name at run time.
  • Public property$(OutputGroups) Gets a collection of OutputGroup objects that contains the names of the files that are outputs for the project.
  • Public property$(Owner) Gets the project or project item for the configuration.
  • Public property$(PlatformName) Gets the name of the platform supported by this assignment.
  • Public property$(Properties) Gets a collection of all properties that pertain to the Configuration object.
  • Public property$(Type) Gets a constant indicating the object type.

For more details, refer to here .


Filed under: Dotnet/C#

mllapack.dll crashing problem: finally solved in Matlab 2010b

$
0
0

If you would like to call matlab functions in DotNet or com, and your function calls involve some functions which rely on lapack functions, and prior to Matlab 2010b, you may find that your program crashes. Tracing the problem, you will find this is due to a dll (mllapack.dll), and the problem is reported here, and here.

In Matlab 2010b, I have tested two functions which depend on the LAPACK, and it works now!

Download demo VS2010 project here.


Filed under: Dotnet/C#, Maths

Add a custom taskpane to Word 2010 using C#

$
0
0

Create a VisualStudio project, in the template, select Word2010 Addin:

OfficeTaskPane_A

Word 2010 addin template: Application-level add-ins

Word 2010 document: Document-level customizations

Add a new user control “DemoTaskPaneControl” to the project, and add some controls to it.

OfficeTaskPane_B

Add the code below to the ThisAddIn_Startup() function

OfficeTaskPane_C

Compile and run the project, and you will see a new taskpane shown in MS Word 2010.

OfficeTaskPane_D

To disable the addin in MS Word 2010, go to File > Options > Addins > Manage, and unslect the addin project:

OfficeTaskPane_E

That is it.


Filed under: Dotnet/C#, Programming

Using Hoops in C# (I) : HelloHoops

$
0
0

Hoops is a good 3D Visualization toolkit with OOP model enabled. In this tutorial, Hoops will be used in combination of .net. C# language will be used to demostrate the typical usage.

  1. Createa a new winform project, name it HelloHoops
  2. In the Hoops installation folder, search the file “HPanel.cs”, and copy it in explorer, and in VisualStudio.net, paste it.

    HelloHoops3

  3. Drag a button and a panel to the form designer

    HelloHoops5

    Implement the event handler of the button click:

    private void Open_Click(object sender, System.EventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Title = "Open Photo"; dlg.Filter = "HMF/HSF files (*.hmf)|*.hmf;"; if (dlg.ShowDialog() == DialogResult.OK) { if (dlg.FileName.EndsWith("hmf")) { HCS.Open_Segment("?picture"); HCS.Flush_Contents(".", "geometry, subsegments"); HCS.Read_Metafile(dlg.FileName, "?picture", ""); HCS.QUnSet_Bounding_Volume("?picture"); HCS.Close_Segment(); HoopsPanel.Refresh(); } } }

  4. Name the panel as “HoopsPanel”, and

    In the MainForm.Designer.cs, replace the type of HoopsPanel from “Panel” to HPanelHelloHoops6

    Change the instanciation code accordingly:

    HelloHoops7

  5. Add two reference dll to the project:

    HelloHoops1

  6. Compile and run. Click the open button and select the \HOOPS-Installation folder\demo\common\standard\fruit.hmf”, now it works!

    HelloHoops8

In this HelloHoops project, we use hoops 3D Graphics System (3DGS) to render the image. The HPanel class handles the image rendering in its OnPaint event handler:

/*! Instructs HOOPS/3dGS to redraw the scene */ override protected void OnPaint(PaintEventArgs e) { base.OnPaint(e); HLONG key = HCS.KOpen_Segment("?picture"); HCS.Control_Update_By_Key(key, "redraw everything"); HCS.Update_Display(); HCS.Close_Segment(); }

And in the button_click event for the “Open” button,  an image file is loaded, and then the panel is refreshed to reflect the update. You can of course define your own OnPaint() and OnOpenClick() code, and do more complex rendering tasks. However this shows the basic mechnism how HOOPS 3DGS works.

Some notes:

  • Properly select the x86 or x64 or AnyCPU platform which matches the assembly you added to the project;
  • Add the Hoops installation\bin folder to the system path directory, or else there may be some errors such as DLL not found exceptions

Download Project file here.


Filed under: CAD, Dotnet/C#

Sequence Diagram of Visual Studio 2010

$
0
0

Just found a new useful feature of VisualStudio 2010, to generate the sequence diagram for a particular function.

Right click a function, select “Generate Sequence Diagram” in the popup menu:

Sequence Diagram

VS will generate the Sequence diagram for you. Really neat!

VisualStudio_SequenceDiagram

By selectively deleting those that are not of interest, and then right click-> Rearrange layout, the level of detail can be tailored as well.

Sequence Diagram_updated


Filed under: Dotnet/C#

UGNX .net API: How to get the parameter range of a curve?

$
0
0
static public void GetCurveParamRange(Tag CurveTag, out double MinPara, out double MaxPara) { UFSession gUfSession = UFSession.GetUFSession(); IntPtr evaluator; double[] pararm_range = new double[2]; gUfSession.Eval.Initialize(CurveTag, out evaluator); gUfSession.Eval.AskLimits(evaluator, pararm_range); MinPara = pararm_range[0]; MaxPara = pararm_range[1]; gUfSession.Eval.Free(evaluator); }

Download Visual Studio 2010 project here.


Filed under: CAD, Dotnet/C#

Message: Unable to load DLL ‘libpart’: The specified procedure could not be found; Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.

$
0
0

In a recent project, I was required to develop a .Net assembly DLL and use it together with COMSOL with Matlab, where Matlab serves as the hub, and the .Net Assembly provides some services, Matlab consumes it, and COMSOL finally perform FEA and output the result:

MatlabNXComsol_B

To start from scratch, I first developed the DLL assembly, and tested it, fine, no error, ok, proceed.

Then I hook the .Net DLL with Matlab, fine, done.

Next when I start COMSOL with Matlab, call the .Net DLL, there are some errors now:

MatlabNXComsol_A

It is apparent that some error occurs during UGNX calls, as the dll ‘libpart’ is required by UGNX.

I then thought of copying the dll to the bin folder of my program, but still no luck.

It is weird since without COMSOL, it works great. This means there is no bug. Why it does not work, when COMSOL joins? Emm, maybe due to x86 or x64 architecture? I am using win7 x64 version, and all the UGNX, Matlab and COMSOL are 64 bits as well. I then tried in Virtual Machine with x86 platform, but still the problem does not disappear!

Oh my…

The I googled, and found that this is usually a DllImport problem, where managed assembly tried to load C DLL, but the dll is not found.

Em, here comes another idea. I copied my DLL to UG_FOLDER\UGII, which corresponds the “UGII_ROOT_DIR” in the system variable. I guess this time, it will be able to find the required DLL then.

Now, it seems to work, as it takes quite some time to run, which I suppose UGNX initialize its required library . ………, but …

MatlabNXComsol_C

Oh my …

Since I am calling from Matlab, how can I get the LoaderExceptions property? And then, it suddenly comes to my mind that some .net assembly are located in “UGII\managed” folder, and I need to copy them to UGII folder as well ?

Haha, it works now!

Analysis: The reason why Matlab calls .net works, while  with COMSOL, it fails, is probably as follows:

  • In Matlab+ .net, the .net assembly is loaded into Matlab ‘s process, and Matlab knows how to load .net assembly, and possibly by searching the system path; and the actual location of DLL does not matter.
  • While for COMSOL + Matlab + UGNX, both Matlab and UGNX assembly are loaded into COMSOL process, where COMSOL has no knowledge about where the UGNX ‘s dlls (both managed and non-managed) are located. If there is a DLL to be loaded, only the folder where the .net assembly resides will be searched.

MatlabNXComsol_EMatlabNXComsol_D


Filed under: CAE, Dotnet/C#

Microsoft LightSwitch standalone download Link (ISO)

WCF Learning Note (I)

$
0
0
  1. How to: Define a Windows Communication Foundation Service Contract
    using System; // Step 5: Add the using statement for the System.ServiceModel namespace using System.ServiceModel; namespace Microsoft.ServiceModel.Samples { // Step 6: Define a service contract. [ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")] public interface ICalculator { // Step7: Create the method declaration for the contract. [OperationContract] double Add(double n1, double n2); [OperationContract] double Subtract(double n1, double n2); [OperationContract] double Multiply(double n1, double n2); [OperationContract] double Divide(double n1, double n2); } }

  1. How to: Implement a Windows Communication Foundation Service Contract

  2. How to: Host and Run a Basic Windows Communication Foundation Service

    Create a base address for the service.

    Create a service host for the service.

    Enable metadata exchange.

    Open the service host.

  3. How to: Create a Windows Communication Foundation Client.
  4. How to: Configure a Basic Windows Communication Foundation Client
  5. How to: Use a Windows Communication Foundation Client.

A WCF service is a construct that exposes one or more endpoints, each of which exposes one or more service operations. The endpoint of a service specifies an address where the service can be found, a binding that contains the information that a client must communicate with the service, and a contract that defines the functionality provided by the service to its clients.

<client> <endpoint address="http://localhost:8000/ServiceModelSamples/Service/CalculatorService" binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_ICalculator" contract="Microsoft.ServiceModel.Samples.ICalculator" name="WSHttpBinding_ICalculator"> </endpoint> </client>


Filed under: Dotnet/C#

Intel AppUp .Net SDK

$
0
0

The Intel AppUpSM developer program:

  • Provides developers with everything they need to create and then sell their applications to users of millions of Intel Atom-based devices.
  • Gives developers, OEMs, and the ecosystem a framework to deliver great new applications directly to consumers.
  • The Program provides software development support, application validation, and a worldwide distribution channel for applications and application components. For more details, see the Intel AppUpSM developer program Overview

“The Developer Program allows you to distribute free or paid applications to Netbook customers through the app store. Take advantage of ready-made components in the Developer Catalog to include in your application.”


To join the program, you need first get an ID, and I have got one “xinyustudio”.

After that, you can login here.


Then you can download Visual Studio AppUp IDE Plug-in (.MSI file) , and for details info about the plugin in Visual Studio.net, visit http://appdeveloper.intel.com/en-us/article/intel-appup-software-development-kit-plugin-visual-studio-software-release-notes


Read API Reference for .NET technology, and you can begin coding then:

public partial class AdpHelloWorldWindow : Window

{

    com.intel.adp.Application app;

    public AdpHelloWorldWindow()

    {

        InitializeComponent();

        try 

        {

            AdpApplication app = new AdpApplication(new AdpApplicationID(AdpConstants.ADP_DEBUG_APPLICATIONID), false);

        }

        catch (AdpException ex)

        {

           if (ex is AdpErrorException)

           {

               if (ex is InitializationException)

               {

                   // TO DO: add your logic to handle the errors during initialization

                   MessageBox.Show(ex.Message, "Initialization Error");

                   System.Environment.Exit(1);

               }

               else if (ex is UnauthorizedException)

               {

                   // TO DO: add your logic to handle the errors during authorization

                   MessageBox.Show(ex.Message, "Authorization Error");

                   System.Environment.Exit(1);

               }

               if (ex is AdpRunTimeException)

               {

                   // TO DO: add your logic to handle the errors during runtime

                   MessageBox.Show(ex.Message, "Initialization Error");

                   System.Environment.Exit(1);

               }

           }

       else if (ex is AdpWarningException)

       {

           // TO DO: add your logic to handle the warnings

           MessageBox.Show(ex.Message, "Warning");

       }

   }

 

More information can be found at http://appdeveloper.intel.com


Filed under: Dotnet/C#

WebMatrix: A cool tool for lightweight asp.net web design

$
0
0

Serialize & Deserialize derived class insances in generic List: Problems & Solutions

$
0
0

There have been numerous discussions on serialize & deserialize derived class insances to and from generic List<T> and XML files. The problem is when you declare the collection as List<BaseClass>, there is no problem in serialization, but you will have a hard time in retrieving data from XML files. Simply reasonable, the List<BaseClass> does not serialize the derived instances’ type information, and it is ignorant which subclass instances to convert to, when deserializtion takes place.

Numerous discussions can be found on the web, and to list a few:

Although there have been many solutions to tackle the problems, however there seems to be no generic implementation that make save/read XML to and from list or collections. What is expected is not a wrapper in the form that:

class Wrapper { public Collection<Item> Items { get; set; } public string Name { get; set; } }

As this will introduce a new hierarchy in the XML.

A perferable data structure would be: XList<T> that support to serialize and deserialize the derived types, and here comes the solution, and similar approaches can be found on the web, and I just encapsulate them into a single class XList<T>.

Usage:

AA D1=new AA(); //Derived type BB D2=new BB(); //Derived type CC D3=new CC(); //Derived type X D4=new X(); //Base Class XList<X> AllData=new XList<X>(); AllData.Add(D1); AllData.Add(D2); AllData.Add(D3); AllData.Add(D4); // ----------------------------------- AllData.Save(@"C:\Temp\Demo.xml"); // ----------------------------------- // Retrieve data from XML file // ----------------------------------- XList<X> AllData=new XList<X>(); AllData.Open(@"C:\Temp\Demo.xml"); // -----------------------------------


For those who wish to know the technical details, the below highlights some interesting points:

  1. The use of XmlInclude attributes is cumbersome to maintain the code
  2. The proposed implementation derives from:
    public class XList<T> : Collection<T>, IXmlSerializable

    Impementing IXmlSerializable enables custom serialization to be controlled at a better granuar level.

  3. The reason why it does not derive from List<T> is that the List<T> does not expose “Items” property, which is highly expected.
  4. The trick to achieve the aforementioned functionality to convert the internal IList<T> Items to/from List<T> during the serialization and deserialization, as IList<T> does not provide functionalities for serialization/deserialization. You will encounter the exception “Cannot serialize interface System.Collections.Generic.IList`1[ … ]” if you directly use IList<T> Items offered by Collection<T>.

A test project is developed to demonstrated the use of this handy class.

SerializeDerivedClass

Download the demo project source here or click this link.

Comments and ranking of this post are strongly welcome. Let me know your feedback!


Filed under: Dotnet/C#

WinForm:Using Numerical Recipe in C#

$
0
0

In my previous post, I have presented how to use the code of Numerical Recipes in MFC/C++. In this post, the use of it in C# is discussed.

The most straightforward way is to use some wrapper class, e.g. the one presneted here, and a wrapper class is downloadable at link1 or from my backup link2 here.

Below is how to use it in C#:

1. Add the C# implementation of the snippets of “Numeric Recipe in C++”, 3rd edition into the project:

SharpNumericRecipe_A

2. Import the related namespace and call the functions of interest:SharpNumericRecipe_B

Note that the starting index of the matrix element is “1”, rather than “0” !

Emm, it works!

SharpNumericRecipe_C

Cheers and happy coding!


Filed under: Dotnet/C#, Programming Tagged: .net, 3rd edition, C#, Cambridge, DotNet, Numeric Recipe

Using /clr and incompatibility troubleshooting in MFC applications

$
0
0

In some circumstances, to use C# Winform or other .Net objects in MFC applications, the “/clr” directive should be used in the MFC project settings. However, it is found not always possible to use “/clr” to avoid conflicts with other projects in the same solution.

The workaround is to apply “/clr” on a specific cpp file, rather than on the entire project!

clip_image002

However this will result in another conflict:

clip_image003

To troubleshoot this, change the setting for this specific cpp file, and change the /Yu to /Yc:

clip_image005

Rebuild ! Now it works!

You can enjoy the Winform and CLR features without changing the entire project with the “/clr” directive!


Filed under: Dotnet/C#, MFC Tagged: /clr /GL Visual Studio Project setting

unresolved external symbol _clReleaseContext@4

$
0
0

When tesging an OpenCL program in 64bit windows, Visual Studio 2010, building the program generates below error:

error LNK2019: unresolved external symbol _clReleaseContext@4 referenced in function
error LNK2019: unresolved external symbol _clGetDeviceInfo@20 referenced in function
error LNK2019: unresolved external symbol _clGetContextInfo@20 referenced in function
error LNK2019: unresolved external symbol _clCreateContextFromType@24 referenced 
error LNK2019: unresolved external symbol _clGetPlatformIDs@12 referenced in function

Although I have added the necessary Include, Lib directory and the needed lib files to the projects, yet it still does not work, see below:

image image

image

Finally when I change the program configuration from x86 to x64, and rebuild, it works!

image

Happy coding!


Filed under: Dotnet/C#, Programming

WPF: Difference of Visibility.Collapsed and Visibility.Hidden

$
0
0

In a recent trial to rename a TreeViewItem in WPF, I added a TextBlock as well as a Hidden TextBox in the Header, so that when in a “rename”, I will toggle of the TextBlock and TextBox’s visibility and allows for the editing vs static text.

image

It seems fine, right? And running this project, you will notice that it is not exactly what we want. Although the TextBlock/TextBox is hidden, yet the rectangle region it occupies still shows up.

image image
Visibility.Hidden

But when we change the Visibility.Hidden to Visibility.Collapsed, it works like a charm!

image image
Visibility.Collapsed

To recap, the collapsed is more than hidden, and try to use it in replacement of the hidden attribute if you just entered the WPF from Winform.


Filed under: Dotnet/C# Tagged: WPF Difference Visibility.Collapsed Visibility.Hidden

Expression Blend 4: cannot see/switch to design view

$
0
0

If you are using Visual Studio 2012 to create a WPF application, and open it in Micosoft Blend 4, it is likely that you can only see the XAML file, but cannot switch to design view.

image

To solve this, in Visual Studio 2012, change the default .Net Framework from 4.5 to 4.0:

image image

Reopen the solution in Blend 4, it works!

image image


Filed under: Dotnet/C# Tagged: cannot, design view, Expression Blend, visual studio 2012

C#: How to get installed Matlab paths and versions

$
0
0

In a recent project, I need get the installed Matlab’s executable path and their versions, and I know that users might not install Matlab in default “C:\Program files\MathWorks\…”.

The first solution that comes to my mind is to use the registry to find the desired results, as also shown in my previous post : How to get SolidWork exe path programmatically. It turns out that it is not as easy as it should be. Then I found another approach that really works well.

Every time when you install a Matlab version, Matlab installer will add the executable path to the system path, as shown below: (The snapshots come from my another freeware SysPathEditor)

image

So it is now easy to do the job:

  1. Get the system path
  2. Loop all items in the system path, and search with keywords with “Matlab” and “Bin”
  3. Return the ouptut.

Running the 7-line code snippet above, oh yeah~~~

image

Download the 7-line source code and exe file. Happy coding!


Filed under: Dotnet/C# Tagged: Matlab path; COMSOL; change; update; with Matlab
Viewing all 204 articles
Browse latest View live