namespace ClassesRa.Classes
{
public class FicheLine
{
public int ItemRef { get; set; }
public double Amount { get; set; }
public string UnitCode { get; set; }
}
public class Fiche
{
public List<FicheLine> FicheLines { get; set; }
public Fiche()
{
FicheLines = new List<FicheLine>();
}
public string ClientCode { get; set; }
}
public class SalesFicheLine : FicheLine
{
public decimal Price { get; set; }
}
public class SalesFiche : Fiche
{
public List<SalesFicheLine> FicheLines { get; set; }
public SalesFiche()
{
FicheLines = new List<SalesFicheLine>();
}
public string PayCode { get; set; }
}
}
I want to derive SalesFiche from Fiche and add new members.
I want to derive SalesFicheLine from FicheLine and add new members.
I want to see SalesFicheLine in SalesFiche as FicheLine.
Is there a mistake or a defect in the above example?
namespace ClassesRa
{
public partial class fMain : Form
{
public fMain()
{
InitializeComponent();
}
private void fMain_Load(object sender, EventArgs e)
{
SalesFiche f = new SalesFiche();
f.ClientCode = "120.001";
f.PayCode = "30";
f.FicheLines.Add(new SalesFicheLine() { ItemRef = 1, Amount = 10, UnitCode = "PK", Price = 100 });
string xmlString = SerializeToString(f);
}
public string SerializeToString(object obj)
{
string str = "";
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
str = writer.ToString();
}
return str;
}
}
}
When I try to convert it to XML with the SerializeToString function, it gives the following error :
{"There was an error reflecting property 'FicheLines'."}
Thanks..
You have to rename the property "FicheLines" in your SalesFiche class. I tested it with "SalesFicheLines". This will fix the crash.
I also recommend that you change your SaleFiche class to this
public class SalesFiche : Fiche
{
public SalesFiche()
:base()
{
}
public string PayCode { get; set; }
}
You already have access to FicheLines's FicheLines property, so there's really no need to create another FicheLines property in SalesFiche.
Related
I have interface where I am setting a list and trying to fill the list later on, however I am getting null exception in the LoadSet() method.
public interface ISettings
{
List<CustomSetting> CustomSettings { get; set; }
}
public class SettingsService : ISettings
{
CameraResolution cameraResolution = new CameraResolution();
public string Name { get; set; }
public List<CustomSetting> CustomSettings { get; set; }
public SettingsService()
{
Name = customSettings.Name;
CustomSettings = new List<CustomSetting>();
LoadSet();
}
public void LoadSet()
{
var detail = new CustomSetting
{
Name = cameraResolution.Name,
Value = cameraResolution.Value,
};
CustomSettings.Add(detail);
}
}
I am not getting JsonConvert.DeserializeObject to work for me.
I get the correct value in JSON from the service. Not finding anything online for this, would appreciate a little help here :)
Here is my code:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void tbPlate_OnServerChange(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(tbPlate.Text))
{
var _res = Responses(tbPlate.Text);
if (_res.Vehicles != null)
{
lblTestText.Text = _res.Vehicles.FirstOrDefault(r => r.regNr == tbPlate.Text)?.ToString();
}
else
{
lblTestText.Text = "No vehicle data";
}
}
}
private static VehicleResults Responses(string regNr)
{
var _jSon = "";
var _url = #"http://apis.is/car";
var _res = new VehicleResults();
var _request = (HttpWebRequest)WebRequest.Create($"{_url}?number={regNr}");
var _response = _request.GetResponse();
using (var _responseStream = _response.GetResponseStream())
{
var _reader = new StreamReader(_responseStream, Encoding.UTF8);
_jSon = _reader.ReadToEnd();
}
_res = JsonConvert.DeserializeObject<VehicleResults>(_jSon);
return _res;
}
}
public class VehicleResponse
{
[JsonProperty("registryNumber")]
public string regNr { get; set; }
public string number { get; set; }
public string factoryNumber { get; set; }
public string type { get; set; }
public string subType { get; set; }
public string color { get; set; }
public string registeredAt { get; set; }
public string status { get; set; }
public string nextCheck { get; set; }
public string pollution { get; set; }
public string weight { get; set; }
}
public class VehicleResults
{
public List<VehicleResponse> Vehicles { get; set; }
}
This is the response JSON from the service:
{"results":[{"type":"MERCEDES BENZ - M (Svartur)","subType":"M","color":"Svartur","registryNumber":"GXS56","number":"GXS56","factoryNumber":"WDC1631131A539035","registeredAt":"23.09.2004","pollution":" g/km","weight":"2200 kg","status":"Í lagi","nextCheck":"01.06.2019"}]}
I am quite new to REST services so I believe that the problem is small....I am just not able to figure it out right now.
Your json has a root object that contains the list of your vehicles.
You need to name the variable that holds your list with the name returned in the json. results
public class VehicleResults
{
// This should be named results
public List<VehicleResponse> results {get;set;}
}
Now you can deserialize with
VehicleResults data = JsonConvert.DeserializeObject<VehicleResults>(json);
foreach(var vei in data.results)
Console.WriteLine(vei.type);
You need to [JsonProperty] on every property in VehicleResponse
Please add _reader.Close() at the end of the using
I am fairly new to C# and I have having problems with adding an object to a class inside a class. It keeps telling me to "Use the 'new' keyword to create an object instance".
Here is my class:
public class Info
{
public List<SourceInfo> sourceInfo { get; set; }
}
public class SourceInfo
{
public short id { get; set; }
public string name { get; set; }
public string icon { get; set; }
public short subpage { get; set; }
public short xpoint { get; set; }
public short mediaPlayerId { get; set; }
public SourceInfo(short ID, string NAME, string ICON, short SUBPAGE, short XPOINT, short MEDIAPLAYERID)
{
id = ID;
name = NAME;
icon = ICON;
subpage = SUBPAGE;
xpoint = XPOINT;
mediaPlayerId = MEDIAPLAYERID;
}
Here is my code:
Info configSelect = new Info();
private void btnSave_Click(object sender, EventArgs e)
{
try
{
configSelect.sourceInfo.Add (new SourceInfo(Convert.ToInt16(txtSrcId.Text),
txtSrcName.Text, txtSrcIcon.Text, Convert.ToInt16(txtSrcSubpage.Text),
Convert.ToInt16(txtSrcXpoint.Text), Convert.ToInt16(txtSrcMPId.Text)));
WriteFile(configSelect);
}
catch (Exception ex)
{
Console.WriteLine(ex);
throw;
}
Your Info class needs to be structured something like this. The "new" it's looking for is for List sourceInfo in your Info class.
public class Info
{
private List<SourceInfo> _sourceInfo = new List<SourceInfo>();
public List<SourceInfo> sourceInfo
{
get { return this._sourceInfo; }
set { this._sourceInfo = value; }
}
}
Below is my XML code.
<programs>
<program>
<ProgrameName>Test</ProgrameName>
<deviceTypes>
<DeviceType>POS</DeviceType>
<deviceTargets>
<DeviceNames>
<DeviceName>POS0001</DeviceName>
<DeviceName>POS0001</DeviceName>
<DeviceName>POS0001</DeviceName>
</DeviceNames>
<AttemptToIstall>True</AttemptToIstall>
<Mandetory>False</Mandetory>
<SkipIfOffline>False</SkipIfOffline>
</deviceTargets>
<AttemptToIstall>True</AttemptToIstall>
<Mandatory>False</Mandatory>
<SkipIfOffline>False</SkipIfOffline>
</deviceTypes>
</program>
please help me to write C# code using XmlSerializer.I want to create an object and serialize those object according to above XML.
below are my C# class.
public class ProgramP
{
public string ProgrameName { get; set; }
[XmlRoot("")]
public class DeviceTypes
{
public string DeviceType { get; set; }
[XmlRoot("")]
public class DeviceTargets
{
public string DeviceNames { get; set; }
public string AttemptToIstall { get; set; }
public string Mandetory { get; set; }
public string SkipIfOffline { get; set; }
}
[XmlElement("DeviceTargets")]
public DeviceTargets[] ArDeviceTargets { get; set; }
public string AttemptToIstall { get; set; }
public string Mandetory { get; set; }
public string SkipIfOffline { get; set; }
}
[XmlElement("DeviceTypes")]
public DeviceTypes[] ArDeviceType { get; set; }
}
Below is my C# code.can any body please correct me or suggest me where i have to add more class or how can i arrange my class so that i can get above XML as output.
public void ExportClass(string strFilePathExportedXML)
{
ProgramP ProgramP = new ProgramP
{
ProgrameName = "Test",
ArDeviceType = new ProgramP.DeviceTypes[] {
new ProgramP.DeviceTypes {
DeviceType = "POS1",
AttemptToIstall="True",
Mandetory="True",
SkipIfOffline="True",
ArDeviceTargets = new ProgramP.DeviceTypes.DeviceTargets[] {
new ProgramP.DeviceTypes.DeviceTargets {
DeviceNames="POS01",
AttemptToIstall="True",
Mandetory="True",
SkipIfOffline="True"
},
new ProgramP.DeviceTypes.DeviceTargets {
DeviceNames="POS02",
AttemptToIstall="True",
Mandetory="True",
SkipIfOffline="True"
}
}
};
TextWriter writer = new StreamWriter(strFilePathExportedXML);
XmlSerializer serializerOut = new XmlSerializer(typeof(ProgramP));
serializerOut.Serialize(writer, ProgramP);
writer.Close();
After mapping, you can use this:
public static YourClass LoadFromXMLString(string xmlText)
{
var stringReader = new System.IO.StringReader(xmlText);
var serializer = new XmlSerializer(typeof(YourClass ));
return serializer.Deserialize(stringReader) as YourClass ;
}
From this topic: Convert Xml to Object
Im a little stuck and after some searching i turn to you:
class StatusResponse
{
protected int _statusCode { get; set; }
protected string _statusMessage { get; set; }
public StatusResponse(string Response)
{
if (!String.IsNullOrEmpty(Response))
{
this._statusCode = int.Parse((Response.Split(' '))[0].Trim());
this._statusMessage = Response;
}
}
}
class GroupStatusResponse : StatusResponse
{
public int Count { get; private set; }
public int FirstArticle { get; private set; }
public int LastArticle { get; private set; }
public string Newsgroup { get; private set; }
public GroupStatusResponse(string Response) : base(Response)
{
string[] splitResponse = Response.Split(' ');
this.Count = int.Parse(splitResponse[1].Trim());
this.FirstArticle = int.Parse(splitResponse[2].Trim());
this.LastArticle = int.Parse(splitResponse[3].Trim());
this.Newsgroup = splitResponse[4].Trim();
}
Why cant i do this:
GroupStatusResponse resp = new GroupStatusResponse("211 1234 3000234 3002322 misc.test");
Console.Writeline(resp._statusCode);
using
Console.Writeline(resp._statusCode);
from outside the derived class is public, and not protected use.
However, you could add something like:
class GroupStatusResponse : StatusResponse
{
public int GetStatusCode()
{
return _statusCode;
}
}
which is completely valid use.
Moreover, if the scenario is that _statusCode should be allowed to read by anyone, but only the base class should be able to set it, you could change its definition to:
public string _statusMessage { get; private set; }
It's because _statusCode is protected. This means the field is inaccessible outside of the class.