asp.net looping through json data error - asp.net

I was using this example:
http://weblog.west-wind.com/posts/2012/Aug/30/Using-JSONNET-for-dynamic-JSON-parsing
to test some dynamic JSON looping but I get an error that one of my data properties does not exist even though I see it in the data. Here is my JSON data:
[
{
"$id": "1",
"$type": "TheAPI.Models.Category, TheAPI",
"Id": 1,
"Name": "Marina Park",
"Description": "Morbi elementum diam sit amet mi viverra.",
"IsActive": true,
"NewsCategories": [
{
"$id": "2",
"$type": "TheAPI.Models.NewsCategory, TheAPI",
"Id": 1,
"NewsId": 2,
"CategoryId": 1,
"News": {
"$id": "3",
"$type": "TheAPI.Models.News, TheAPI",
"Id": 2,
"Headline": "Fake News Heading 2",
"ShortDesc": "A short description about the news item 2.",
"Body": "Mortgage loan rates may change daily. To ensure that you receive the rate you were quoted, you may elect to lock in your rate by paying an up-front authorization fee",
"CreateDate": "2014-07-04T00:00:00.000",
"PublishDate": "2014-07-04T00:00:00.000",
"ExpireDate": "2014-12-31T00:00:00.000",
"NewsCategories": [
{
"$ref": "2"
}
]
},
"Category": {
"$ref": "1"
}
},
{
"$id": "4",
"$type": "TheAPI.Models.NewsCategory, TheAPI",
"Id": 5,
"NewsId": 4,
"CategoryId": 1,
"News": {
"$id": "5",
"$type": "TheAPI.Models.News, TheAPI",
"Id": 4,
"Headline": "Fake News Heading 4",
"ShortDesc": "A short description about the news item 4.",
"Body": "Mortgage loan rates may change daily. To ensure that you receive the rate you were quoted, you may elect to lock in your rate by paying an up-front authorization fee",
"CreateDate": "2014-07-04T00:00:00.000",
"PublishDate": "2014-07-04T00:00:00.000",
"ExpireDate": "2014-12-31T00:00:00.000",
"NewsCategories": [
{
"$ref": "4"
}
]
},
"Category": {
"$ref": "1"
}
}
]
}
]
And here is my .Net code to consume it:
private void LoadNews()
{
//var url = apiurl + "/news";
var url = apiurl + "/categories?$filter=Id eq 1&$expand=NewsCategories/News";
var syncClient = new WebClient();
var content = syncClient.DownloadString(url);
//Response.Write(content);
JArray jsonVal = JArray.Parse(content) as JArray;
dynamic categories = jsonVal;
foreach (dynamic category in categories)
{
Response.Write("Cat Name: " + category.Name + "<br>");
foreach (dynamic newscat in category.NewsCategories)
{
foreach (dynamic news in newscat.News)
{
Response.Write(news.Headline + "<br>");
}
}
}
//ListView1.DataSource = categories.News;
//ListView1.DataBind();
}
When I run the above it seems like my news for each does not have all the data properties like the newscat and categories do. I get the following error:
An exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll but was not handled in user code
Additional information: 'Newtonsoft.Json.Linq.JProperty' does not contain a definition for 'Headline'
Any help would be greatly appreciated. Thank you very much.

The News property on your NewsCategory isn't an array (just a single object). The .c# code below probably explains better than that...
foreach (dynamic category in categories)
{
Response.Write("Cat Name: " + category.Name + "<br>");
foreach (dynamic newscat in category.NewsCategories)
{
Response.Write(newscat.News.Headline + "<br>");
}
}

Related

how to filter only one data with a specific slug in sanity.io?

Data:
[
{
"name": "Gates of Olympus",
"slug": {
"_type": "slug",
"current": "gates-of-olympus"
}
},
{
"name": "Floating Dragon",
"slug": {
"_type": "slug",
"current": "floating-dragon"
}
},
{
"name": "Buffalo King Megaways",
"slug": {
"_type": "slug",
"current": "buffalo-king-megaways"
}
},
{
"name": "Fruit Party",
"slug": {
"_type": "slug",
"current": "fruit-party"
}
}
]
How do I query only objects with slug gates-of-olympus ?
Code:
export const getServerSideProps = async ({params}:any) => {
const query = `*[_type=="game"]{
name,
slug,
}`;
const games = await sanityClient.fetch(query);
return {
props: {
games,
},
};
};
slug is obtained through context (params.game).
I also tried,
*[_type=="game" && slug.current == ${params.game}] but still returns all data.
Wrap ${params.game} with the quotes. Like this "${params.game}". It will work
You get back all the data but the first one or first item in that array of data is the one your searching for so at the end of your query put [0] at the end to get the first value you should be solid eg *[_type=="game" && slug.current == '${params.game}'][0]
Ref
go to this video which is taught by js mastery skip to 1:21:27 he starts explaining how to get the current slug/product https://www.youtube.com/watch?v=4mOkFXyxfsU&t=5153s

