Foxtrek_64
Foxtrek_64
CC#
Created by Foxtrek_64 on 11/22/2024 in #help
Custom Logger
Hi all, been trying to figure this out for a bit now but I'm not sure what's happening. I am writing a custom extension for Microsoft.Extensions.Logging to write to a Sql Server database with a particular schema. However, I'd opted to make it as generic as possible. After doing a lot of research, I've created a DbLoggingProvider and a MSSqlDatabaseLogger. The logging provider creates new instances of the database logger, as expected, and the database logger expects an instance of a type implementing ILogAgent which it forwards its log method to. The log agent is responsible for performing the database-specific operations. However, when doing unit tests, I am unable to prove that logging works. In fact, it appears to not. Take the following test.
[Fact]
public void LogsToDatabase()
{
using var accessor = new SqlServerAccesor(_connectionString); // SqlServerAccessor wraps a SqlConnection and exposes helpers to run queries and non-queries.

int? oldCount = GetCount(accessor); // Uses the accessor to run a query to check count of rows in a table.
Assert.NotNull(oldCount);

var logger = _host.Services.GetService<ILogger<LoggerTests>>();
Assert.NotNull(logger);

var exception = Record.Exception(() => logger.LogInformation("..."));
Assert.Null(exception);

int? newCount = GetCount(accessor);
Assert.NotNull(newCount);
Assert.NotEqual(oldCount, newCount);
}
[Fact]
public void LogsToDatabase()
{
using var accessor = new SqlServerAccesor(_connectionString); // SqlServerAccessor wraps a SqlConnection and exposes helpers to run queries and non-queries.

int? oldCount = GetCount(accessor); // Uses the accessor to run a query to check count of rows in a table.
Assert.NotNull(oldCount);

var logger = _host.Services.GetService<ILogger<LoggerTests>>();
Assert.NotNull(logger);

var exception = Record.Exception(() => logger.LogInformation("..."));
Assert.Null(exception);

int? newCount = GetCount(accessor);
Assert.NotNull(newCount);
Assert.NotEqual(oldCount, newCount);
}
I'm sure that there are better ways to test if a logger is logging (this could in theory pass if something else is writing logs to this table even if the log operation fails), but it's fine for right now while I'm the only person logging to this table. That said, advice on fixing up this test would be appreciated. Every assert passes except for the assertion that the counts are not equal (they are) and going to the database reveals that my message was not inserted into the log table. I have unit tests that pass for SqlServerAccessor and I am able to demonstrate that, by itself, it is able to insert log entries by executing a non-query and writing directly to the table in question. The issue appears to be in the glue layer - despite the log agent being present in the same service provider which is producing logger instances, it does not appear to be using my particular logger. I don't see any breakpoints being hit in my logger class, though I am hitting the logger provider several times. What is it exactly that I am missing here?
13 replies
CC#
Created by Foxtrek_64 on 11/22/2024 in #help
SqlConnection Connection Disposed
Hi all, I have class library which provides a custom type called SqlServerAccessor This custom type wraps a SqlConnection and its ctor accepts a connection string, news up a SqlConnection, and calls _connection.Open(). This type implements IDisposable and is intended to be used as follows:
try
{
using var sql = new SqlServerAccessor(connectionString);
DataTable result = sql.ExecuteQuery(...);
// Do something with the result
}
catch (Exception ex)
{
// Sql connection failed
}
try
{
using var sql = new SqlServerAccessor(connectionString);
DataTable result = sql.ExecuteQuery(...);
// Do something with the result
}
catch (Exception ex)
{
// Sql connection failed
}
Internally, I have a method called EnsureNotDisposed() to handle use after the type has been disposed which throws an InvalidOperationException stating the underlying SqlConnection has been disposed. Using the code sample from above, this catch is always hit and the sql connection is always closed. There does not seem to be a "keep alive" function or anything - my understanding is that SqlConnection should keep its connection open until it is manually closed. I could connect and disconnect for each operation, which might resolve the issue, but the intent is for it to be used in a small using scope like this and calling Dispose() or Close() is responsible for closing the connection. Any idea why the connection is being closed immediately after leaving the ctor?
13 replies
CC#
Created by Foxtrek_64 on 9/30/2024 in #help
VS hangs while typing
Curious if you guys had any ideas My machine at work is running VS When I type in the code editor, it's often several seconds before the editor catches up to what I typed and several seconds again before I get suggestions or the intellisense browser. I've watched memory and cpu usage and I'm seeing neither noticeable spikes nor is either utilization at 100%. Where should I look to diagnose the lag?
13 replies
CC#
Created by Foxtrek_64 on 9/20/2024 in #help
Blazor - Identity Scaffolding Fails
Hi all, trying to scaffold identity into a blazor app. I have an AuthDbContext that looks like this
public sealed class AuthDbContext(DbContextOptions<AuthDbContext> options)
: IdentityDbContext<IdentityUser>(options);
public sealed class AuthDbContext(DbContextOptions<AuthDbContext> options)
: IdentityDbContext<IdentityUser>(options);
When in the scaffolding wizard, I select this db context. It works up to a point, but then I get an exception popup from Visual Studio:
---------------------------
Microsoft Visual Studio
---------------------------
Error

