JSON won't work in Prism environment - json

In a project WITHOUT the Prism library I had this code working to get a collection of "Persoon" objects:
Dim ObjectCollectie As New ObservableCollection(Of Persoon)()
If MijnAPIResponse.IsSuccessStatusCode Then
Dim AntwoordVanAPI = Await MijnAPIResponse.Content.ReadAsStringAsync
ObjectCollectie = JsonConvert.DeserializeObject(Of ObservableCollection(Of Persoon))(AntwoordVanAPI)
This code refers to a WebAPI to fetch the data and everything works fine.
This same statement won't work in the Prism ViewModel. It goes perfect until the ObjectCollectie is trying to use the JsonConvert statement. The AntwoordVanAPI contains the same JSON string like before.
The error message I get is:
__The API 'System.Collections.ObjectModel.ObservableCollection1[[Dossier365.BusinessModels.Persoon, Dossier365.BusinessModels, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5ff36822ea527de6]]..ctor(System.Collections.Generic.List1[Dossier365.BusinessModels.Persoon])' cannot be used on the current platform. See http://go.microsoft.com/fwlink/?LinkId=248273 for more information.__
This refers to a nonexisting page on the Internet (I have seen more than a few complaints about that!). It is not easy to find anything recent on the subject "API cannot be used". The newest posts were about 2 years old.
Because the code has not changed, I suspect the Prism library. But why? And how to overcome? I have posted this on the CodePlex Prism issuelist as well, but I get the impression that only a few readers are active there. No response for over a week on issues. I hope StackOverflow does a better job.
Please, PLEASE, anyone knows an answer to this??
Peter

After a couple of hours of comparning the code and about everything else, I finally figured out that the cause of this error lies in JSON.Net version 6.0.4. After stepping back to JSON.Net version 6.0.3 everything worked perfectly again. I have reported this in the JSON project on CodePlex.

Related

.NET CORE 3 Upgrade CORS and Json(cycle) XMLHttpRequest Error