Query Sum of Nested Array-Length COSMOS DB

Assume this model:
Having a collection of Writers documents, each Writer has some Posts. and each Post contains an array of Comments.
JSON:
{
"id": "1",
"partitionKey": "somePK",
"name": "John",
"posts": [
{
"id": "20",
"title": "post1",
"comments": [
{
"body": "some body"
}
]
},
{
"id": "21",
"title": "post2",
"comments": [
{
"body": "some new body"
}
]
}
]
}
I need a query that returns the following output:
[
{
"WriterName": "John",
"WriterCommentsCount": 2
}
]
I managed to get the writer's comment but I have a problem getting the name(or other properties) beside the WriterCommentsCount. Any idea of how to get the writer's name?
this is what I've tried so far (only the writer's comments count)
Along your thought, if we execute sql
SELECT c.name,array_length(post.comments) as countC FROM c join post in c.posts where c.id = '1'
we'll get response like below:
[
{
"name": "John",
"countC": 1
},
{
"name": "John",
"countC": 3
},
{
"name": "John",
"countC": 0
}
]
So using this SELECT c.name,sum(array_length(post.comments)) as countC FROM c join post in c.posts where c.id = '1' will return error 'Property reference 'c.name' is invalid'. The solution is using 'group by c.name'.
My answer in the comment and the one from #404 are all the same in this point, the difference is that I followed your thought using sum function and he uses count(1) after expand all the child item. My sql costs '3.09 RUs' and his costs the same on my test data.
Here's the situation screenshot.
The easiest is making a flat structure where you have an entry for each comment. After that you can use GROUP BY to group all entries for the same name. Try the following:
SELECT
c.name AS WriterName,
COUNT(1) AS WriterCommentsCount
FROM c
JOIN s IN c.posts
JOIN t IN s.comments
WHERE c.id = '1'
GROUP BY c.name

CosmosDb Sql query that matches common values in array between documents

