Mvc5 getting data list from controller to ajax function c# - asp.net-mvc-5

i am getting data list from controller to ajax function to my datatable.all works well but my question is, I want to get one of list property to textbox and other values to datatable columns.for example:
list= TotalAMount,PAidAmount,RemAmount
and datatable
Totalamount| PaidAMount | RemAmount| ---------??
20 | 4 | 16 |
so this works fine but i want to get TotalAmount value to some textbox also like textbox=20.
my JS function==>>
`
function AddGetHistoryView(SupplierID) {
$('#HistoryModal').modal('show');
Datatabless = $("#HistoryTable").DataTable({
"autoWidth": false,
"ajax": {
"type": "GET",
"url": "#Url.Action("getHistoryData", "Supplier")/" + SupplierID,
"datatype": "JSON",
data: {
"Amount": $("#TotalAmount").val()
},
data: { SupplierID: SupplierID },
},
"columns": [
{
"data": "DetailID",
"visible": false,
},
{
"data": "TotalAmount",
"width": "5%",
},
{
"data": "PaidAmount",
"width": "5%",
},
{
"data": "RemAmount",
"width": "5%",
},
{
"data": "PaidDate",
"width": "5%",
},
{
"data": "PaymentType",
"width": "5%",
},
{
"data": "DetailID", "render": function (data) {
return "<a class='btn btn-success' onclick=EditRow(" + data + ") style='margin-left:12px'><i class='glyphicon glyphicon-edit'> Update</i><a/>,<a class='btn btn-danger' onclick=deleteRow(" + data + ") style='margin-left:12px'><i class='glyphicon glyphicon-trash'> Delete</i> <a/>";
},
"width": "40%",
"orderable": false,
"pagingType": "full_numbers",
"paging": true,
},
],
});
}
`
Controller Method==>
public ActionResult getHistoryData(int SupplierID)
{
ob.Configuration.ProxyCreationEnabled = false;
var data = ob.Table_Supplier.Join(ob.Table_SupplierDetails, sup => sup.SupplierID, det => det.SupplierID, (sup, det) => new
{
DetailID=det.DetailID,
SupplierID = sup.SupplierID,
TotalAmount = det.TotalAmount,
RemAmount = det.RemAmount,
PaidAmount = det.PaidAmount,
PaidDate = det.PaidDate,
PaymentType = det.PaymentType,
Amount = sup.Amount
}).Where(x=>x.SupplierID==SupplierID).ToList();
return Json(new { data = data }, JsonRequestBehavior.AllowGet);
}

Related

Unable to retrive ordered job list from Google Transcoder API

i'm using the node.js client library of google transcoder api. I'm able to retrive a paginated list of some jobs, but i'm not able to order elements by start date. Here my codes:
const { TranscoderServiceClient } = require('#google-cloud/video-transcoder').v1;
class TranscoderApiController {
constructor() {
this.projectId = process.env.GOOGLE_CLOUD_PROJECT;
this.location = process.env.TASK_LOCATION;
}
async getEntries(req, res, next) {
const params = {
pageSize: req.query.pageSize ? parseInt(req.query.pageSize) : 10,
pageToken: req.query.pageToken,
filter: req.query.filter,
orderBy: req.query.orderBy
}
const client = new TranscoderServiceClient();
const result = await client.listJobs({
parent: client.locationPath(this.projectId, this.location),
pageSize: params.pageSize,
orderBy: 'createTime.seconds'
}, {
autoPaginate: false
});
if (result.length == 3 && result[2] != undefined) {
return result[2];
} else {
return result[1];
}
}
}
module.exports = new TranscoderApiController();
When i call the getEntries method i receive the following error:
"3 INVALID_ARGUMENT: The request was invalid: sort order \"createTime.seconds\" is unsupported"
If i remove the orderBy: 'createTime.seconds' line then the api works but is not ordered as i want. The result is something like that (i abbreviate the json):
{
"jobs": [
{
"labels": {},
"name": "projects/<id>/locations/europe-west1/jobs/<uuid>",
"inputUri": "",
"outputUri": "",
"state": "SUCCEEDED",
"createTime": {
"seconds": "1656602896",
"nanos": 386772728
},
"startTime": {
"seconds": "1656602900",
"nanos": 755000000
},
"endTime": {
"seconds": "1656603062",
"nanos": 428000000
},
"ttlAfterCompletionDays": 30,
"error": null,
"config": {
"inputs": [
{
"key": "input0",
"uri": "gs://<url>/render_md.mp4",
"preprocessingConfig": null
}
],
"editList": [...],
"elementaryStreams": [...],
"muxStreams": [...],
"manifests": [],
"adBreaks": [],
"spriteSheets": [],
"overlays": [],
"output": {
"uri": "gs://<url>/md.mp4/"
},
"pubsubDestination": {
"topic": "projects/<id>/topics/transcoder_api"
}
},
"jobConfig": "config"
},
...
],
"unreachable": [],
"nextPageToken": "Co8BCjgKDGV1cm9wZS13ZXN0MRIZdHJhbnNjb2Rlci5nb29nbGVhcGlzLmNvbRgBII..."
}
As you can see each job have the startTime.seconds property. I follow the syntax described here:
https://google.aip.dev/132#ordering
Any support to solve the ordered issue is appreciated.

