Self Reference loop EntityFramework problem, another way to solve it? - reference

My project is Web Api Core 5.0 and i have got problems with self reference loop EntityFrameworkCore
In my last project i have used this:
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);
but on my current version .Net core it's not working,
i found something like this:
services.AddMvc().AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
});
but I dont like it, it shows $Id and $value on response, which i dont want to see
Is there another way of the way get rid of that self reference loop?
I read before:
JSON.NET Error Self referencing loop detected for type
and these don't help me

It was only a suggestion ... because your questions is about EF -- but the contents seem to stem from NewtonSoft and possibly Swagger. So I thought it might have more to do with Swagger for your reference loopoing issue. In any case, I've found this solves that type of issue for me. (you would need Swashbuckle.AspNetCore.Newtonsoft)
First add NewtonSoft options.
services.AddControllers()
.AddNewtonsoftJson(opts =>
{
//opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
//opts.SerializerSettings.Converters.Add(new Newtonsoft.Json.Converters.StringEnumConverter());
opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
Then add swaggergen... and then newtonsoft support.
services.AddSwaggerGen(c =>
{
...
});
// NOW add
services.AddSwaggerGenNewtonsoftSupport();

Related

Blazor - cannot convert from 'method group' to 'EventCallback'

I have a parent component and a child component with an event callback where I want it to pass back a type of T.
The issue I'm having is that I have an error about converting
MethodGroup to EventCallback.
If I convert this to using an Action then it works, but I can't do it async which isn't ideal.
Any ideas what I'm doing wrong?
Parent
<Child DeleteCallback="#OnDelete"></Child>
public async Task OnDelete(T item)
{ ... }
Child
#typeparam T
[Parameter]
public EventCallback<T> DeleteCallback { get; set; }
<a #onclick="() => DeleteCallback.InvokeAsync(item)"></a>
I've added a repo here explaining the problem. Looking at the Issues for Blazor, this should;ve been fixed in 2019. https://github.com/scott-david-walker/EventCallbackError
You were close:
<ChildComponent Item="someModel" T="SomeModel" DeleteCallback="OnDeleteSomeModel" />
#code {
SomeModel someModel = new SomeModel();
void OnDeleteSomeModel(SomeModel someModel)
{
...
}
}
The EventCallback uses a generic type and blazor cannot infer it if you don't pass the type to the component.
This means that if you have a EventCallback<T> you need to pass the value of T to the component e.g. T="SomeType".
In my case I declared a nullable EventCallback? - you can't do that.
I've experienced that the syntax was spot on and still getting this error.
Restarting Visual Studio 2019 solved the problem for me. Cleaning and rebuilding was not enough.
For some reason Visual Studio kept a previous signature I had used. Cleaning, restarting, emptying bin/obj folders etc did not work. I had to rename the method, which worked for me.
The following syntax worked for me:
// in the component (C#):
[Parameter]
public EventCallback<MovingEventArgs> OnMoving { get; set; }
// on the using side (Razor):
OnMoving="(Component.MovingEventArgs o) => OnMoving(o)"
// on the using side (C#):
protected void OnMoving( Component.MovingEventArgs e ) {
}
There seems to have been a change and the documentation is not up to date.
This event is also using custom event arguments.
For anyone fighting this with the MudBlazor MudTable I found this worked use #bind-SelectedItem and don't pass any parameters to the commit function.
<MudTable T="POCO" Items="#MyState.POCOs"
#bind-SelectedItem="_selectedPOCO"
OnCommitEditClick="#(() => commitPOCO())"
CommitEditTooltip="Save Changes?">
#code {
private POCO _selectedPOCO;
private async void commitPOCO()
{
// all the changed values are in _selectedPOCO
...
}
In my case, the problem solved when I defined the #typeparam manually(not by inference)(TItem="int").
<MyComponent TItem="int" OnChange="Component_Changed" />
Okay I just spent hours trying to figure this out. Turns out on my end the problem was I have sync fusion in the project and I had explicitly define the name space of the Event call back arguments which in my case were Microsoft.AspNetCore.Components.ChangeEventArgs in the child component and then creating an async method to pass back data to the parent.
In my case it was a phantom error among tens others that never went away no matter what I do. Meaning I could still build and run a solution without problems, despite so many erorrs.
What helped me was this solution: https://stackoverflow.com/a/66219566/1215913
However, I finally found a solution after a few hours of digging. To
get rid of the phantom errors I closed Visual Studio, deleted the
files in the following folder, and then re-opened the solution:
C:\Users<Username>\AppData\Local\Temp\VSFeedbackIntelliCodeLogs\Suggestions\
The only difference is I removed all of the folders that start with VS (C:\Users\<Username>\AppData\Local\Temp\VS*) since there was no this exact path as #rovert mentions in his post.
This seems to be some common problem with Blazor and IntelliSense. I also often see that auto-formatter fails to correctly format the razor code (text indentations are a mess).
In my case I got the error
Error (active) CS1503 Argument 2: cannot convert from 'method group'
to 'EventCallback'
for ValueChanged with the following code:
<MatAutocompleteList TItem="UseCase" Items="#selectUseCases" ValueChanged=#SelectUseCases>
<ItemTemplate>
#context?.Label
</ItemTemplate>
</MatAutocompleteList>
#code
{
private UseCase SelectUseCases(UseCase useCaseDto)
{
if (useCaseDto != null)
{
//Do stuff
}
return null;
}
}
Changed to private void SelectUseCases(UseCase useCaseDto), removed all returns and the error disappeared.
After trying all other solutions proposed here, including:
Making sure I was providing T=myType
Clean and rebuild
Restart Visual Studio
Rename the method by appending a letter to its name and aligning its binding
The only thing that worked for me was literally deleting the line with the binding, saving, recompiling, then writing it back.
In doing so, I in fact realized that I was typing:
SelectedItemChanged="#SelectedItemsChanged"
instead of:
SelectedItemsChanged="#SelectedItemsChanged"
I was missing an s in the binding. The method itself had a signature receiving a HashSet of my type, so it could only deal with Items, not a single item.

Azure Function: "Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information"

I have an F# Azure Function that is failing, in a bizarre way, and don't know how to approach fixing the issue. I created a minimum repro of the actual case below. The test function is manually triggered and uses FSharp.Compiler.Service as a dependency, as specified in the project.json below:
{
"frameworks": {
"net46":{
"dependencies": {
"FSharp.Compiler.Service": "11.0.6"
}
}
}
}
The run.fsx file looks like this:
open System
open Microsoft.FSharp.Compiler
open Microsoft.FSharp.Compiler.Ast
open Microsoft.FSharp.Compiler.Interactive.Shell
let Run(input: string, log: TraceWriter) =
// code here that uses FsiEvaluationSession
// and runs just fine
log.Info "I RAN"
So far, so good. The part that baffles me is that if I add the following function above Run,
// same dependencies as before
open Microsoft.FSharp.Compiler.Interactive.Shell
let foo (longIdent:LongIdent) =
// version 1
// "FOO"
// version 2
// longIdent.ToString ()
// version 3
longIdent |> List.map string
let Run(input: string, log: TraceWriter) =
// same as before
Uncommenting section 1 alone works fine, uncommenting section 2 alone works fine, uncommenting section 3 causes hell to break loose. The function compiles, but running it causes the following exception:
Exception while executing function: Functions.fsc-1. mscorlib: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.
... which is puzzling to me, because
foo isn't even called anywhere
the signature and the 2nd version both use LongIdent, so this type doesn't seem to be the source of the problem.
Any suggestion on how to approach the problem, and what the problem itself might be, would be very appreciated - I don't even know where to start, and the same code runs perfectly fine in a local script.
I believe the reason for this is that Azure Functions SDK depend on FSharp.Compiler.Service (FCS) version 9.0.1. This means that when you try to load a different version of FCS, you will get the already loaded version 9.0.1.
This works as long as the public API of the FCS version you are using matches the public API of version 9.0.1, but when there are differences, it will crash, because your code assumes that the public API looks different. I suppose this might be triggering the issue here, although I'm not 100% sure how (possibly, LongIdent is now a different thing than it was in version 9.0.1?)
The very same issue used to happen with FAKE, which also bundles FCS and prevented loading of different versions. One of the options is to rename the assembly to avoid the clash.
I also got the same error, I solved it by doing the following workaround, please refer if it works for you also.
Right-click on the Project and select properties.
Goto Debug tab and create a profile with the reference to the below
screenshot.
Note: Replace UserName with your username.

Common php functions in hack

I decided to start a new project to get into hacklang, and after fixing some if the problems I initially ran into transitioning from php habits, I ran into the following errors:
Unbound name: str_replace
Unbound name: empty
Doing some research I found that this is due to using 'legacy' php which isn't typechecked, and will error with //strict.
That's fine and all, empty() was easy enough to replace, however str_replace() is a bit more difficult.
Is there an equivalent function that will work with //strict? Or at least something similar.
I'm aware that I could use //decl but I feel like that defeats the purpose in my case.
Is there at least any way to tell which functions are implemented in hack and which are not in the documentation as I couldn't find one?
For reference (though it isn't too relevant to the question itself), here is the code:
<?hh //strict
class HackMarkdown {
public function parse(string $content) : string {
if($content===null){
throw new RuntimeException('Empty Content');
}
$prepared = $this->prepare($content);
}
private function prepare(string $contentpre) : Vector<string>{
$contentpre = str_replace(array("\r\n","\r"),"\n",$contentpre);
//probably need more in here
$prepared = Vector::fromArray(explode($contentpre,"\n"));
//and here
return $prepared;
}
}
You don't need to change your code at all. You just need to tell the Hack tools about all the inbuilt PHP functions.
The easiest way to do this is to download this folder and put it somewhere in your project. I put it in a hhi folder in the base of my project. The files in there tell Hack about all the inbuilt PHP functions.
Most of them don't have type hints, which can lead to Hack thinking the return type of everything is mixed instead of the actual return, that is actually correct in most cases as, for example, str_replace can return either a string or a bool. However, it does stop the "unbound name" errors, which is the main reason for adding them.

c# 4.0 and async with Microsoft.Bcl.Async. I don't have all the type for async modifiy

I am using VS2012 and my project is 4.0, but I want to use the async/await keywords, so I install Microsoft.Bcl.Async.
I try to implement my async method in the following way:
public async Task<bool> myMethodAync(int paramInteger)
{
//my code, a simple code that return a bool. Is only an example
if(paramInteger == 2)
{
return true;
}
else return false;
}
I get an error and I get marked the name of the method and the error says something like this: it is not find all the types needed for the modify async. is it the target of the project a wrong version or is it missing the reference for some assembly?
I have the reference for the three assemblies Microsoft.Threading.Task, Microsoft.Threading.Task.Extensions and Microsoft.Threading.Task.Extensions.Desktop and I have the using in my class, System.Threading.task.
What else I need to do?
Thanks.
From http://michaelmairegger.wordpress.com/2012/09/19/cannot-find-all-types-required-by-the-async-modifier/:
The solution to this problem is to reference following nuGet package into all projects in which you want to use the ‘async’ and ‘await’ keyword.
Microsoft.CompilerServices.AsyncTargetingPack
So, right click on References, then select Manage NuGet Packages..., then search online. You may find the package under the name Async Targeting Pack for Visual Studio 11. Install it and the problem should be solved.

Refactoring statement from windsor to structuremap

I have the below windsor statement and trying to convert it into a structuremap statement. I really can't find any suggestion how to do it.
Container.Register(AllTypes.FromThisAssembly().
BasedOn<IType>().If(MatchStatement).Configure(c => c.LifeStyle.Transient.
Named(c.Implementation.Name)));
Anyone knows how this is written with structuremap?
EDIT: To make it more clear.. I've got the statement above (almost anyway) written with Windsor Castle but as we will be using Structuremap instead I need to do the same but with Structuremap. I got pieces of it but not all;
Registry.Scan(x =>
{
x.TheCallingAssembly();
x.AddAllTypesOf<IType>();
//{What more?}
});
What I further need is to meet the MatchStatement condition and return the named instance.
StructureMap's default lifecycle is PerGraph (a mix of transient and singleton).
The following code scans the calling assembly and adds all implentations of IType and each implementation is registered with the name of the implementation.
Scan(scan =>
{
scan.TheCallingAssembly();
scan.AddAllTypesOf<IType>().NameBy(type => type.Name);
});

Resources