I'm trying to run WebDriver + NUnit test from .txt file via .NET Framework console app, here is my demo code:
class Program
{
static void Main(string[] args)
{
string source = File.ReadAllText(#"C:\Users\user\Desktop\SomeTest.txt");
Dictionary<string, string> providerOptions = new Dictionary<string, string>
{
{"CompilerVersion", "v4.0"}
};
CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions);
CompilerParameters compilerParams = new CompilerParameters
{
GenerateInMemory = false,
GenerateExecutable = false,
};
compilerParams.ReferencedAssemblies.Add("nunit.framework.dll");
compilerParams.ReferencedAssemblies.Add("System.dll");
compilerParams.ReferencedAssemblies.Add("WebDriver.dll");
compilerParams.ReferencedAssemblies.Add("nunit.core.interfaces.dll");
compilerParams.ReferencedAssemblies.Add("nunit.core.dll");
compilerParams.OutputAssembly = #"C:\Users\user\Desktop\test.dll";
CompilerResults compileResults = provider.CompileAssemblyFromSource(compilerParams, source);
var assembly = compileResults.CompiledAssembly;
CoreExtensions.Host.InitializeService();
SimpleTestRunner runner = new SimpleTestRunner();
TestPackage package = new TestPackage(assembly.Location);
if (runner.Load(package))
{
TestResult res = runner.Run(new NullListener(),
TestFilter.Empty, false, LoggingThreshold.Off);
}
}
and I'm ending up with this error:
Unhandled Exception: System.IO.FileNotFoundException: Could not load file or assembly 'nunit.core, Version=2.6.4.14350, Culture=neutral, PublicKeyToken=96d09a1eb7f44a77' or one of its dependencies. The system cannot find the file specified.
Here are my references:
Does anyone know what is the issue here?
I found the issue, Copy Local property of these references must be set to true. It works now
Related
I was able to install Google Speech API in my Unity3D project. I am building on UWP platform (developing for Hololens)
private static async Task<object> StreamingRecognizeAsync(string filePath)
{
var speech = SpeechClient.Create();
var streamingCall = speech.StreamingRecognize();
// Write the initial request with the config.
await streamingCall.WriteAsync(
new StreamingRecognizeRequest()
{
StreamingConfig = new StreamingRecognitionConfig()
{
Config = new RecognitionConfig()
{
Encoding =
RecognitionConfig.Types.AudioEncoding.Linear16,
SampleRateHertz = 16000,
LanguageCode = "en",
},
InterimResults = true,
}
});
return null;
}
When I added this snippet mentioned here https://cloud.google.com/speech-to-text/docs/streaming-recognize#speech-streaming-recognize-csharp
it throws me an error The type 'ServiceEndpoint' is defined in an assembly that is not referenced. You must add a reference to assembly 'Google.Api.Gax.Grpc, Version=2.9.0.0, Culture=neutral'.
I clicked on AddReference, still it doesn't change anything. What do I do? I am encountering this type of problem for the first time.
I am trying to generate Semantic Model of a code file with below code:
IEnumerable<string> DefaultNamespaces =
new[]
{
"System","System.IO","System.Net","System.Linq","System.Text","System.Text.RegularExpressions","System.Collections.Generic"
};
//string runtimePath = #"C:\Program Files\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\{0}.dll";
//var z = MetadataReference.CreateFromFile(#"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETPortable\v4.5\Profile\Profile7\System.Runtime.dll");
IEnumerable<MetadataReference> DefaultReferences =
new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
};
CSharpCompilationOptions DefaultCompilationOptions =
new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithOverflowChecks(true).WithOptimizationLevel(OptimizationLevel.Release).WithUsings(DefaultNamespaces);
var compilation = CSharpCompilation.Create("Test.dll", new SyntaxTree[] { syntaxTree }, DefaultReferences, DefaultCompilationOptions);
var result = compilation.GetSemanticModel(syntaxTree, true);
But line :
IEnumerable<MetadataReference> DefaultReferences =
new[]
{
MetadataReference.CreateFromFile(typeof(object).Assembly.Location)
};
is throwing exception:
Could not load file or assembly 'System.Reflection.Metadata.
Please help me to fix this.
You need to set Copy Local to true in the properties for that reference in your project (if it isn't referenced, add it from NuGet).
Roslyn needs this DLL at runtime.
EDIT: Never mind, it turns that out the task does not actually implement the Microsoft.Build.Framework.ITask interface. I had made the erroneous assumption that it did. D'oh!
I use Visual Studio 2015.
Relevant code:
string solutionFilePath = args.Single();
var fileLogger = new FileLogger { Verbosity = LoggerVerbosity.Detailed, Parameters = #"logfile=C:\MSBuildResults.txt" };
var projectCollection = new ProjectCollection {DefaultToolsVersion = "14.0"};
var buildParameters = new BuildParameters(projectCollection) { Loggers = new List<ILogger> { fileLogger } };
var globalProperties = new Dictionary<string, string> { { "Configuration", "Debug" }, { "Platform", "Any CPU" } };
var buildRequestData = new BuildRequestData(solutionFilePath,
globalProperties,
targetsToBuild: new[] { "Build" },
toolsVersion: "14.0",
hostServices: null);
BuildResult buildResult = BuildManager.DefaultBuildManager.Build(buildParameters, buildRequestData);
buildResult.OverallResult is BuildResultCode.Failure, with error messages like the following printed to my log file:
C:\Workspaces\SomeProject.csproj(67,5): error MSB4127: The "DummyTask"
task could not be instantiated from the assembly
"\networkDrive\Dummy.dll". Please verify the task assembly has been
built using the same version of the Microsoft.Build.Framework assembly
as the one installed on your computer and that your host application
is not missing a binding redirect for Microsoft.Build.Framework.
Unable to cast object of type 'DummyTask' to type
'Microsoft.Build.Framework.ITask'.
Following the advice here, I added the <bindingRedirect> tag in the .exe.config file of my program. The same error messages were thrown nonetheless.
Instead of using Microsoft.Build libraries, I decided to invoke MSBuild.exe using Process.Start() (which I know is not recommended):
var processStartInfo = new ProcessStartInfo(#"C:\Program Files (x86)\MSBuild\14.0\Bin\MSBuild.exe")
{
Arguments = $"{solutionFilePath} /t:Build",
RedirectStandardOutput = false,
UseShellExecute = true,
CreateNoWindow = false
};
var process = Process.Start(processStartInfo);
process.WaitForExit();
process.Close();
This time, the build was successful and the process ran to completion with exit code 0.
What did I do wrong when using Microsoft.Build libraries to build my solution? What should I do instead to ensure that the build succeeds when I use BuildManager?
Let me know if you need any more information to help me with my issue.
Hello I have been trying to figure this out for a while now and cannot get it correct. I have found a few threads that do similar to what I want to do. but I keep getting a system.Io Assembly cannot be found compile and run the string that was created.
private bool CalculateBooleanExpression(string expression)
{
var classExpression = stringClass.Replace(ReplaceMe,expression);
var complierParameters = new CompilerParameters()
{
GenerateExecutable=false,
GenerateInMemory = true
};
var complier = new CSharpCodeProvider();
var compilerResults = complier.CompileAssemblyFromSource(complierParameters, classExpression);
//break point here compilerResults.CompiledAssembly is null
object typeInstance = compilerResults.CompiledAssembly.CreateInstance("BooleanEvaluator");
MethodInfo methodInfo = typeInstance.GetType().GetMethod("Calculate");
bool value = (bool)methodInfo.Invoke(typeInstance, new object[] { });
return true;
}
Could not load file or assembly 'file:///C:\Users\james.tays\AppData\Local\Temp\22ozhhme.dll' or one of its dependencies. The system cannot find the file specified.
can anyone tell me how to debug this so i can figure out where there error is?
EDIT:
While debugging I have found this error too.
error CS0116: A namespace cannot directly contain members such as fields or methods}
I'm trying to compile an assembly from my code with C# code provider.
When I access the compiled assembly with compilerResult.CompiledAssembly, everything works. However, when I instead do Assembly.Load(path), I get the following exception:
System.IO.FileLoadException : Could not load file or assembly
'C:\Users\Name\Desktop\output.dll' or one of its dependencies. The
given assembly name or codebase was invalid. (Exception from HRESULT:
0x80131047)
What am I doing wrong?
Here's the code:
[Test]
public static void CompileCodeIntoAssembly()
{
var code = "public class X { }";
var file = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "output.cs");
File.WriteAllText(file, code);
using (var provider = new CSharpCodeProvider())
{
var parameters = new CompilerParameters
{
GenerateInMemory = false, // we want the dll saved to disk
GenerateExecutable = false,
CompilerOptions = "/target:library /lib:\"" + typeof(Class2).Assembly.Location + "\"",
OutputAssembly = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "output.dll"),
};
parameters.ReferencedAssemblies.AddRange(new[]
{
"System.dll",
typeof(Class1).Assembly.Location,
});
var compilerResult = provider.CompileAssemblyFromFile(parameters, file);
if (compilerResult.Errors.Count > 0)
{
compilerResult.Errors.Cast<object>().ToDelimitedString(Environment.NewLine).Dump();
throw new Exception();
}
var assembly = Assembly.Load(parameters.OutputAssembly);
//var assembly = compilerResult.CompiledAssembly; // this method works
var type = assembly.GetTypes().Single(t => t.Name == "X");
}
You need to use the method .LoadFile if you want to load an assembly from a file path:
var assembly = Assembly.LoadFile(parameters.OutputAssembly);
^^^^
According to the documentation, the method .Load:
Loads an assembly given the long form of its name.
It expects an assembly name, like SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3