Moq does not want to work with ActiroSoftware on net core 3.1
I'm having the following issue: creating a net core 3.1 project with the following structure:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp3.1</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Moq" Version="4.14.7" />
<PackageReference Include="Actiprosoftware.Controls.WPF" Version="20.1.0" />
</ItemGroup>
</Project>
then in Program.cs try to write the following:
using Moq;
namespace moqtest
{
class Program
{
static void Main(string[] args)
{
var q = It.IsAny<string>();
}
}
}
Note that this won't compile, due to the following error:
error CS0234: The type or namespace name 'IsAny' does not exist in the namespace 'It' (are you missing an assembly reference?)
Furthermore, specifying the namespace implicitly, will work:
var q = Moq.It.IsAny<string>();
I have looked into msbuild diagnostics and it seems everything is compatible with netcoreapp3.1, but when you compile it, it seems it does not recognize It class anymore.
Please help!
Open up View > Object Browser, and search for It. You'll notice that first result is a namespace called It brought in by ActiproSoftware.BarCode.Wpf.dll
It also happens to be an empty namespace, but that's irrelevant. If it did contain anything under it, you'd refer to them as It.Something. So what happens now is that, even after you do using Moq, It is still ambiguous to the compiler.
The presence of that silly empty namespace is what's forcing to qualify your calls with Moq.
Related
I removed my IsExternalInit definition, as we are now using .net 5.0:
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<WarningsAsErrors>nullable</WarningsAsErrors>
</PropertyGroup>
However I still get this error
CS0518 Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported
In files like this
public sealed record TestDTO
{
public string SomePropert{ get; private init; } = default!; // error occurs here
}
I can see this is expected behaviour when targeting older frameworks, but shouldn't it work in my case? What am I doing wrong?
I think this is happening because one of the projects I reference has a dependency on some library using .net standard
To avoid adding IsExternalInit.cs to every project, I just added one to the solution root folder and also added a file called Directory.Build.Props with these contents
<?xml version="1.0" encoding="utf-8"?>
<Project>
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)IsExternalInit.cs" Visible="false" />
</ItemGroup>
</Project>
I am trying do a very simple thing in console app:
using Microsoft.Azure.WebJobs.Extensions.Timers;
using NCrontab;
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
var nCrontabSchedule = CrontabSchedule.Parse("5 4 * * * *");
}
}
}
But it gives me this error:
Severity Code Description Project File Line Suppression State
Error CS0433 The type 'CrontabSchedule' exists in both 'NCrontab.Signed, Version=3.2.20120.0, Culture=neutral, PublicKeyToken=5247b4370afff365' and 'NCrontab, Version=3.2.20120.0, Culture=neutral, PublicKeyToken=null' ConsoleApp3 C:\Users\bowmanzh\source\repos\ConsoleApp3\Program.cs 12 Active
It didn't even finish compile! It’s hard for me to understand what’s going on here, I just want to use a simple thing.
Why is there a version conflict here? In fact, I referenced two packages, this is my .csproj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.6" />
<PackageReference Include="NCrontab" Version="3.2.0" />
</ItemGroup>
</Project>
I have already googled, they say something like Aliases, but in fact on my side it doesn't have this property.
I have already tried:
using v2 = NCrontab;
using System;
using Microsoft.Azure.WebJobs.Extensions.Timers;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
v2.CrontabSchedule nCrontabSchedule = v2.CrontabSchedule.Parse("5 4 * * *");
}
}
}
But it didn't work.
How can I solve this problem?
Thank you so much for taking the time to check!
I encountered this same problem. Trying unstalling the NCrontab nuget package and installing NCrontab.Signed instead. This resolved the issue for me.
I am currently building a tool which will support the development of an ASP.NET Core project. This tool uses the Roslyn APIs and other methods for verifying some development requirements (such as project-specific attributes being applied on API Controllers, enforcing naming conventions, and generating some source code for the JavaScript SPA which accesses an API written using the ASP.NET Core Web API template).
In order to do that, I am currently using hardcoded paths to generate code for the SPA app. But in the app's *.csproj file there is actually a "SpaRoot" property specifying where the SPA application is located inside the project:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TypeScriptCompileBlocked>true</TypeScriptCompileBlocked>
<TypeScriptToolsVersion>Latest</TypeScriptToolsVersion>
<IsPackable>false</IsPackable>
<SpaRoot>ClientApp\</SpaRoot>
...
</PropertyGroup>
...
</Project>
My question is: how can I read the "SpaRoot" property's value using the Roslyn APIs?
I have written a minimum code sample to create a Workspace, open the Solution, and retrieve the Project's reference, which resembles the following:
static async Task Main(string[] args)
{
string solutionFile = #"C:\Test\my-solution.sln";
using (var workspace = MSBuildWorkspace.Create())
{
var solution = await workspace.OpenSolutionAsync(solutionFile);
string projectName = "some-project";
var project = solution.Projects.Single(p => p.Name == projectName);
// How to extract the value of "SpaRoot" from the Project here?
}
I've tried searching on how to extract the "SpaRoot" property from the Project reference, and even went as far as debugging to see if I could spot a way myself. Unfortunately, I came up with no answers to that, and I'm still using hardcoded paths in my original code.
Is it even possible to retrieve the value of .csproj properties of a Project using the current Roslyn APIs?
This is more difficult that you would think :) The Roslyn apis only know what the compiler knows and the compiler is not going to be given anything regarding the SpaRoot property. We can use the MSBuild apis to figure this out though. specifically the Microsoft.Build.Evaluation.Project class.
Some assumptions I am making
You only want to examine .NET Core projects
You will have the .NET Core SDK installed on which ever system runs this tool
So first we want a project file that looks like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<!--NOTE: If the project you are analyzing is .NET Core then the commandline tool must be as well.
.NET Framework console apps cannot load .NET Core MSBuild assemblies which is required
for what we want to do.-->
<TargetFramework>netcoreapp3.1</TargetFramework>
<LangVersion>Latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<!-- NOTE: We put ExcludeAssets="runtime" on all direct MSBuild references so that we pick up whatever
version is being used by the .NET SDK instead. This is accomplished with the Microsoft.Build.Locator
referenced further below. -->
<PackageReference Include="Microsoft.Build" Version="16.4.0" ExcludeAssets="runtime" />
<PackageReference Include="Microsoft.Build.Locator" Version="1.2.6" />
<PackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="2.9.8" PrivateAssets="all" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.VisualBasic.Workspaces" Version="3.4.0" />
<PackageReference Include="Microsoft.CodeAnalysis.Workspaces.MSBuild" Version="3.4.0" />
<!-- NOTE: A lot of MSBuild tasks that we are going to load in order to analyze a project file will implicitly
load build tasks that will require Newtonsoft.Json version 9. Since there is no way for us to ambiently
pick these dependencies up like with MSBuild assemblies we explicitly reference it here. -->
<PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
</ItemGroup>
</Project>
and a Program.cs file that looks like this:
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.Build.Evaluation;
using Microsoft.Build.Locator;
using Microsoft.CodeAnalysis.MSBuild;
// I use this so I don't get confused with the Roslyn Project type
using MSBuildProject = Microsoft.Build.Evaluation.Project;
namespace loadProject {
class Program {
static async Task Main(string[] args) {
MSBuildWorkspaceSetup();
// NOTE: we need to make sure we call MSBuildLocator.RegisterInstance
// before we ask the CLR to load any MSBuild types. Therefore we moved
// the code that uses MSBuild types to its own method (instead of being in
// Main) so the CLR is not forced to load them on startup.
await DoAnalysisAsync(args[0]);
}
private static async Task DoAnalysisAsync(string solutionPath) {
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);
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}'");
// We just select the first project as a demo
// you will want to use your own logic here
var project = solution.Projects.First();
// Now we use the MSBuild apis to load and evaluate our project file
using var xmlReader = XmlReader.Create(File.OpenRead(project.FilePath));
ProjectRootElement root = ProjectRootElement.Create(xmlReader, new ProjectCollection(), preserveFormatting: true);
MSBuildProject msbuildProject = new MSBuildProject(root);
// We can now ask any question about the properties or items in our project file
// and get the correct answer
string spaRootValue = msbuildProject.GetPropertyValue("SpaRoot");
}
private static void MSBuildWorkspaceSetup() {
// Attempt to set the version of MSBuild.
var visualStudioInstances = MSBuildLocator.QueryVisualStudioInstances().ToArray();
var instance = visualStudioInstances.Length == 1
// If there is only one instance of MSBuild on this machine, set that as the one to use.
? visualStudioInstances[0]
// Handle selecting the version of MSBuild you want to use.
: SelectVisualStudioInstance(visualStudioInstances);
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);
}
private static VisualStudioInstance SelectVisualStudioInstance(VisualStudioInstance[] visualStudioInstances) {
Console.WriteLine("Multiple installs of MSBuild detected please select one:");
for (int i = 0; i < visualStudioInstances.Length; i++) {
Console.WriteLine($"Instance {i + 1}");
Console.WriteLine($" Name: {visualStudioInstances[i].Name}");
Console.WriteLine($" Version: {visualStudioInstances[i].Version}");
Console.WriteLine($" MSBuild Path: {visualStudioInstances[i].MSBuildPath}");
}
while (true) {
var userResponse = Console.ReadLine();
if (int.TryParse(userResponse, out int instanceNumber) &&
instanceNumber > 0 &&
instanceNumber <= visualStudioInstances.Length) {
return visualStudioInstances[instanceNumber - 1];
}
Console.WriteLine("Input not accepted, try again.");
}
}
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}");
}
}
}
}
after I followed the instructions on the following articles
https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-first-azure-function
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs
I have created an EventHubTrigger, which looks like this:
using System;
public static void Run(string myEventHubMessage, ILogger log)
{
log.LogInformation($'C# Event Hub trigger function processed a message: {myEventHubMessage}');
}
This did work without any problems, but since I do need additional meta information, I changed the code to the following (described in the second linked article):
#r 'Microsoft.ServiceBus'
using System.Text;
using System;
using Microsoft.ServiceBus.Messaging;
public static void Run(EventData myEventHubMessage, ILogger log)
{
log.LogInformation($'EnqueuedTimeUtc={myEventHubMessage.EnqueuedTimeUtc}');
log.LogInformation($'SequenceNumber={myEventHubMessage.SequenceNumber}');
log.LogInformation($'Offset={myEventHubMessage.Offset}');
}
But this code results in the following error messages (btw I have also tied to use the deprected TraceWriter instead of ILogger to exactly follow the article but this results in the same error)
2018-10-11T14:22:24.814 [Error] run.csx(1,1): error CS0006: Metadata file 'Microsoft.ServiceBus' could not be found
2018-10-11T14:22:24.903 [Error] run.csx(4,17): error CS0234: The type or namespace name 'ServiceBus' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
My question is now, does anyone have a clue what to do in order to get this small piece of code running?
Of course it has to have something to do with the assemblies but the aricle states, that when working in the online portal-editor, there are no further steps to do,.
Man thanks in advance
Felix
PS:
host.json :
{
"version": "2.0"
}
Content of extensions.csproj is:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsAsErrors />
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.EventHubs" Version="3.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="3.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator" Version="1.0.1" />
</ItemGroup>
</Project>
Well, the sample is for function 1.x. After 2.x is generally available the function we create is on ~2 runtime by default, as we can see "version":"2.0" in host.json.
Have a try at code below, metadata is stored in SystemProperties of Microsoft.Azure.EventHubs.EventData.
#r "../bin/Microsoft.Azure.EventHubs.dll"
using System;
using Microsoft.Azure.EventHubs;
public static void Run(EventData myEventHubMessage, ILogger log)
{
log.LogInformation($"EnqueuedTimeUtc={myEventHubMessage.SystemProperties.EnqueuedTimeUtc}");
log.LogInformation($"SequenceNumber={myEventHubMessage.SystemProperties.SequenceNumber}");
log.LogInformation($"Offset={myEventHubMessage.SystemProperties.Offset}");
}
Also note that we need to use double quotation " for string in C#, see ' in your code.
This is my first question here and I am hoping I will be able to receive some help.
To preface what I am trying to do is run a Data Driven test script using MSTest on VSCode.
When I attempt to get the value from the file by using
string webSiteTwo = TestContext.DataRow["Website"];
DataRow is showing an error saying:
'TestContext' does not contain a definition for 'DataRow' and no
extension method 'DataRow' accepting a first argument of type
'TestContext' could be found (are you missing a using directive or an
assembly reference?)
When looking online the DataRow object seems to come from System.Data so I added using System.Data to my program to see if that settled it, but that did not work. I then tried to add using System.Data.Datarow to see if that worked but it seems that I do not have the assemblies for that.
I was wondering if anyone has run into this problem and if they have how did they fix it.
I am using a Macbook Pro, with VSCode 1.20.1, C#
.csproj file includes these References.
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0"/>
<PackageReference Include="MSTest.TestAdapter" Version="1.2.0"/>
<PackageReference Include="MSTest.TestFramework" Version="1.2.0"/>
<PackageReference Include="Selenium.WebDriver" Version="3.10.0"/>
<PackageReference Include="Appium.WebDriver" Version="3.0.0.2"/>
<PackageReference Include="System.Data.Common" Version="4.3.0"/>
I have set up both the Datasource and
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
According to the docs, the correct Namespace is:
using Microsoft.VisualStudio.TestTools.UnitTesting;
Take a look here: TestContext.DataRow