how to assign value class within class property [duplicate] - c#

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
my recent post one developer provide me solution. create class but how to assign values this class.. please help me
Create a class with required properties to be sent in request.
//for example
public class BookingInformation
{
public string booking_id { get; set; }
public ToLocation to_location { get; set; }
public string notes { get; set; }
}
public class ToLocation
{
public double latitude { get; set; }
public double longitude { get; set; }
public Address2 address { get; set; }
public object comment { get; set; }
public object airport { get; set; }
}
public class Address2
{
public string display_address { get; set; }
public string building_number { get; set; }
public string street_name { get; set; }
public string city { get; set; }
public string region { get; set; }
public string postal_code { get; set; }
public string country { get; set; }
}
Assign the values to the object
Request request =new Request();
request.vehicles = new List<Vehicle>();
// and so on
//Use Newtonsoft.Json to serialize the object as:
var json = JsonConvert.SerializeObject(request);
//Invoke your request with json
using (var response = await httpClient.PostAsync("{supplier_id}/availability?version=2", json))
{
string responseData = await response.Content.ReadAsStringAsync();
}
but my method show error
public void ConvertJson()
{
BookingInformation objbooking = new BookingInformation();
objbooking.booking_id = "33";
objbooking.to_location.comment= "Saloon black";
objbooking.to_location.address.country= "UK";
var json = JsonConvert.SerializeObject(objbooking);
}

public void ConvertJson()
{
BookingInformation objbooking = new BookingInformation();
objbooking.booking_id = "33";
objbooking.to_location.comment= "Saloon black";
objbooking.to_location.address.country= "UK";
var json = JsonConvert.SerializeObject(objbooking);
}
You do not yet have a reference to an instance of ToLocation. Change to this:
public void ConvertJson()
{
BookingInformation objbooking = new BookingInformation();
objbooking.to_location = new ToLocation();
objbooking.to_location.address = new Address2();
objbooking.booking_id = "33";
objbooking.to_location.comment= "Saloon black";
objbooking.to_location.address.country= "UK";
var json = JsonConvert.SerializeObject(objbooking);
}
Based on your edits, you would also not yet have an instance of Address2, I updated the above to account for that as well.
Also read through the responses in: What is a NullReferenceException, and how do I fix it? for more information on how/why NullReferenceExceptions occur.
Another method of getting around this problem, so you don't have to remember to new up properties of the object that require it, is to do it from construction of the parent, like so:
public class BookingInformation
{
public string booking_id { get; set; }
public ToLocation to_location { get; set; }
public string notes { get; set; }
public BookingInformation()
{
to_location = new ToLocation();
}
}
public class ToLocation
{
public double latitude { get; set; }
public double longitude { get; set; }
public Address2 address { get; set; }
public object comment { get; set; }
public object airport { get; set; }
public ToLocation()
{
address = new Address2();
}
}
This will ensure when you create a new instance of BookingInformation the ToLocation and in turn Address2 have instances created at construction.

first create an instance of class ToLocation like this :
objbooking.to_location = new ToLocation();

Related

Loop through 4 object lists & add their data in a ListView C# Xamarin.Forms