I am working with Cosmos DB and I want to write a SQL query that will match common value in array of documents based on id.
To elaborate, imagine you have the following three documents:
{
"id": "2ECF4568-CB0E-4E11-A5CD-1206638F9C39",
"entityType": "ServiceInformationFacility",
"facilities": [
{
"id": "6F706BA3-27AD-45B8-9831-A531E37C4C17",
"facilityName": "Kat Service Center",
"phoneNumber": "9879561234"
},
{
"id": "7F706BA3-27AD-45B8-9831-A531E37C4C17",
"facilityName": "Honda Service Center",
"phoneNumber": "9879561234"
}]
},
{
"id": "3ECF4568-CB0E-4E11-A5CD-1206638F9C39",
"entityType": "ServiceInformationFacility",
"facilities": [
{
"id": "8F706BA3-27AD-45B8-9831-A531E37C4C17",
"facilityName": "Hyundai Service Center",
"phoneNumber": "9879561234"
},
{
"id": "7F706BA3-27AD-45B8-9831-A531E37C4C17",
"facilityName": "Honda Service Center",
"phoneNumber": "9879561234"
}]
},
{
"id": "6ECF4568-CB0E-4E11-A5CD-1206638F9C39",
"entityType": "ServiceInformationFacility",
"facilities": [
{
"id": "8F706BA3-27AD-45B8-9831-A531E37C4C17",
"facilityName": "Hyundai Service Center",
"phoneNumber": "9879561234"
},
{
"id": "7F706BA3-27AD-45B8-9831-A531E37C4C17",
"facilityName": "Honda Service Center",
"phoneNumber": "9879561234"
} ]
}
I want to write a query that return all the common facility based on id.That means when passing the list of Ids, the facility exists in the given Ids should be display(not either or).
so in the above collection it should only return "facilityName": "Honda Service Center" by passing parameter id("2ECF4568-CB0E-4E11-A5CD-1206638F9C39","3ECF4568-CB0E-4E11-A5CD-1206638F9C39","6ECF4568-CB0E-4E11-A5CD-1206638F9C39").
So far I have tried:
SELECT q.facilityName FROM c
join q in c.facilities
where c.id in('6ECF4568-CB0E-4E11-A5CD-1206638F9C39','2ECF4568-CB0E-4E11-A5CD-1206638F9C39')AND c.entityType = 'ServiceInformationFacility'
It gives me all the facility name but I need only facility which are common in the above documents that is "facilityName": "Honda Service Center".
Thanks in advance
It gives me all the facility name but I need only facility which are
common in the above documents that is "facilityName": "Honda Service
Center".
I may get your point now.However,i'm afraid that's impossible in cosmos sql. I try to count number of appearance of facilitiesName cross the documents and get below solution which is closest with your need.
sql:
SELECT count(c.id) as cnt, f.facilityName from c
join f in c.facilities
where array_contains(['6ECF4568-CB0E-4E11-A5CD-1206638F9C39','2ECF4568-CB0E-4E11-A5CD-1206638F9C39'],c.id,true)
AND c.entityType = 'ServiceInformationFacility'
group by f.facilityName
output:
Then i tried to extend it with some subquery but no luck. So i'd suggest using stored procedure to finish the next job.The main purpose is looping above result and judge if the cnt equals the [ids array].length.
Update Answer for Stored procedure code:
input param for #idArray:["6ECF4568-CB0E-4E11-A5CD-1206638F9C39","2ECF4568-CB0E-4E11-A5CD-1206638F9C39"]
Sp code:
function sample(idArray) {
var collection = getContext().getCollection();
var length = idArray.length;
var sqlQuery = {
"query": 'SELECT count(c.id) as cnt, f.facilityName from c join f in c.facilities '+
'where array_contains( #idArray,c.id,true) ' +
'AND c.entityType = "ServiceInformationFacility" group by f.facilityName',
"parameters": [
{"name": "#idArray", "value": idArray}
]
}
// Query documents and take 1st item.
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
sqlQuery,
function (err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var response = getContext().getResponse();
var returenArray = [];
for(var i=0;i<feed.length;i++){
if(feed[i].cnt==length)
returenArray.push(feed[i])
}
response.setBody(returenArray);
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
Output:

React/redux : this.props returns undefined value + array

I am using React/redux to build my app.
Here is my data (json)
{
"categories": [
{
"id": 1,
"name": "category 1",
"slug": "category-1"
"content": [
{
"id": 1,
"title": "title 1 "
},
{
"id": 2,
"title": "title 2 "
}
]
}
]
}
what I want to do :
select a category
display the content of the category selected
my store is like that :
categoryItems: [], // list of categories
categorySelected: []
data is saved correctly on my state when I select a category
on Category component I implement the function selectCategory which calls the action SELECT_CATEGORY and dispatch data to reducer. so far so good!
getCategoryList() {
return this.props.categories.map((category) => {
return (<li key={category.id}>
<Link to={`/category/${category.slug}`} onClick={() =>this.props.selectCategory(category.slug)} >{category.name} </Link>)});}
and on CategoryDetail, when I console.log(this.props.categorySelected.name) I got:
undefined
name
here is the problem because I can not read this.props.categorySelected.name
How to fix this and read proprely this props?
You have to give the complete object to your selectCategory() function.
Like this:
getCategoryList() {
return this.props.categories.map((category) => {
return (<li key={category.id}>
<Link to={`/category/${category.slug}`} onClick={() =>this.props.selectCategory(category)} >{category.name} </Link>)});
}

Ember Data FilterBy

I am trying to filter the data coming back from FindAll cause I only want data from a certain provider
// Data coming back from API
{
"-KDinaItb7lkHpai-DlG": {
"email": "johns#test.com",
"name": "John Smith",
"notes": "John is a great employee and is the best",
"phone": "215-543-9830",
"provider": "-KDhzbilOvv7Evuc5S_X"
},
"-KDjS0cCxFWQctcwXg0V": {
"email": "amanda#test.com",
"name": "Amanda Harrington",
"notes": "Amanda is a great employee",
"phone": "215-543-9830",
"provider": "-KDiokWebdhTNKTORWwn"
},
"-KDyf7pU_PyxRQSgFB59": {
"email": "lguy#test.com",
"name": "Larry Guy",
"notes": "He is a funny guy",
"phone": "702-454-2397",
"provider": "-KDhzbilOvv7Evuc5S_X"
}
}
// In the route
let providerId = model.get('provider').get('id');
​
this.store.findAll('employee').then(function(results) {
let prov = results.filterBy('provider', providerId);
​
console.log(prov);
});
When the console log happens and it returns an empty array. I think its because of the ID and its not looking at the nested object. Anyone got any thoughts?
Ok so your hash looks quite odd. Property name shouldn't be some generated hash.
code should be something like that.
I assume you have 1 wrapper object on index 0 within an array.
var filteredEmployees_promise = this.store.findAll('employee').then(function(results) {
var filteredResults = [];
Object.keys(Results[0]).forEach(key => {
var filteredObj = Results[0][key][providerId];
if(Ember.isPresent(filteredObj) {
filteredResults.pushObject(filteredObj)
}
});
return filteredResults;
});
And later
filterEmployees_promise.then(employees => { // Custom stuff })

Resources