There was an error running the selected code generator:

'value cannot be null or empty

Parameter name: projectRelativePath'
---------------------------
OK
---------------------------
---------------------------
Microsoft Visual Studio
---------------------------
Error

There was an error running the selected code generator:

'value cannot be null or empty

Parameter name: projectRelativePath'
---------------------------
OK
---------------------------
Googling this issue doesn't find me any results for this particular error. Any ideas?
14 replies
CC#
Created by Foxtrek_64 on 6/6/2024 in #help
INumberBase<>.TryConvertFromTruncating()
I have a Bit type which wraps bool and implements INumberBase and IComparable. I need to implement the TryConvertFromTruncating method Should I just reimplement my FromSaturating method which returns Bit.One if the value is not zero, otherwise Bit.Zero? Or is there another better implementation. I do have int.CreateTruncating() in the body temporarily but this naturally creates unexpected limitations in the type The purpose of this type is just to test a case for my SSN type where it should throw if converting to a numeric type that doesn't support 0-9, and no such built in type satisfies this, but it is at least good practice for building an integral numeric type.
8 replies
CC#
Created by Foxtrek_64 on 6/4/2024 in #help
Attribute Style Preference
Not sure if #help is the right place for this but I was hoping for some thoughts on attribute style.
// Style 1
[Foo]
[Bar]
public void Bizz(Buzz buzz) { }

// Style 2
[Foo, Bar]
public void Bizz(Buzz buzz) { }
// Style 1
[Foo]
[Bar]
public void Bizz(Buzz buzz) { }

