Using a list from JSON in MVC - asp.net-mvc

I am using a Utilities.Cache.Insert to insert the JSON output from a URI.
[
{
Id": 44,
"Address": "nho:87, Huston",
"Name": "Ann"
},
{
"Id": 87,
"Address": "nho:17, Texas",
"Name": "Robert"
}
...
...
]
Utilities.Cache.Insert("my_list", AddList);
Then using a "SelectListItem" List to store the "Name" and "Address"
List<SelectListItem> d = new List<SelectListItem>();
foreach (Dictionary<string, string> item in AddList)
{
d.Add(new SelectListItem() { Text = item["Name"], Value = item["Address"] });
}
However, I need a way to store all three values, "Name","Address" and "Id" so "selectListItem" cannot be used. What are the other alternatives?

Related

OData GroupBy and Select

Expecting the following example table CustomerOrders
Id
CustomerId
Customer
Product
1
1
Alice
Pizza
2
1
Alice
Pasta
3
2
Bob
Burger
In C# I'm was able to use the following Linq query to produce a nice List<Customer> result with a nested orders collection for every customer:
List<CustomerOrders> queryResult = GetCustomerOrders();
return queryResult
.GroupBy(x => x.CustomerId)
.Select(x => new Customer
{
Id = x.First().CustomrId,
Customer = x.First().Customer,
Orders = x.ToList()
})
.ToList();
Now I want to achive this result directly over an odata query in the client application to get the following JSON result:
[
{
"id": 1,
"customer": Alice,
"orders": [ "Pizza", "Pasta" ]
},
{
"id": 2,
"customer": Bob,
"orders": [ "Burger" ]
}
]
Is there a way to transfer this query in odata?
GroupBy in OData is similar to SQL, only the aggregates and common columns are returned, we lose access to the individual items, so we can return a grouping and a count of the orders, using group by, but not the array of orders.
If your schema has a Customer entity and there is a collection navigation property from Customer to Orders, then we do not need to use grouping at all:
~/Customers?$expand=Orders($select=Product)&$select=Id,Name
The output is structured in a slightly similar manner and should resemble something like this:
{
"#odata.context": "~/$metadata#Customers(Id,Name,Orders(Product))",
"value": [
{
"Id": 1,
"Name": "Alice",
"Orders": [{"Product": "Pizza"},
{"Product": "Pasta"}]
},
{
"Id": 2,
"Name": "Bob",
"Orders": [{"Product": "Burger"}]
}
]
}
A key concept in OData is that the shape of the overall graph should not be modified, it is designed deliberately to always maintain the structure of the Entities that are returned. This means that the definition document is always correct, the only thing missing from this response is the additional fields that were not requested.
If you need the output in the client specifically as mentioned, then you can expose that as a custom function on the controller:
[EnableQuery]
public IQueryable<CustomerSummary> GetCustomersWithOrderSummary()
{
List<CustomerOrders> queryResult = GetCustomerOrders();
return queryResult
.GroupBy(x => x.CustomerId)
.Select(x => new CustomerSummary
{
Id = x.Key,
Customer = x.First().Customer,
Orders = x.Select(o => o.Product)
});
}
If using GroupBy, the closest response we can get is this:
~/CustomerOrders?$apply=groupby((CustomerId,Customer),aggregate($count as Orders))
But here we will return a count of the orders, and not an array of the product values as expected:
{
"#odata.context": "~/$metadata#CustomerOrders(CustomerId,Customer,Orders)",
"value": [
{
"#odata.id": null,
"CustomerId": 1,
"Customer": "Alice",
"Orders": 2
},
{
"#odata.id": null,
"CustomerId": 2,
"Customer": "Bob",
"Orders": 1
}
]
}

How to convert List<List<Map<String, String>>> into List<List<CustomObject>> in dart

