Translate C# code to VBNET - c#

I need to translate this C# code from NReplayGain library here https://github.com/karamanolev/NReplayGain to a working VBNET code.
TrackGain trackGain = new TrackGain(44100, 16);
foreach (sampleSet in track) {
trackGain.AnalyzeSamples(leftSamples, rightSamples)
}
double gain = trackGain.GetGain();
double peak = trackGain.GetPeak();
I've translate this:
Dim trackGain As New TrackGain(samplerate, samplesize)
Dim gain As Double = trackGain.GetGain()
Dim peak As Double = trackGain.GetPeak()

Use an online converter. C# to VB converters:
dotnet Spider
SharpDevelop
teletrik.
developerFusion
Your c# code shown above has errors. Probably it is written in pseudo code. I have not found any declaration of a sample set at the github address you mentioned.
A semicolon is missing (inside the loop). The loop variable sampleSet is not declared. Where do leftSamples and rightSamples come from? The loop variable is not used inside the loop. Probably the left and right samples are part of the sampleSet. If I correct this, I can convert the code by using one of these online converters.
C#:
TrackGain trackGain = new TrackGain(44100, 16);
foreach (SampleSet sampleSet in track) {
trackGain.AnalyzeSamples(sampleSet.leftSamples, sampleSet.rightSamples);
}
double gain = trackGain.GetGain();
double peak = trackGain.GetPeak();
VB:
Dim trackGain As New TrackGain(44100, 16)
For Each sampleSet As SampleSet In track
trackGain.AnalyzeSamples(sampleSet.leftSamples, sampleSet.rightSamples)
Next
Dim gain As Double = trackGain.GetGain()
Dim peak As Double = trackGain.GetPeak()
After all, the two versions don't look that different!

It is fairly simple to reference within assemblies written in different languages.
I frequently reference C# code from F# and have referenced VB.NET code from C#.
Just be sure to compile both projects to target the same framework version, say .NET 4.5 or Mono 2.10 , and CPU architecture.
If you need the files to reside in the same assemblies. I would suggest you study the C# syntax and convert it manually.
Edit: After browsing the Repository, I only see a handful of classes.
Besides learning new languages is a great way to improve both your ability to write code and read code in the languages you are already comfortable with.

A good one online solution to translate .NET to C# and vice-versa, to another language, as JavaScript is CodeTranslator - Carlossag. Until now, I didn't have problems with this translator.

Related

C# to Python (not IronPython) Sending and Recieving Array's, Int, String, Decimals

I have been researching a simple way to start a Python (not IronPython) script and pass parameters such as an Array, String, Int, Decimal and then retrieve an output such as an array from the Python script.
All research points to very complicated methods that are unreliable or IronPython which is limited.
If VBA can do this via xlwings (really well), why cant C# within Visual Studio?
Any advise, links or an example would be really helpful. Thank you
As #denfromufa mentioned, Pythonnet is the way to go. Here is how you can start a module and pass objects to it from C#.
Note:
numpy is given here for example but you can replace it with any other module, even a custom one.
an array object is showed as example but it is the exact same thing for string, double, int, etc.
In this example I execute everything directly in the Python engine using PyScope, since your question was from C# to Python. If you need the object on the C# side, you can use dynamic types instead and import the module with Py.Import().
using Python.Runtime;
double[] a = [2.1, 3.5, 5.4];
using (Py.GIL())
{
using (PyScope scope = Py.CreateScope())
{
scope.Exec("import numpy as np");
scope.Set("a", a.ToPython())
scope.Exec("b = np.array(a)");
}
}

ILNumerics equivalent of MatLab/Octave statement

