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; }
}
}
Related
I am working with a WPF .Net Core 3 project.
In my UnbalancedViewModel I need to access an ID from another class (TestRunDto.cs).
UnbalancedViewModel
public class UnbalancedViewModel : ViewModelBase, IUnbalancedViewModel
{
private TestRunApi _testRunApi;
public UnbalancedViewModel(TestRunApi testRunApi, INotificationManager notifications)
{
_testRunApi = testRunApi;
}
private void StartTestRunJobExecuted(object obj)
{
_testRunApi.StartTestRun(1); ////I need the Id from TestRunDto (TestRunDto.Id)
}
}
TestRunApi
public async Task<TestRunLiveValueDto> GetTestRunLiveValue(int jobRunId)
{
await using var dbContext = new AldebaDbContext(_connectionString);
return await TestRunInteractor.GetTestRunLiveValue(jobRunId, dbContext);
}
public async Task StartTestRun(int testRunId)
{
await using var dbContext = new AldebaDbContext(_connectionString);
await TestRunInteractor.StartTestRun(dbContext, testRunId);
}
TestRunLiveValueDto
public class TestRunLiveValueDto
{
public TestRunDto TestRun { get; }
public bool ShowInstantaneousValue { get; set; }
public bool EnableStart { get; set; }
public bool EnableStop { get; set; }
public bool EnableMeasure { get; set; }
public int RecipeRpm { get; }
public string ActualRecipeName { get; }
public int DefaultSetOfPlaneId { get; }
public ICollection<BalancePlaneDto> ListBalancePlane { get; }
public ICollection<SetOfPlaneDto> ListSetOfPlane { get; }
public ICollection<SensorVibrationDto> SensorVibrations { get; set; }
public ICollection<EstimationDto> InstantaneousValues { get; set; }
public ICollection<EstimationDto> EstimationsValues { get; set; }
private TestRunLiveValueDto(TestRunDto testRun, bool enableStart, bool enableStop, int recipeRpm, ICollection<SensorVibrationDto> sensorVibrations)
{
EnableStart = enableStart;
EnableStop = enableStop;
TestRun = testRun;
RecipeRpm = recipeRpm;
SensorVibrations = sensorVibrations;
}
public static TestRunLiveValueDto Create(TestRunDto testRun, bool enableStart, bool enableStop, int recipeRpm, ICollection<SensorVibrationDto> sensorVibrations)
=> new TestRunLiveValueDto(testRun, enableStart, enableStop, recipeRpm, sensorVibrations);
}
TestRunDto
public class TestRunDto
{
public int Id { get; set; }
public int JobRunId { get; set; }
public string Name { get; set; }
public int TestRunNumber { get; set; }
public RunState State { get; set; }
public ICollection<BalancePlaneDto> BalancePlanes { get; set; } // Todo remove
private TestRunDto(int id, int jobRunId, RunState state, string name, int testRunNumber)
{
Id = id;
JobRunId = jobRunId;
Name = name;
TestRunNumber = testRunNumber;
State = state;
}
public static TestRunDto Create(int id, int jobRunId, RunState state, string name, int testRunNumber)
=> new TestRunDto(id, jobRunId, state, name, testRunNumber);
}
I have been trying to understand this, but I can not get a hold of the proper method to do this. Do I first declare a new TestRunDto class in my viewmodel or am I supposed to access it some other way?
You need to ensure class A has a reference to an instance of class B to access the properties, for example one way of doing this is to pass class A to B in a method where you can manipulate or access properties.
public class FooA
{
public string PropertyA { get; set; }
}
public class FooB
{
public string PropertyB { get; set; }
public void CanAccessFooA(FooA a)
{
a.PropertyA = "See, I can access this here";
}
}
Another is to pass class A to B in the constructor (known as dependency-injection)
public class FooB
{
FooA _a;
public FooB(FooA a)
{
// Pass instance of FooA to constructor
// (inject dependency) and store as a member variable
this._a = a;
}
public string PropertB { get; set; }
public void CanAccessFooA()
{
if (this._a != null)
this._a.PropertyA = "See, I can access this here";
}
}
Exactly how to structure your code is up to you, but the principle remains the same: Class B can only access Class A if it has a reference to an instance of it.
Look into 'Dependency Injection' as there are many techniques to achieve this.
Edit
One such technique might be abstracting the code to provide the ID to both, like so
public class IdProvider
{
public int Id { get; set; }
}
public class FooA
{
private int _id;
public FooA(IdProvider idProvider)
{
_id = idProvider.Id;
}
}
public class FooB
{
private int _id;
public FooB(IdProvider idProvider)
{
_id = idProvider.Id;
}
}
Now both classes have the same ID;
StartTestRun takes the tesRunId as it's parameter.
public async Task StartTestRun(int testRunId)
{
I think you need to call StartTestRunJobExecuted with this testRunId.
You will to change
private void StartTestRunJobExecuted(object obj)
to
private void StartTestRunJobExecuted(int testRunIdn)
{
_testRunApi.StartTestRun(testRunId); ////I need the Id from TestRunDto (TestRunDto.Id)
}
(This based on me guessing).
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
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.
I've done the googling to no avail. This is the one sole error preventing my code from compiling and running but I can't seem to figure it out. The exact text of the error is "...Dictionary is less accessible than property FleetAirliner.InsuranceProperties"
Any ideas what could be causing this?
namespace TheAirline.Model.AirlinerModel
{
[Serializable]
public class FleetAirliner
{
public Airliner Airliner { get; set; }
public string Name { get; set; }
public Airport Homebase { get; set; }
public enum PurchasedType { Bought, Leased,BoughtDownPayment }
public DateTime PurchasedDate { get; set; }
public PurchasedType Purchased { get; set; }
public Boolean HasRoute { get { return this.Routes.Count > 0; } set { ;} }
public AirlinerStatistics Statistics { get; set; }
/*Changed for deleting routeairliner*/
public enum AirlinerStatus { Stopped, On_route, On_service, Resting, To_homebase, To_route_start }
public AirlinerStatus Status { get; set; }
public Coordinates CurrentPosition { get; set; }
public List<Route> Routes { get; private set; }
public Flight CurrentFlight { get; set; }
public DateTime GroundedToDate { get; set; }
public List<Pilot> Pilots { get; set; }
public Dictionary<string, AirlinerInsurance> InsurancePolicies { get; set; } //error occurs here
public int NumberOfPilots {get {return this.Pilots.Count;} private set {;}}
public FleetAirliner(PurchasedType purchased,DateTime purchasedDate, Airline airline,Airliner airliner,Airport homebase)
{
this.Airliner = airliner;
this.Purchased = purchased;
this.PurchasedDate = purchasedDate;
this.Airliner.Airline = airline;
this.Homebase = homebase;
this.Name = airliner.TailNumber;
this.Statistics = new AirlinerStatistics(this);
this.Status = AirlinerStatus.Stopped;
this.CurrentPosition = new Coordinates(this.Homebase.Profile.Coordinates.Latitude, this.Homebase.Profile.Coordinates.Longitude);
this.Routes = new List<Route>();
this.Pilots = new List<Pilot>();
this.InsurancePolicies = new Dictionary<string, AirlinerInsurance>();
}
It means that class "AirlinerInsurance" Is not Public.
It is a property that is public, but other classes, that are allowed to use the property, might not have access rights to the class itself (it is private / internal).
Edit
Now that you have posted the code of class "AirlinerInsurance", just add a "public" modifier to it.
You can read more about it here and here
you need
class AirlinerInsurance {
// stuff
}
to be
public class AirlinerInsurance {
//stuff
}
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.