Setting ComplexType in MathLink - c#

I have another one. I tried to use ml.ComplexType = System.Type.GetType("Complex"); in C# with the Mathematica MathLink, but when I tried to read the numbers with GetComplexArray, it threw an exception stating that I must use the method IMathLink.SetComplexType(), which does not appear to exist.
Is there any way to do this without parsing strings, since I can't for the life of me do that correctly?

The documentation for SetComplexType is here: http://reference.wolfram.com/mathematica/NETLink/ref/SetComplexType.html. You can also find this by pasting "NETLink/ref/SetComplexType" into the Mathematica documentation center. Both these sources indicate that you must execute Needs["NETLink]" prior to use in Mathematica.

For anyone else's reference, I discovered the answer to this one on my own.
What you do is create a dummy instance of any class that has the necessary properties/methods (such as System.Numerics.Complex), here named myVar. Now assuming ml is an instance of IKernelLink, call
ml.ComplexType = myVar.GetType();
You can then use ml.GetComplex() or ml.GetComplexArray().

Related

How to find all particular type object initilializations in code

When refactoring a good piece of code I ran into the problem: I have to find and check all places where new instances of a particular type of object are created. Whether it is: methods, constructors, 'new' keyword. I can't do it without checking all references to the class with CodeLens, but there are too many references!
Ok, thanks for the guys who commented this section the solution was found and it was trivial: create parameterless contstuctor - than you can navigate to all object creations using any constructor with CodeLens.

Calling A Method That Was Just Created. Error Calculating Max Stack Value