Question
In MatLab/Octave, I have the statement x(isnan(x)) = 0. I am porting this over to ILNumerics in C#. I am having trouble finding the ILNumerics equivalent to the MatLab/Octave statement mentioned.
In our case, x is a 2x2 array.
What we've tried
noNaNDataValues = dataValues[ILMath.isnan(dataValues)] = 0.0; where dataValues is an ILArray<double>
We have resorted to standard C# for loops and that works fine. But we would rather use ILNumerics considering how much we've invested in it already.
Just use
x[isnan(x)] = 0;
This is directly equivalent to Matlabs syntax. Your first attempt suggests that you want to seperate non-NaN values from NaNs? If so, please clarify.

Passing data between Python and C# without writing a file

I would like to pass binary information between Python and C#. I would assume that you can open a standard in/out channel and read and write to that like a file, but there are a lot of moving parts, and I don't know C# too well. I want to do this sort of thing, but without writing a file.
# python code
with open(DATA_PIPE_FILE_PATH, 'wb') as fid:
fid.write(blob)
subprocess.Popen(C_SHARP_EXECUTABLE_FILE_PATH)
with open(DATA_PIPE_FILE_PATH, 'rb') as fid:
'Do stuff with the data'
// C# code
static int Main(string[] args){
byte[] binaryData = File.ReadAllBytes(DataPipeFilePath);
byte[] outputData;
// Create outputData
File.WriteAllBytes(outputData)
I've tried several different ways of using standard in/out, but I've had no luck matching them up, like I said, there are a lot of moving parts. I've tried things like
p = subprocess.Popen(C_SHARP_EXECUTABLE_FILE_PATH, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
p.stdin.write(blob)
p.stdin.close()
or
p = subprocess.Popen(C_SHARP_EXECUTABLE_FILE_PATH, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
out, err = p.communicate(blob)
on the python side along with
TextReader tIn = Console.In;
TextWriter tOut = Console.Out;
String str = tIn.ReadToEnd();
//etc...
as well as a couple of other things that didn't work on the C# side. I've had mild success with some things, but I've changed it around so much that I don't remember what has worked for what. Could somebody give me a hint as to which pieces would work the best, or if this is even possible?
The data I want to pass has null and other non-printable characters.
This python code was correct
p = Popen(C_SHARP_EXECUTABLE_FILE_PATH, stdout=PIPE, stdin=PIPE, stderr=PIPE)
out, err = p.communicate(blob)
And on the C# side, I got it to work with
Stream ms = Console.OpenStandardInput();
One possibility would be to use something like Python for .NET, which provides interop directly between C# and (standard, C) Python.
Depending on what your Python routines need to do, IronPython can also be a good option, as this is directly consumable and usable from within C#.
Both of these options avoid trying to communicate through the command line, as you have direct access to the Python objects from .NET, and vice versa.

evaluate an arithmetic expression stored in a string (C#)

I'm working on a application in C# in which I want to calculate an arithmetic expression that is given as a string.
So like I got a string:
string myExpr="4*(80+(5/2))+2";
And I want to calculate the outcome of the arithmetic expression.
While in a language such as Javascript, PHP etc. you could just use Eval to do the trick this doesnt seem to be an option in C#.
I suppose it is possible to write a code to devide it into countless simple expressions, calculate them and add them together but this would take quite some time and I'm likely to have lots of troubles in my attempt to do so.
So... my question, Is there any 'simple' way to do this?
There's a javascript library you can reference, then just do something like:
var engine = VsaEngine.CreateEngine();
Eval.JScriptEvaluate(mySum, engine);
Edit;
Library is Microsoft.JScript
You could just call the JScript.NET eval function. Any .NET language can call into any other.
Have you seen http://ncalc.codeplex.com ?
It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse:
Expression e = new Expression("Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)");
e.Parameters["Pi2"] = new Expression("Pi * Pi");
e.Parameters["X"] = 10;
e.EvaluateParameter += delegate(string name, ParameterArgs args)
{
if (name == "Pi")
args.Result = 3.14;
};
Debug.Assert(117.07 == e.Evaluate());
It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions.
It also supports logical operators, date/time's strings and if statements.
I've used NCalc with great success. It's extremely flexible and allows for variables in your formulas. The formula you listed in your question could be evaluated this easily:
string myExpr = "4*(80+(5/2))+2";
decimal result = Convert.ToDecimal(new Expression(myExpr).Evaluate());
You need to implement an expression evaluator. It's fairly straightforward if you have the background, but it's not "simple". Eval in interpreted environments actually re-runs the language parser over the string; you need to emulate that operation, for the bits you care about, in your C# code.
Search for "expression evaluators" and "recursive descent parser" to get started.
If you have Bjarne Stroustrup's The C++ Programming Language, in Chapter 6 he explains step by step (in C++) how to do exactly what Chris Tavares suggests.
It's straightforward but a little heady if you're not familiar with the procedure.
I needed to do something similar for an undergrad projectand I found this
Reverse Polish Notation In C#
Tutorial and code to be extremely valuable.
It's pretty much just an implementation of converting the string to Reverse Polish Notation then evaluating it. It's extremely easy to use, understand and add new functions.
Source code is included.
Try something like this:
int mySum = 4*(80+(5/2))+2;
var myStringSum = mySum.toString();

adding stock data to amibroker using c#

I have had a hard time getting and answer to this and i would really , really appreciate some help on this.
i have been on this for over 2 weeks without headway.
i want to use c# to add a line of stock data to amibroker but i just cant find a CLEAR response on how to instantiate it in C#.
In VB , I would do it something like;
Dim AmiBroker = CreateObject("Broker.Application")
sSymbol = ArrayRow(0).ToUpper
Stock = AmiBroker.Stocks.Add(sSymbol)
iDate = ArrayRow(1).ToLower
quote = Stock.Quotations.Add(iDate)
quote.Open = CSng(ArrayRow(2))
quote.High = CSng(ArrayRow(3))
quote.Low = CSng(ArrayRow(4))
quote.Close = CSng(ArrayRow(5))
quote.Volume = CLng(ArrayRow(6))
The problem is that CreateObject will not work in C# in this instance.
I found the code below somewhere online but i cant seem to understand how to achieve the above.
Type objClassType;
objClassType = Type.GetTypeFromProgID("Broker.Application");
// Instantiate AmiBroker
objApp = Activator.CreateInstance(objClassType);
objStocks = objApp.GetType().InvokeMember("Stocks", BindingFlags.GetProperty,null, objApp, null);
Can anyone help me here?
Thanks
The VB code uses something called late binding against a "COM IDispatch" compatible component. Late binding is not supported by C# (up to C# version 3). The C# compiler only compiles code it knows how bind to (called early bind).
To do what you want to do, it would be easier to generate a proxy dll via Visual Studio - select add reference on a project, then select the tab COM, and then search for that ami broker component in the list. This will generate a proxy dll which you can program against using similar code as the one you have showed for VB.
In C# 3.0, you'll discover that you sometimes have to use Type.Missing and that you have to do some additional explicit casting, even though you'd think that it doesn't seem logical.
C# 4.0 has something called dynamic, which allows you to write much cleaner code when accessing COM components.
See my answer here for the code:
https://stackoverflow.com/a/20101274/1581495
I actually use this method now. I save text files from MetaTrader then import them realtime into AmiBroker. Doing it this way is essentially like importing quotes using the ASCII import, so you'll need to make sure that you prepare your import format file. For me, a line of sample data looks like this:
EURAUD,20170607,00:00:00.4885,1.50174,1.50231,1 //Symbol, Date, Time (HH:MM:SS.tttt), Bid, Ask, Volume
I use the default.format file, which looks like this:
$FORMAT TICKER,DATE_YMD,TIME,CLOSE,AUX1,VOLUME
$SEPARATOR ,
$AUTOADD 0
$BREAKONERR 0
$SKIPLINES 0
Find the guide and some examples here on importing and formats:
https://www.amibroker.com/guide/d_ascii.html
EDIT: this might also help with importing
http://www.amibroker.com/kb/2016/01/23/how-to-create-custom-import-definition-for-ascii-importer/

Categories