Compile using babel in a C#/.NET project - c#

Trying to use babel to compile some code in C#/.NET project, following the example https://babeljs.io/setup#installation for C#/.NET.
Installed the package React.Core using NuGet Package Manager (Install-Package React.Core) in a simple Hello world project (https://learn.microsoft.com/en-us/dotnet/core/tutorials/with-visual-studio-code).
using System;
using React;
//using React.Web;
//using React.TinyIoC;
//using React.Web.Mvc4;
//using React.Web.TinyIoC;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// Console.WriteLine("Hello World!");
var babel = ReactEnvironment.Current.Babel;
// Transpiles a file
// You can instead use `TransformFileWithSourceMap` if you want a source map too.
// var result = babel.TransformFile("foo.js");
// Transpiles a piece of code
var result = babel.Transform("class Foo { }");
Console.WriteLine(result);
}
}
}
Alls getting error at: Unhandled Exception: React.TinyIoC.TinyIoCResolutionException: Unable to resolve type: React.IReactEnvironment
at React.TinyIoC.TinyIoCContainer.ResolveInternal
following this post tried adding the package React.Web and React.Web.Mvc4 but still get the same error, am importing the wrong packages?? or what is it? the version of the packages React.Core and the other are 5.1.0

Related

How to find out Target framework name and version from exe?

I have some exe files which has been created using either .net framework 4.5 or .net core 2.1 or .net core 3.1.
I want to get framework name and version information from this DLL using only c# application.
I have written below piece of code which is beneficial and works great with DLL files but not with exe.
var dllInformation = Assembly.LoadFrom(#"D:\\MyProgram.dll");
Console.WriteLine(dllInformation.FullName);
Console.WriteLine(dllInformation.ImageRuntimeVersion);
Console.WriteLine(((TargetFrameworkAttribute)dllInformation.GetCustomAttributes(typeof(TargetFrameworkAttribute)).First()).FrameworkName);
I have also gone through these links but I didn't found them useful for exe files:
information from exe file
Determine .NET Framework version for dll
Please let me know if any suggestions available.
The following program should display the version of the assembly. The program
loads two assemblies during runtime using Assembly.LoadFrom method. 1) is a .NET Fx assembly and 2) is a .NET Core assembly. It loads both and displays the framework version without issues. This project is in github. If you are using the github project, you need to have .NET Core 3.1 installled.
using System;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
namespace net007
{
class Program
{
static void Main(string[] args)
{
//A .net framwwork dll in the same output fodler
//as the current executable
var fxAssembly = Assembly.LoadFrom("fx.console.app.exe");
//A .net core dll in the same output fodler
//as the current executable
var netCoreAssembly = Assembly.LoadFrom("core.console.app.dll");
ShowFrameworkVersion(fxAssembly); //.NETFramework,Version=v4.7.2
ShowFrameworkVersion(netCoreAssembly);//.NETCoreApp,Version = v3.1
}
static void ShowFrameworkVersion(Assembly assembly)
{
var attributes = assembly.CustomAttributes;
foreach (var attribute in attributes)
{
if (attribute.AttributeType == typeof(TargetFrameworkAttribute))
{
var arg = attribute.ConstructorArguments.FirstOrDefault();
if (arg == null)
throw new NullReferenceException("Unable to read framework version");
Console.WriteLine(arg.Value);
}
}
}
}
}
You can use PowerShell to detect for the target framework version:
$path = "C:\your dll here.dll"
[Reflection.Assembly]::ReflectionOnlyLoadFrom($path).CustomAttributes |
Where-Object {$_.AttributeType.Name -eq "TargetFrameworkAttribute" } |
Select-Object -ExpandProperty ConstructorArguments |
Select-Object -ExpandProperty value
This is my full class to get an "Name.exe" target framework.
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Versioning;
public class TargetVersionChecker : MarshalByRefObject
{
public string GetTargetedFrameWork(string exePath)
{
Assembly fxAssembly;
try
{
fxAssembly = Assembly.ReflectionOnlyLoadFrom(exePath);
var targetFrameworkAttribute = fxAssembly.GetCustomAttributesData().FirstOrDefault(x => x.AttributeType == typeof(TargetFrameworkAttribute));
return targetFrameworkAttribute?.ConstructorArguments.FirstOrDefault().Value.ToString();
}
catch (Exception ex)
{
// I log here the error but is to specific to our system so I removed it to be more simple code.
return string.Empty;
}
}
}

