I cannot seem to work out how to populate a sub class...
These are the classes I have:
public class Item
{
public Meta meta { get; set; }
public Items[] objects { get; set; }
}
public class Meta
{
public int limit { get; set; }
public object next { get; set; }
public int offset { get; set; }
public object previous { get; set; }
public int total_count { get; set; }
}
public class Items
{
public Additionalprices additionalPrices { get; set; }
public string barcode { get; set; }
public Category category { get; set; }
public int categoryPosition { get; set; }
public string cdate { get; set; }
public DateTime ctime { get; set; }
public DateTime ctimeOnServer { get; set; }
public Dimensions dimensions { get; set; }
public string entityType { get; set; }
public object imageURL { get; set; }
public object[] imageURLs { get; set; }
public string longDesc { get; set; }
public string manufacturer { get; set; }
public int minQty { get; set; }
public DateTime mtime { get; set; }
public DateTime mtimeOnServer { get; set; }
public int multQty { get; set; }
public string name { get; set; }
public int objID { get; set; }
public string owner { get; set; }
public string resource_uri { get; set; }
public string sku { get; set; }
public object thumbnailURL { get; set; }
public object[] thumbnailURLs { get; set; }
public string unitPrice { get; set; }
public string uuid { get; set; }
public Variant[] variants { get; set; }
}
I want to add some dummy objects...
This is the code I have...
// Create a dummy Category
HandShake_Classes.Category categoryToUpload = new HandShake_Classes.Category();
categoryToUpload.name = "Trev Category";
// Create a dummy Item
HandShake_Classes.Item itemToUpload = new HandShake_Classes.Item();
// THIS IS WHERE MY PROBLEM IS...
itemToUpload.objects = new HandShake_Classes.Items();
// THE ERROR I AM GETTING IS Error 2 Cannot implicitly convert type 'handshake.com.HandShake_Classes.Items' to 'handshake.com.HandShake_Classes.Items[]'
// Only populate required fields at the moment
itemToUpload.objects[0].sku = "ljklj";
itemToUpload.objects[0].name = "Trevs Product";
itemToUpload.objects[0].unitPrice = "1.23";
itemToUpload.objects[0].minQty = 1;
itemToUpload.objects[0].category = categoryToUpload;
I just cannot work out how define the Items[] I think
Can anyone point me in the right direction please?
Thanks
You have to initialize the array first. Let's say you need 10 items:
itemToUpload.objects = new HandShake_Classes.Items[10];
And then you can set every array item to the new Items() instance:
itemToUpload.objects[0] = new HandShake_Classes.Items();
itemToUpload.objects[0].sku = "ljklj";
itemToUpload.objects[0].name = "Trevs Product";
itemToUpload.objects[0].unitPrice = "1.23";
itemToUpload.objects[0].minQty = 1;
itemToUpload.objects[0].category = categoryToUpload;
And just to make it clear: if you don't know how many items object property will have to handle, you should consider changing it to List<Items> instead of Items[] array:
itemToUpload.objects = new List<HandShake_Classes.Items>();
var newItem = new HandShake_Classes.Items();
newItem = new HandShake_Classes.Items();
newItem.sku = "ljklj";
newItem.name = "Trevs Product";
newItem.unitPrice = "1.23";
newItem.minQty = 1;
newItem.category = categoryToUpload;
itemToUpload.objects.Add(newItem);
Instantiate the array of type items as
itemToUpload.objects = new HandShake_Classes.Items[10];
After this instantiation, you would require to instantiate every index of the object.
For example
itemToUpload.objects[i] = new HandShake_Classes.Items();
This means you are instantiating a single object, and that object would be in array at index 'i'.
you can then set the properties of the Items in objects array by writing as
itemToUpload.objects[i].barcode
even call the functions
itemToUpload.objects[i].CalculateTax()
similarly you can use any constructors if defined.
Related
I'm building a feature with a jquery datatable, the idea is to have a list of stores in the parent row, and then when expanding the parent to list all the licensed terminals in child rows that are linked to the store parent row by a StoreLicenseId column. The issue I am having is that I have a ViewModel with two models, one for the list of stores and one for the licensed terminals. I'm busy building the method into my controller, my problem is in the second part of the method where I new up "StoreLicenseDetails = sl.Select(tl => new TerminalListViewModel()", all the references to tl.terminalId and tl.Terminalname. I get this error "StoreListViewModel does not contain a definition for TerminalID and no accessible extension method". I can see why this is happening, so my question really is, how do I include this "second" TerminalListViewModel into my method to form part of the query ?
ViewModel
public partial class StoreListViewModel
{
public List<TerminalListViewModel> StoreLicenseDetails { get; set; } = null!;
public int Id { get; set; }
public Guid StoreLicenseId { get; set; }
[DisplayName("Store Name")]
public string StoreName { get; set; } = null!;
[DisplayName("App One Licenses")]
public int QtyAppOneLicenses { get; set; }
[DisplayName("App Two Licenses")]
public int QtyAppTwoLicenses { get; set; }
[DisplayName("Date Licensed")]
public DateTime DateLicensed { get; set; }
[DisplayName("Licensed Days")]
public int LicenseDays { get; set; }
[DisplayName("Is License Active")]
public bool LicenseIsActive { get; set; }
}
public partial class TerminalListViewModel
{
public int Id { get; set; }
public Guid StoreLicenseId { get; set; }
public Guid TerminalId { get; set; }
public string TerminalName { get; set; } = null!;
public string LicenseType { get; set; } = null!;
public int TerminalLicenseDays { get; set; }
public DateTime DateLicensed { get; set; }
public bool LicenseIsActive { get; set; }
public bool IsDecommissioned { get; set; }
public DateTime LastLicenseCheck { get; set; }
}
Controller Method
//sl = StoreList
//tl = TerminalList
public IEnumerable<StoreListViewModel> GetStoreList()
{
return GetStoreList().GroupBy(sl => new { sl.StoreLicenseId, sl.StoreName, sl.QtyAppOneLicenses,
sl.QtyAppTwoLicenses, sl.DateLicensed, sl.LicenseDays,
sl.LicenseIsActive })
.Select(sl => new StoreListViewModel()
{
StoreName = sl.Key.StoreName,
QtyAppOneLicenses = sl.Key.QtyAppOneLicenses,
QtyAppTwoLicenses = sl.Key.QtyAppTwoLicenses,
DateLicensed = sl.Key.DateLicensed,
LicenseDays = sl.Key.LicenseDays,
LicenseIsActive = sl.Key.LicenseIsActive,
StoreLicenseId = sl.FirstOrDefault().StoreLicenseId,
StoreLicenseDetails = sl.Select(tl => new TerminalListViewModel()
{
StoreLicenseId = tl.StoreLicenseId,
TerminalId = tl.TerminalId,
TerminalName = tl.TerminalName,
}).ToList()
}).ToList();
}
Based on the error,I suppose your GetStoreList() method returns List<OrderListViewModel> ,but your OrderListViewModel doesn't contains properties of TerminalListViewModel,So you got the error
GetStoreList() method should return List<SourceModel>( Source is the model which contains all the properties of StoreListViewModel and TerminalListViewModel)
For example,the link your provided:Multiple child rows in datatable, data from sql server in asp.net core
public class OrderList
{
//source of properties of OrderListViewModel(parent rows)
public int OrderId { get; set; }
public string Customer { get; set; }
public string OrderDate { get; set; }
//source of properties of OrderListDetailViewModel(child rows)
public int KimlikId { get; set; }
public string Product { get; set; }
public string Color { get; set; }
public int Qntty { get; set; }
}
public class OrderListViewModel
{
public int OrderId { get; set; }
public string Customer { get; set; }
public string OrderDate { get; set; }
public List<OrderListDetailViewModel> OrderListDetails { get; set; }
}
public class OrderListDetailViewModel
{
public int KimlikId { get; set; }
public string Product { get; set; }
public string Color { get; set; }
public int Qntty { get; set; }
}
Orderlist contains all columns OrderListViewModel and OrderListDetailViewModel needs.
When it comes to your case,you should
create 3 models (source,parentrow,childrows)
model for parentrows contains the properties
StoreLicenseId,StoreName, QtyAppOneLicenses,QtyAppTwoLicenses, DateLicensed, LicenseDays,LicenseIsActive
and model for childrows contains the other properties of source model
If you still have questions,please show the data you pulled form db,and I'll write a demo for you
I want to know which one performs faster
from JsonConvert.DeserializeObject or Custom model binding
for Example:
My ViewModel class:
public class AssessmentViewModel : BaseViewModel
{
public Guid AssessmentGUID { get; set; }
public string AssessmentCategory { get; set; }
public string AssessmentType { get; set; }
public string AssessmentName { get; set; }
public string AssessmentNameEnglish { get; set; }
public string AssessmentInstruction { get; set; }
public string AssessmentInstructionEnglish { get; set; }
public int? SequenceNum { get; set; }
public int? MaxScore { get; set; }
public bool? IsNegativeMarking { get; set; }
public decimal? NegativeRatio { get; set; }
public List<StringMapDDLViewModel> AssessmentCategoryDDList { get; set; }
public List<StringMapDDLViewModel> AssessmentTypeDDList { get; set; }
public List<FOFormSectionViewModel> FOFormSectionList { get; set; }
public List<StringMapDDLViewModel> FieldTypeList { get; set; }
public List<StringMapDDLViewModel> ValidationTypeList { get; set; }
}
I am calling Stored Procedure and it returns 100 thousands of data.
So my question is which will perform faster from below code:
Method 1: Serialize result then Deserialize it.
var assessmentList = db.AssessmentSP(Constant.ActionGetAll, null, status).ToList<AssessmentSP_Result>();
objALVM.AssessmentList = JsonConvert.DeserializeObject<List<AssessmentViewModel>>(JsonConvert.SerializeObject(assessmentList));
Method 2: One by one property binding
var assessmentList = db.AssessmentSP(Constant.ActionGetAll, null, status).ToList<AssessmentSP_Result>().ToList();
objALVM.AssessmentList = assessmentList.Select(x => new AssessmentViewModel()
{
AssessmentGUID = x.AssessmentGUID,
AssessmentType = x.AssessmentType,
AssessmentName = x.AssessmentName,
AssessmentNameEnglish = x.AssessmentNameEnglish,
AssessmentInstruction = x.AssessmentInstruction,
AssessmentInstructionEnglish = x.AssessmentInstructionEnglish,
SequenceNum = x.SequenceNum,
MaxScore = x.MaxScore,
IsNegativeMarking = x.IsNegativeMarking,
NegativeRatio = x.NegativeRatio,
}).ToList();
I'm trying to deserialize a Json String to a object but I only get 0 and null back.
Here is my code:
string result = "[{\"page\":1,\"pages\":1,\"per_page\":\"50\",\"total\":1},[{\"id\":\"BEL\",\"iso2Code\":\"BE\",\"name\":\"Belgium\",\"region\":{ \"id\":\"ECS\",\"value\":\"Europe & Central Asia(all income levels)\"},\"adminregion\":{ \"id\":\"\",\"value\":\"\"},\"incomeLevel\":{ \"id\":\"OEC\",\"value\":\"High income: OECD\"},\"lendingType\":{ \"id\":\"LNX\",\"value\":\"Not classified\"},\"capitalCity\":\"Brussels\",\"longitude\":\"4.36761\",\"latitude\":\"50.8371\"}]]";
var serializer = new DataContractJsonSerializer(typeof(LandRootObject));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(result));
var data = (LandRootObject)serializer.ReadObject(ms);
public class LandRootObject
{
public int page { get; set; }
public int pages { get; set; }
public string per_page { get; set; }
public int total { get; set; }
[DataMember]
public List<Land> land { get; set; }
}
Thanks!
I have tested this method and it's working.
Your entity classes. (I did not code all these classes. They are code generated using paste special.)
public class LandRootObject
{
public int page { get; set; }
public int pages { get; set; }
public string per_page { get; set; }
public int total { get; set; }
}
public class LandBodyObject
{
public string id { get; set; }
public string iso2Code { get; set; }
public string name { get; set; }
public Region region { get; set; }
public Adminregion adminregion { get; set; }
public Incomelevel incomeLevel { get; set; }
public Lendingtype lendingType { get; set; }
public string capitalCity { get; set; }
public string longitude { get; set; }
public string latitude { get; set; }
}
public class Region
{
public string id { get; set; }
public string value { get; set; }
}
public class Adminregion
{
public string id { get; set; }
public string value { get; set; }
}
public class Incomelevel
{
public string id { get; set; }
public string value { get; set; }
}
public class Lendingtype
{
public string id { get; set; }
public string value { get; set; }
}
Then the deserialisation method. Your Json has two parts. So I am splitting it in to 2 for deserialisation.
string result = "[{\"page\":1,\"pages\":1,\"per_page\":\"50\",\"total\":1},[{\"id\":\"BEL\",\"iso2Code\":\"BE\",\"name\":\"Belgium\",\"region\":{ \"id\":\"ECS\",\"value\":\"Europe & Central Asia(all income levels)\"},\"adminregion\":{ \"id\":\"\",\"value\":\"\"},\"incomeLevel\":{ \"id\":\"OEC\",\"value\":\"High income: OECD\"},\"lendingType\":{ \"id\":\"LNX\",\"value\":\"Not classified\"},\"capitalCity\":\"Brussels\",\"longitude\":\"4.36761\",\"latitude\":\"50.8371\"}]]";
var parts = result.Split(new[] {",["}, StringSplitOptions.None);
if (parts.Length > 1)
{
var header = parts[0].Replace("[", "");
var jsonHeader = JsonConvert.DeserializeObject<LandRootObject>(header);
var body = "[" + parts[1].Replace("]]","]");
var jsonBody = JsonConvert.DeserializeObject<List<LandBodyObject>>(body);
}
Use List type
var serializer = new DataContractJsonSerializer(typeof(List<LandRootObject>));
// ...
var data = (List<LandRootObject>)serializer.ReadObject(ms);
Edit:
Now I see - your json array consists of 2 different elements. I suppose its [RootObject, Lands]. You better use the Newtonsoft.Json to deserialize the object.
var str = "[{\"page\":1,\"pages\":1,\"per_page\":\"50\",\"total\":1},[{\"id\":\"BEL\",\"iso2Code\":\"BE\",\"name\":\"Belgium\",\"region\":{ \"id\":\"ECS\",\"value\":\"Europe & Central Asia(all income levels)\"},\"adminregion\":{ \"id\":\"\",\"value\":\"\"},\"incomeLevel\":{ \"id\":\"OEC\",\"value\":\"High income: OECD\"},\"lendingType\":{ \"id\":\"LNX\",\"value\":\"Not classified\"},\"capitalCity\":\"Brussels\",\"longitude\":\"4.36761\",\"latitude\":\"50.8371\"}]]";
var arr = JArray.Parse(str);
var rootJson = arr.ElementAt(0).ToString();
var root = JsonConvert.DeserializeObject<LandRootObject>(rootJson);
var landsJson = arr.ElementAt(1).ToString();
root.Lands = JsonConvert.DeserializeObject<List<Land>>(landsJson);
tryto change the above code to following
ms.Position = 0; // change only this line
var data = (LandRootObject)serializer.ReadObject(ms);
I am trying to initialise values to the children array in Rootobject but it gave me error.
- I tried t make an object of class Child but it did not work either, I just need to know how to set values to the array of type another class which contains other values. Your help would be appreciated.
public class Rootobject{
public Child[] children { get; set; }
public Data data { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Data{
// public string name { get; set; }
}
public class Child{
public Child1[] children { get; set; }
public Data1 data { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Data1{
public int playcount { get; set; }
public int area { get; set; }
}
public class Child1{
public object[] children { get; set; }
public Data2 data { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Data2{
public string playcount { get; set; }
public string color { get; set; }
public string image { get; set; }
public int area { get; set; }
}
this is where I initialise the values (what should i write in children):
var RegisteredUsers = new List<Rootobject>();
RegisteredUsers.Add(new Rootobject() { children = { }, data = { },
id = "102", name = "zaki" });
If you want to hand in an array just create one of type Child.
Child[] children = new Child[10];
//Then initialize each element.
In your Child class it looks like your expecting type Child1 which is not the same as Child. That will most likely cause the error.
Also I'm not sure why you tagged this question with java.
Yes, you have uninitialized arrays in your code.
To make it work change arrays to List
public List<Child>children { get; set; }
The type Child1 does not exist in the context of your application. Search for it, and rename it to Child.
It's ugly looking, but if you really want...
var RegisteredUsers = new List<Rootobject>();
RegisteredUsers.Add(new Rootobject()
{
children = new Child[] {
new Child { id= "1", name="Ivan"},
new Child { id= "2", name="Vladimir"}
},
data = { },
id = "102",
name = "zaki"
});
if you are using LinqPad, you can copy/paste this code there and will see that it is working
var RegisteredUsers = new List<Rootobject>();
RegisteredUsers.Add(new Rootobject() { children = { }, data = { },
id = "102", name = "zaki" });
RegisteredUsers.Dump();
}
public class Rootobject{
public Child[] children { get; set; }
public Data data { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Data{
// public string name { get; set; }
}
public class Child{
public Child1[] children { get; set; }
public Data1 data { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Data1{
public int playcount { get; set; }
public int area { get; set; }
}
public class Child1{
public object[] children { get; set; }
public Data2 data { get; set; }
public string id { get; set; }
public string name { get; set; }
}
public class Data2{
public string playcount { get; set; }
public string color { get; set; }
public string image { get; set; }
public int area { get; set; }
I am creating a web application and I have two classes:
public class MOrderMain
{
public int ID { get; set; }
public int CompanyID { get; set; }
public string CompanyName { get; set; }
public DateTime OrderDate { get; set; }
public string BillingName { get; set; }
public string BillingAddress { get; set; }
public string DeliveryName { get; set; }
public string DeliveryAddress { get; set; }
}
public class MOrder
{
public int ID { get; set; }
public int OrhID { get; set; }
public int ProID { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public double Rate { get; set; }
public double Amount { get; set; }
public int DeliveredQty { get; set; }
}
I would like to retrieve details from both classes. For example, I want to get
ID and Billing Name from class MorderMain and all the properties from class MOrder. How can I do this?
I am getting the values by database. I have the query but how will I assign the data and how will I retrieve from both?
var mylist = new List<MOrder>();
_con = _db.GetConnection();
if (_con.State.Equals(ConnectionState.Closed))
{
_con.Open();
}
_cmd = new SqlCommand("Get_All_Order_Details", _con)
{ CommandType = CommandType.StoredProcedure };
_dr = _cmd.ExecuteReader();
while (_dr.Read())
{
mylist.Add(new MOrder
{
ID = Convert.ToInt32(_dr["ordID"]),
OrhID = Convert.ToInt32(_dr["orhID"]),
ProID = Convert.ToInt32(_dr["proID"]),
Name = _dr["pName"].ToString(),
Quantity = Convert.ToInt32(_dr["ordQty"]),
Rate = Convert.ToDouble(_dr["ordRate"]),
Amount = Convert.ToDouble(_dr["ordAmount"]),
DeliveredQty = Convert.ToInt32(_dr["ordQtyDelivered"])
});
}
return mylist;
Since you are retrieving data from both tables in your database but want to combine them in your application, the solution would be to create a single class that contains the data you return from your stored procedure:
public class MAllOrderDetails
{
public int ID { get; set; }
public string BillingName { get; set; }
// include the other billing details you want here
public int OrhID { get; set; }
public int ProID { get; set; }
public string Name { get; set; }
public int Quantity { get; set; }
public double Rate { get; set; }
public double Amount { get; set; }
public int DeliveredQty { get; set; }
}
Then, your query changes to filling in a List<MAllOrderDetails>.
This leaves your application with only dealing with a collection of a single class with all the data nicely contained in single objects.
var mylist = new List<MAllOrderDetails>();
//...
while (_dr.Read())
{
mylist.Add(new MAllOrderDetails
{
ID = Convert.ToInt32(_dr["ordID"]),
BillingName = _dr["BillingName"].ToString(),
// etc.
OrhID = Convert.ToInt32(_dr["orhID"]),
ProID = Convert.ToInt32(_dr["proID"]),
Name = _dr["pName"].ToString(),
Quantity = Convert.ToInt32(_dr["ordQty"]),
Rate = Convert.ToDouble(_dr["ordRate"]),
Amount = Convert.ToDouble(_dr["ordAmount"]),
DeliveredQty = Convert.ToInt32(_dr["ordQtyDelivered"])
});
}
Update
You could probably get away with this as the closest solution to not creating an additional classes:
class MAllOrderDetails
{
public MOrder Order { get; set; }
public MOrderMain OrderMain { get; set; }
}
I feel, though, that from a maintainability standpoint, this will cause you more headaches than just creating additional classes.