I am trying to deserialize the following JSON to an array using C# dynamics:
[
{
"itemId":"15",
"quantity":101,
"eventTimestamp":"00000000-0000-0000-0000-000000000000",
"salesChannel":"1",
"unlimitedQuantity":false
},
{
"itemId":"15",
"quantity":101,
"eventTimestamp":"00000000-0000-0000-0000-000000000000",
"salesChannel":"2",
"unlimitedQuantity":false
}
]
I have already tried two different approaches, without success:
dynamic itemsBalance = JObject.Parse(content);
and
var itemBalanceType = new {
itemId = "", quantity = 0, eventTimestamp = "", salesChannel = ""
};
var itemsBalance = JsonConvert.DeserializeAnonymousType(content, itemBalanceType);
I am currently using C# dynamics with all other deserializations, and would not like to create classes for each response.
Is there any way to do this ?
Thanks
I found a solution:
JArray itemsBalance = JArray.Parse(content);
if (itemsBalance != null)
{
for (int i = 0; i < itemsBalance.Count; i++)
{
string itemBalanceJSON = itemsBalance[i].ToString();
dynamic itemBalance = JObject.Parse(itemBalanceJSON);
lbxResponse.Items.Add(itemBalance.itemId + " - " + itemBalance.salesChannel +": " + itemBalance.quantity.ToString());
}
}
Should there be any better, please let me know...
You could do it with less amount of code:
dynamic result = JsonConvert.Deserialize(content);
foreach(var entry in result)
{
lbxResponse.Items.Add(entry.itemId + " - " + entry.salesChannel + ": " + entry.quantity);
}
Related
Well, I am preparing a data entry application on the ASP platform, netcore2.1, it's my first application so I have approached it like a laravel project, so with little to no Razor format that could have saved me a lot of time, I get it.
The problem I am facing is there is a method called getAllData, which flies around the database and fetch data for editing of around 60 boxes. I run it repeatedly since I faced many smaller errors and after a few reruns the result just stops coming in. breakpoints show at least some of the data is being prepared to be set to a List but never makes it there. I used nested datareaders to get a single long list. it now will only run once and it's no more detected. There is no error prompt. I am baffled as to why and need help.
Controller Action from JS, same story when running from controller too...
var theId = $("#ProjectId").val();
var theId2 = $("#InvestorId").val();
$.ajax({
url: '/Home/getAllData/',
dataType: "json",
type: "GET",
data: { id: theId, id2: theId2 },
contentType: 'application/json',
async: true,
processData: true,
cache: false,
success: function (response) {
response = JSON.parse(JSON.stringify(response));
if (response[0] == null) {
alertify.error("Nothing is Coming In!! possibly too many tries at setting its values");
} else {
//LOAD THE DATA TO PAGE ELEMENTS
}
it keeps triggering the alertify and a console.log shows an empty array...message reflects my exp.
public List<AllData> getAllData(int id, int id2)
{
SqlConnection con = new SqlConnection(GetConStringTemp.ConString());
string query = "Select --- where ProjectId=" + id + "";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
var temp = new List<AllData>();
var plannedProjectOutput = new List<PlannedServiceViewModel>();
var actualProjectOutput = new List<ActualServiceViewModel>();
var investorAddress = new List<InvestorAddressViewModel>();
//a bunch more vars...
var queryOutput = "Select --- where ProjectId=" + id + "";
var cmdOutput = new SqlCommand(queryOutput, con);
var readerOutput = cmdOutput.ExecuteReader();
while (readerOutput.Read())
{
if (readerOutput.GetBoolean(1) == true)
{
actualProjectOutput.Add(new ActualServiceViewModel
{
TypeOfProduct = readerOutput.IsDBNull(0) ? "" : readerOutput.GetString(0),
ActualQuantity = readerOutput.IsDBNull(2) ? 0 : readerOutput.GetDecimal(2),
ActualUnits = readerOutput.IsDBNull(3) ? "" : readerOutput.GetString(3),
ActualDomestic = readerOutput.IsDBNull(4) ? 0 : readerOutput.GetDecimal(4),
ActualExport = readerOutput.IsDBNull(5) ? 0 : readerOutput.GetDecimal(5)
});
}
else
{
plannedProjectOutput.Add(new PlannedServiceViewModel
{
TypeOfProduct = readerOutput.IsDBNull(0) ? "" : readerOutput.GetString(0),
PlannedQuantity = readerOutput.IsDBNull(2) ? 0 : readerOutput.GetDecimal(2),
PlannedUnits = readerOutput.IsDBNull(3) ? "" : readerOutput.GetString(3),
PlannedDomestic = readerOutput.IsDBNull(4) ? 0 : readerOutput.GetDecimal(4),
PlannedExport = readerOutput.IsDBNull(5) ? 0 : readerOutput.GetDecimal(5)
});
}
}
readerOutput.Close();
// a bunch more definitions too...
while (reader.Read())
{
var cmd2 = new SqlCommand("Select --- from Investor where InvestorId=" + id2 + "", con);
SqlDataReader reader2 = cmd2.ExecuteReader();
while (reader2.Read())
{
if (reader2.GetString(0) == "4")
{
var queryCompany = "Select ---- from Investor where InvestorId=" + id2 + "";
var cmdCompany = new SqlCommand(queryCompany, con);
var readerCompany = cmdCompany.ExecuteReader();
while (readerCompany.Read())
{
var queryReq = "Select ---- where ProjectId=" + id + "";
var cmdReq = new SqlCommand(queryReq, con);
var readerReq = cmdReq.ExecuteReader();
while (readerReq.Read())
{
var queryCostPlanned = "Select ---- ProjectCost where ProjectId=" + id + " AND isActual=0";
var cmdCostPlanned = new SqlCommand(queryCostPlanned, con);
var readerCostPlanned = cmdCostPlanned.ExecuteReader();
while (readerCostPlanned.Read())
{
var queryCostActual = "Select --- from ProjectCost where ProjectId=" + id + " AND isActual=1";
var cmdCostActual = new SqlCommand(queryCostActual, con);
var readerCostActual = cmdCostActual.ExecuteReader();
while (readerCostActual.Read())
{
var queryEmployementPlanned = "Select --- where ProjectId=" + id + " AND isActual=0";
var cmdEmployementPlanned = new SqlCommand(queryEmployementPlanned, con);
var readerEmployementPlanned = cmdEmployementPlanned.ExecuteReader();
while (readerEmployementPlanned.Read())
{
var queryEmployementActual = "Select --- where ProjectId=" + id + " AND isActual=1";
var cmdEmployementActual = new SqlCommand(queryEmployementActual, con);
var readerEmployementActual = cmdEmployementActual.ExecuteReader();
while (readerEmployementActual.Read())
{
temp.Add(new AllData
{
LegalStatus = reader2.IsDBNull(0) ? "" : reader2.GetString(0),
FirstName = readerCompany.IsDBNull(1) ? "" : readerCompany.GetString(1),
FirstNameAmh = readerCompany.IsDBNull(0) ? "" : readerCompany.GetString(0),
TINNumber = readerCompany.IsDBNull(2) ? "" : readerCompany.GetString(2),
UserId = readerCompany.IsDBNull(3) ? "" : readerCompany.GetString(3),
TypeInvestor = readerCompany.IsDBNull(4) ? "" : readerCompany.GetString(4),
BranchPlace = readerCompany.IsDBNull(5) ? "" : readerCompany.GetString(5),
CountryOfOrigin = readerCompany.IsDBNull(6) ? "" : readerCompany.GetString(6),
ProjectName = reader.IsDBNull(1) ? "" : reader.GetString(1),
ProjectDescription = reader.IsDBNull(2) ? "" : reader.GetString(2),
FileNumber = reader.IsDBNull(19) ? "" : reader.GetString(19),
StartDate = reader.IsDBNull(3) ? "" : reader.GetString(3),
OperationDate = reader.IsDBNull(4) ? "" : reader.GetString(4)
// a bunch more assignments
});
}
readerEmployementActual.Close();
}
readerEmployementPlanned.Close();
}
readerCostActual.Close();
}
readerCostPlanned.Close();
}
readerReq.Close();
}
readerCompany.Close();
}
else
{
same with some difference....
}
reader.Close();
con.Close();
AllDatas = temp;
return AllDatas;
}
its a handful, it usually works, it won't if you attempt to get it one too many times,
Thanks
I managed to get the resultset. the way i approached it, while i made all the queries cascade to get a single unified List, I discovered there were some blanks or null returns, but since i coded it with nulls in mind i didn't get why it didn't work in this specific instance. while i still did not find out why, i disassembled the queries from nested datareaders to individual ones and it isolated the faulty query and made others work.
Rule of thumb, don't cascade datareaders if you can, i have them working in some other section of the program but this was the most complex. it will save you a lot of headaches.
Ok so I am trying to load a CSVStream into an ExcelPackage (I am using EPPlus).
It always fails at line 221482, no matter what option I choose. I am running on x64 and I have in my app.config...
The error given is the one from the title :(
public ExcelPackage ExcelPackageFromCsvStream(Stream csvStream)
{
var excelPackage = new ExcelPackage();
var workSheet = excelPackage.Workbook.Worksheets.Add("Sheet1");
var csvFormat = new ExcelTextFormat
{
Delimiter = ',',
TextQualifier = '"',
DataTypes = new[] { eDataTypes.String }
};
using (var sr = new StreamReader(csvStream))
{
int i = 1;
foreach (var line in sr.ReadLines("\r\n"))
{
workSheet.Cells["A" + i].LoadFromText(line, csvFormat);
i++;
}
}
return excelPackage;
}
Resolved it by creating multiple ExcelPackages and also I've read the stream in batches (e.g. 200k lines at once)
public List<ExcelPackage> ExcelPackagesFromCsvStream(Stream csvStream, int batchSize)
{
var excelPackages = new List<ExcelPackage>();
int currentPackage = -1; // so that first package will have the index 0
var csvFormat = new ExcelTextFormat
{
Delimiter = ',',
TextQualifier = '"',
DataTypes = new[] {eDataTypes.String}
};
using (var sr = new StreamReader(csvStream))
{
int index = 1;
foreach (var line in sr.ReadLines("\r\n"))
{
if ((index - 1) % batchSize == 0)
{
var excelPackage = new ExcelPackage();
excelPackage.Workbook.Worksheets.Add("Sheet1");
excelPackages.Add(excelPackage);
currentPackage++;
index = 1;
}
excelPackages[currentPackage].Workbook.Worksheets.First().Cells["A" + index].LoadFromText(line, csvFormat);
index++;
}
}
return excelPackages;
}
I have to bind an <asp:calendar> with data fetched from a database using a linq query.
Here is the linq code
public List<AllCalander> SearchCalender(int month, int zip, string type, int cause)
{
var xyz = (from m in DB.Calenders
where(m.DateFrom.Value.Month==month || m.Zip==zip || m.ActivityType==type || m.CauseID==cause)
group m by new { m.DateFrom } into grp
select new
{
caustitle = grp.Select(x => x.Caus.CauseTitle),
datfrm = grp.Key.DateFrom,
total = grp.Count()
})
.ToList()
.Select(m => new AllCalander
{
DateFrom =Convert.ToDateTime(m.datfrm),
CauseTitle = string.Join(",", m.caustitle),
Total = m.total
});
My aspx.cs code is here
List<AllCalander> calnder = calbll.SearchCalender(mnth,ZipString,type,causeString);
foreach (var myItem in calnder)
{
string datetime = myItem.DateFrom.ToString();
Literal myEventNameLiteral = new Literal();
myEventNameLiteral.ID = i + myItem.CauseID.ToString();
// string currentcalanderDate = e.Day.Date.Day.ToString() ;
if (string.Equals(DateTime.Parse(datetime).ToString("MMM dd yyyy"), e.Day.Date.ToString("MMM dd yyyy")))
{
string a = myItem.CauseTitle;
if (a != cause)
cause = a;
coun++;
myEventNameLiteral.Mode = LiteralMode.PassThrough;
myEventNameLiteral.Text = "<br /><span style='font-family:verdana; font-size:10px;'>" + myItem.CauseTitle + "(" + myItem.Total + ")"+ " ";
e.Cell.Controls.Add(myEventNameLiteral);
}
i++;
}
but on output it only shows the last value from database instead of showing all the data.
Can somebody please tell me what's wrong?
Thanks in advance
group m by new { m.DateFrom, m.Caus.CauseTitle } into grp
I am using the Extjs4 multigrouping plugin from here.
I have used it successfully, however i want to show the summary of the totals of each column within the group header itself . how do i set up the appropriate CSS for that ?
In Multigrouping.js
getFragmentTpl: function() {
var me = this;
return {
indentByDepth: me.indentByDepth,
depthToIndent: me.depthToIndent,
renderGroupHeaderTpl: function(values, parent) {
return Ext.XTemplate.getTpl(me, 'groupHeaderTpl').apply(values, parent);
//var z = new Ext.XTemplate('{name} ({rows.grouplength})');
//return z.apply(values, parent);
}
};
},
In my grid
features: [
{
ftype:'multigrouping',
groupHeaderTpl: [
'{[this.readOut(values)]}',
{
readOut:function(values) {
debugger;
var sum1 =0 ,sum2=0,sum3=0;
for( var i = 0 ; i< values.records.length ; i++)
{
var val = parseFloat(values.records[i].data.d2012.mp);
sum1 += isNaN(val) ? 0.0 : val;
val = parseFloat(values.records[i].data.d2013.mp);
sum2 += isNaN(val) ? 0.0 : val;
val = parseFloat(values.records[i].data.d2014.mp);
sum3 += isNaN(val) ? 0.0 : val;
}
return values.name + '(' + values.records.length + ')' + ' ' + sum1.toFixed(2) + ' ' + sum2.toFixed(2) + ' ' + sum3.toFixed(2);
}
}
]
},
had to resort to a few hacks to get this to work. still waiting on an official answer.
The main reason i had to do this and not use the multigrouping summary is because
- i want to limit the number of records from the server. I can do some smart grouping of
my business objects at the server side.
- the main reason to do this is because of IE8's performance on larger sets of data.
- had already tried the extjs4 tree grid component which works well on chrome but had performance issues on IE8.
the hack is to
a) use an array property in the grid to store the dom elements which i want to manipulate
b) use a boolean to know when the layout is completed the first time
b) add listeners for afterlayout ( when your app can do an Ext.get('..dom element..') you know you are done )
The listener :
listeners :
{
afterlayout : function(eopts)
{
var x = this.mOwnArray;
if(!this.loadedwithVals && x.length > 0)
{
for(var i =0 ; i<x.length ; i++)
{
var dom = Ext.get(x[i].id);
var theId = dom.id;
theId = theId.match(/\d+/)[0];
var title = dom.query("td[class='x-grid-cell x-grid-cell-first']");
title[0].className = 'x-grid-cell x-grid-cell-gridcolumn-' + theId + ' x-grid-cell-first';
title[0].colSpan=1;
var groupedHeader = dom.query("div[class='x-grid-group-title']");
groupedHeader[0].innerHTML = x[i].name + '(' + x[i].length + ')';
for(var year=2012;year<=2018;year++)
{
var t = "t"+year;
var someText1 = '<td class=" x-grid-cell x-grid-cell-numbercolumn">';
var someText2 = '<div class="x-grid-cell-inner " style="text-align: left; ;">';
var someText3 = '<div class="x-grid-group-title">' + x[i].total[t] + '</div></div></td>';
var someText = someText1 + someText2 + someText3;
dom.insertHtml("beforeEnd",someText);
}
}
this.loadedwithVals = true;
}
}
And the feature as in
features: [
{
ftype:'multigrouping',
startCollapsed : true,
groupHeaderTpl: [
'{[this.readOut(values)]}',
{
readOut:function(values) {
var header = new Object();
header.id = values.groupHeaderId;
header.sum = [];
header.total = new Object();
for(var year = 2012 ; year <= 2018 ; year++)
{
var t = "t"+year;
header.total[t] = [];
}
// all the records in this header
for( var i = 0 ; i< values.records.length ; i++)
{
// for all the 'years' in this record
for(var year=2012;year<=2018;year++)
{
var d = "d"+year;
var ct = "t" + year;
var arecord = values.records[i].data;
var val = parseFloat(arecord[d].mp);
val = isNaN(val) ? 0.0 : val;
Ext.Array.push(header.total[ct],val);
}
}
// push the sum of the records into its top level group
for(var year = 2012 ; year <= 2018 ; year++)
{
var t = "t"+year;
var sum = Ext.Array.sum(header.total[t]);
header.total[t] = sum.toFixed(2);
}
header.name = values.name;
header.length = values.records.length;
var headerName = values.name;
if(values.hasOwnProperty('parent'))
{
var parent = values.parent;
headerName = headerName.replace(parent,'');
}
header.name = headerName;
header.length = values.records.length;
Ext.Array.push(grid.mOwnArray,header);
// really not used
return values.name + '(' + values.records.length + ')';
}
}
]
},
]
i have to fetch those records where cityname like'zipcode' where zipcode is variable and apply conditions
var zipcd = (from u in db.ZipCodes1
where u.CityName.Contains(zipcode) && u.CityType == "D"
select u).ToList().Select(u => new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
stateabbr = u.StateAbbr
}).Distinct();
Viewsearch vs = (Viewsearch)zipcd;
if (zipcd.Count() > 1)
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName;
}
else if (locations == "")
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName;
}
else
{
locations = "United States;" + vs.stateabbr + ";" + vs.CityName + "," + locations;
}
if (zipcd.Count() > 3) is greater than 3
{
locations = locations.Replace(locations, "," + "<br>");
}
The problem is that you're casting an iterator to the type of a single element on the line
ViewSearch vs = (ViewSearch)zipcd.
If you want vs to be a single object, you must call First() or FirstOrDefault() on your collection:
ViewSearch vs = zipcd.First(); // Throws if there are no elements
ViewSearch vs = zipcd.FirstOrDefault(); // null if there are no elements
First of all I would suggest that you download and use the lovely LINQPad not only to run your LINQ queries first but also to learn from it (has a lot of samples that you can run right form there, no more config needed)
for your question:
var zipcd = (
from u in db.ZipCodes1
where u.CityName.Contains(zipcode) && u.CityType == "D"
select new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
stateabbr = u.StateAbbr
}).Distinct().ToList();
As you can see the query works:
Distinct at the end of your query uses IEqualityComparer, and I'm guessing you haven't defined one for Viewsearch. It would look something like this:
public class ViewsearchComparer : IEqualityComparer<Viewsearch>
{
public bool Equals(Viewsearch vs1, Viewsearch vs2)
{
// Implementation
}
public int GetHashCode(Viewsearch vs)
{
// Implementation
}
}
After you have that defined, you pass it into your distinct call:
.Select(u => new Viewsearch
{
Zipcode = u.ZIPCode,
CityName = u.CityName,
Stateabbr = u.StateAbbr
})
.Distinct(new ViewsearchComparer());