JsForce API calls loading extremely slowly

I'm currently using JsForce + Express, but I find that when I attempt to manipulate the data in the backend, the API call is extremely slow. Specifically, when I drill down to the Ids/Names of each of the individual objects, it slows down dramatically/fails to load.
It loads in less a second if I use this code:
router.get("/testChain", (req, res) => {
conn
.query(
"SELECT Id, Name, (SELECT Id, Part_Type__c FROM Monster_Parts__r) FROM Monster_Frame__c"
)
.then((result) => {
let gMonster = {};
let frames = result.records;
// Select Frame
let sFrameNo = randomNumber(frames.length);
let sFrame = frames[sFrameNo];
gMonster["Monster_Frame__c"] = sFrame.Id;
// Break into parts
let parts = sFrame.Monster_Parts__r.records;
let sortedParts = parts.reduce((r, o) => {
var k = o.Part_Type__c;
if (r[k] || (r[k] = [])) r[k].push(o);
return r;
}, {});
// Select Part
Object.keys(sortedParts).forEach((key, i, arr) => {
let parts = sortedParts[key];
let partNo = randomNumber(parts.length);
let selectedPart = parts[partNo];
gMonster[key] = selectedPart;
});
// Generate Name
gMonster["Name"] = sFrame.Name + "-" + randomNumber();
return gMonster;
})
.then((result) => {
res.json(result);
});
});
And gives me the following output:
{
"Monster_Frame__c": "a025j000004GsdXAAS",
"Tail__c": {
"attributes": {
"type": "Monster_Parts__c",
"url": "/services/data/v42.0/sobjects/Monster_Parts__c/a015j00000CfGUXAA3"
},
"Id": "a015j00000CfGUXAA3",
"Part_Type__c": "Tail__c"
},
"Leg__c": {
"attributes": {
"type": "Monster_Parts__c",
"url": "/services/data/v42.0/sobjects/Monster_Parts__c/a015j00000CfGUeAAN"
},
"Id": "a015j00000CfGUeAAN",
"Part_Type__c": "Leg__c"
},
"Head__c": {
"attributes": {
"type": "Monster_Parts__c",
"url": "/services/data/v42.0/sobjects/Monster_Parts__c/a015j00000CfGU0AAN"
},
"Id": "a015j00000CfGU0AAN",
"Part_Type__c": "Head__c"
},
"Body__c": {
"attributes": {
"type": "Monster_Parts__c",
"url": "/services/data/v42.0/sobjects/Monster_Parts__c/a015j00000CfGUKAA3"
},
"Id": "a015j00000CfGUKAA3",
"Part_Type__c": "Body__c"
},
"Back__c": {
"attributes": {
"type": "Monster_Parts__c",
"url": "/services/data/v42.0/sobjects/Monster_Parts__c/a015j00000CfGUPAA3"
},
"Id": "a015j00000CfGUPAA3",
"Part_Type__c": "Back__c"
},
"Name": "Serpent-7210"
}
However, if I change this line from:
gMonster[key] = selectedPart;
to populate the specific Id (instead of all the fields):
gMonster[key] = selectedPart.Id;
The API call fails 60% of the time. (Sometimes it returns with the desired output of carrying only the Ids.
Does anyone know how to fix this?

Traversing array and changing object values

I'm trying to update the values ​​of my payments array objects
{
"balance": 109610,
"gifts": [],
"orders": [],
"payments": [{
"isPaid": 0,
"status": "Pending",
"address": "3KsdQbmADyz1KNN7qqX1yZcMXBbfFCm31r",
"date": 1624057559970
}, {
"isPaid": 0,
"status": "Pending",
"address": "3FYQK6YiAaL8fEbDWaXYw38CJN3K2y5dPD",
"date": 1624058531601
}],
"isVendedor": false,
"isAdmin": true,
"createdAt": {
"$date": "2021-06-17T21:10:15.020Z"
},
"username": "teste",
"email": "teste#teste.com",
"password": "$2a$10$qUNkorDuvbf.AYLTvjNc4ebKyNgLa7L9NoTBwAIV8.BfN51umaD9O",
"__v": 3
}
First, I look for the object of the user who made a request to my server
const userPayment = await User.find({"payments.address": notification.address}).exec();
Then I go through the user object and find it until I find the position where I find notification.address again
userPayment.forEach((AllPayments, index) => {
AllPayments.payments.forEach((payment, index) => {
if (payment.address == notification.address) {
if (payment.isPaid || payment.status != "Pending")
return res.json({
success: false,
error: "Payment Already Processed!",
});
const valueToDeposit = Math.round(notification.fiat_amount);
console.log(
userPayment[0].payments[index].isPaid,
userPayment[0].payments[index].status
);
// Set payments[index].isPaid = true
// Set payments[index].status = "Paid"
});
});
So I tried to make these 3 ways and none of them was successful.
userPayment[0].balance += valueToDeposit; // this works when save() is triggered
userPayment[0].payments[index].isPaid = 1; // this doesnt works when save() is triggered
userPayment[0].payments[index].status = "Paid"; // this doesnt works when save() is triggered
userPayment[0].updateOne({"payments.address": notification.address}, { $set: { "payments.$.isPaid": 1,"payments.$.status":"Paid" } },(err, result) => { console.log(err, result); }); this doesnt works
userPayment[0].save()

How to show data in React Table with structure {_id:" xx",timestamp:"xx" ,message:"{"temperature:22","humi":45}" }?

React-Table
I have made an axios.get request to the back-end which in turn gives a large data-set from mongodb. The
structure of data returned is :
[
1: {_id: "5dd3be2ecf55e1ec388f502b", timestamp: 1574157870567, message: "{"temperature":58,"humidity":59,"pressure":"1 bar"}"}
2: {_id: "5dd3be2ecf55e1ec388f502a", timestamp: 1574157870067, message: "{"temperature":78,"humidity":79,"pressure":"1 bar"}"}
...
]
I want to show it to react-table.The id and timestamp is being displayed but the temperature and other variable are not being displayed.The message is string.How can I parse such amount of data at back-end to convert message into object?
Back-end code
router.get('/viewData',async(req,res) =>{
collection.find({},{_id:0,timestamp:0}).sort({timestamp:-1}).limit(400).toArray(function (err, resultantData) {
if (err)
throw err;
//var storedDataArray ;
//var gotData=[];
//var index =0;
//storedDataArray=resultantData;
//console.log(storedDataArray)
// storedDataArray.forEach(element => {
// gotData[index]=JSON.parse(element);
// console.log(gotData[index])
// index++;
// })
// console.log(gotData.length);
res.status(200).json(resultantData);
});
Is there any way to show temperature and other quantities in react table?
React-Table
class deviceData extends Component {
constructor(props) {
super(props)
this.state = {
dataList:[],
data : ' '
};
}
componentDidMount(){
const url="http://localhost:5000/api/data/viewData";
fetch (url,{
method: "GET"
}).then(response=> response.json()).then(result=>{
console.log(result);
this.setState({
dataList : result,
});
});
}
render() {
const columns =[
{
Header:"Message ID",
accessor:"_id",
sortable: true,
filterable: false,
style:{
textAlign: "left"
},
width: 300,
maxWidth: 100,
minWidth: 100,
},
{
Header:"Time Stamp",
accessor:"timestamp",
width: 300,
maxWidth: 100,
minWidth: 100,
},
{
Header:"Temperature",
id:'temperature',
filterable: false,
accessor: 'temperature'
},
{
Header:"Pressure",
id:'pressure',
filterable: false,
accessor: 'pressure'
},
{
Header:"Humidity",
id:'humidity',
filterable: false,
accessor: 'humidity'
},
]
return(
<div className="ReactTable">
<ReactTable
columns={columns}
data={this.state.dataList}
defaultPageSize={10}
className="-striped -highlight"
>
</ReactTable>
<div id={"#"+ this.props.id} ></div>
</div>
);
}
}
[![React-Table][1]][1]
Backend Response
[
{
"_id": "5dd3be2fcf55e1ec388f502c",
"timestamp": 1574157871067,
"message": "{\"temperature\":93,\"humidity\":94,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ecf55e1ec388f502b",
"timestamp": 1574157870567,
"message": "{\"temperature\":58,\"humidity\":59,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ecf55e1ec388f502a",
"timestamp": 1574157870067,
"message": "{\"temperature\":78,\"humidity\":79,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2dcf55e1ec388f5029",
"timestamp": 1574157869567,
"message": "{\"temperature\":88,\"humidity\":89,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2dcf55e1ec388f5028",
"timestamp": 1574157869066,
"message": "{\"temperature\":99,\"humidity\":100,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ccf55e1ec388f5027",
"timestamp": 1574157868567,
"message": "{\"temperature\":38,\"humidity\":39,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2ccf55e1ec388f5026",
"timestamp": 1574157868067,
"message": "{\"temperature\":82,\"humidity\":83,\"pressure\":\"1 bar\"}"
},
{
"_id": "5dd3be2bcf55e1ec388f5025",
"timestamp": 1574157867566,
"message": "{\"temperature\":76,\"humidity\":77,\"pressure\":\"1 bar\"}"
}
]
Convert string back to object by using parse()
ex: var object = JSON.parse(str);
Important thing is to define column with correct accessor. Try this one:
const columns = [
{
Header: "Id",
accessor: "_id"
},
{
Header: "timestamp",
accessor: "timestamp"
},
{
Header: "Temprature",
accessor: "message.temprature"
},
{
Header: "humidity",
accessor: "message.humidity"
},
{
Header: "pressure",
accessor: "message.pressure"
}
];
And Use it in React-table like this:
<ReactTable
data={loans} // Instead of loans, use variable where you store your response
columns={columns}
defaultPageSize={10}
sortable={true}
/>
I think you can try with adding a headers in your fetch method
fetch (url,{
method: "GET",
headers: {
"Accept": "application/json",
"Content-Type": "application/json",
}
})
It will ensure your response is JSON
N.B. Try your url with postman first, setting those headers and see whether result is JSON or not, if it is JSON I believe my code will help you, if it is not a JSON return try to change your back-end code to ensure it return JSON using postman

Count unseen messages from object Lodash

I am trying to get count of unseen messages from object in lodash.
below is my object
[
"conversation_id": "5a88779b2321141f2864e484"
"messages": [
{
"message_id": "5a88779b2321141f2864e483",
"sender_uid": 2,
"receiver_uid": 1,
"created": "2018-02-17T18:42:35.252Z",
"status": 1,
"delivered": false,
"seen": true,
}
]
]
I want to get count of seen: false messages
You can use filter to get all see = false messages and then can check length
var users = {
"conversation_id": "5a88779b2321141f2864e484",
"messages": [
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": true,},
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": false },
{ "message_id": "5b88779b2321141f2864e483","sender_uid": 2, "receiver_uid": 1, "created": "2018-02-17T18:42:35.252Z", "status": 1,"delivered": false,"seen": false,}
]
}
var unseen_messages = _.filter(users.messages, message => { return !message.seen; }).length;
console.log(unseen_messages);
<script src="https://cdn.jsdelivr.net/lodash/4.13.1/lodash.min.js"></script>
Without lodash you can use reduce
var users = {
"conversation_id": "5a88779b2321141f2864e484",
"messages": [
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": true,},
{ "message_id": "5a88779b2321141f2864e483","sender_uid": 2,"receiver_uid": 1,"created": "2018-02-17T18:42:35.252Z","status": 1,"delivered": false,"seen": false },
{ "message_id": "5b88779b2321141f2864e483","sender_uid": 2, "receiver_uid": 1, "created": "2018-02-17T18:42:35.252Z", "status": 1,"delivered": false,"seen": false,}
]
}
items = users.messages;
var totalCount = items.reduce((total, obj) => { return (!obj.seen) ? (total +1) : total }, 0);
console.log(totalCount);
_.sumBy would do the trick
const unseenMessages = _.sumBy(users.messages, message => message.seen === false);

Resources