Convert IQueryable generic to JSON - asp.net-mvc

I'm producing a projection via:
var query = from book in books
select new
{
label = book.Title,
value = book.ID
};
In my razor page I need to use:
var booksArray = [{
#(json)
}];
such that the resulting array looks like:
label: 'c++',
value: 'c++'
}, {
label: 'java',
value: 'java'
}, {
label: 'php',
value: 'php'
}, {
label: 'coldfusion',
value: 'coldfusion'
}
I've come very very close from a couple different approaches - I can get a string that looks correct on the server side but when rendered to the page itself, all the ' marks become ' .
But focusing on achieving this via JSON.net...
The most likely approach seems like it should be:
var json = JsonConvert.ToString(query);
but that tosses:
Unsupported type: System.Linq.Enumerable+WhereSelectListIterator`2[Project.Entity.Book,<>f__AnonymousType3`2[System.String,System.Int32]]. Use the JsonSerializer class to get the object's JSON representation.
What's the correct JSON.net syntax?
thx

You need a combination of .ToArray() and Html.Raw()
ToArray() to evaluate the query and make JsonConvert happy
var query = from book in books
select new
{
label = book.Title,
value = book.ID
};
var json = JsonConvert.SerializeObject(query.ToArray());
Note: you need to use JsonConvert.SerializeObject if you want to serialize complex types. JsonConvert.ToString is used to convert simple types like bool, guid, int, uri etc.
And in your view Html.Raw to not html encode the JSON:
var booksArray = #(Html.Raw(json))

Related

java swagger 3 annotations #ExampleObject from jsonfile

