I have a working Mongo and .Net Core app, but still need to access the mongo DB through C#. I am just testing this by trying to make the connection in the program.cs file. At the top I have:
using MongoDB.Driver;
using MongoDB.Driver.Core;
using MongoDB.Bson;
When I run:
var mongo = new MongoClient("mongodb://localhost:27017");
var db = mongo.GetDatabase("cvpz");
mongo.getCollection("people");
I get this error:
Program.cs(16,19): error CS1061: 'MongoClient' does not contain a definition for 'getCollection' and no extension method 'getCollection' accepting a first argument of type 'MongoClient' could be found (are you missing a using directive or an assembly reference?) [/src/src/Identity.api/Identity.api.csproj]
Now, I can access the DB through the commandline through 'mongo localhost/cvpz'. Btw, I am using Ubuntu to run .Net Core.
When I run createCollection() I get a similar error. How do I use C# to interact with Mongo?
One last thing, I should have all the necessary packages, I have these in my .csproj:
<PackageReference Include="MongoDB.Driver" Version="2.3.0" />
<PackageReference Include="MongoDB.Driver.Core" Version="2.3.0" />
<PackageReference Include="MongoDB.Bson" Version="2.3.0" />
Thanks so much guys!
Two things. 'GetCollection' should have an uppercase G. It also requires a generic parameter indicating the document type being stored. For you example:
var mongo = new MongoClient("mongodb://localhost:27017");
var db = mongo.GetDatabase("cvpz");
var coll = mongo.GetCollection<People>("people");
Reference: IMongoDatabase.GetCollection
Related
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.
I work with SQL Server Db in my .Net Core 3.1 project and some stored procedures and views have hierarchyid types for parameters and data.
I use Microsoft.Data.SqlClient package. And when I try to read data with SqlDataReader I get the exception:
System.IO.FileNotFoundException : Could not load file or assembly 'Microsoft.SqlServer.Types, Version=10.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91'. The system cannot find the file specified.
ok, I tried to use Microsoft.SqlServer.Types as it suggests but this package is not .NET Standard and it doesn't work.
Also, I found EntityFrameworkCore.SqlServer.HierarchyId but when I use it I get:
System.InvalidCastException : Unable to cast object of type 'Microsoft.SqlServer.Types.SqlHierarchyId' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.
So how on Earth can one use HierarchyId type in .NET Core 3.1?
I'm planning to host this solution on linux.
UPDATE
I do use Microsoft.Data.SqlClient 2.0 which is compatible with .NET Core. Also, I added then EntityFrameworkCore.SqlServer.HierarchyId, and I get this error:
System.InvalidCastException : Unable to cast object of type 'Microsoft.SqlServer.Types.SqlHierarchyId' to type 'Microsoft.Data.SqlClient.Server.IBinarySerialize'.
Here's the .csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="EntityFrameworkCore.SqlServer.HierarchyId" Version="1.1.0" />
<PackageReference Include="Microsoft.Data.SqlClient" Version="2.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
</ItemGroup>
<ItemGroup>
<Folder Include="Helpers\" />
</ItemGroup>
</Project>
No luck so far.
UPDATE 2
This is the code where the exception is thrown:
using (SqlDataReader reader = await detailsCmd.ExecuteReaderAsync())
{
while (reader.Read())
{
details.Add(new HierarchyDetails
{
Id = reader.GetInt32(0),
groupPath = reader.GetValue(1).ToString(), // <==== EXCEPTION
name = reader.GetString(2),
optionalData = reader.IsDBNull(3) ? null : reader.GetString(3)
});
}
}
And the table has the only row:
id groupPath culture name optionalData
24 0x58 en-US testing
Your error message suggests that you use something which uses nuget https://www.nuget.org/packages/Microsoft.SqlServer.Types/10.50.1600.1 which is .NET Framework dll, not .NET Core.
You mention that you use Microsoft.Data.SqlClient, please ensure that you use https://www.nuget.org/packages/Microsoft.Data.SqlClient/ which is compatible with .NET Core.
In case of other errors please check also Entity Framework Core hierarchyid
The solution at the moment to cast hierarchyid to NVARCHAR in all your queries:
... CAST(groupPath as NVARCHAR(4000)) as groupPath ...
and then use it as string.
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}");
}
}
}
}
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
using code like
using OfficeOpenXml; // namespace for the ExcelPackage assembly
…
FileInfo newFile = new FileInfo(#"C:\mynewfile.xlsx");
using (ExcelPackage xlPackage = new ExcelPackage(newFile)) { … }
I get an exception error of
'IBM437' is not a supported encoding name. For information on defining
a custom encoding, see the documentation for the
Encoding.RegisterProvider method. Parameter name: name
Any ideas as to what the problem could be?
Thanks
Martin
if your project is .net core edit your project file then add
<ItemGroup>
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.3.0" />
</ItemGroup>
and in your startup.cs
add
System.Text.Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
The problem is in the ZIP file reader (ZipInputStream). You need to add the encodings like windows-1252 manually:
dotnet add package System.Text.Encoding.CodePages
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
More info here: .NET Core doesn't know about Windows 1252, how to fix?