Having trouble including MediaFile in .NET project

I've never used .NET or C# before, so this might be an easy one. I'm on a mac running this project from the command line and using VScode to edit. I created an app using the command dotnet new console -o myApp. The error I get when I try dotnet run is:
Program.cs(3,7): error CS0246: The type or namespace name 'MediaFile'
could not be found (are you missing a using directive or an assembly
reference?) [/Users/me/myApp/myApp.csproj]
The build failed. Fix the build errors and run again.
Here is my code. I'm attempting to use a library called MediaToolkit to convert a video from flv to mp4
using System;
using MediaToolkit; // installed using command: 'dotnet add package MediaFile'
// using MediaFile; doesn't work
namespace myApp
{
class Program
{
static void Main(string[] args)
{
var inputFile = new MediaFile {Filename = "/Users/me/Desktop/example.flv"};
var outputFile = new MediaFile {Filename = "/Users/me/Desktop/example.mp4"};
using (var engine = new Engine())
{
engine.Convert(inputFile, outputFile);
}
}
}
}
using MediaToolkit.Model;
try this namespace.It works in my code.

How to properly use ControlFlowGraph from roslyn code analysis in C#

I cannot understand why I am getting an error (using VS2017) for the code in below related to not finding the class ControlFlowGraph which is supposed to be part of the package Microsoft.CodeAnalysis.FlowAnalysis:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.FlowAnalysis;
namespace CodeAnalysisApp3
{
class Program
{
static async Task Main(string[] args)
{
// Attempt to set the version of MSBuild.
var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray();
var instance = visualStudioInstances[0];
Console.WriteLine($"Using MSBuild at '{instance.MSBuildPath}' to load projects.");
// NOTE: Be sure to register an instance with the MSBuildLocator
// before calling MSBuildWorkspace.Create()
// otherwise, MSBuildWorkspace won't MEF compose.
MSBuildLocator.RegisterInstance(instance);
using (var workspace = MSBuildWorkspace.Create())
{
// Print message for WorkspaceFailed event to help diagnosing project load failures.
workspace.WorkspaceFailed += (o, e) => Console.WriteLine(e.Diagnostic.Message);
var solutionPath = args[0];
Console.WriteLine($"Loading solution '{solutionPath}'");
// Attach progress reporter so we print projects as they are loaded.
var solution = await workspace.OpenSolutionAsync(solutionPath, new ConsoleProgressReporter());
Console.WriteLine($"Finished loading solution '{solutionPath}'");
// TODO: Do analysis on the projects in the loaded solution
CSharpParseOptions options = CSharpParseOptions.Default
.WithFeatures(new[] { new KeyValuePair<string, string>("flow-analysis", "") });
var projIds = solution.ProjectIds;
var project = solution.GetProject(projIds[0]);
Compilation compilation = await project.GetCompilationAsync();
if (compilation != null && !string.IsNullOrEmpty(compilation.AssemblyName))
{
var mySyntaxTree = compilation.SyntaxTrees.First();
// get syntax nodes for methods
var methodNodes = from methodDeclaration in mySyntaxTree.GetRoot().DescendantNodes()
.Where(x => x is MethodDeclarationSyntax)
select methodDeclaration;
foreach (MethodDeclarationSyntax node in methodNodes)
{
var model = compilation.GetSemanticModel(node.SyntaxTree);
node.Identifier.ToString();
if (node.SyntaxTree.Options.Features.Any())
{
var graph = ControlFlowGraph.Create(node, model); // CFG is here
}
}
}
}
}
private class ConsoleProgressReporter : IProgress<ProjectLoadProgress>
{
public void Report(ProjectLoadProgress loadProgress)
{
var projectDisplay = Path.GetFileName(loadProgress.FilePath);
if (loadProgress.TargetFramework != null)
{
projectDisplay += $" ({loadProgress.TargetFramework})";
}
Console.WriteLine($"{loadProgress.Operation,-15} {loadProgress.ElapsedTime,-15:m\\:ss\\.fffffff} {projectDisplay}");
}
}
}
}
However, when I compile the above code I am getting the following error message with VS2017:
1>Program.cs(67,41,67,57): error CS0103: The name 'ControlFlowGraph' does not exist in the current context
1>Done building project "CodeAnalysisApp3.csproj" -- FAILED.
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========
Version used:
Microsoft (R) Visual C# Compiler version 4.8.3761.0
for C# 5
Based on my test, I find I can use class ControlFlowGraph.
I installed the following nugetpackage.
Microsoft.CodeAnalysis
Microsoft.Build.Locator
Then, you will see the following result.
Besides, I used .net framwork 4.6.1.
I was able to solve the problem when I used roslyn CodeAnalysis packages with the proper versions:
CodeAnalysis.CSharp.Workspaces (3.4.0)
CodeAnalysis.FlowAnalysis.Utilities (2.9.6)
CodeAnalysis.Workspaces.MSBuild (3.4.0)
The target framework is .NETFramework 4.7.2
A link to a closed issue created for this question on roslyn Github repo is here