I am working on a Xamarin.Forms Project and I am at a dead-end of sorts. My issue is that I want to display user transactions which I pull from a server, in a listview, however I need four different pull requests to get all the data which means I have four different objects lists which I grouped by the transaction number as you can see in this screenshot:
The key transaction number can be seen and if you expand you'll see the other data within each transaction
Here is the code where I group the deserialised json lists with the common key:
var t = JsonConvert.DeserializeObject<List<trans_mod>>(transactions);
var l = JsonConvert.DeserializeObject<List<loc_mod>>(loc);
var d = JsonConvert.DeserializeObject<List<disc_mod>>(disc);
var it = JsonConvert.DeserializeObject<List<item_mod>>(itm);
var q = it.AsQueryable().GroupBy(g => g.trans).ToList();
var q2= d.AsQueryable().GroupBy(g => g.trans).ToList();
var q3 = l.AsQueryable().GroupBy(g => g.trans).ToList();
var q4 = t.AsQueryable().GroupBy(g => g.position).ToList();
Object Models for each list
public class loc_mod
{
[DataMember]
public string location { get; set; }
[JsonProperty(PropertyName = "#modify_stamp")]
public string stamp { get; set; }
[JsonProperty(PropertyName = "$trans")]
public string trans { get; set; }
}
public class disc_mod
{
[DataMember]
public string discount { get; set; }
[JsonProperty(PropertyName = "#modify_stamp")]
public string stamp { get; set; }
[JsonProperty(PropertyName = "$trans")]
public string trans { get; set; }
}
public class item_mod
{
[JsonProperty(PropertyName = "item.price")]
public string price { get; set; }
[JsonProperty(PropertyName = "item.name")]
public string name { get; set; }
[JsonProperty(PropertyName = "#modify_stamp")]
public string stamp { get; set; }
[JsonProperty(PropertyName = "$trans")]
public string trans { get; set; }
}
public class trans_mod
{
[DataMember]
public string refer { get; set; }
[DataMember]
public string date { get; set; }
[DataMember]
public string time { get; set; }
[DataMember]
public int points { get; set; }
[DataMember]
public string _total { get; set; }
[JsonProperty(PropertyName = "$$position")]
public string position { get; set; }
[JsonProperty(PropertyName = "#modify_stamp")]
public string stamp { get; set; }
[JsonProperty(PropertyName = "$trans")]
public string trans { get; set; }
}
public class itms
{
public string price { get; set; }
public string name { get; set; }
public DateTime stamp { get; set; }
[JsonProperty(PropertyName = "$trans")]
public string trans { get; set; }
}
What I want to do is to loop through all four lists and add the data from each list in the listview but I can't think of a way I can do that.
Listview Add() code Example:
Transactions.Add(new Transaction
{
Details = "Date: " + ti[i].date + " | Time: " + ti[i].time + " |
Reference: " + ti[i].refer,
Isvisible = false, Items= ti[i].item, Total = ti[i].total, Discount
= ti[i].discount
});
Sorry if this is a bit confusing, it's confusing for me as well as I am a relative beginner. Any help is welcome!
Define an Interface that your item classes all implement.
That interface has a method that returns whatever you need for listview.
public Interface IHasTransaction
{
Transaction GetTransaction();
}
public class loc_mod : IHasTransaction
{
...
public Transaction GetTransaction()
{
// Use fields of this class to create a Transaction.
return new Transaction(...);
}
}
public class disc_mod : IHasTransaction
{
...
}
If you want, you can make a list that has a mixture of these:
public List<IHasTransaction> models = new List<IHasTransaction>();
models.Add(new loc_mod(...));
models.Add(new disc_mod(...));
Given any of these items
IHasTransaction model
You can easily get the corresponding Transaction:
model.GetTransaction()
OR
var lm = new loc_mod(...);
lm.GetTransaction()

How to populate object with another object with almost same structure? [duplicate]