// Style 2
[Foo, Bar]
public void Bizz(Buzz buzz) { }
It goes without saying that functionally, the two styles make absolutely no difference. They are handled identically by the compiler. I have noticed however that decompiled C#, such as when looking at lowered code in SharpLab, tends to prefer style 1. I think that's mostly because it's easier to render it as C# that way, not because of any functional reason. Which style do you guys prefer, and what is your reasoning? Does it depend, e.g. based on the length of the attribute name or the number of attributes? Do you mix and match styles?
8 replies
CC#
Created by Foxtrek_64 on 1/2/2024 in #help
SDK Project - Duplicate ExcludeFromCodeCoverage in generated file
Hey all, working on an SDK project and running into an interesting issue and I'm not entirely sure how to fix it. When compiling for tests, my test projects get the following exception:
error CS0579: Duplicate 'System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage' attribute
error CS0579: Duplicate 'System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage' attribute
This attribute is being defined in <Project>.AssemblyInfo.cs, a compiled file. Background Initially the LibraryFrameworks value below had targeted netstandard2.1 inline with the rest of the libraries. In order to facilitate phasing out of support of this library, we've done a couple things: 1. In Sdk.props, alongside ExecutableFrameworks and LibraryFrameworks, we've defined a new boolean property TargetNetStandard and removed the netstandard2.1 target from LibraryFrameworks. In order to remain backwards compatibility, TargetNetStandard defaults to true.
<!-- Default targeting configuration -->
<PropertyGroup>
<ExecutableFrameworks Condition="'$(ExecutableFrameworks)' == ''">net8.0</ExecutableFrameworks>
<LibraryFrameworks Condition="'$(LibraryFrameworks)' == ''">net6.0;net7.0;$(ExecutableFrameworks)</LibraryFrameworks>
<TargetNetStandard Condition="'$(TargetNetStandard)' == ''">true</TargetNetStandard>
</PropertyGroup>
<!-- Default targeting configuration -->
<PropertyGroup>
<ExecutableFrameworks Condition="'$(ExecutableFrameworks)' == ''">net8.0</ExecutableFrameworks>
<LibraryFrameworks Condition="'$(LibraryFrameworks)' == ''">net6.0;net7.0;$(ExecutableFrameworks)</LibraryFrameworks>
<TargetNetStandard Condition="'$(TargetNetStandard)' == ''">true</TargetNetStandard>
</PropertyGroup>
1. In Sdk.Targets, the second TargetFrameworks definition was added which adds the netstandard2.1 target alongside the standard library frameworks.
<!--
Fallback targeting properties - VS sets for DesignTime builds only TargetFramework
but requires information about all TargetFrameworks
-->
<PropertyGroup Condition="'$(TargetFrameworks)' == ''">
<!--suppress MsbuildTargetFrameworkTagInspection -->
<TargetFrameworks>$(LibraryFrameworks)</TargetFrameworks>

<!--suppress MsbuildTargetFrameworkTagInspection -->
<TargetFrameworks Condition="'$(TargetNetStandard)' == true">netstandard2.1;$(LibraryFrameworks)</TargetFrameworks>

<!--suppress MsbuildTargetFrameworkTagInspection -->
<TargetFrameworks Condition="'$(OutputType)' == 'Exe'">$(ExecutableFrameworks)</TargetFrameworks>
</PropertyGroup>
<!--
Fallback targeting properties - VS sets for DesignTime builds only TargetFramework
but requires information about all TargetFrameworks
-->
<PropertyGroup Condition="'$(TargetFrameworks)' == ''">
<!--suppress MsbuildTargetFrameworkTagInspection -->
<TargetFrameworks>$(LibraryFrameworks)</TargetFrameworks>

<!--suppress MsbuildTargetFrameworkTagInspection -->
<TargetFrameworks Condition="'$(TargetNetStandard)' == true">netstandard2.1;$(LibraryFrameworks)</TargetFrameworks>