I'm documention one of my api with multiple examples like this:
#Operation(summary = "Create new")
#PostMapping("")
public ResponseEntity<Object> createOne(
#Parameter(description = "MyDto")
#io.swagger.v3.oas.annotations.parameters.RequestBody(
content = #Content(examples = {
#ExampleObject(name = "one", value = EXAMPLE_ONE),
#ExampleObject(name = "two", value = EXAMPLE_TWO),
#ExampleObject(name = "three", value = EXAMPLE_THREE)}
))
#RequestBody MyDTO body
) {
...
}
This works fine, though EXAMPLE_ONE is a string value. This is pretty unclear as you can see from the example below
private static final String EXAMPLE_ONE = "{\"glossary\":{\"title\":\"example glossary\",\"GlossDiv\":{\"title\":\"S\",\"GlossList\":{\"GlossEntry\":{\"ID\":\"SGML\",\"SortAs\":\"SGML\",\"GlossTerm\":\"Standard Generalized Markup Language\",\"Acronym\":\"SGML\",\"Abbrev\":\"ISO 8879:1986\",\"GlossDef\":{\"para\":\"A meta-markup language, used to create markup languages such as DocBook.\",\"GlossSeeAlso\":[\"GML\",\"XML\"]},\"GlossSee\":\"markup\"}}}}}";
I looking for a better way to provide the example. A json file would be nice, but I couldn't find anything about that.
You can use externalValue instead of value. See here
Use java text-block instead of normal quoted string
e.g. putting triple double (""")
see https://www.baeldung.com/java-text-blocks

Dynamic Lists to String Lists

I am getting data from my firestore, but I am only interested in the array part for this. I've prepared a dartpad for it:
https://dartpad.dev/9b99f0e2e8c83913f9cd2bd71bd70d81
How do I convert List data = ['Room 1', 'Room 2']; to List<String> stringData = ['Room 1', 'Room 2'];
There are similar questions, but I am probably too stupid to understand how the fix works, I tried to implement them but I think their input data looks a bit different. (like these: How to cast <dynamic> to List<String>? or How to Create DropdownButton with a list of JSON data within a list in flutter)
Use cast():
List data = ['Room 1', 'Room 2'];
List<String> stringData;
void main() {
stringData = data.cast<String>(); // <- look here
print(stringData);
print(data);
}

Can't serialize records, in F#, with json.net

A very basic example:
type private test =
{
a : string
b : string list
}
let t = { a = "hello"; b = ["1"; "2"] }
let s = JsonConvert.SerializeObject(t)
This will produce an empty string.
I have seen that json.net supports F# and that there are a lot of posts related to enum types, etc but I'm not there yet: I'm trying to serialize something very simple.
Many posts point toward another json serializer project, called Chiron, but it was updated a year ago and they're still like:
We’re working on Guides and reference content for working with Chiron, so keep an eye on the Updates
Is there something obvious I haven't seen?
So ideally, working with json.net would be better, especially since I'm used to it in C#
The issue seems to be that Json.Net only serializes public fields of F# records. When you mark the record as private, all its fields also become private and those are ignored. The following works as expected for me:
type test =
{
a : string
b : string list
}
let t = { a = "hello"; b = ["1"; "2"] }
let s = JsonConvert.SerializeObject(t)
This produces the expected JSON:
{"a":"hello","b":["1","2"]}

Dynamic table names in Entity Framework linq

I'm using Entity Framework 6 with ASP.Net MVC 5. When using a database context object, is there a way to use a variable for the table name, without having to manually write the query?
For example:
var tableName = "NameOfTable";
result = context.tableName.Find(...);
I know that particular code won't work, because tableName is not defined in context, but is there a way to achieve the desired effect?
There are some similar questions on this site, but they never really solved the problem and they were for earlier versions of entity framework, so I'm hoping that there is an answer now.
Here's a simple solution using a switch to associate a particular Type to a table. You could also maintain use some sort of Dictionary<string, Type> object.
var tableName = "Table1";
// Get proper return type.
Type returnType;
switch(tableName) {
case "Table1":
returnType = typeof(Table1EntityType);
break;
case "Table2":
returnType = typeof(Table2EntityType);
break;
}
var query = context.Set(returnType);
// Filter against "query" variable below...
var result = query.Where(...);
-or-
var tableName = "Table1";
Dictionary<string, Type> tableTypeDict = new Dictionary<string, Type>()
{
{ "Table1", Table1Type },
{ "Table2", Table2Type }
};
var query = context.Set(tableTypeDict[tableName]);
// Filter against "query" variable below...
var result = query.Where(...);
EDIT: Modified for Entity Framework
EDIT2: Use typeof per #thepirat000 's suggestion
In addition to the helpful answers above, I also want to add this in case it helps someone else.
If you are getting this error on the "Where" clause in Mark's answer:
'DbSet does not contain a definition for 'Where' and no acceptable extension method 'Where' accepting an argument of the type 'DbSet' could be found.
Installing the Nuget Package "System.Linq.Dynamic.Core" made the error disappear for us.
If you need to access the LINQ methods and the column names from the table, you can code something like this:
var tableName = "MyTableName";
var tableClassNameSpace = "MyProject.Models.EntityModels";
using (var dbContext = new MyEntities())
{
var tableClassName = $"{tableClassNameSpace}.{tableName}";
var dynamicTableType = Type.GetType(tableClassName); // Type
var dynamicTable = dbContext.Set(dynamicTableType); // DbSet
var records = dynamicTable
.AsQueryable()
.ToDynamicList()
.OrderBy(d => d.MyColumnName)
.Select(d => new { d.MyColumnName })
.ToList();
// do stuff
}

Dart: How to bind to variables annotated with int via Web UI?

What is the best practice in Dart when dealing with classes as data records?
To Elaborate: When writing an app, it is likely that a class for a table row will be created. As in
class Item { int itemid, String itemName, double score }
Item item = new Item();
This allows compile time catching of any typos etc. in Dart. (Unlike using a class that relies on NoSuchMethod.)
It will also need a corresponding string structure to bind to the HTML such as
<input id="itemname" type="text" bind-value="itemEdit.itemName">
So the Dart would be:
class ItemEdit { String itemId, String itemName, String score }
ItemEdit itemEdit = new ItemEdit();
Next we need a way to get from one to the other, so we add a method to Item
fromStrings(ItemEdit ie) {
itemid = ie.itemId == null ? null : int.parse(ie.itemId);
itemName = ie.ItemName;
score = ie.score == null ? null : double.parse(ie.score);
}
And the other way around:
toStrings(ItemEdit ie) {
ie.itemid = itemId == null ? '' : ie.itemId.toString();
ie. itemName = itemName == null ? '' : itemname; // Web_ui objects to nulls
ie.score = score == null ? null : score.toStringAsFixed(2);
}
Also, we get jason data from a database, so we need to add another method to Item:
fromJson(final String j) {
Map v = JSON.parse(j);
itemid = v['itemid'];
itemname = v['itemname'];
score = v['score'];
}
And we need to be able to revert to default values:
setDefaults() { itemId = 0; itemName = "New item"; score = 0; }
This verbosity gets me feeling like I am writing COBOL again!
There is something fundamental missing here - either in my understanding, or in the Dart/WebUI libraries.
What I would like to write is something like
class Item extends DataRecord {
int itemid = 0,
String itemName = 'New item',
double score = 0.0;
}
Then, without further coding, to be able to write code such as
item.toStrings();
...
item.fromStrings();
...
item.fromJson(json);
...
item.setDefaults(); // results in {0,'New item',0.0}
And to be able to write in the HTML:
value="{{item.strings.score}}"
If this was possible, it would be quicker, simpler, clearer, and less error prone than the code I am writing at the moment.
(Full disclosure, this answer is written with the assumption that at least one bug will be fixed. See below)
Three suggestions that might help.
Use named constructors to parse and create objects.
Take advantage of toJson() when encoding to JSON.
Use bind-value-as-number from Web UI
1) Named constructors
import 'dart:json' as json;
class Item {
int itemid;
String itemName;
double score;
Item.fromJson(String json) {
Map data = json.parse(json);
itemid = data['itemid'];
itemName = data['itemName'];
score = data['score'];
}
}
2) Encoding to JSON
The dart:json library has a stringify function to turn an object into a JSON string. If the algorithm encounters an object that is not a string, null, number, boolean, or collection of those, it will call toJson() on that object and expect something that is JSON-encodable.
class Item {
int itemid;
String itemName;
double score;
Map toJson() {
return {'itemid':itemid, 'itemName':itemName, 'score':score};
}
}
3) Now, having said that, sounds like you want to easily bind to HTML fields and get primitive values back, not just strings. Try this:
<input type="number" min="1" bind-value-as-number="myInt" />
(Note, there seems to be a bug with this functionality. See https://github.com/dart-lang/web-ui/issues/317)
(from https://groups.google.com/a/dartlang.org/forum/#!topic/web-ui/8JEAA5OxJOc)
Just found a way to perhaps help a little in the this situation:
class obj {
int gapX;
String get gapXStr => gapX.toString();
set gapXStr(String s) => gapX = int.Parse(s);
...
Now, from the HTML you can use, for example
bind-value="gapXStr"
and in code you can use
x += ob.gapX;

Resources