I want to convert a List<List<Map<String, String>>> into List<List> a custom class, how to achieve this in dart.
How to convert this
List<List<Map<String, String>>> = [
{
"course_name": "Estimation & Quantity Surveying",
"credit": "4",
"hours": "40",
},
{
"course_name": "IDP - Industrial Design Project phase II",
"credit": "4",
"hours": "40",
}
],
[
{
"course_name": "Data Base Management System",
"credit": "4",
"hours": "40",
},
{
"course_name": "Estimation & Quantity Surveying",
"credit": "4",
"hours": "40",
},
],
];
into
List<List<StudentTimeTable>>
This is my custom class
class StudentTimeTable{
final String courseName;
final String credit;
final String hours;
}
Something like this would do the trick:
class StudentTimeTable {
final String courseName;
final String credit;
final String hours;
StudentTimeTable.fromMap(Map<String, String> map)
: courseName = map['course_name'],
credit = map['credit'],
hours = map['hours'];
#override
String toString() =>
'StudentTimeTable(courseName = $courseName, credit = $credit, hours = $hours)';
}
void main() {
List<List<Map<String, String>>> input = [
[
{
"course_name": "Estimation & Quantity Surveying",
"credit": "4",
"hours": "40",
},
{
"course_name": "IDP - Industrial Design Project phase II",
"credit": "4",
"hours": "40",
}
],
[
{
"course_name": "Data Base Management System",
"credit": "4",
"hours": "40",
},
{
"course_name": "Estimation & Quantity Surveying",
"credit": "4",
"hours": "40",
},
],
];
List<List<StudentTimeTable>> output = [
...input.map(
(subList) => [...subList.map((map) => StudentTimeTable.fromMap(map))])
];
output.forEach(print);
// [StudentTimeTable(courseName = Estimation & Quantity Surveying, credit = 4, hours = 40), StudentTimeTable(courseName = IDP - Industrial Design Project phase II, credit = 4, hours = 40)]
// [StudentTimeTable(courseName = Data Base Management System, credit = 4, hours = 40), StudentTimeTable(courseName = Estimation & Quantity Surveying, credit = 4, hours = 40)]
}
Explanation of what going on!
The solution makes use of "spread operator" which you can read more about here:
https://dart.dev/guides/language/language-tour#spread-operator
In shot, it is a easy way to create a new list and take all elements in an iterable and put into the list.
So lets see what I do:
List<List<StudentTimeTable>> output = [...input.map((subList) => ...)]
Here we define a new list which are filled with the elements from input.map. The map method are used to take each element in the input and convert it to something else. In our case we want to convert each element in our input (which are also a List) from List<Map<String, String>> to List<StudentTimeTable>
We are then mapping each List<Map<String, String>> to the value from this:
[...subList.map((map) => StudentTimeTable.fromMap(map))]
Which returns a list filled with the elements from the iterator returned from subList.map. The purpose of this map is to convert Map<String, String> into StudentTimeTable.
This is done by calling our new constructor which takes a Map<String, String>:
StudentTimeTable.fromMap(Map<String, String> map)
: courseName = map['course_name'],
credit = map['credit'],
hours = map['hours'];
The same code could have been written something like this which is properly easier to read:
final output = <List<StudentTimeTable>>[];
for (final sublist in input) {
final studentTimeTableSubList = <StudentTimeTable>[];
for (final map in sublist) {
studentTimeTableSubList.add(StudentTimeTable.fromMap(map));
}
output.add(studentTimeTableSubList);
}
And a third way would be something like this which uses "collection for" from the same link about "spread operator":
final output = [
for (final sublist in input)
[for (final map in sublist) StudentTimeTable.fromMap(map)]
];

Post method with multiple parameter

