ToIntArray - Replacement function - c#

According to http://crsouza.blogspot.com.br/2012/01/decision-trees-in-c.html I use
DataTable symbols = codebook.Apply(data);
int[][] inputs = symbols.ToIntArray("Outlook", "Temperature", "Humidity", "Wind");
int[] outputs = symbols.ToIntArray("PlayTennis").GetColumn(0);
But in .net 4.0 and in mono there is no ToIntArray, also I could not find any replacement function for it.
How does ToIntArray convert symbols or, what does ToIntArray look like?

If you don't want to download and add the Accord framework to your project (Note: there is a chance it might have dependencies which are not supported by Xamarin's .NET implementation), then luckily it's open source, so if you want to just see the code it's available to the public.
To answer the specific question, the .ToIntArray extension method (which is just an "alias" method for ToArray<int>()) can be seen here:
https://code.google.com/p/accord/source/browse/trunk/Sources/Accord.Math/Matrix/Matrix.Conversions.cs
However, the .Apply and .GetColumn methods (from your sample code) is also part of the framework, so you'd probably need to look at that code as well. See Matrix.Common and Matrix.Selection.

As of the current version, you can use ToInt32(), as well as ToDouble(), ToSingle(), ToBoolean() and others to perform type conversions of arrays.

Related

Profile Time Spent in the Inner .NET Framework Methods

In Visual Studio - is there a way to profile the time spent in the inner methods of .NET Framework ?
An example - consider a good-old fashioned ArrayList, and adding some random numbers to it:
static void Main(string[] args)
{
const int noNumbers = 10000; // 10k
ArrayList numbers = new ArrayList();
Random random = new Random(1); // use the same seed as to make
// benchmarking consistent
for (int i = 0; i < noNumbers; i++)
{
int currentNumber = random.Next(10); // generate a non-negative
// random number less than 10
numbers.Add(currentNumber); // BOXING occurs here
}
}
I can step into the .NET Framework source code just fine while debugging. One can use the default Microsoft symbols and the source code for .NET (as described in this answer) or go the dotPeek route (detailed here). As for the cleanest option of just using the Reference Source symbols - as Hans Passant was saying in his answer almost 5 years ago - the framework version (down to security updates installed) for which the symbols were created would have to match exactly to your version; you'd have to be really lucky to get that working (I wasn't). Bottom line - there are 2 ways I can successfully use to step into the .NET source code.
For the sample at hand, there aren't big differences between the Reference Source code and the dotPeek reverse-engineered code - that is for the methods invoked by ArrayList's Add - namely the Capacity setter and ArrayList's EnsureCapacity, of which the latter can be seen below (ReferenceSource code on the left, dotPeek source code on the right):
Running an "Instrumentation" profiling session will return a breakdown of the time spent in each method, but as long as the .NET types go, it appears that one only gets to see the methods the respective code called "directly" - in this case the function that Adds elements to the ArrayList, the one that generates a Random int, and the respective types' constructors. But there's no trace of EnsureCapacity or Capacity's setter, which are both invoked heavily by ArrayList's Add.
Drilling down on a specific .NET method doesn't show any of the methods it called in turn, nor any source code (despite being able to see that very code earlier, while stepping into with the debugger):
How can one get to see those additional, "inner" .NET methods ? If Visual Studio can't do it, perhaps another tool can ?
PS There is a very similar question here, however it's almost 10 years old, and there's not much there that brings light to the problem.
Later Update: As KolA very well points out, JetBrains dotTrace can show this. A line-by-line profiling session below:
perhaps another tool can ?
DotTrace can profile performance down to properties if that's what you're looking for. This example is for generic List<T> not ArrayList but I think it shouldn't matter.

Creating a .NET List<List<double>> to call a .NET DLL from MATLAB?

I have a .NET DLL I'm loading into MATLAB R2016B through the asm = NET.addAssembly('C:\My.dll') It is fairly easy to create a .NET list of doubles using netDouble = NET.createGeneric('System.Collections.Generic.List',{'System.Double'},1) which MATLAB shows as 1x1 List<System*Double>, but there is no tutorial out there that shows how to create a .NET List<List<double>> structure. MATLAB can't access the code I need to run as a result - it shows the error as: Value must be
'System.Collections.Generic.List<System*Collections*Generic*List<System*Double>>'.
Anyone out there know how to create the above structure? Much appreciated.
Actually MATHWORKS tech support got back to me with a solution that works. Since I don't see it documented anywhere, I'm posting this example in case someone else runs into this issue:
genCls = NET.GenericClass('System.Collections.Generic.List','System.Double');
obj = NET.createGeneric('System.Collections.Generic.List',{genCls},5);
And how they explained it: In this method, we first create a generic class as List and this class is provided as an argument to the 'NET.createGeneric' method hence the created list is of type List<List<double>>
Then to populate it... here's a function I wrote to take the Matlab array and convert to the proper type all rolled into 1:
function [NETobj] = ML_NET_ListListDouble(MLarray)
genCls = NET.GenericClass('System.Collections.Generic.List','System.Double');
NETobj = NET.createGeneric('System.Collections.Generic.List',{genCls},size(MLarray,1));
for i=1:size(MLarray,1)
obj1 = NET.createGeneric('System.Collections.Generic.List',{'System.Double'},size(MLarray,2));
AddRange(obj1, NET.convertArray(MLarray(i,:))) %insert the current MATLAB row into the NET structure
Add(NETobj, obj1)
end
end
That function hopefully comes in useful for someone else - a brainless conversion from a MATLAB array to a .NET <List<List<double>>