I had my working project written in asp.net core 2.1 for a long time, but yesterday, I was forced to upgrade it to .net core 3.0 (due to 2.1 cannot call Dll' s which are written in 3.0 already).
With that, a lot of functions were obsolete or already removed. I fixed almost all of it, but one problem with CORS.
Like many people before me, I used:
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader()
.AllowCredentials());
in Configure function. And services.AddCors() in ConfigureServices function.
I was able to fixed this quite easily with setting WithOrigins() or .SetIsOriginAllowed(_ => true) instead of AllowAnyOrigin() which does not work anymore with AllowCredentials().
After that, I was able to start the application and I thought everything is fine, but then I get stuck until now with problem I do not know, how to fix.
I have DB relation N:N and relation table which handle that, that means I have Admin entity with AdminProject list property, then I have AdminProject entity with Admin list and Project list properties and Project entity with AdminProject list property once again.
When I am listing my projects of certain admin, I am returning in Controller this return Ok(projects), where I just use getAll on AdminProject entity and then with Select return only project.
For that, I have to use[JsonIgnore] in project/admin for properties which I do not need to avoid cycling when creating json.
With that said: NOW IN .NET CORE 3.0 AND CORS SETTINGS IT DOES NOT WORK.
I am getting an error:
System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
when debugging in console and error Access to XMLHttpRequest at 'http://localhost:5000/api/project/adminlist/1' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. in WEB browser
I think I tried almost everything with Cors settings etc and I do not know why is this happening now. I also tried to JsonConvert.SerializeObject() before return it ---> return Ok(JsonConvert.SerializeObject(projects)) and this is working, but I am not able (mentally) to do this in every single controllers functions.
Please help! Thanks a lot!
The problem was occurring because in .NET Core 3 they change little bit the JSON politics. Json.Net is not longer supported and if you want to used all Json options, you have to download this Nuget: Microsoft.AspNetCore.Mvc.NewtonsoftJson.
After that in your Startup.cs file change/fix/add line where you are adding MVC (in the ConfigureServices method.
So: here is what I did and what fixed my issue:
services.AddMvc(option => option.EnableEndpointRouting = false)
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
.AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);
I hope it will help somebody else.
Cheers!
A couple other things have changed in .net core 3 and now instead of using addMVC you can use addControllers. So your code might look like the follow:
services.AddControllers().AddNewtonsoftJson(x => x.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

parse4cn1 has some issue when working with Node JS and parse-server open source

The parse4cn1 library works well with parse.com but it has some issues when working with Node 4.3.2 and parse-server open source. For example, when calling the ParseUser.signup() function, the "Invalid key name" exception is always happened. I tried to debug and figure out that the ParseCommand object should add the ParseConstants.CONTENT_TYPE_JSON to its header in order to make it can work. I don't why because it still works without doing this with parse.com.
Another issue is the ParseQuery.find() is always failed when using the ParseQuery.whereContainedIn(). The server exception is "ParseException [code=102, msg=Improper encode of parameter, cause=null]". I guess this issue probably regarding the parameter has the json format in this case as well but I don't know to to resolve it. Any advice is appreciate. Sidiabale, do you have any advice? Thanks!
These problems are solved in version 3.0 of parse4cn1. Apparently, Parse Server is stricter with the need to specify the content-type header so code that previously worked with Parse.com does not work with Parse Server. I've addressed these issues in the aforementioned release. Try again with version 3.0 and let me know if you encounter any issues.

Box API .NET SDK: "pad block corrupted" exception when instantiating BoxJWTAuth

I'm using the Box SDK for .NET and just trying to get started authenticating using the Java Web Token workflow. I'm using code that's pretty much the same as the code sample that's included in the SDK's code examples.
var jwtPrivateKey = File.ReadAllText("private_key.pem");
var boxConfig = new BoxConfig(ClientId, ClientSecret, EnterpriseId, jwtPrivateKey, JwtPrivateKeyPassword, JwtPublicKeyId);
var boxJwt = new BoxJWTAuth(boxConfig);
But at that last line I'm getting an exception that says "pad block corrupted". The stack trace seems to indicate that it involves reading the private key, but I don't see what I could be doing wrong considering this is basically the same as the code sample (https://github.com/box/box-windows-sdk-v2/blob/master/Box.V2.Samples.JWTAuth/Program.cs).
Any ideas?
After re-generating the private key with Cygwin, things are working for me.
I believe what happened was I opened the private key in Notepad or something, then saved it in some format it didn't like (maybe changed encoding to UTF-8, or saved it with Windows-style line breaks).

JsonLocalisation and WPF cannot find my translation files

My app runs in WPF and Android (Windows Phone later) with mvvmcross as framework. I implemented localization with JsonLocalisation like the Babel (N21) example and it is working fine in Android. But whatever I try in WPF I get this message;
mvx:Warning: 0,22 Language file could not be loaded for Danish.SettingsViewModel -
FileNotFoundException: Unable to find resource file MyAppResources/Text/Danish/SettingsViewModel.json
at Cirrious.MvvmCross.Plugins.JsonLocalisation.MvxContentJsonDictionaryTextProvider.
LoadJsonFromResource(String namespaceKey, String typeKey, String resourcePath) at >Cirrious.MvvmCross.Plugins.JsonLocalisation.MvxTextProviderBuilder.LoadResources(String >whichLocalisationFolder)"
Stuart says in his video tutorial that the json translation files must be included as "Content" and not copied to the output folder - like;
But looking at the compiled executable with "dotPeek" doesn't reveal the files.
Am I missing something obvious? Any hints would be highly appreciated. Even confirmation from somebody who has JsonLocalisation working in WPF would be nice.
EDIT:
Well, I tried this code in my WPF mainWindow. I understand this call is used internally in MvxWPFResourceLoader.
public MainWindow()
{
....
//This return null without exceptions.
var t = Application.GetResourceStream(new Uri("MyAppResources/Text/Danish/SettingsViewModel.json", UriKind.Relative));
//This throwns an IOException; Cannot locate resource 'thisdoesnotexist/text/danish/settingsviewmodel.json'.
var y = Application.GetResourceStream(new Uri("ThisDoesNotExist/Text/Danish/SettingsViewModel.json", UriKind.Relative));
}
It seems when the path if wrong an exception is thrown. When it is correct it just returns null!!?! I am a bit puzzled, any ideas?
Best regards
Thank you for such fast answer (and for mvvmcross!).
The link you provided is to a Babel solution with a WPF sample - exactly what I needed. I mistakenly used the one from N21 without WPF sample :-)
Anyway, when looking at the sample I noticed that the json files must be included as 'Resource' and not 'Content'. That made all the difference - hurray!
Best regards

Why do I get a slew of question marks when I parse a string with SuperObject?

I'm trying to parse this string using SuperObject in Delphi 7.
procedure TForm1.btn1Click(Sender: TObject);
var
obj: ISuperObject;
fw:string;
begin
fw:= '{"type":"normal","info":{"Name":"frank","Number":"01","Age":"21","registered":"Yes","Support":"Expired"}}';
obj := TSuperObject.ParseString(PWideChar(fw), false);
mmo1.lines.Add(obj.AsJSon(true,false));
end;
But result in the memo is like this:
"????????????????????????????????????????????????????}"
What am I doing wrong?
fw is a string which in Delphi 7 is 8 bit ANSI encoded. The cast to PWideChar is thus incorrect. It will treat the 8 bit text as if it were UTF-16 encoded.
If the function you are calling really does receive PWideChar then you need to convert to UTF-16 first. For example like this:
PWideChar(WideString(fw))
You also report a separate problem that arises in the super object code. Specifically this line of code:
h := h*129 + ord(k[i]) + $9e370001;
raises an overflow error.
That happens because your project has the overflow checking option enabled (good practice to do so), but the super object code has been written under the assumption that the option is disabled. This is really a flaw in the super object code. You can solve it by disabling overflow checking in the super object code by adding {$OVERFLOWCHECKS OFF}. Ideally this would be disabled very locally for just the code that intentionally overflows. However, unless you fully understand the code it may just be easier to stuff {$OVERFLOWCHECKS OFF} at the top of the unit and move on.
Now, I'm looking at the very latest super object code and right at the top of the unit is {$OVERFLOWCHECKS OFF}. So I wonder if you are perhaps using an out of date version of the code. Pull the latest version from the repo.
I had the same problem using SuperObjects1.2.4 in delphi 7. As many people said, the solution is: to get the latest version. So, to get the lastest SuperObjects version from repository do:
1. Install git (http://git-scm.com/)
2. Right click in some Folder, choose 'Git bash' and paste the following
git clone https://code.google.com/r/steve-superobject/
Done!