This question already has answers here:
copy chosen properties to object of other type
(2 answers)
How to cast between 2 types of the same name and internal sturcture but from different assemblies?
(5 answers)
Copy two identical object with different namespaces (recursive reflection)
(7 answers)
Closed 2 years ago.
I'm trying to find the best way to populate my constructor with another constructor that have almost the same structure without setting each attribute,
So i have constructor Altridatiidentificativi in ModelRA constructor:
public class Altridatiidentificativi
{
public string denominazione { get; set; }
public string indirizzo { get; set; }
public string numeroCivico { get; set; }
public string cap { get; set; }
public string comune { get; set; }
public string provincia { get; set; }
public string nazione { get; set; }
public bool modificati { get; set; }
public string defAliquotaIVA { get; set; }
public bool nuovoUtente { get; set; }
}
And Altridatiidentificativi in Documenti:
public class Altridatiidentificativi
{
public bool nuovoUtente { get; set; }
public string denominazione { get; set; }
public string indirizzo { get; set; }
public string numeroCivico { get; set; }
public string cap { get; set; }
public string comune { get; set; }
public string provincia { get; set; }
public string nazione { get; set; }
}
As you can see the structure is almost the same, just constructor in ModelRA has this two extras modificati and defAliquotaIVA
So i was wondering if it's possible in some way to pass inside ModelRA.Altridatiidentificativi the Documenti.Altridatiidentificativi and then add the value to the extras
I was trying to do something like this :
public ModelRA initializeRA(Documento documento)
{
ModelRA model = new ModelRA();
model.altriDatiIdentificativi = <Altridatiidentificativi>(documento.altriDatiIdentificativi);
model.altriDatiIdentificativi.defAliquotaIVA = "";
model.altriDatiIdentificativi.modificati = false;
return model;
}
but i get error in <Altridatiidentificativi> "it's a type not a valid constructor in specific context"
Is there a way to reach what i'm trying to do or i have to set all the attributes manually?
Usually this pattern is a signal that there's a concept in your business model that needs to be abstracted into a composable pattern. The ModelRA.Altridatiidentificativi class could look like:
public class Altridatiidentificativi
{
public ModelRA.Altridatiidentificativi ModelRAAltridatiidentificativi { get; set; }
public bool modificati { get; set; }
public string defAliquotaIVA { get; set; }
}
Then your initialization code could look like this:
public ModelRA initializeRA(Documento documento)
{
ModelRA model = new ModelRA();
model.altriDatiIdentificativi.ModelRAAltridatiidentificativi = documento;
model.altriDatiIdentificativi.defAliquotaIVA = "";
model.altriDatiIdentificativi.modificati = false;
return model;
}
Tangentially I should mention that it's usually good practice to use property initializers and constructors unless you have a specific reason that you need initialization methods.
public class Altridatiidentificativi
{
public string ModelRA.Altridatiidentificativi ModelRAAltridatiidentificativi { get; set; }
public bool modificati { get; set; } = false; // unnecessary: this is default.
public string defAliquotaIVA { get; set; } = "";
public Altridatiidentificativi(ModelRA.Altridatiidentificativi modelRAAltridatiidentificativi)
{
this.modelRAAltridatiidentificativi = ModelRAAltridatiidentificativi;
}
}

Remembering the Syntax for adding a list inside a list