so I was fooling around with DNLIB recently, and I was trying to add methods to a .net file. I got the methods from a previously compiled file, so basically, I was trying to mimic the method.
There are 3 methods: GetTheTypes, InvokeIt, and InvokeCall.
Firstly, I had to create the methods GetTheTypes and InvokeIt because InvokeCall calls both the GetTheTypes method and the InvokeIt method. So I added those methods, and they were added perfectly. It compiled and saved, and I was able to see them in a reflector/ILSpy with no problem. Note: when I add the methods, I have a check to see if they should be static or non-static, so that is not an issue. They are also all public methods.
Then, I wanted to add the InvokeCall method. So I did the same thing I did for the other methods, opened the methods I wanted mimicked in ILSpy, then basically copied all of the instructions and local variables into a new CilBody which were added to the InvokeCall method that I was mimicking. The only problem was it threw an error saying "Error Calculating Max Stack Value". The weird thing was, if I changed the OPCode from Call to NewObj, it compiled fine. But that is not what I want to do. What I want to do throws the error mentioned above.
Here is the code I use to add the instruction:
cBody.Instructions.Add(OpCodes.Call.ToInstruction(_getTheTypesMethod))
The _getThetypesMethod variable is defined as a MethodDefUser and consists of the method I created ealier and compiled just fine. I have also tried this:
cBody.Instructions.Add(OpCodes.Call.ToInstruction(t.Asm.Import(_getTheTypesMethod)))
That also did not work. I have also tried to get the DeclaringType of the method as well, then Finding the method like this:
cBody.Instructions.Add(OpCodes.Call.ToInstruction(t.Asm.Import(_getTheTypesMethod.GetDeclaringType().FindMethod("GetTheTypes")))
That didn't work either.
So if anyone has any suggestions as to how to call a method that was just created, please tell me. I've been trying to find out how to fix this problem for the last day or so, with no prevail. Thanks.
The answer was my MethodSig was wrong. I was referencing a static method with a instance MethodSig. I only had a check when creating the method for the method attributes, not the creation attributes.

Seeking guidance reading .yaml files with C#

Two months later:
The YAML (Eve Online blueprint.yaml) file I tried to parse changed a huge deal which also made it much easier to parse using de deserializer. If someone (for whatever reason) would like to see the code, it's updated on https://github.com/hkraal/ParseYaml
Based on the comment of Steve Wellens I've adjusted the code to do less things at once. It didn't matter in the error itself. I've created another project (Example1) in my solution to test the actual example found on aaubry.net I referenced to earlier.
It gave me the same error when using an "dynamic" key which lead to my current conclusion:
There is a difference between:
items:
- part_no: A4786
and
items:
part_no: A4786
The first is being used in the example which I (wrongly) assumed I could apply to my .yaml file which is using the second syntax.
Now it remains to find out how I can get the 'child' elements of my key with the syntax used in my yaml file...
As C# is used at work I started thinking about a nice project to learn about various aspects of the language while having a direct goal to work towards. However I'm hitting my first wall quite early in my project parsing a Yaml file. My goal is to create an List of YamlBlueprint objects as defined in YamlBlueprint.cs but I don't even get to the end of the Yaml file.
I've setup a testcase on github which demonstrates the problem:
https://github.com/hkraal/ParseYaml
The example on http://www.aaubry.net/page/YamlDotNet-Documentation-Loading-a-YAML-stream works up untill I want to loop trough the items. Based on what I see I should be able to give myKey as parameter to the YamlScalarNode() to access the items below it.
var items = (YamlSequenceNode)mapping.Children[new YamlScalarNode(myKey)];
I'm gettting the following error if I do:
An unhandled exception of type 'System.InvalidCastException' occurred in yamldotnet.exe
Additional information: Unable to cast object of type 'YamlDotNet.RepresentationModel.YamlMappingNode' to type 'YamlDotNet.RepresentationModel.YamlSequenceNode'.
When passing "items" as parameter to YamlScalarNode() it just complains about the item not being there which is to be expected. As I'm not sure where my toughttrain is going wrong I would love a bit assistance on how to troubleshoot this further.
Your question has already been correctly answered, but I would like to point out that your approach is probably not the best one for parsing files. The YamlDotNet.RepresentationModel.* types offer an object model that directly represents the YAML stream and its various parts. This is useful if you are creating an application that processes or generates YAML streams.
When you want to read a YAML document into an object graph, the best approach is to use the Deserializer class. With it you can write your code as follows:
using(var reader = File.OpenText("blueprints.yaml")
{
var deserializer = new Deserializer();
var blueprintsById = deserializer.Deserialize<Dictionary<int, YamlBlueprint>>(reader);
// Use the blueprintsById variable
}
The only difference is that the Id property of the YamlBlueprint instances won't be set, but that's just a matter of adding this:
foreach(var entry in blueprintsById)
{
entry.Value.Id = entry.Key;
}
You have too much stuff going on in one line of code. Create a new YamlScalarNode object in one line, access the array in another line, cast the resultant object in another line. That way, you'll narrow down the problem area to a single step.
The message is telling you that you are retrieving a YamlMappingNode from the array but you are casting it to a YamlSequenceNode. Which is not allowed since the two types are obviously not related.
Well that was kinda stupid... it's kind of hard to create an mapping of something which only contains one element. I've edited the repo linked in the OP with an working example in case somebody runs into the same problem.

Auto-generate variable *name* to match parameter you're providing?

R# 4.5 (answers to 5 are welcome)
VS2008 (answers to VS2010 are welcome)
C# (FWIW)
I'm using a constructor (the question applies for methods, too), and there's Intellisense:
I don't yet have a value to specify for this first parameter, "firstName". Today, I type "firstName", then let the IDE create that variable for me (which I initialize to some value).
I understand that the IDE will create the variable for me. I want it to create the variable name for me.
I don't want to have to type "firstName". I like the variable name the parameter author chose, and I want to use that variable name in my (calling) code.
Is there a way to have these acceptable variable names re-generated for me (the calling code) automatically as I move, parameter by parameter, through this line of (calling) code?
You may get close to what you are looking for with VS2010.
Type p.Foo(
This will open the description of the currently selected constructor, out of the list of all constructors. If you type a letter, or hit ctrl + space, intellisense auto completion will open.
A difference here between VS2008 and VS2010 is named parameters. In VS2010, your completion list will have entries for the named parameters firstName: and lastName:.
Type the first letter of the parameter name (what you are referring to as "the variable name the parameter author chose")
Intellisense should jump straight to that entry, and allow you to do completion the same way it usually does.
Type a space, enter, or comma
Intellisense it will insert the identifier used for the named parameter. It won't insert the colon (unless you type it), so you don't have to use the named parameter feature to accomplish your goal here. You can just take advantage of the fact that the text you are looking for is in your completion list.
How you get Visual Studio to actually generate the local variables (which, according to your question, it seems like you have already solved) baffles me, and would be up to you to take care of :) If you've got that second problem licked, I'd like to know how, too.
You can make a code snippet that creates the variable and inserts it as parameters.
MSDN Reference on snippets
I don't understand your scenario entirely but I'm assuming you want to inject a variable name from calling assembly into the called code. if so, you may want to look into System.CodeDom that lets you create class and its memebers during runtime beside plethora of other functionality it offers.
I am pretty sure you can do it with Resharper or CodeRush/Refactor.
It sounds like to me that what your trying to do is get out of typing at all! To have the IDE put the code in you intend so you don't have to. A quite lofty goal - with the exception that you'd put us all out of work ;-(
All fun aside, what you're probably reaching for is a code gen tool such as the T4 Toolbox ( one of my new favorite toys). If you're looking for a tool that will auto-generate your code snippets as you type, that's a tall order. The nearest thing available would be Resharper.
Here is an example of a class constructor I generated from my customization of T4 Toolbox templates:
public partial class EvaluationController : SmartController
{
private readonly IEvaluationService _evaluationSvc;
private readonly IEvaluationMapper _evaluationMapper;
private readonly IEvaluationCriterionMapper _evaluationCriterionMapper;
private readonly IParticipantEvaluationMapper _participantEvaluationMapper;
public EvaluationController( IEvaluationRepository repository, IEvaluationService evaluationSvc, IEvaluationMapper evaluationMapper, IEvaluationCriterionMapper evaluationCriterion, IParticipantEvaluationMapper participantEvaluation)
{// : base(repository, evaluationMapper)
_evaluationSvc = evaluationSvc;
_evaluationMapper = evaluationMapper;
_evaluationCriterionMapper = evaluationCriterion;
_participantEvaluationMapper = participantEvaluation;
}
If that is what you're after, the place to start would be: http://t4toolbox.codeplex.com/
I've got an example project where I use customizations of the templates to spin up my business classes, various methods & repository layer.http://t4tarantino.codeplex.com/
There's an example of the level of complexity of output you can generate at
http://geekswithblogs.net/JamesFleming/archive/2010/08/18/code-generation-with-t4-toolbox.aspx
HTH

Property or Method? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Properties vs Methods
When is it best to use a property or a method?
I have a class which is a logger. When I create this class I pass in a file name.
My file name for the log is fairly simple, basically it just gets the application path and then combines it with myapp.log.
Now instead of having the log file name lines in my method I want to create a new method to get this.
So my question is, since it's fairly simple, is creating a property a good idea instead of creating a method since there are no parameters.
Duplicate Properties vs Methods
Properties are typically used to store a state for an object. Method are typically used to perform an action on the object or return a result. Properties offer both getters and setters and can have different scope (at least in .NET 2.0). There is also some advantages to using a property vs methods for serialization or cloning and UI controls look for properties via reflection to display values.
Properties can be used to return simple values. Methods should always been used when fetching the value might incur any kind of performance hit. Simple linear operations can be fine in properties, though.
Ask yourself whether it's an aspect of your class (something it has) versus a behaviour of your class (something it does).
In your case, I'd suggest a property is the way to go.
I'd definitely go with the property. If you were doing something complex or computationally or time intensive, then you would go the method route. Properties can hide the fact that a complex operation is taking place, so I like to reserve properties for fast operations and ones that actually describe a property on the object. Simply: Methods "do" something, properties describe.
When you want to use it like a variable, you should go for a property. When you want it to be clear that this is a method, you should use a method.
As a property is a method, it depends on the semantic/design you want to communicate here.
Properties should be used to wrap instance variables or provide simple calculated fields. The rule of thumb that I use is if there is anything more that very light processing make it a method.
If you are not doing anything significant, use proerties.
In your case, a readonly property (get only) should be good.
Methods make sense when you are doing something other than returning reference to an internal member.
Properties are a design smell.
They are sometimes appropriate in library classes, where the author cannot know how the data will be used but must simply output the same value that was put in (e.g. the Key and Value properties of the KeyValuePair class.)
IMHO some uses of properties in library classes are bad. e.g. assigning to the InnerHTML property of a DOM element triggers parsing. This should probably be a method instead.
But in most application classes, you do know exactly how the value will be used, and it is not the class's responsibility to remind you what value you put in, only to use the data to do its job. Messages should exercise capabilities, not request information
And if the value you want is computed by the class (or if the class is a factory and the value is a newly-created object), using a method makes it more clear that there is computation involved.
If you are setting the log filename, then there is also the side effect of opening the file (which presumably may throw an exception?) That should probably be a method.
And if the filename is just part of the log message, you do not need a getter for the property, only a setter. But then you would have a write-only property. Some people find these confusing, so I avoid them.
So I would definitely go for the method.
The answer in the dupicate question is correct. MSDN has a very good article on the differences and when one should be used over an other. http://msdn.microsoft.com/en-us/library/ms229054.aspx
In my case I believe using the Property would be correct because it just returns the path of the exe + a file name combined.
If however I decided to pass a file name to get it to combine with the exe path, then I would use a method.

Categories