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.
Related
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
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
I’m running Visual Studio 2015 and Windows 8.1. I am struggling with a console application project.
The solution works fine in Visual Studio 2015, but when I try to compile it with mcs-compiler I get two errors (Kattis codetest use mcs-kompiler). Two external classes can not be found.
I'm getting the following error:
Program.cs(28,13): error CS0246: The type or namespace name Graph'
could not be found. Are you missing an assembly reference?
Program.cs(58,34): error CS0246: The type or namespace nameSolver'
could not b e found. Are you missing an assembly reference?
Compilation failed: 2 error(s), 0 warnings
The code is large so a I have pasted in just parts of it:
The Program class, where main is and the calls to ”Graph” and ”Solver” are made from:
Call in Program.cs:
-----------------------------------------------------------------------------
// first call:
var edges = CliquesToEdges(cliques);
sudokuColour.Graph graph = new Graph(81, edges);
string line = "";
string storeLine = "";
string puzzle = "";
.
.
.
// second call:
for (int i = 0; i < store.Count(); i++)
{
puzzle = store.ElementAt(i);
sudokuColour.Solver solver = new Solver(graph, 9);
int node = -1;
foreach (char c in puzzle)
{
----------------------------------------------------------------------------
//Beginning of "Graph" class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using sudokuColour;
namespace sudokuColour
{
public class Graph
{
.
.
----------------------------------------------------------------------------
//Beginning of "Solver" class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using sudokuColour;
namespace sudokuColour
{
public class Solver
{
private enum Result { Solved, Unsolved, Busted }
private readonly Graph graph;
----------------------------------------------------------------------------
What can the error be?
sudokuColour.Solver solver = new Solver(graph, 9);
The fact that you had to namespace-qualify it on the left probably means you should namespace-qualify it on the right too:
sudokuColour.Solver solver = new sudokuColour.Solver(graph, 9);
Alternatively, add a using directive at the top of the code file:
using sudokuColour;
or:
using Solver = sudokuColour.Solver;
likewise for:
sudokuColour.Graph graph = new Graph(81, edges);
If that still doesn't work: you're probably missing a project reference (or package reference, or assembly reference - but a project reference seems the most appropriate) between the two projects.
I am new in C#, and I have spent the entire night just trying to compile my code. I am not asking for a logic, but rather some help with compiling using csc.
I have an app that uses System.Net.Http, and I am trying to get it compiled into an executable using csc, but I always get the following result:
C:\Users\farao\Documents\Visual Studio 2017\source\repos\SimpleWebCrawlerApp\SimpleWebCrawlerApp>csc Program.cs
Microsoft (R) Visual C# Compiler version 2.6.0.62329 (5429b35d)
Copyright (C) Microsoft Corporation. All rights reserved.
Program.cs(4,18): error CS0234: The type or namespace name 'Http' does not exist in the namespace 'System.Net' (are you missing an assembly reference?)
C:\Users\farao\Documents\Visual Studio 2017\source\repos\SimpleWebCrawlerApp\SimpleWebCrawlerApp>
However, I can compile in Visual Studio 2017, but I do need to compile it using csc for quick distribution.
I tried almost everything from this link
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Collections;
using System.Text.RegularExpressions;
namespace SimpleWebCrawlerApp
{
class Program
{
internal static int SUCCESS = 0;
internal static int FAIL = -1;
static void Main(string[] args)
{
TextWriter errorWriter = Console.Error;
if (args.Length != 2)
{
errorWriter.WriteLine("usage: <program_name>.exe <http/https url> <number of hops>");
}
else
{
if (IsValidUrl(args[0]))
{
int hops;
if (int.TryParse(args[1], out hops))
{
new HTTPCrawler(args[0], hops).Crawl();
Environment.Exit(SUCCESS);
}
errorWriter.WriteLine("not a valid integer for number of hops");
}
else
{
errorWriter.WriteLine("observe proper http/https protocol");
}
}
Environment.Exit(FAIL);
}
I solved my problem thanks to UnholySheep.
csc /r:System.Net.Http.dll Program.cs
References:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/reference-compiler-option
https://msdn.microsoft.com/en-us/library/system.net.http.httpclient(v=vs.118).aspx
I want to use the Bluetooth LE functions in .NET Core (specifically, BluetoothLEAdvertisementWatcher) to write a scanner which logs information to a file. This is to run as a desktop application and preferably as a command line app.
Constructors like System.IO.StreamWriter(string) are not available, apparently. How do I create a file and write to it?
I would be just as happy to be able to do a System.Console.WriteLine(string) but that doesn't seem to be available under .NET Core either.
Update: To clarify, if I could have a program that looks like this run without error, I'll be off to the races.
using System;
using Windows.Devices.Bluetooth.Advertisement;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
BluetoothLEAdvertisementWatcher watcher = new BluetoothLEAdvertisementWatcher();
Console.WriteLine("Hello, world!");
}
}
}
Update 2: Here's the project.json file:
{
"dependencies": {
"Microsoft.NETCore.UniversalWindowsPlatform": "5.0.0"
},
"frameworks": {
"uap10.0": {}
},
"runtimes": {
"win10-arm": {},
"win10-arm-aot": {},
"win10-x86": {},
"win10-x86-aot": {},
"win10-x64": {},
"win10-x64-aot": {}
}
}
The output of the command dotnet -v run contains this error message:
W:\src\dotnet_helloworld>dotnet -v run
...
W:\src\dotnet_helloworld\Program.cs(2,15): error CS0234: The type or namespace name 'Devices' does not exist in the namespace 'Windows' (are you missing an assembly reference?)
...
This code is the skeleton I was looking for when I posed the question. It uses only facilities available in .NET Core.
var watcher = new BluetoothLEAdvertisementWatcher();
var logPath = System.IO.Path.GetTempFileName();
var logFile = System.IO.File.Create(logPath);
var logWriter = new System.IO.StreamWriter(logFile);
logWriter.WriteLine("Log message");
logWriter.Dispose();
This is the solution I'm using. It uses fewer lines of code and does the job just as good. It's also very compatible with .NET core 2.0
using (StreamWriter writer = System.IO.File.AppendText("logfile.txt"))
{
writer.WriteLine("log message");
}
Even better:
using System.IO;
var logPath = Path.GetTempFileName();
using (var writer = File.CreateText(logPath)) // or File.AppendText
{
writer.WriteLine("log message"); //or .Write(), if you wish
}
If writing fewer lines of code is your thing, the above can be re-written as
using (var writer = System.IO.File.CreateText(System.IO.Path.GetTempFileName()))
{
writer.WriteLine("log message"); //or .Write(), if you wish
}
As of today, with RTM, there seems to be this shorter way as well:
var watcher = new BluetoothLEAdvertisementWatcher();
var logPath = System.IO.Path.GetTempFileName();
var logWriter = System.IO.File.CreateText(logPath);
logWriter.WriteLine("Log message");
logWriter.Dispose();
To write to files in .NET Core, you can use two methods:
AppendText()
CreateText()
These two methods are static members of the File class in the System.IO namespace. The difference between them is one appends to an existing file while the other overwrites the file.
Usage examples:
AppendText
using (StreamWriter writer = System.IO.File.AppendText("file.txt"))
{
writer.WriteLine("message");
}
CreateText
using (StreamWriter writer = System.IO.File.CreateText("file.txt"))
{
writer.WriteLine("message");
}
You can get the System.IO references by using the corefx git repository. This will make the StreamWrite(string) constructor you are looking for available.
This repository will also give you the Console.WriteLine(string) function you are looking for.
Here is an async FileWriter class.
using System.IO;
public static class AsyncFileWriter
{
public static async Task WriteToFile(string content)
{
var logPath = #"SOME_PATH\log.txt";
using (var writer = File.CreateText(logPath))
{
await writer.WriteLineAsync(content);
}
}
}