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.
Related
I'm sure someone has tried to do something like this before, but I'm unsure if what I'm finding in my searches fits what I'm trying to do.
In my .Net 6 Web API I have a class to get data passed by the request:
public abstract class QueryStringParameters {
private readonly int _maxPageSize = Constants.DefaultPageSizeMax;
private int _pageSize = Constants.DefaultPageSize;
public int? PageNumber { get; set; } = 1;
public int? PageSize {
get => _pageSize;
set => _pageSize = value > _maxPageSize ? _maxPageSize : value ?? Constants.DefaultPageSize;
}
public string OrderBy { get; set; }
public string Fields { get; set; }
}
For each controller I create a view model which inherits from this:
public class ProgramParameters : QueryStringParameters {
public bool MapDepartment { get; set; } = true;
public bool MapAnother1 { get; set; } = true;
public bool MapAnother2 { get; set; } = true;
...
public ProgramParameters() {
// Default OrderBy
OrderBy = "Id";
}
}
This works fine when calling an endpoint expecting multiple results and single results. However, I want to split the QueryStringParameters properties that are for pagination, something like this:
public abstract class QueryStringParameters {
public string Fields { get; set; }
}
public abstract class QueryStringParametersPaginated : QueryStringParameters {
private readonly int _maxPageSize = Constants.DefaultPageSizeMax;
private int _pageSize = Constants.DefaultPageSize;
public int? PageNumber { get; set; } = 1;
public int? PageSize {
get => _pageSize;
set => _pageSize = value > _maxPageSize ? _maxPageSize : value ?? Constants.DefaultPageSize;
}
public string OrderBy { get; set; }
}
The problem is that then my view modal looks like this:
public class ProgramParameters : QueryStringParameters {
public bool MapDepartment { get; set; } = true;
public bool MapAnother1 { get; set; } = true;
public bool MapAnother2 { get; set; } = true;
...
public ProgramParameters() {
}
}
public class ProgramParametersPaginated : QueryStringParametersPaginated {
public bool MapDepartment { get; set; } = true; // repeated
public bool MapAnother1 { get; set; } = true; // repeated
public bool MapAnother2 { get; set; } = true; // repeated
...
public ProgramParameters() {
// Default OrderBy
OrderBy = "Id";
}
}
How can I rewrite this so that ProgramParameters and ProgramParametersPaginated don't have to have the same properties (MapDepartment, MapAnother1, MapAnother2) defined in both?
I tried something like this but that's not allowed and I am unsure how to proceed.
public class ProgramParametersPaginated : ProgramParameters, QueryStringParametersPaginated {
public ProgramParametersPaginated() {
// Default OrderBy
OrderBy = "Id";
}
}
If I understood correctly, you need to extract interfaces instead of using classes as you did, so you can apply multiple implementation.
First define the interfaces and constants for you filter properties:
public enum Constants
{
DefaultPageSizeMax = 500,
DefaultPageSize = 100
}
public interface IQueryStringParameters
{
string Fields { get; set; }
}
public interface IQueryStringParametersPaginated : IQueryStringParameters
{
string OrderBy { get; set; }
int PageSize { get; set; }
int MaxPageSize { get; set; }
int? PageNumber { get; set; }
}
Then you create an abstract class that inherit from both interfaces defined so you can write some behaviour like you did with the setters and getters:
public abstract class BaseProgramParameters : IQueryStringParameters, IQueryStringParametersPaginated
{
public string Fields { get; set; }
public string OrderBy { get; set; }
private int _pageSize = (int)Constants.DefaultPageSize;
private int _maxPageSize = (int)Constants.DefaultPageSizeMax;
public int PageSize
{
get => _pageSize;
set => _pageSize = value > _maxPageSize ? _maxPageSize : value;
}
public int MaxPageSize { get; set; }
public int? PageNumber { get; set; }
public bool MapDepartment { get; set; } = true;
public bool MapAnother1 { get; set; } = true;
public bool MapAnother2 { get; set; } = true;
public BaseProgramParameters()
{
}
public BaseProgramParameters(string orderBy)
{
this.OrderBy = orderBy;
}
}
Since you may want to define a different value on MapDeparment, MapAnother, etc, you can use the constructor on the child classes:
public class ProgramParametersPaginated : BaseProgramParameters
{
public ProgramParametersPaginated() : base("Id")
{
}
}
public class ProgramParameters : BaseProgramParameters
{
public ProgramParameters()
{
this.MapAnother1 = false;
}
}
Let me know if you have any further doubts.
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 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; }
}
}
I have implemented a common operation result for my methods and it look like this
public class OperResult
{
public string ErrorCode { get; private set; }
public string Message { get; private set; }
public object Data { get; private set; }
public bool Ok { get; private set; }
public string IncidentNumber { get; set; }
public static OperResult Success(Object data = null)
{
return new OperResult(data);
}
}
And the same operation result using generics
public class OperResult<T>
{
public string ErrorCode { get; private set; }
public string Message { get; private set; }
public T Data { get; private set; }
public bool Ok { get; private set; }
public string IncidentNumber { get; private set; }
public static OperResult<T> Success(T data = null)
{
return new OperResult<T>(data);
}
}
Is there any way to combine these two implementations and at the same time provide both Generic and non Generic version of this class?
Edit add more info about the type usage:
I want to easily create functions that return this type, for example i want to been able to create the following functions:
OperResult MakeAction()
OperResult<int> GetCount()
If I use inheritance OperResult:OperResult<Object> then OperResult.Suceess() will produce OperResult<Object> and the following will generate a compilation error:
OperResult MakeAction(){
return OperResult.Suceess(); //Cannot convert OperResult<Object> to OperResult
}
GitHub link to OperResult
As already mentioned in the comments, the non generic appears to be a OperResult<object>.
Originally went down that route but it proved to not suit the desired use case.
Switched it around to having the generic derive from the non generic and provide a new Data property.
public class OperResult {
protected OperResult(object data) {
this.Data = data;
}
public string ErrorCode { get; protected set; }
public string Message { get; protected set; }
public object Data { get; protected set; }
public bool Ok { get; protected set; }
public string IncidentNumber { get; protected set; }
public static OperResult Success(object data = null) {
return new OperResult(data ?? new object());
}
public static OperResult<T> Success<T>(T data) {
return new OperResult<T>(data);
}
}
public class OperResult<T> : OperResult {
public OperResult(T data)
: base(data) {
}
public new T Data { get; protected set; }
}
this allows the following syntax
int data = 10;
var result = OperResult.Success(data);
//result is OperResult<int>
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
}