Best way to run a string as c# code

Let's say I have:
#{
var str= "DateTime.Now";
}
I want to process this string as a c# code
#Html.Raw(App.ProcessAsCode(str));
The output should be the current date time.
Final Edit:
Based on further information - if the goal here is to simply have a formatting engine there are lots of options out there. One such option is based around the .liquid syntax from shopify (see here). You can find a .NET port of this on gitHub here: https://github.com/formosatek/dotliquid/. The main purpose of this is to turn something like:
<h2>{{product.name}}</h2>
Into something like:
<h2>Beef Jerky</h2>
I would strongly recommend reading more about the liquid engine and syntax and I believe this will lead you in the right direction. Best of luck!
Initial Answer
This is definitely possible - although as others have said you will want to be careful in what you do. Using C# the key to compiling and running code generically is the "CSharpCodeProvider" class. Here is a brief example of how that looks:
string[] references = { "System.dll" };
CompilerParams.ReferencedAssemblies.AddRange(references);
var provider = new CSharpCodeProvider();
CompilerResults compile = provider.CompileAssemblyFromSource(CompilerParams, formattedCode);
In this example, "formattedCode" is a string with the C# code. Any references must be manually added. For the full example see this stack question (How to get a Type from a C# type name string?).
NOTE -- If all you are looking to do here is a format string or something simple like that you might have the user pass in a .NET format string (eg "MM/dd/yyyy"), then use that in a call to the "ToString" method. That would provide the user some configurability, while still making sure your system stays secure. In general running code on a server that hasn't been properly checked/escaped is really dangerous!
Reference - For your reference, the current msdn page for CSharpCodeProvider also has some examples.
Another option would be using a dynamic language such as IronRuby or IronPython.

Create COM-object on server in C#

I need to create a COM object on server.
In VB you can do this: (tutorial)
xlApp = CreateObject("Excel.Application", "\\MyServer")
But how to do same thing on C#?
I know how to do it locally:
var infsrv = new InfoServ.TInfoServerClass();
But don't know how to do it on server..
There's nothing wrong with adding a reference to Microsoft.VisualBasic so that you can simply use the same method. This is very much a nicety of .NET, it would be a waste not to use it. It is however simple to do, just two lines of code:
public static object CreateObject(string progid, string server) {
var t = Type.GetTypeFromProgID(progid, server, true);
return Activator.CreateInstance(t);
}
Well, one line if you push it. In this specific case you definitely should consider adding a reference to Microsoft.Office.Interop.Excel. You can then simply use the new operator, get speedier code because you are not late-binding and get IntelliSense. If you want to stick with late binding then be sure to use the C# version 4 support for the dynamic keyword. Writing late bound code in earlier C# versions is quite painful.
You can add a reference to the Microsoft.VisualBasic.dll to your C# project and use CreateObject directly. This might be the easiest solution if you have an existing codebase that uses a lot of VB.NET specific features:
using Microsoft.VisualBasic;
...
dynamic xlApp = Interaction.CreateObject("Excel.Application", "MyServer");
Note: Since the backslash is a special character in C#, either remove the \\ from the server name (see above) or escape the string #"\\MyServer".
Use this overload of Type.GetTypeFromCLSID.

How will you use the C# 4 dynamic type?