there I have done this before but forgotten the syntax. I am making a JSON file which looks list the classes below but on the submit button I want to add them but I can't remember the syntax for when there is a list inside a list if that makes sense! my classes are:
public class LineItemCheck
{
public string Id { get; set; }
public string Check { get; set; }
public bool Yes { get; set; }
public bool No { get; set; }
}
public class LineItem
{
public string Category { get; set; }
public List<LineItemCheck> LineItemChecks { get; set; }
}
public class RootObject
{
public object SerialNumber { get; set; }
public object UnitNumber { get; set; }
public object Refrigerant { get; set; }
public object ModelNumber { get; set; }
public object BeltSize { get; set; }
public object FreezingUnitComments { get; set; }
public object VisualInspectionComments { get; set; }
public List<LineItem> LineItems { get; set; }
}
private void SubmitButton_Clicked(object sender, EventArgs e)
{
var checklist = new RootObject();
var checklistLineItem = new List<LineItem>();
var checklistLineItemChecks = new List<LineItemCheck>();
checklist.SerialNumber = SerialNumber.Text.ToString();
checklist.UnitNumber = UnitNumber.Text.ToString();
checklist.Refrigerant = Refrigerant.Text.ToString();
checklist.ModelNumber = ModelNumber.Text.ToString();
checklist.BeltSize = BeltSize.Text.ToString();
checklistLineItem.Add(new LineItem() {
Category = "Ziegra Machines Only",
LineItemChecks = new LineItemCheck(LineItemCheck.
),
});
as you can see the bottom section is wrong which is what i am trying to solve thanks
UPDATE: I remember the syntax myself sorry for posting but the answer i was looking for was:
var checklist = new RootObject();
var checklistLineItem = new List<LineItem>();
var checklistLineItemChecks = new List<LineItemCheck>();
checklist.SerialNumber = SerialNumber.Text.ToString();
checklist.UnitNumber = UnitNumber.Text.ToString();
checklist.Refrigerant = Refrigerant.Text.ToString();
checklist.ModelNumber = ModelNumber.Text.ToString();
checklist.BeltSize = BeltSize.Text.ToString();
checklistLineItem.Add(new LineItem() {
Category = "Ziegra Machines Only",
LineItemChecks = new List<LineItemCheck>()
{
new LineItemCheck()
{
Check = "",
},
new LineItemCheck()
{
Check = ""
}
}
});
If I understand your question correctly the following should be the right syntax:
checklistLineItem.Add(new LineItem()
{
Category = "Ziegra Machines Only",
LineItemChecks = new List<LineItemCheck>()
{
new LineItemCheck(),
new LineItemCheck(), ...
},
});
If I may: I would amend your models like so.
public class LineItem
{
public string Category { get; set; }
public List<LineItemCheck> LineItemChecks { get; private set; }
public LineItem()
{
LineItemChecks = new List<LineItemCheck>();
}
}
public class RootObject
{
public object SerialNumber { get; set; }
public object UnitNumber { get; set; }
public object Refrigerant { get; set; }
public object ModelNumber { get; set; }
public object BeltSize { get; set; }
public object FreezingUnitComments { get; set; }
public object VisualInspectionComments { get; set; }
public List<LineItem> LineItems { get; private set; }
public RootObject()
{
LineItems = new List<LineItem>();
}
}
That is, initializing all the collections in a constructor. Properties that expose collections and that can be null are ugly and, more importantly, unexpected. I never expect a collection to be null if it's exposed through a property, I expect it to just be empty, and that I can add stuff to it right away. I'm not in charge of a collection exposed by your object, it's your object's business to initialize itself properly.
This is the consensus in .NET land, you will be hard-pressed to find an example of a collection exposed by a library that is null upon instantiation of the object.
Also notice that I made the setters private, because no other object should be able to flat-out replace a collection exposed by a different object.
Then adding items to collections is simply a matter of:
var root = new RootObject();
var lineItem = new LineItem();
lineItem.LineItemChecks.Add(new LineItemCheck() { /* init properties here */ });
root.LineItems.Add(lineItem);

AutoMapper returns NULL when returning a list

Code without AutoMapper:
List<CountryDM> countryDMList = _countryRepo.GetCountry();
List<CountryVM> countryVMList = new List<CountryVM>();
foreach (CountryDM countryDM in countryDMList)
{
countryVMList.Add(CountryVM.ToViewModel(countryDM));
}
return countryVMList;
I used AutoMapper for the above task. But it returns a NULL list. Please refer the below code:
List<CountryDM> countryDMList = _countryRepo.GetCountry();
Mapper.CreateMap<List<CountryDM>, List<CountryVM>>();
List<CountryVM> countryVMList = new List<CountryVM>();
return Mapper.Map<List<CountryVM>>(countryDMList);
public class CountryDM
{
public int ID { get; set; }
public string CountryCode { get; set; }
public string Description { get; set; }
}
public class CountryVM
{
public int ID { get; set; }
public string CountryCode { get; set; }
public string Description { get; set; }
}
You don't need to define a mapping between lists, just between objects, AutoMapper will know how to extrapolate that:
Mapper.CreateMap<CountryDM, CountryVM>();
the rest stays the same

How to populate list as class object?

How do you populate a list as a class object? For example, this does not work:
[DataContract]
public class JsonReviewFormFields
{
[DataMember]
public PersonalDevelopmentPlan personalDevelopmentPlan { get; set; }
}
public class PersonalDevelopmentPlan
{
public List<ShortTerm> shortTerm { get; set; }
public List<LongTerm> longTerm { get; set; }
}
public class ShortTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}
public class LongTerm
{
public string workRelated { get; set; }
public string structured { get; set; }
public string informal { get; set; }
public string reviewDate { get; set; }
}
This is controller action:
public JsonReviewFormFields GetReviewForm()
{
PersonalDevelopmentPlan personalDevelopmentPlan = new PersonalDevelopmentPlan();
List<ShortTerm> _itemsShort = new List<ShortTerm>();
_itemsShort.Add(new ShortTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;
List<LongTerm> _itemsLong = new List<LongTerm>();
_itemsLong.Add(new LongTerm { workRelated = "workRelated text", structured = "structured text", informal = "informal text", reviewDate = "reviewDate" });
jsonReviewFormFields.personalDevelopmentPlan.longTerm = _itemsLong;
return jsonReviewFormFields;
}
The code crashes at
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort;
It's probably a basic object orientated error. How do you populate the list?
You are not instantiating it, you have to instantiated the type first:
jsonReviewFormFields.personalDevelopmentPlan = new PersonalDevelopmentPlan();
and then set property of it:
jsonReviewFormFields.personalDevelopmentPlan.shortTerm = _itemsShort
before that you also have to instantiate main class which i don't see in your controller action anywhere :
JsonReviewFormFields jsonReviewFormFields = new JsonReviewFormFields();

Categories

Resources