I am unable to insert multiple rows in database using Post method in MVC web API. I have written code for it but when i am testing by inserting multiple rows through postman it is giving error. At line first the variable "delegatetable" shows null due to which error is coming. i am not doing database connection through entity framework, i have created a DelegateTable class.
public HttpResponseMessage Post(List<DelegateTable> delegatetable)
{
try
{
using (var delegateContext = new ShowContext())
{
foreach (DelegateTable item in delegatetable)
{
DelegateTable delegates = new DelegateTable();
delegates.Salutation__c = item.Salutation__c;
delegates.First_Name__c = item.First_Name__c;
delegates.Last_Name__c = item.Last_Name__c;
delegates.Account_Name__c = item.Account_Name__c;
delegates.Contact_Email__c = item.Contact_Email__c;
delegates.Category__c = item.Category__c;
delegates.Conference_Type__c = item.Conference_Type__c;
delegates.Conference_Selection__c = item.Conference_Selection__c;
delegates.Payment_Statuss__c = item.Payment_Statuss__c;
delegates.Barcode__c = item.Barcode__c;
delegateContext.SaveChanges();
}
var message = Request.CreateResponse(HttpStatusCode.Created, delegatetable);
message.Headers.Location = new Uri(Request.RequestUri.ToString());
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
Json data that i am passing is below
[
{
"attributes": {
"type": "Registration__c",
"url": "/services/data/v43.0/sobjects/Registration__c/a3h8E0000009VuVQAU"
},
"Salutation__c": "Dr.",
"First_Name__c": "Test",
"Last_Name__c": "Test",
"Account_Name__c": "Test",
"Contact_Email__c": "test123#gmail.com",
"Category__c": "Test",
"Conference_Type__c": null,
"Conference_Selection__c": null,
"Payment_Statuss__c": null,
"Barcode__c": "Test"
},
{
"attributes": {
"type": "Registration__c",
"url": "/services/data/v43.0/sobjects/Registration__c/a3hD0000001kEfOIAU"
},
"Salutation__c": "Mr.",
"First_Name__c": "Demo",
"Last_Name__c": "Demo",
"Account_Name__c": "Demo",
"Contact_Email__c": "Demo#gmail.com",
"Category__c": "Demo",
"Conference_Type__c": null,
"Conference_Selection__c": null,
"Payment_Statuss__c": null,
"Barcode__c": null
}
]
You may try to reformat your payload as a JSON array, as the problem might be that the payload cannot be converted to a List.
Try this:
{
"delegates" :
[
{
"attributes": ..., ...
},
{ "attributes": ..., ...
},
...
]
}

Couchdb Reference Document

I'm new to CouchDB and struggling to implement a basic example. I have three documents Customer, Contact, Address and I want join them into a single document.
Account Document
{
"_id": "CST-1",
"_rev": "8-089da95f148b446bd3b33a3182de709f",
"name": "Customer",
"code": "CST-001",
"contact_Key": "CNT-001",
"address_Key": "ADD-001",
"type": "Customer"
}
Contact Document
{
"_id": "CNT-001",
"_rev": "8-079da95f148b446bd3b33a3182de709g",
"fullname": "Happy Swan",
"type": "Contact"
}
Address Document
{
"_id": "ADD-001",
"_rev": "8-179da95f148b446bd3b33a3182de709c",
"street1": "9 Glass View",
"street2": "Street 2",
"city": "USA",
"type": "Address"
}
Map/Query:
var map= function (doc) {
if (doc.type === 'Customer') {
emit(doc.id, { contact_Key: doc.contact_Key, address_Key: doc.address_Key })
}
};
db.query({ map: map }, { include_docs: true }, function (err, res) {
});
I want all 3 documents in a single document when I query account e.g.
Expected result
{
"_id": "CST-1",
"_rev": "8-089da95f148b446bd3b33a3182de709f",
"name": "Customer",
"code": "CST-001",
"contact_Key": "CNT-001",
"address_Key": "ADD-001",
"type": "Customer",
"Contact: {
"_id": "CNT-001",
"_rev": "8-079da95f148b446bd3b33a3182de709g",
"fullname": "Happy Swan",
"type": "Contact"
}",
"Address: {
"_id": "ADD-001",
"_rev": "8-179da95f148b446bd3b33a3182de709c",
"street1": "9 Glass View",
"street2": "Street 2",
"city": "USA",
"type": "Address"
}"
}
I don't see any better solution than querying the account document first and then querying the other two once you know their IDs. If you think about it, it makes sense because the only link between these documents is the IDs stored in the account document, so to get all three at the same time, internally the DB would have to do two queries: first the account document, then the other two. And by design CouchDB only does one query at a time.
If you had the account doc ID stored into the contact and address documents however, you could use a list function to merge them all into one.
First you would need a view:
function(doc) {
if (doc.type === 'Customer') {
emit(doc._id, doc);
}
if (doc.type === 'Contact' || doc.type === 'Address') {
emit(doc.account_id, doc);
}
}
Then a list function:
function(head, req) {
var row, account, contact, address;
while (row = getRow()) {
if (row.value.type === 'Customer') {
account = row.value;
} else if (row.value.type === 'Contact') {
contact = row.value;
} else if (row.value.type === 'Address') {
address = row.value;
}
}
account['Contact'] = contact;
account['Address'] = address;
provides("json", function() {
return { 'json': account };
});
}
And you would query it with:
GET /db/_design/foo/_list/the-list/the-view?key="CST-1"

How to access CouchDB documents using CouchRest model

Please help me to solve this. I’ve around 1500 documents in my CouchDB, each document belongs to any one of the types (‘Survey’ and ’Response’).
I need solution for followings
1] Need to display Document Ids (_id) in a Dropdown list which has document type (documentType) as ‘Survey’
2] If I select an item (_id) from drop down, I need to display all document Ids (_id) in list box which belongs to selected ID (_id selected from drop down list)
I've total 1500 documents like this
{
"_id": "ff2fb2554682ba613c2f83c63502808a",
"_rev": "4-dd559696434a402739e789ccc8c9a481",
"answers": [
{
"answers": [
"Aug 19,2011"
],
"questionId": "50f3df434ae02ac7fff48c1c2bde83e4"
},
{
"answers": [
"Bechu Yadav"
],
"questionId": "15504f006e58872fd94871fe0c9d32ad"
},
{
"answers": [
"35"
],
"questionId": "3c447a2f5cc6ca1985ce2c81463a3c47"
},
{
"answers": [
"Male"
],
"questionId": "a6df7c25602939554612ef6de762f5b9"
},
{
"questionId": "2f66155965e60094f23f01af531d5af1",
"subAnswers": [
{
"questionId": "1dae2d86eef846c967254c9e369170ce"
},
{
"questionId": "40ffeb4d33dab1fe8d2d8b73c02ed13b"
},
{
"questionId": "2db1e8b6e97d5baa8935b9b31fcc9648"
},
{
"questionId": "0f8bb9f91ea8085b4ffb839ee8deabb5"
},
{
"questionId": "22a93ecb72c50ff8899f8b2937776e51"
},
{
"questionId": "e5106384790c2be745c952c4b867a0ff"
}
]
"questionId": "492cf9bd41257ea478c5222fbba06616"
}
],
"createdAt": "2011-08-19T21:05:36.486+0000",
"createdBy": "user4",
"documentType": "Response",
"ipAddress": "42.110.85.67",
"location": {
"latitude": 26.8415613,
"longitude": 75.8222883,
"provider": "network"
},
"surveyId": "6df022f0f371752167ad4920b38e1c37",
"published": true
}
And my CouchRest model looks like as follows
class Android < CouchRest::Model::Base
property :description, String
property :_id, String
property :_rev, String
property :documentType, String
design do
view :by_documentType,:map =>"function(doc){if (doc.documentType == 'Survey') {emit(doc._id);}}"
view :by_createdBy
end
end
But when I access by_documentType it's returning nil
Android.find_by_documentType('Survey')
Thanks Friends!
Finally I found the Answer, I changed my Model as follows
require 'couchrest_model'
class Android < CouchRest::Model::Base
property :description, String
property :_id, String
property :_rev, String
property :documentType, String
property :surveyId, String
design do
view :by_document_type,:map =>"function(doc) {if (doc.documentType == \"Survey\") {emit([doc._id,doc.title], 1);}}",:reduce=>"function(keys, values, rereduce) {return sum(values);}"
view :by_surveyId,:map =>"function(doc) {emit([doc.surveyId], 1);}",:reduce=>"function(keys, values, rereduce) {return sum(values);}"
end
end
And now able to call this view as required. following returns all the documents which has document type 'Survey'
Android.by_document_type.rows
And Based on Survey ID selection, I can retrieve all documents which belongs to selected survey id, as follows
Android.by_surveyId.key('Selected Survey ID goes here').rows
Try Android.by_documentType.key('Survey')

Resources