C# 4 will contain a new dynamic keyword that will bring dynamic language features into C#.
How do you plan to use it in your own code, what pattern would you propose ? In which part of your current project will it make your code cleaner or simpler, or enable things you could simply not do (outside of the obvious interop with dynamic languages like IronRuby or IronPython)?
PS : Please if you don't like this C# 4 addition, avoid to bloat comments negatively.
Edit : refocussing the question.
The classic usages of dynamic are well known by most of stackoverflow C# users. What I want to know is if you think of specific new C# patterns where dynamic can be usefully leveraged without losing too much of C# spirit.
Wherever old-fashioned reflection is used now and code readability has been impaired. And, as you say, some Interop scenarios (I occasionally work with COM).
That's pretty much it. If dynamic usage can be avoided, it should be avoided. Compile time checking, performance, etc.
A few weeks ago, I remembered this article. When I first read it, I was frankly appalled. But what I hadn't realised is that I didn't know how to even use an operator on some unknown type. I started wondering what the generated code would be for something like this:
dynamic c = 10;
int b = c * c;
Using regular reflection, you can't use defined operators. It generated quite a bit of code, using some stuff from a Microsoft namespace. Let's just say the above code is a lot easier to read :) It's nice that it works, but it was also very slow: about 10,000 times slower than a regular multiplication (doh), and about 100 times slower than an ICalculator interface with a Multiply method.
Edit - generated code, for those interested:
if (<Test>o__SiteContainer0.<>p__Sitea == null)
<Test>o__SiteContainer0.<>p__Sitea =
CallSite<Func<CallSite, object, object, object>>.Create(
new CSharpBinaryOperationBinder(ExpressionType.Multiply,
false, false, new CSharpArgumentInfo[] {
new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null),
new CSharpArgumentInfo(CSharpArgumentInfoFlags.None, null) }));
b = <Test>o__SiteContainer0.<>p__Site9.Target(
<Test>o__SiteContainer0.<>p__Site9,
<Test>o__SiteContainer0.<>p__Sitea.Target(
<Test>o__SiteContainer0.<>p__Sitea, c, c));
The dynamic keyword is all about simplifying the code required for two scenarios:
C# to COM interop
C# to dynamic language (JavaScript, etc.) interop
While it could be used outside of those scenarios, it probably shouldn't be.
Recently I have blogged about dynamic types in C# 4.0 and among others I mentioned some of its potential uses as well as some of its pitfalls. The article itself is a bit too big to fit in here, but you can read it in full at this address.
As a summary, here are a few useful use cases (except the obvious one of interoping with COM libraries and dynamic languages like IronPython):
reading a random XML or JSON into a dynamic C# object. The .Net framework contains classes and attributes for easily deserializing XML and JSON documents into C# objects, but only if their structure is static. If they are dynamic and you need to discover their fields at runtime, they can could only be deserialized into dynamic objects. .Net does not offer this functionality by default, but it can be done by 3rd party tools like jsonfx or DynamicJson
return anonymous types from methods. Anonymous types have their scope constrained to the method where they are defined, but that can be overcome with the help of dynamic. Of course, this is a dangerous thing to do, since you will be exposing objects with a dynamic structure (with no compile time checking), but it might be useful in some cases. For example the following method reads only two columns from a DB table using Linq to SQL and returns the result:
public static List<dynamic> GetEmployees()
{
List<Employee> source = GenerateEmployeeCollection();
var queyResult = from employee in source
where employee.Age > 20
select new { employee.FirstName, employee.Age };
return queyResult.ToList<dynamic>();
}
create REST WCF services that returns dynamic data. That might be useful in the following scenario. Consider that you have a web method that returns user related data. However, your service exposes quite a lot of info about users and it will not be efficient to just return all of them all of the time. It would be better if you would be able to allow consumers to specify the fields that they actually need, like with the following URL
http://api.example.com/users?userId=xxxx&fields=firstName,lastName,age
The problem then comes from the fact that WCF will only return to clients responses made out of serialized objects. If the objects are static then there would be no way to return dynamic responses so dynamic types need to be used. There is however one last problem in here and that is that by default dynamic types are not serializable. In the article there is a code sample that shows how to overcome this (again, I am not posting it here because of its size).
In the end, you might notice that two of the use cases I mentioned require some workarounds or 3rd party tools. This makes me think that while the .Net team has added a very cool feature to the framework, they might have only added it with COM and dynamic languages interop in mind. That would be a shame because dynamic languages have some strong advantages and providing them on a platform that combines them with the strengths of strong typed languages would probably put .Net and C# ahead of the other development platforms.
Miguel de Icaza presented a very cool use case on his blog, here (source included):
dynamic d = new PInvoke ("libc");
d.printf ("I have been clicked %d times", times);
If it is possible to do this in a safe and reliable way, that would be awesome for native code interop.
This will also allow us to avoid having to use the visitor pattern in certain cases as multi-dispatch will now be possible
public class MySpecialFunctions
{
public void Execute(int x) {...}
public void Execute(string x) {...}
public void Execute(long x) {...}
}
dynamic x = getx();
var myFunc = new MySpecialFunctions();
myFunc.Execute(x);
...will call the best method match at runtime, instead of being worked out at compile time
I will use it to simplify my code which deals with COM/Interop where before I had to specify the member to invoke, its parameters etc. (basically where the compiler didn't know about the existence of a function and I needed to describe it at compile time). With dynamic this gets less cumbersome and the code gets leaner.

Categories

Resources