Change application type with Mono.Cecil?

How can I modify an application from Console Application Type to Windows Application Type and vice versa with Mono.Cecil?
To convert a console .exe to windows .exe, you can use:
var file = "foo.exe";
var module = ModuleDefinition.ReadModule (file);
// module.Kind was previously ModuleKind.Console
module.Kind = ModuleKind.Windows;
module.Write (file);
The other way around is as simple as choosing the appropriate ModuleKind value. From Cecil's source:
public enum ModuleKind {
Dll,
Console,
Windows,
NetModule,
}
For people who needed more help on this like me :)
you may need the apt pacakge libmono-cecil-cil-dev
//mono-cecil-set-modulekind-windows.cs
using System;
using Mono.Cecil;
namespace CecilUtilsApp {
class CecilUtils {
static void Main(string[] args) {
var file = args[0];
var module = ModuleDefinition.ReadModule (file);
module.Kind = ModuleKind.Windows;
module.Write (file);
}
}
}
// -----
//Makefile
//mono-cecil-set-modulekind-eq-windows.exe:
// mcs $(shell pkg-config --libs mono-cecil) ./mono-cecil-set-modulekind-windows.cs
./mono-cecil-set-modulekind-windows.exe myprog.exe

How can I use Ruby code in .NET?

I'd like to use a RubyGem in my C# application.
I've downloaded IronRuby, but I'm not sure how to get up and running. Their download includes ir.exe, and it includes some DLLs such as IronRuby.dll.
Once IronRuby.dll is referenced in my .NET project, how do I expose the objects and methods of an *.rb file to my C# code?
Thanks very much,
Michael
This is how you do interop:
Make sure you have refs to IronRuby, IronRuby.Libraries, Microsoft.Scripting and Microsoft.Scripting.Core
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IronRuby;
using IronRuby.Builtins;
using IronRuby.Runtime;
namespace ConsoleApplication7 {
class Program {
static void Main(string[] args) {
var runtime = Ruby.CreateRuntime();
var engine = runtime.GetRubyEngine();
engine.Execute("def hello; puts 'hello world'; end");
string s = engine.Execute("hello") as string;
Console.WriteLine(s);
// outputs "hello world"
engine.Execute("class Foo; def bar; puts 'hello from bar'; end; end");
object o = engine.Execute("Foo.new");
var operations = engine.CreateOperations();
string s2 = operations.InvokeMember(o, "bar") as string;
Console.WriteLine(s2);
// outputs "hello from bar"
Console.ReadKey();
}
}
}
Note, Runtime has an ExecuteFile which you can use to execute your file.
To get the Gems going
Make sure you install your gem using igem.exe
you will probably have to set some search paths using Engine.SetSearchPaths

Categories