<!--suppress MsbuildTargetFrameworkTagInspection -->
<TargetFrameworks Condition="'$(OutputType)' == 'Exe'">$(ExecutableFrameworks)</TargetFrameworks>
</PropertyGroup>
Expected Behavior This should in theory create behavior identical to the original - unless the user opts out by setting <TargetNetStandard>false</TargetNetStandard>, the default set of target frameworks should include netstandard2.1;net6.0;net7.0;net8.0 (when it's a library type and not an executable type). If the user specifies false, then the netstandard2.1 target should be excluded. Actual Behavior JIT building (when saving changes made to Skd.targets) appears to work properly, and Rider shows that my test library TargetNetStandardFalse appears to update its targets correctly to indicate that it is no longer targeting netstandard2.1. However, running dotnet build with either debug or release targets results in the duplicate attribute exception, which prevents tests from running. Deleting obj/bin folders has no effect on this behavior, except that it will change which test project receives the error. I imagine this is just dependent on the order the projects are discovered and built rather than some sort of phantom shifting error. Does anyone know why this is happening or how to fix it?
1 replies
CC#
Created by Foxtrek_64 on 7/26/2023 in #help
✅ Console Logging - No New Lines
Not sure if this is M.E.L or Serilog or Microsoft Terminal doing this Developing a service as a console app as one does, but when logging to the console, new lines only appear after stack traces. Everything else always appears on the same line. The {Newline} piece in my format doesn't seem to be working either. Exception messages are smashed up against the actual message. I am running on Windows with NET7 and the latest version of all relevant packages. Anyone run into this before? Google hasn't
8 replies
CC#
Created by Foxtrek_64 on 7/13/2023 in #help
❔ fluent api naming/design
Hi all, working on designing a fluent api inspired by EF Core, in this case the IEntityTypeBuilder I am trying to determine language to describe these situations: Exactly one of (set of properties) required One or more (set of properties) required If property 1 is present, property 2 must be present If any of (set of properties), (set of properties) is required Here's some I've thought of: builder.OneOf(x => x.Foo, x => x.Bar) builder.AnyOf(x => x.Foo, x => x.Bar) Builder.Required(x => x.Property2).When(x => x.Property1, isPresent: true) I should note, if a property is always mandatory, it is a naked property in the model (public string Name { get;}) If it is optional or conditionally optional, it exists as an Optional<T>, which helps account for cases where logically null and logically missing are two different scenarios.
6 replies
CC#
Created by Foxtrek_64 on 4/6/2023 in #help
❔ Net461 Needs Reference to NetStandard 2.0
I'm encountering an error that only gets thrown when executing an app. Building works great. The error says that System.ValueType is not defined and I need a reference to netstandard 2.0.0. I am not using anything that relies on netstandard, nor do I know of anywhere that I'm using System.ValueType, yet my app seems to think I am. Any thoughts of where I might look? I would just add a reference as suggested, but I don't have a .csproj. I have a project.json file which only supports nuget.
6 replies
CC#
Created by Foxtrek_64 on 3/20/2023 in #help
✅ Multi-targeting NetFx and NetCore - Targeting wrong version?
History My last post was a bit of a mess so I've come here to help clean it up a bit. I have a project called Tafs.Activities.Finance. It multi-targets net461, net462, net6.0, and net7.0. In the project file, I have a few conditional includes. If we're working with NetFx, it includes a reference to Tafs.Activities.Results. If we're working with Net6/7, it instead includes a reference to Remora.Results. These two libraries provide the same types, though for NetFx and Net6.0+ respectively. In the Finance library, I have a type called SocialSecurityNumber which references a ValidationError. ValidationError exists in a third library: Tafs.Activities.Results.Extensions. The extensions library is set up very similarly to the finance library in its conditional includes. The ValidationError type implements ResultError, which is provided by either Tafs.Activities.Results or Remora.Results depending on the target.
#if NET6_OR_GREATER
using Remora.Results;
#endif

namespace Tafs.Activities.Results.Extensions.Errors;

public sealed record class ValidationError(string Message) : ResultError(Message);
#if NET6_OR_GREATER
using Remora.Results;
#endif

namespace Tafs.Activities.Results.Extensions.Errors;

public sealed record class ValidationError(string Message) : ResultError(Message);
Intellisense on ResultError does update properly between Tafs.Activities.Results and Remora.Results based on the selected build target. The Error When consuming ValidationError in my Finance project, I do so by assigning it to a Result type. The source of the Result type should likewise correspond to the selected build target, and Intellisense does confirm this. NetFx should only be aware of Tafs.Activities.Results and Net6/7 should only be aware of Remora.Results. This assignment operation relies on an implicit converter which handles anything of type ResultError:
// Result.cs
public static implicit operator Result(ResultError error)
=> new(error, defeault);

// SocialSecurityNumber.cs
public static Result Validate(SocialSecurityNumber ssn)
{
if (ssn.AreaNumber == Default.AreaNumber)
{
return new ValidationError("The area number cannot be '000'.");
}
// Rest of function omitted for brevity.
}
// Result.cs
public static implicit operator Result(ResultError error)
=> new(error, defeault);

// SocialSecurityNumber.cs
public static Result Validate(SocialSecurityNumber ssn)
{
if (ssn.AreaNumber == Default.AreaNumber)
{
return new ValidationError("The area number cannot be '000'.");
}
// Rest of function omitted for brevity.
}
I get two exceptions on the return statement when targeting net461 or net462:
"Cannot implicitly convert type 'Tafs.Activities.Results.Extensions.Errors.ValidationError' to 'Tafs.Activities.Results.Result'"

"The type 'ResultError' is defined in an assembly that is not referenced. You must add a reference to assembly 'Remora.Results, Version=7.2.3.0, Culture=neutral, PublicKeyToken=null'."
"Cannot implicitly convert type 'Tafs.Activities.Results.Extensions.Errors.ValidationError' to 'Tafs.Activities.Results.Result'"

"The type 'ResultError' is defined in an assembly that is not referenced. You must add a reference to assembly 'Remora.Results, Version=7.2.3.0, Culture=neutral, PublicKeyToken=null'."
Adding a reference to Remora.Results as suggested, even though NetFx can't use it, does resolve the second error, but I think that's a fake error anyways so I'm ignoring that. What I think is happening is that when the Finance library is referencing Tafs.Activities.Results.Extensions, it's somehow grabbing the Net6/Net7 target, even though the Finance library itself is targeting net461 or net462. If I change the target selector for the finance library to Net6 or Net7, the error goes away and the Result type changes to Remora.Results.Result. I have tried doing a project clean, then building the projects one at a time, but this does not have any effect on the issue. Does anyone have any ideas as to what might be happening here or how to fix it?
8 replies
CC#
Created by Foxtrek_64 on 3/20/2023 in #help
✅ Multi-target, wrong version
I am multi-targeting a project for NetFx and Net6/7. Specifically, there are four projects in play here: Remora.Results - Provides the base Result and ResultError types for Net6/7 Tafs.Activities.Results - Provides the base Result and ResultError types for NetFx Tafs.Activities.Results.Extensions - Conditionally includes Remora.Results or Tafs.Activities.Results based on framework version. Tafs.Activities.Serialization - Targets Remora.Results or Tafs.Activities.Results based on target version. Additionally targets Tafs.Activities.Results.Extensions for extra error types. My SocialSecurityNumber class relies on Tafs.Activities.Results.Extensions.Errors.ValidationError. This is happy on NetFx, but on Net6/7, I get an error saying I cannot implicitly convert it to Remora.Results.Result. I would expect this error if it picked the wrong version of the error to provide. The source code of the ValidationError is this:
#if NET461_OR_GREATER
using Tafs.Activities.Results;
#else
using Remora.Results;
#endif

namespace Tafs.Activities.Results.Extensions.Errors
{
public sealed record class ValidationError(string Message) : ResultError(Message);
}
#if NET461_OR_GREATER
using Tafs.Activities.Results;
#else
using Remora.Results;
#endif

namespace Tafs.Activities.Results.Extensions.Errors
{
public sealed record class ValidationError(string Message) : ResultError(Message);
}
Whether it implements Tafs.Activities.Results.ResultError or Remora.Results.ResultError should in theory depend on the dotnet version, but it does not appear to be behaving as such. To make things even stranger, this framework comparison extends to the csproj too. So in theory, the Net6/7 version shouldn't even be aware of Tafs.Activities.Results.
<ItemGroup Condition="'$(TargetFramework)' == 'net461' Or '$(TargetFramework)' == 'net462'>
<ProjectReference Include="..\Tafs.Activities.Results\Tafs.Activities.Results.csproj" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'Net6.0' Or '$(TargetFramework)' == 'net7.0'">
<PackageReference Include="Remora.Results" Version="7.2.3" />
<PackageReference Include="Remora.Results.Analyzers" Version="1.0.0" />
</ItemGroup>
<ItemGroup Condition="'$(TargetFramework)' == 'net461' Or '$(TargetFramework)' == 'net462'>
<ProjectReference Include="..\Tafs.Activities.Results\Tafs.Activities.Results.csproj" />
</ItemGroup>

<ItemGroup Condition="'$(TargetFramework)' == 'Net6.0' Or '$(TargetFramework)' == 'net7.0'">
<PackageReference Include="Remora.Results" Version="7.2.3" />
<PackageReference Include="Remora.Results.Analyzers" Version="1.0.0" />
</ItemGroup>
Any thoughts as to what might be going on here?
4 replies
CC#
Created by Foxtrek_64 on 3/20/2023 in #help
✅ IsExternalInit Issue Not Found and Duplicate
Hi all, I'm working in a project that multi-targets net461, net461, net6.0, and net7.0. On the net461 target, I'm encountering an error stating "Predefined type 'System.Runtime.CompilerServices.IsExternalInit' is not defined or imported." The IsExternalInit nuget package is installed. StackOverflow suggested that I can create a custom internal class like so:
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit {}
}
namespace System.Runtime.CompilerServices
{
internal static class IsExternalInit {}
}
Adding this class does not get rid of the error, but it does add a new error saying "The namespace 'System.Runtime.CompilerServices.' already contains a definition for 'IsExternalInit'." So it both can't find it and reports a duplicate at the same time. Restarting Visual Studio and deleting obj, bin, and output folders does not resolve the issue. Any ideas of what might be going on here?
20 replies
CC#
Created by Foxtrek_64 on 3/14/2023 in #help
❔ Recommendations for Fuzzy Equation algorithm
Hi all, I'm looking for recommendations on nuget packages or Linq queries I could use to accomplish a fuzzy equation algorithm. In my case, are comparing company names to find a match, but because of human entry, the names are inconsistent. For example, you could have "Contoso," "Contoso LLC," and "Contoso llc." And sometimes we have some spelling errors because they're typed by someone listening over the phone. So "Cantoso" could be a possibility, for instance. Because we use this comparison for verification purposes, we need it to be able to be tuned to eliminate false positives. AI is also a potential candidate but that sounds like a huge can of worms I don't want to get into. I don't mind rolling my own but ideally I would like to use something actively maintained since this is not an area of expertise.
9 replies
CC#
Created by Foxtrek_64 on 3/7/2023 in #help
❔ Name split considerations
I have a name in the form of First Last. I need to split this into individual first and last name variables in the least internationally destructive way possible. Any considerations or is String.Split() enough?
6 replies
CC#
Created by Foxtrek_64 on 11/25/2022 in #help
❔ Cannot open output file for writing
Hi all, trying to build my project with Visual Studio. Whenever I do I get an error from CSC stating the following:
Cannot open 'D:\Projects\apps\LuzFaltex\Selkhound\Selkhound\src\Selkhound.API.Abstractions\obj\Debug\Selkhound.API.Abstractions.dll' for writing -- 'The process cannot access the file 'D:\Projects\apps\LuzFaltex\Selkhound\Selkhound\src\Selkhound.API.Abstractions\obj\Debug\Selkhound.API.Abstractions.dll' because it is being used by another process.'
Cannot open 'D:\Projects\apps\LuzFaltex\Selkhound\Selkhound\src\Selkhound.API.Abstractions\obj\Debug\Selkhound.API.Abstractions.dll' for writing -- 'The process cannot access the file 'D:\Projects\apps\LuzFaltex\Selkhound\Selkhound\src\Selkhound.API.Abstractions\obj\Debug\Selkhound.API.Abstractions.dll' because it is being used by another process.'
To fix this, I have tried closing out of Visual Studio and deleting both the Selkhound/output and Selkhound/Selkhound.API.Abstractions/obj directory, but the next time it builds I just get the same exception on build again. I also get this exception for the Selkhound.Client.dll file. Building using Visual Studio, with or without cleaning the solution, or using dotnet build on the command line has the same results. The build log suggests that the projects are being built multiple times in parallel, though I'm not sure if that's a contributing factor here. Any thoughts of what I might do to fix this?
19 replies
CC#
Created by Foxtrek_64 on 11/20/2022 in #help
MAUI Entry Point - MauiProgram.cs [Answered]
Typically when creating a new application, be it Console, WPF, WinForms, or Web, the main entry point of the application is Program.Main(). I created a new Maui app to find that the main entry point appears to be MauiProgram.CreateMauiApp(). Why is there a difference in the entry point of the application? Was it intended to mirror the Startup.cs file from asp.net core apps and they just hid Program.cs from me?
3 replies
CC#
Created by Foxtrek_64 on 9/22/2022 in #help
SendKeys() Access Denied
I'm using UiPath's SendKeys activity which maps to the SendKeys() function. For some reason, I am experiencing an intermittent access denied error when trying to send F8 to an application. Pressing F8 manually when this error is experienced does not open the F8 window. Restarting the application fixes the error. When researching this error, the only suggestions online are to disable UAC or run as administrator, neither of which are options due to company policy. Are there any other suggestions?
14 replies
CC#
Created by Foxtrek_64 on 9/2/2022 in #help
LINQPad 7 - Insert Record [Answered]
Hi all, I'm using LINQPad to insert records from json into a SQL database. All of the documentation seems to suggest that it builds a model based on the table that is a singular name of the table (e.g., if the table name is Regions, the model is named Region). However, this does not seem to be the case for my table, and unfortunately LINQPad seems to lack any sort of intellisense for inspecting the namespace for the correct type name. My table is RVIDocumentCodes but there does not appear to be an RVIDocumentCode type. The InsertOnSubmit() line has an expected error because jsonDocument is the json model. This error is "Cannot convert from UserQuery.RVIDocumentCodeJson to LINQPad.Users.RVIDocumentCodes". This tells me that the RVIDocumentCodes type is my model, but there does not appear to be a constructor that I'm allowed to consume. Both of these lines tell me that RVIDocumentCodes doesn't contain a constructor that accepts that many arguments.
foreach (var jsonDocument in documents)
{
// var document = new RVIDocumentCodes(jsonDocument.DocumentCode, jsonDocument.DocumentTitle, jsonDocument.DocumentUrl);
var document = new RVIDocumentCodes(0, jsonDocument.DocumentCode, jsonDocument.DocumentTitle, jsonDocument.DocumentUrl);
RVIDocumentCodes.InsertOnSubmit(jsonDocument);
}
SubmitChanges();
foreach (var jsonDocument in documents)
{
// var document = new RVIDocumentCodes(jsonDocument.DocumentCode, jsonDocument.DocumentTitle, jsonDocument.DocumentUrl);
var document = new RVIDocumentCodes(0, jsonDocument.DocumentCode, jsonDocument.DocumentTitle, jsonDocument.DocumentUrl);
RVIDocumentCodes.InsertOnSubmit(jsonDocument);
}
SubmitChanges();
What am I missing here?
4 replies
CC#
Created by Foxtrek_64 on 8/26/2022 in #help
JsonPath Query [Answered]
I have some json that looks like this:
{
"teams": [
{
"BusinessUnitId": 1234,
"TeamId": 5678,
"TeamName": "Foo",
"IsActive": true,
"Description": "",
"Notes": ""
},
{
...
}
]
}
{
"teams": [
{
"BusinessUnitId": 1234,
"TeamId": 5678,
"TeamName": "Foo",
"IsActive": true,
"Description": "",
"Notes": ""
},
{
...
}
]
}
Using a JsonPath query, I want to filter results where IsActive is true and return the TeamName. I have put together this query:
var document = JsonDocument.Parse(rawJson);
var teams = document.SelectElements("$.teams[?(@.IsActive == true)].TeamName").ToList();
var document = JsonDocument.Parse(rawJson);
var teams = document.SelectElements("$.teams[?(@.IsActive == true)].TeamName").ToList();
The way I read it, it should select from teams where IsActive is true, then return the TeamName property, however the resulting teams object is always null (specifically, for whatever reason it returns List<JsonElement?>?). Removing the .TeamName reference at the end also returns a null collection. According to this stackoverflow post, the JsonPath query is properly formatted (https://stackoverflow.com/questions/46931964/json-path-to-check-equals-condition). Any thoughts of what I might be doing wrong here? I'm using System.Text.Json and the JsonDocumentPath libraries.
12 replies