Back end cant see front end post like nulls - c#

I have c# controller
[EnableCors("AllowSpecificOrigin")]
[Route("AddCar"), HttpPost]
public async Task<CarStatus> AddCar(Car car)
{
return _carService.AddCar(car);
}
and Angular services
AddCar(addCarModel: CarModel): Promise<CarStatus>{
const headers = new Headers({ 'Content-Type': 'application/json'});
return this.http.post("http://localhost:54116/AddCar", JSON.stringify({RegistrationNumber : addCarModel.RegistrationNumber, TypeOfCar: addCarModel.TypeOfCar, Model: addCarModel.Model,
YearOfProduction: addCarModel.YearOfProduction, Power: addCarModel.Power, vinNumber: addCarModel.VinNumber, Factory: addCarModel.Factory, CarReviewDate: addCarModel.CarReviewDate ,
OcEndDate: addCarModel.OcEndDate, Insurer: addCarModel.Insurer,UdtElevatorReviewWhen : addCarModel.UdtElevatorReviewWhen, UdtElevatorReviewFrom: addCarModel.UdtElevatorReviewFrom,
TachografReviewWhen: addCarModel.TachografReviewWhen, TachografReviewFrom: addCarModel.TachografReviewFrom,FaultList: null ,Owner: addCarModel.Owner}), { headers: new Headers({ 'Content-Type': 'application/json' }) }).toPromise().
then(response => {
var y = response.json();
return y;
});
and AddCar.ts
import { Component, OnInit } from '#angular/core';
import { CarService } from '../../services/car.service';
import { NgForm } from "#angular/forms";
#Component({
selector: 'app-add-car',
templateUrl: './add-car.component.html',
styleUrls: ['./add-car.component.css']
})
export class AddCarComponent implements OnInit {
constructor(private carService: CarService) { }
ngOnInit() {
}
onSubmit(form: NgForm): void {
console.log(form.value);
this.carService.AddCar(form.value);
}
}
My Angular CarModel
export class CarModel{
RegistrationNumber: string;
CarReviewDate : Date;
Factory: string;
Insurer: string;
Model : string;
OcEndDate: Date;
Owner : string;
Power : number;
TypeOfCar: string;
YearOfProduction: number;
VinNumber: string;
UdtElevatorReviewFrom: Date;
UdtElevatorReviewWhen: Date;
TachografReviewFrom: Date;
TachografReviewWhen: Date;
FaultList : Fault[];
}
My c# Car Model
public class Car
{
[Key]
public string RegistrationNumber { get; set; }
public string TypeOfCar { get; set; }
public string Model { get; set; }
public int YearOfProduction { get; set; }
public int Power { get; set; }
public string VinNumber { get; set; }
public string Factory { get; set; }
public DateTime CarReviewDate { get; set; }
public DateTime OcEndDate { get; set; }
public string Insurer { get; set; }
public DateTime? UdtElevatorReviewWhen { get; set; }
public DateTime? UdtElewatorReviewFrom { get; set; }
public DateTime? TachografReviewWhen { get; set; }
public DateTime? TachografReviewFrom { get; set; }
public List<Fault> FaultList { get; set; }
public string Owner { get; set; }
In back end i have braekpoint and connection is good, but all values in sending car are nulls. Why? and how can i fix that?
link to project https://github.com/BialekM/TransportApp
network status https://imgur.com/QRZ4KJw
C# inform me the all values are null without 2 datetime wchick cant be null

Related

How to Set Salary Currency Exchange for one currency to another using API?

I'm really confused right now.
I'm not sure how to implement correctly Currency Exchange from one Currency to another using asp.net core, using this API: Currency Exchange-API
What I'm trying to do is when user input Salary it should exchange that value from foreign currency in EUR and USD currency.
This provided API is very weird, I mean I don't have much experience with API's. With SDK's yes but with API's unfortunately not much.
So here is my Code so hopefully someone will know what I need to do to Implement this API right.
using System.ComponentModel.DataAnnotations;
using System.Security.AccessControl;
namespace Test_Project_Web.Models
{
public class EmployeeCategory
{
[Key]
public int Id { get; set; }
[Required]
public double GrossSalary_ForeignCurrency { get; set; }
[Required]
public double NetSalary_EUR { get; set; }
public double NetSalary_USD { get; set; }
using Newtonsoft.Json;
namespace Test_Project_Web.Models
{
public class ExchangeRate_API
{
class Rates
{
public static bool Import()
{
try
{
String URLString = "https://v6.exchangerate-api.com/v6/YOUR-API-KEY/latest/USD";
using (var webClient = new System.Net.WebClient())
{
var json = webClient.DownloadString(URLString);
API_Obj Test = JsonConvert.DeserializeObject<API_Obj>(json);
return true;
}
}
catch (Exception)
{
return false;
}
}
}
public class API_Obj
{
public string ? result { get; set; }
public string ? documentation { get; set; }
public string ? terms_of_use { get; set; }
public string ? time_last_update_unix { get; set; }
public string ? time_last_update_utc { get; set; }
public string ? time_next_update_unix { get; set; }
public string ? time_next_update_utc { get; set; }
public string ? base_code { get; set; }
public ConversionRate ? conversion_rates { get; set; }
}
public class ConversionRate
{
public double EUR { get; set; }
public double USD { get; set; }
}
}
}
using Microsoft.AspNetCore.Mvc;
using Test_Project_Web.Data;
using Test_Project_Web.Models;
namespace Test_Project_Web.Controllers
{
public class EmployeeCategoryController : Controller
{
private readonly ApplicationDbContext _db;
public EmployeeCategoryController(ApplicationDbContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<EmployeeCategory> objEmployeeCategoryList = _db.EmployeeCategories;
return View(objEmployeeCategoryList);
}
//GET
public IActionResult Create()
{
return View();
}
//POST
[HttpPost]
[AutoValidateAntiforgeryToken]
public IActionResult Create(EmployeeCategory obj)
{
if (ModelState.IsValid)
{
_db.EmployeeCategories.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}
}
}
To use the data from the Currency Exchange API, you could wrap the API call in a service provider:
public class ExchangeRateProvider
{
public ConversionRate? Rate { get; private set; }
private const string ApiUrl = "https://v6.exchangerate-api.com/v6/<API-KEY>/latest/{0}";
public ExchangeRateProvider()
{
}
public async Task UpdateRatesAsync(string foreignCurrency = "USD")
{
try
{
using var httpClient = new HttpClient();
API_Obj? jsonResponse = await httpClient.GetFromJsonAsync<API_Obj>(string.Format(ApiUrl, foreignCurrency));
Rate = jsonResponse?.conversion_rates;
}
catch(Exception ex)
{
throw new Exception("Unable to download Exchange API data.", ex);
}
}
public class API_Obj
{
public string? result { get; set; }
public string? documentation { get; set; }
public string? terms_of_use { get; set; }
public long? time_last_update_unix { get; set; }
public string? time_last_update_utc { get; set; }
public long? time_next_update_unix { get; set; }
public string? time_next_update_utc { get; set; }
public string? base_code { get; set; }
public ConversionRate? conversion_rates { get; set; }
}
public class ConversionRate
{
public double EUR { get; set; }
public double USD { get; set; }
}
}
To use this provider, you first set up the dependency injection in the Program.cs or Startup.cs,
builder.Services.AddRazorPages();
builder.Services.AddSingleton<ExchangeRateProvider>();
Now, inject this service into your controller or other controllers where you want to use it,
public EmployeeCategoryController(ApplicationDbContext db, ExchangeRateProvider exchangeRateProvider)
{
_db = db;
_exchangeRateProvider = exchangeRateProvider;
}
The provider can be called like this,
public async Task<IActionResult> Create(EmployeeCategory obj)
{
//your other code
var foreignCurrency = "GBP";
await _exchangeProvider.UpdateRatesAsync(foreignCurrency);
var rates = _exchangeProvider.Rate;
var grossSalary = 100; //salary in GBP
var usdSalary = rates.USD * grossSalary;
var eurSalary = rates.EUR * grossSalary;
//check for null or do some calculation with this.
}
I hope this gives you some ideas. There are many other ways to do this depending on your project requirements, e.g. do you want to cache the rate or do you need it always to be the latest? my code is just a POC.
Refactored POC Code:
To use the data from the Currency Exchange API, you could wrap the API call in a service provider:
public class ExchangeRateProvider
{
public ConversionRate? Rate { get; private set; }
private const string ApiUrl = "https://v6.exchangerate-api.com/v6/<API-KEY>/latest/GBP"; //Currency you want to exchange salary in this example GBP. Otherwise Will return 404 error if you put ".../latest/{0}"
public ExchangeRateProvider()
{
}
public async Task UpdateRatesAsync(string foreignCurrency = "USD", string foreignCurrency_02 = "EUR") //Update Rates for USD & EUR
{
try
{
using var httpClient = new HttpClient();
API_Obj? jsonResponse = await httpClient.GetFromJsonAsync<API_Obj>(string.Format(ApiUrl, foreignCurrency, foreignCurrency_02));
Rate = jsonResponse?.conversion_rates;
}
catch(Exception ex)
{
throw new Exception("Unable to download Exchange API data.", ex);
}
}
public class API_Obj
{
public string? result { get; set; }
public string? documentation { get; set; }
public string? terms_of_use { get; set; }
public long? time_last_update_unix { get; set; }
public string? time_last_update_utc { get; set; }
public long? time_next_update_unix { get; set; }
public string? time_next_update_utc { get; set; }
public string? base_code { get; set; }
public ConversionRate? conversion_rates { get; set; }
}
public class ConversionRate
{
public double EUR { get; set; }
public double USD { get; set; }
}
}
The provider can be called like this,
public async Task<IActionResult> Create(EmployeeCategory obj)
{
if(ModelState.IsValid)
{
//your other code
var foreignCurrency = "EUR";
var foreignCurrency_02 = "USD";
await _exchangeRateProvider.UpdateRatesAsync(foreignCurrency);
await _exchangeRateProvider.UpdateRatesAsync(foreignCurrency_02);
var rates = _exchangeRateProvider.Rate;
var grossSalary = GrossSalary_GBP; //salary in GBP
var usdSalary = rates.USD * grossSalary;
var eurSalary = rates.EUR * grossSalary;
obj.NetSalary_USD = eurSalary;
obj.NetSalary_EUR = usdSalary;
obj.NetSalary_GBP = GrossSalary_GBP;
_db.EmployeeCategories.Add(obj);
_db.SaveChanges();
return RedirectToAction("Index");
}
return View(obj);
}

ASP.Net Core 5.0 Binding model to action with [Bind] attribute for nested child collection

I am trying to bind a model in a post action method. i.e binding with the help of [Bind] attribute.
Where I post some fields for parent while a collection of child properties at the same time.
Supose I have parent as following
class Parent
{
int field0;
string field1;
string field2;
ICollection<Child> Children;
}
class Child
{
int field3;
string field4;
string field5;
}
at the time of binding I can choose fields to bind for simple binding like [Bind("field1, field2")] and to include children as well then [Bind("field1,field2,children")]
But I need to include some fields of children like children("field4", "field5")
Is there any possibility so that I can write like following
public IActionResult UTOneFlight([Bind("field1, field2, children(field4, field5)")] Parent p)
{
}
UPDATE
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> UTOneFlight([Bind("FlightID, SrcAirportID, DestAirportID, FlightDate, Sector, RegistrationNo, FlightNo, CallSign, CrewMembers, EmbDetails, UpdateRemarks")] FlightViewModel f)
{
if (f != null && f.EmbDetails != null)
{
if (f.FlightID == 0)
{
var flight = new Flight()
{
EmbDetails = new List<EmbDetail>(),
FlightType = "emb",
AirlineOperatorID = _user.OperatorID,
SrcAirportID = f.SrcAirportID,
DestAirportID = f.DestAirportID,
FlightDate = f.FlightDate,
Sector = f.Sector.ToString().ToLower()[0],
FlightNo = f.FlightNo.Trim().ToLower(),
CallSign = f.CallSign.Trim().ToLower(),
RegistrationNo = f.RegistrationNo.Trim().ToLower(),
CrewMembers = f.CrewMembers,
UpdateRemarks = f.UpdateRemarks?? f.UpdateRemarks,
EmbDataStatus = 'u',
CreatedBy = _user.UserID
};
foreach (var e in f.EmbDetails)
{
flight.EmbDetails.Add(
new EmbDetail()
{
PaxType = e.PaxType,
PaxClass = e.PaxClass,
AdultPax = e.AdultPax,
Infants = e.Infants,
Dips = e.Dips,
FOC = e.FOC,
TransferPax = e.TransferPax,
CreatedBy = _user.UserID
}
);
}
await _db.AddAsync(flight);
return RedirectToAction("Index");
}
else
{
//var flight = await _db.SingleAsync<Flight>(x => x.FlightID == f.FlightID);
//return RedirectToAction("Index");
}
}
else
return NotFound();
}
and my models are
public class FlightViewModel
{
public long FlightID { get; set; }
public int SrcAirportID { get; set; }
public int DestAirportID { get; set; }
public string RegistrationNo { get; set; }
public string FlightNo { get; set; }
public string CallSign { get; set; }
public DateTime FlightDate { get; set; }
public int CrewMembers { get; set; }
public char Sector { get; set; }
public string UpdateRemarks { get; set; }
public ICollection<EmbDetViewModel> EmbDetails { get; set; }
}
and
public class EmbDetViewModel
{
public string PaxType { get; set; }
public char PaxClass { get; set; }
public int AdultPax { get; set; }
public int Infants { get; set; }
public int Dips { get; set; }
public int Crew { get; set; }
public int FOC { get; set; }
public int TransferPax { get; set; }
}
I need to write signature of the method like
public async Task<IActionResult> UTOneFlight([Bind("FlightID, SrcAirportID, DestAirportID, FlightDate, Sector, RegistrationNo, FlightNo, CallSign, CrewMembers, EmbDetails(PaxType, PaxClass), UpdateRemarks")] FlightViewModel f)
Please have a look at
EmbDetails(PaxType, PaxClass)
How do you send your request body? I test in my side and here's the result.
My model:
public class ParentTestModel
{
public int id { get; set; }
public ICollection<TestModel> testModels { get; set; }
}
public class TestModel
{
public string prefix { get; set; }
}
==============================Update=============================
I test in my side with [JsonIgnore] and the property which added this annotation will be ignored and this is suitable when the request body is a json object like the screenshot above. And if you are sending the request in form-data then you can use [Bind] annotation, I think you may have referred to this document.

Parsing [FromBody] JSON: model null

I'm trying to parse some json in my action which will then do things with it. However I keep getting null as my model instead of the filled out model.
This is the json I'm trying to parse:
{
"sameLanguages":true,
"sameDeadlines":true,
"sameDeliverables":false,
"quotations":[
{
"name":"zasd",
"deliverable":"538184e1-9a62-4ce9-baa7-ed746f267a9a",
"subtitleAssignments":{
"languageCombinations":[
{
"from":"d177b276-8f10-472f-84c6-f2ef59052a09",
"to":"d177b276-8f10-472f-84c6-f2ef59052a09",
"startDate":"19-09-2017",
"endDate":"19-09-2017"
}
],
"amount":12
},
"translationAssignments":{
"languageCombinations":[
]
}
}
]
}
This is my action:
[HttpPost]
public IActionResult Add([FromBody] SubmitQuotationsModel model)
{
//Do things...
return View();
}
These are my models:
public class SubmitQuotationsModel
{
public bool SameLanguages { get; set; }
public bool SameDeadlines { get; set; }
public bool SameDeliverables { get; set; }
public List<SubmitQuotationModel> Quotations { get; set; } = new List<SubmitQuotationModel>();
}
public class SubmitQuotationModel
{
public string Name { get; set; }
public string Deliverable { get; set; }
public List<AssignmentModel> SubtitleAssignments { get; set; }
public List<AssignmentModel> TranslationAssignments { get; set; }
}
public class AssignmentModel
{
public List<LanguageCombinationModel> LanguageCombinations { get; set; }
public int Amount { get; set; }
}
public class LanguageCombinationModel
{
public string From { get; set; }
public string To { get; set; }
public DateTimeOffset StartDate { get; set; }
public DateTimeOffset EndDate { get; set; }
}
I am sending the json from my knockout/typescript script as such:
fetch('/Quotation/Add', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
credentials: 'include',
body: this.toJSON()
});
public toJSON(): string {
let model = {
sameLanguages: this.step1().sameLanguages(),
sameDeadlines: this.step1().sameDeadlines(),
sameDeliverables: this.step1().sameDeliverables(),
quotations: this.step2().quotations().filter((q) => q.isFilledIn()).map((q) => {
return {
name: q.name(),
deliverable: q.selectedDeliverable().id,
subtitleAssignments: this.getAssignmentModel(q.subtitleAssignmentGroup()),
translationAssignments: this.getAssignmentModel(q.translationAssignmentGroup())
}
})
};
return ko.toJSON(model);
}
private getAssignmentModel(model: AssignmentGroupModel) {
return {
languageCombinations: model.assignments().map((a) => {
return {
from: a.fromLanguage().value,
to: a.toLanguage().value,
startDate: a.startDate().format('DD-MM-YYYY'),
endDate: a.endDate().format('DD-MM-YYYY')
}
}),
amount: model.amount()
}
}
I'm not getting any exceptions, the model parameter just remains null. I have found that if I comment out the SubtitleAssignments and TranslationAssignments in SubmitQuotationModel, it deserializes the other parts of the json just fine. But I can't figure out why it won't deserialize with those two ...Assignments declarations not commented out.
SubtitleAssignments and TranslationAssignments aren't lists in the json but they are lists in the models. They just need to be AssignmentModel and not List<AssignmentModel>

Angular 2 to post data to asp.net mvc controller

I am trying to post data from angularjs2 to asp.net mvc controller.
The actual issue is that when I am trying with it then
See how am I trying ?
this is the typescript ---
save(company: Company): Observable<boolean> {
let headers = new Headers({ 'Content-Type': 'application/json' });
this._http.post(this._postUrl, /*JSON.stringify(*/company/*)*/, { headers: headers })
.subscribe(
(data) => {
console.log('Response');
new Observable<true>()
},
(err) => { console.log(err); new Observable<false>(); },
() => console.log('Complete')
);
return new Observable<false>();
}
onSignUpClicked(message: string): void {
this._service.save(this.company).subscribe(
res => console.log(res),
error => this.errorMessage = <any>error
);
this is the typescript class:
import { Address } from '../shared/Address';
import { Contact } from '../shared/Contact';
export class Entity {
Id: string;
InsertionTime: Date;
InsertUserId: number;
IsDeleted: boolean;
IsLocked: boolean;
UpdateTime: Date;
UpdateUserId: number;
}
export class Company extends Entity {
Name: string;
Address: Address;
Contact: Contact;
Password: string;
ConfirmPassword: string;
UserName: string;
RegistrationDate: Date;
IsActive: boolean;
NextBillingDate: string;
TransactionLimit: number
}
and C# class
public class Company : Entity
{
public string Name { get; set; }
public Address Address { get; set; }
public Contact Contact { get; set; }
public string Password { get; set; }
public string UserName { get; set; }
public Image LogoImage { get; set; }
public DateTime RegistrationDate { get; set; }
public DateTime LastUpdated { get; set; }
public bool IsActive { get; set; }
public DateTime NextBillingDate { get; set; }
public Int64 TransactionLimit { get; set; }
}
public class Entity : IEntity
{
public Entity()
{
Id = Guid.NewGuid();
InsertionTime = DateTime.Now;
IsDeleted = false;
IsLocked = false;
}
public Guid Id
{
get;set;
}
public DateTime InsertionTime
{
get;set;
}
public int InsertUserId
{
get; set;
}
public bool IsDeleted
{
get; set;
}
public bool IsLocked
{
get; set;
}
public DateTime? UpdateTime
{
get;set;
}
public int? UpdateUserId
{
get; set;
}
}
any help appreciated
Here is a basic call to the server from an ng2 app:
getMeSomeServerData(someVar: string): Promise < IGenericRestResponse > {
let headers = new Headers();
headers.append("Content-Type", "application/json");
let url = "/getMeSomeServerData";
let post = this.http.post(url, JSON.stringify(someVar), {
headers: headers
}).map(response => response.json());
return post.toPromise();
}
And on the asp.net mvc backend:
// this of course goes within a controller
[HttpPost()]
[Route("getMeSomeServerData")]
public JsonNetResult GetMeSomeServerData(string someVar) {
GenericRestResponse response = new GenericRestResponse();
response.Error = false;
// do somthing
return new JsonNetResult(response);
}
JsonNetResult is simply a custom method for serializing an object into json. Obviously, you can modify someVar and IGenericRestResponse to your own needs.
On the client side, you also can return an Observable instead of a promise; the promise method is more familiar to me, so I use it unless I need some of the special functionality of an Observable.

Set Properties within base function and call function in child function inheritance

I am trying to refactor some old code and wanted to create more logical inheritance.
We have struct Custom Class which we have separated into (3) levels:
AccountView > Details > Full with inheritance. We set the properties of each one as needed.
After looking at the setters, we wanted to combine them into a single class 'SetAccountProp' with methods that set the properties.
We have the 'CustomerBaseView' where we pass in Models ACCOUNT data which works.
Now for the CustomerDetailView pass the same Model ACCOUNT data, but we would like to fill the properties of 'CustomerBaseView' use function 'CustomerBaseView' then fill the details.
Also, for CustomerFullView pass the Model ACCOUNT data, and fill the properties of 'CustomerBaseView' THEN 'CustomerBaseView' and then the remaining fields for CustomerFullView.
How can I call and fill the 'CustomerBaseView' within the 'CustomerDetailView' function? Do I initialize new AccountsView(); in each function?
Not sure how to finish up the refactor without repeating the:
// -- CustomView <--- replace with func?
view.Email = data.Email;
view.Active = data.Active;
view.FirstName = data.FirstName;
view.LastName = data.LastName;
in the Details and Full functions.
CODE
namespace BLL.Presenters
{
public class AccountsView
{
public string Email { get; set; }
public bool Active { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Details : AccountsView
{
public bool Administrator { get; set; }
public DateTime? LastLogin { get; set; }
}
public class Full : Details
{
public Guid ID { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public string FullName { get; set; }
}
public class SetAccountProp
{
public static AccountsView CustomerBaseView(Account data)
{
var view = new AccountsView();
view.Email = data.Email;
view.Active = data.Active;
view.FirstName = data.FirstName;
view.LastName = data.LastName;
return view;
}
public static Details CustomerDetailView(Account data)
{
var view = new Details();
// -- CustomView <--- replace with func?
view.Email = data.Email;
view.Active = data.Active;
view.FirstName = data.FirstName;
view.LastName = data.LastName;
// -- Details
view.Administrator = data.Administrator;
view.LastLogin = data.LastLogin;
return view;
}
public static Full CustomerFullView(Account data)
{
var view = new Full();
// -- CustomView <--- replace with func?
view.Email = data.Email;
view.Active = data.Active;
view.FirstName = data.FirstName;
view.LastName = data.LastName;
// -- Details <--- replace with func?
view.Administrator = data.Administrator;
view.LastLogin = data.LastLogin;
// -- Full
view.ID = data.ID;
view.Created = data.Created;
view.Modified = data.Modified;
view.FullName = data.LastName + ", " + data.FirstName;
return view;
}
}
}
Using constructor chaining, you could have something like this:
Each constructor calls it's base class' constructor first, so you don't have to repeat code.
namespace BLL.Presenters
{
using System;
public class Account // dummy to make it compile
{
public string Email;
public bool Active;
public string FirstName;
public string LastName;
public bool Administrator;
public DateTime? LastLogin;
public Guid ID;
public DateTime Created;
public DateTime Modified;
}
public class AccountsView
{
public string Email { get; set; }
public bool Active { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public AccountsView(Account data)
{
this.Email = data.Email;
this.Active = data.Active;
this.FirstName = data.FirstName;
this.LastName = data.LastName;
}
}
public class Details : AccountsView
{
public bool Administrator { get; set; }
public DateTime? LastLogin { get; set; }
public Details(Account data) : base(data)
{
this.Administrator = data.Administrator;
this.LastLogin = data.LastLogin;
}
}
public class Full : Details
{
public Guid ID { get; set; }
public DateTime Created { get; set; }
public DateTime Modified { get; set; }
public string FullName { get; set; }
public Full(Account data) : base(data)
{
this.ID = data.ID;
this.Created = data.Created;
this.Modified = data.Modified;
this.FullName = data.LastName + ", " + data.FirstName;
}
}
class Program
{
static void Main()
{
Console.WriteLine();
Console.ReadLine();
}
}
}
Why not something like this:
public class CustomerBase
{
public string Email { get; private set; }
public bool Active { get; private set; }
public string FirstName { get; private set; }
public string LastName { get; private set; }
protected void SetAccountInfo(Account account)
{
this.Email = account.Email;
this.Active = account.Active;
this.FirstName = account.FirstName;
this.LastName = account.LastName;
}
}
public class CustomerA : CustomerBase
{
public string IsAdmin { get; private set; }
public DateTime? LastLogin { get; private set; }
public void SetAccountInfo(Account account)
{
base.SetAccountInfo(account);
this.IsAdmin = account.IsAdmin;
this.LastLogin = account.LastLogin;
}
}
public class Account
{
//your properties
public string Email { get; set; }
public bool Active { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string IsAdmin { get; set; }
public DateTime? LastLogin { get; set; }
}
Or let the SetAccountInfo() return this
public CustomerA SetAccountInfo(Account account)
{
base.SetAccountInfo(account);
this.IsAdmin = account.IsAdmin;
this.LastLogin = account.LastLogin;
return this;
}

Categories

Resources