Parent class notified if child class properties change - c#

I have to view ViewModels, OrganizationContact and PersonalInformationModel.
OrganizationContact uses PersonalInformationModel.
They are setup like so:
OrganizationContact:
public class OrganizationContact : ViewModelBase
{
private PersonalInformationModel _contactInfo;
public PersonalInformationModel ContactInfo
{
get
{
return _contactInfo;
}
set
{
_contactInfo = value;
RaisePropertyChanged(nameof(ContactHeader), "", "", true);
RaisePropertyChanged(nameof(ContactInfo), null, _contactInfo, true);
}
}
//Generate Header
public string ContactHeader
{
get
{
var header = "";
if (!string.IsNullOrWhiteSpace(ContactInfo.Title?.TitleAbbreviation))
{
header += ContactInfo.Title.TitleAbbreviation + " ";
}
if (!string.IsNullOrWhiteSpace(ContactInfo.FirstName))
{
header += ContactInfo.FirstName + " ";
}
if (!string.IsNullOrWhiteSpace(ContactInfo.MiddleInitial))
{
header += ContactInfo.MiddleInitial + ". ";
}
if (!string.IsNullOrWhiteSpace(ContactInfo.LastName))
{
header += ContactInfo.LastName + " ";
}
return header;
}
}
public int OrganizationLink { get; set; }
public string Position { get; set; }
public int Priority { get; set; }
}
PersonalInformationModel:
public class PersonalInformationModel : ViewModelBase
{
private string _firstName;
private string _middleInitial;
private string _lastName;
private string _phoneNumber;
private string _phoneExtension;
private string _faxNumber;
private string _email;
public int PersonalIdentity { get; set; }
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
RaisePropertyChanged(nameof(FirstName), "", _firstName, true);
}
}
public string MiddleInitial
{
get
{
return _middleInitial;
}
set
{
_middleInitial= value;
RaisePropertyChanged(nameof(MiddleInitial),"",_middleInitial,true);
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
RaisePropertyChanged(nameof(LastName), "", _lastName, true);
}
}
public string PhoneNumber
{
get
{
return _phoneNumber;
}
set
{
_phoneNumber = value;
RaisePropertyChanged(nameof(PhoneNumber), "", _phoneNumber, true);
}
}
public string PhoneExtension
{
get
{
return _phoneExtension;
}
set
{
_phoneExtension = value;
RaisePropertyChanged(nameof(PhoneExtension), "", _phoneExtension, true);
}
}
public string FaxNumber
{
get
{
return _faxNumber;
}
set
{
_faxNumber = value;
RaisePropertyChanged(nameof(FaxNumber), "", _faxNumber, true);
}
}
public string Email
{
get
{
return _email;
}
set
{
_email = value;
RaisePropertyChanged(nameof(Email),"",_email, true);
}
}
public string FullName => $"{FirstName} {LastName}";
}
PersonalInformationModel is used by other classes.
What I'm looking for is a way for OrganizationContact to be informed if any property inside of PersonalInformationModel changes so the ContactHeader inside of OrganizationContact can be notified of the change.

Okay, so to get what you want you'll need to do a few things. First, register a PropertyChanged handler when you set your ContactInfo property on OrganizationContact:
public PersonalInformationModel ContactInfo
{
get
{
return _contactInfo;
}
set
{
if (_contactInfo != null)
{
_contactInfo.PropertyChanged -= ContactInfo_PropertyChanged;
}
_contactInfo = value;
if (_contactInfo != null)
{
_contactInfo.PropertyChanged += ContactInfo_PropertyChanged
}
RaisePropertyChanged(nameof(ContactInfo), null, _contactInfo, true);
}
}
Now, create your handler. You should be able to just raise the PropertyChanged event on ContactHeader to update your bindings.
void ContactInfo_PropertyChanged(object sender, PropertyChangedEventArgs args)
{
RaisePropertyChanged(nameof(ContactHeader), "", "", true);
}

Related

C# OrderBy on nested object Property

I'm using reflection to order by list of objects.
I would like to order this list on a property of a nested object.
This is the code in which I get the list, and I do the sorting of the list
List<DocumentModel> documentList;
if (contractid == -1)
documentList = helpsi.framework.core.CustomerProvider.DocumentModel.getAllDocumentModelListByCustomer(custid, custtypeid);
else
documentList = helpsi.framework.core.CustomerProvider.DocumentModel.getAllDocumentModelListGridByContract(contractid);
if (sord.Equals("asc")) documentList = documentList.OrderBy(x => x.GetType().GetProperty(sidx.ToUpper()).GetValue(x, null)).ToList();
else documentList = documentList.OrderByDescending(x => x.GetType().GetProperty(sidx.ToUpper()).GetValue(x, null)).ToList();
The DocumentModel object has a DocumentModelType property that contains a DocumentStateDesc string property.
Can I sort the list by the DocumentTypeDesc property using reflection? What can I use in the sidx parameter?
Thanks
This is the DocumentModel class
public class DocumentModel : ObjBase
{
#region Attributi
private long _id;
private string _documentModel;
private long? _documentModelTypeId;
private long? _documentModelIssuingEntityId;
private string _documentModelFilename;
private string _documentModelPath;
private DateTime? _documentModelStart;
private DateTime? _documentModelEnd;
private string _documentModelVersion;
private long _contractId;
private string _contractNumber;
private long _contractTypeId;
private long _contractStateId;
private string _contractState;
private long _documentModelStateId;
private string _documentModelValoId;
private DateTime? _documentModelUploadDate;
private byte[] _documentModelContent;
private long _documentModelFilter;
private bool _flagDeleted;
private long _userId;
private int _orderDocumentModel = 0;
private string _placeOfIssue;
private string _issuingEntity;
private DateTime? _releaseDate;
private int? _idOpInsert;
private int? _idOpId;
private long? _customerId;
private long? _customerTypeId;
private string _customerNumber;
private DateTime? _documentModelInvalidated;
private bool _flagValidating;
private string _fileRemotePath;
private long? _folderId;
private string _folderName;
protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_ID")]
public long CODE_DOCUMENT_MODEL_ID
{
get { return _id; }
set { _id = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL")]
public string DESC_DOCUMENT_MODEL
{
get { return _documentModel; }
set { _documentModel = value; }
}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_TYPE_ID")]
public long? CODE_DOCUMENT_MODEL_TYPE_ID
{
get { return _documentModelTypeId; }
set { _documentModelTypeId = value; }
}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_ISSUING_ENTITY_ID")]
public long? CODE_DOCUMENT_MODEL_ISSUING_ENTITY_ID
{
get { return _documentModelIssuingEntityId; }
set { _documentModelIssuingEntityId = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_FILENAME", IsNullable = true)]
public string DESC_DOCUMENT_MODEL_FILENAME
{
get { return _documentModelFilename; }
set { _documentModelFilename = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_PATH", IsNullable=true)]
public string DESC_DOCUMENT_MODEL_PATH
{
get { return _documentModelPath; }
set { _documentModelPath = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_MODEL_START")]
public DateTime? DATE_DOCUMENT_MODEL_START
{
get { return _documentModelStart; }
set { _documentModelStart = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_MODEL_END")]
public DateTime? DATE_DOCUMENT_MODEL_END
{
get { return _documentModelEnd; }
set { _documentModelEnd = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_VERSION", IsNullable = true)]
public string DESC_DOCUMENT_MODEL_VERSION
{
get { return _documentModelVersion; }
set { _documentModelVersion = value; }
}
[XmlElement(ElementName = "CODE_CONTRACT_ID")]
public long CODE_CONTRACT_ID
{
get { return _contractId; }
set { _contractId = value; }
}
[XmlElement(ElementName = "FLAG_DELETED")]
public bool FLAG_DELETED
{
get { return _flagDeleted; }
set { _flagDeleted = value; }
}
[XmlElement(ElementName = "CODE_USER_ID")]
public long CODE_USER_ID
{
get { return _userId; }
set { _userId = value; }
}
[XmlElement(ElementName = "ORDER_DOCUMENT_MODEL")]
public int ORDER_DOCUMENT_MODEL
{
get { return _orderDocumentModel; }
set { _orderDocumentModel = value;}
}
private DocumentModelType _documentModelType;
[XmlElement(ElementName = "DocumentModelType", IsNullable = true)]
public DocumentModelType documentModelType
{
get { return _documentModelType; }
set { _documentModelType = value; }
}
private DocumentModelState _documentModelState;
[XmlElement(ElementName = "DocumentModelState", IsNullable = true)]
public DocumentModelState documentModelState
{
get { return _documentModelState; }
set { _documentModelState = value; }
}
private DocumentModelIssuingEntity _documentModelIssuingEntity;
[XmlElement(ElementName = "DocumentModelIssuingEntity", IsNullable = true)]
public DocumentModelIssuingEntity documentModelIssuingEntity
{
get { return _documentModelIssuingEntity; }
set { _documentModelIssuingEntity = value; }
}
//private DocumentModelFolder _documentModelFolder;
//[XmlElement(ElementName = "DocumentModelFolder", IsNullable = true)]
//public DocumentModelFolder documentModelFolder
//{
// get { return _documentModelFolder; }
// set { _documentModelFolder = value; }
//}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_STATE_ID")]
public long CODE_DOCUMENT_MODEL_STATE_ID
{
get { return _documentModelStateId; }
set { _documentModelStateId = value; }
}
[XmlElement(ElementName = "VALO_DOCUMENT_MODEL_ID")]
public string VALO_DOCUMENT_MODEL_ID
{
get { return _documentModelValoId; }
set { _documentModelValoId = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_MODEL_UPLOAD")]
public DateTime? DATE_DOCUMENT_MODEL_UPLOAD
{
get { return _documentModelUploadDate; }
set { _documentModelUploadDate = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_CONTENT")]
public byte[] DESC_DOCUMENT_MODEL_CONTENT
{
get { return _documentModelContent; }
set { _documentModelContent = value; }
}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_FILTER_ID")]
public long CODE_DOCUMENT_MODEL_FILTER_ID
{
get { return _documentModelFilter; }
set { _documentModelFilter = value; }
}
private long _code_siteId;
[XmlElement(ElementName = "CODE_SITEID")]
public long CODE_SITEID
{
get { return _code_siteId; }
set { _code_siteId = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_RELEASE_PLACE")]
public string DESC_DOCUMENT_RELEASE_PLACE
{
get { return _placeOfIssue; }
set { _placeOfIssue = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_RELEASED_BY")]
public string DESC_DOCUMENT_RELEASED_BY
{
get { return _issuingEntity; }
set { _issuingEntity = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_RELEASED")]
public DateTime? DATE_DOCUMENT_RELEASED
{
get { return _releaseDate; }
set { _releaseDate = value; }
}
[XmlElement(ElementName = "CODE_OP_INSERT_ID")]
public int? CODE_OP_INSERT_ID
{
get { return _idOpInsert; }
set { _idOpInsert = value; }
}
[XmlElement(ElementName = "CODE_OP_ID_ID")]
public int? CODE_OP_ID_ID
{
get { return _idOpId; }
set { _idOpId = value; }
}
[XmlElement(ElementName = "CODE_CUSTOMERID")]
public long? CODE_CUSTOMERID
{
get { return _customerId; }
set { _customerId = value; }
}
[XmlElement(ElementName = "CODE_CUSTOMERTYPEID")]
public long? CODE_CUSTOMERTYPEID
{
get { return _customerTypeId; }
set { _customerTypeId = value; }
}
[XmlElement(ElementName = "DATE_DOCUMENT_MODEL_INVALIDATED")]
public DateTime? DATE_DOCUMENT_MODEL_INVALIDATED
{
get { return _documentModelInvalidated; }
set { _documentModelInvalidated = value; }
}
[XmlElement(ElementName = "FLAG_VALIDATING")]
public bool FLAG_VALIDATING
{
get { return _flagValidating; }
set { _flagValidating = value; }
}
[XmlElement(ElementName = "CODE_CONTRACT_STATES_ID")]
public long CODE_CONTRACT_STATES_ID
{
get { return _contractStateId; }
set { _contractStateId = value; }
}
[XmlElement(ElementName = "DESC_CONTRACT_STATES")]
public string DESC_CONTRACT_STATES
{
get { return _contractState; }
set { _contractState = value; }
}
[XmlElement(ElementName = "CODE_CONTRACT_TYPE_ID")]
public long CODE_CONTRACT_TYPE_ID
{
get { return _contractTypeId; }
set { _contractTypeId = value; }
}
[XmlElement(ElementName = "DESC_CONTRACT_NUMBER")]
public string DESC_CONTRACT_NUMBER
{
get { return _contractNumber; }
set { _contractNumber = value; }
}
[XmlElement(ElementName = "DESC_CONTACT_NUMBER")]
public string DESC_CONTACT_NUMBER
{
get { return _customerNumber; }
set { _customerNumber = value; }
}
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_FOLDER_ID")]
public long? CODE_DOCUMENT_MODEL_FOLDER_ID
{
get { return _folderId; }
set { _folderId = value; }
}
[XmlElement(ElementName = "DocumentModelFolderName")]
public string DocumentModelFolderName
{
get { return _folderName; }
set { _folderName = value; }
}
[XmlElement(ElementName = "DESC_FILEREMOTEPATH")]
public string DESC_FILEREMOTEPATH
{
get { return _fileRemotePath; }
set { _fileRemotePath = value; }
}
#endregion
}
And this is the DocumentModelType Class
public class DocumentModelType : ObjBase
{
#region Attributi
private long _id;
private string _documentModelType;
private bool _flagDeleted;
private long _userId;
protected new HELPSI_Database HELPSI_Database = Common.HELPSI_Database.HELPSI_Anag;
[XmlElement(ElementName = "CODE_DOCUMENT_MODEL_TYPE_ID")]
public long CODE_DOCUMENT_MODEL_TYPE_ID
{
get { return _id; }
set { _id = value; }
}
[XmlElement(ElementName = "DESC_DOCUMENT_MODEL_TYPE")]
public string DESC_DOCUMENT_MODEL_TYPE
{
get { return _documentModelType; }
set { _documentModelType = value; }
}
[XmlElement(ElementName = "FLAG_DELETED")]
public bool FLAG_DELETED
{
get { return _flagDeleted; }
set { _flagDeleted = value; }
}
[XmlElement(ElementName = "CODE_USER_ID")]
public long CODE_USER_ID
{
get { return _userId; }
set { _userId = value; }
}
#endregion
}
You should be using x => x.DocumentModelType.GetType().GetProperty(sidx.ToUpper()).GetValue(x.DocumentModelType, null) inside OrderBy clause. Here sidx should be DocumentStateDesc as you mentioned that you want order on this column.
Complete code will be like below.
List<DocumentModel> documentList;
if (contractid == -1)
documentList = helpsi.framework.core.CustomerProvider.DocumentModel.getAllDocumentModelListByCustomer(custid, custtypeid);
else
documentList = helpsi.framework.core.CustomerProvider.DocumentModel.getAllDocumentModelListGridByContract(contractid);
if (sord.Equals("asc"))
documentList = documentList.OrderBy(x => x.DocumentModelType.GetType().GetProperty(sidx.ToUpper()).GetValue(x.DocumentModelType, null)).ToList();
else
documentList = documentList.OrderByDescending(x => x.DocumentModelType.GetType().GetProperty(sidx.ToUpper()).GetValue(x.DocumentModelType, null)).ToList();
One quick and dirty fix is to introduce property in parent class that just returns the property value of another property. Just don't assign XmlElement attribute to it. If the classes are auto-generated you can't change them, but they are probably declared as partial, and then you can add this new property in additional class definition.
public string DocumentModelType_DocumentStateDesc { get => DocumentModelType.DocumentStateDesc; }
But if you want to have a general solution for several properties with several sub-properties then some sort of pathing is required. You could String.Split sidx on some delimiter like '\' or '.', use recursion, and then OrderBy the last item in the path.

Serialize object in WPF to XML

So I'm building an application in WPF using MVVM and I want to save various object model data as XML. Using Serialize an object to XML I can correctly serialize objects to XML, but the issue I'm having is with the MVVM itself.
I can't directly access the Model of the object within the ICommand segments of the ViewModel code (E.G. When I hit save, that goes to an ICommand method inside the ViewModel).
I've made the Model is question serializable, I just have no way to pass it directly to my Serialize method (which is contained in it's own static Helper class) so even if I weren't getting "Unexpected type" spit back at me (since VieWModel is not serializable) I'd end up with a lot of excess garbage, not just the Model class being serialized.
I'm not sure if I'm just designing this incorrectly, or if there's a better way to do it or...?
P.S. All of these fields are just being written into TextBox controls that are bound appropriately. Right now I'm only trying to do the name fields to avoid any kind of issues with other data types not working right.
EDIT: As requested in a comment, the goal right now is just to be able to write some bits of text in a few text boxes (First, middle, last names), then save that to an XML file.
Summarized Model in question:
namespace XMLaw.Model
{
[Serializable]
public class ClientModel
{
private string firstName { get; set; }
private string middleName { get; set; }
private string lastName { get; set; }
private DateTime dateOfBirth { get; set; }
private string ssn { get; set; } //Format: AA ## ## ## A, spaces optional
private string address { get; set; }
private string phone { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#region Name Properties
public string FirstName
{
get { return firstName; }
set
{
if( firstName != value )
{
firstName = value;
OnPropertyChanged("FirstName");
}
}
}
public string MiddleName
{
get { return middleName; }
set
{
if (middleName != value)
{
middleName = value;
OnPropertyChanged("MiddleName");
}
}
}
public string LastName
{
get { return lastName; }
set
{
if (lastName != value)
{
lastName = value;
OnPropertyChanged("LastName");
}
}
}
#endregion
public DateTime DateOfBirth
{
get { return dateOfBirth; }
set
{
if ( dateOfBirth != value )
{
DateTime dt = Convert.ToDateTime(value); //This will probably need to revisited since DateTime objects are fucking stupid
dateOfBirth = dt.Date;
OnPropertyChanged("DateOfBirth");
}
}
}
public string SSN
{
get { return ssn; }
set
{
if( ssn != value)
{
ssn = value;
OnPropertyChanged("SSN");
}
}
}
public string Address
{
get { return address; }
set
{
if( address != value)
{
address = value;
OnPropertyChanged("Address");
}
}
}
public string Phone
{
get { return phone; }
set
{
if( phone != value )
{
phone = value;
OnPropertyChanged("Phone");
}
}
}
}
}
And the ViewModel in question (The Save command that calls the serialization is at the bottom)
namespace XMLaw.ViewModel
{
public class ClientViewModel : INotifyPropertyChanged
{
private ClientModel client;
private string displayMessage;
private ICommand btnSave;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public ClientViewModel()
{
client = new ClientModel();
}
public ClientModel ClientModel
{
get { return client; }
}
public string DisplayMessage
{
get { return displayMessage; }
set
{
if( displayMessage != value)
{
displayMessage = value;
OnPropertyChanged("DisplayMessage");
}
}
}
public ICommand SaveCommand
{
get
{
if (btnSave == null)
btnSave = new Save();
return btnSave;
}
set { btnSave = value; }
}
protected class Save : ICommand
{
public bool CanExecute(object param) { return true; }
public event EventHandler CanExecuteChanged; //Compiler yells at you if you don't implement this from inhereted ICommand
public void Execute(object param)
{
ClientViewModel viewModel = (ClientViewModel)param;
//TODO: Insert XML serialization and save to a file
var xml = Helper.Serialize(param);
//Placeholder to make sure the button works
viewModel.DisplayMessage = "You clicked the button at " + DateTime.Now;
}
}
}
}
And the Serailization method I shamelessly took from the above link
public static class Helper
{
public static string Serialize<T>(this T value)
{
if (value == null)
{
return string.Empty;
}
try
{
var xmlserializer = new XmlSerializer(typeof(T));
var stringWriter = new StringWriter();
using (var writer = XmlWriter.Create(stringWriter))
{
xmlserializer.Serialize(writer, value);
return stringWriter.ToString();
}
}
catch (Exception ex)
{
throw new Exception("An error occurred", ex);
}
}
}
Change your Client-Model to this:
[Serializable]
public class ClientModel
{
private string firstName;
private string middleName;
private string lastName;
private DateTime dateOfBirth;
private string ssn;
private string address;
private string phone;
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
#region Name Properties
public string FirstName {
get { return firstName; }
set {
if (firstName != value)
{
firstName = value;
OnPropertyChanged("FirstName");
}
}
}
public string MiddleName {
get { return middleName; }
set {
if (middleName != value)
{
middleName = value;
OnPropertyChanged("MiddleName");
}
}
}
public string LastName {
get { return lastName; }
set {
if (lastName != value)
{
lastName = value;
OnPropertyChanged("LastName");
}
}
}
#endregion
public DateTime DateOfBirth {
get { return dateOfBirth; }
set {
if (dateOfBirth != value)
{
DateTime dt = Convert.ToDateTime(value); //This will probably need to revisited since DateTime objects are fucking stupid
dateOfBirth = dt.Date;
OnPropertyChanged("DateOfBirth");
}
}
}
public string SSN {
get { return ssn; }
set {
if (ssn != value)
{
ssn = value;
OnPropertyChanged("SSN");
}
}
}
public string Address {
get { return address; }
set {
if (address != value)
{
address = value;
OnPropertyChanged("Address");
}
}
}
public string Phone {
get { return phone; }
set {
if (phone != value)
{
phone = value;
OnPropertyChanged("Phone");
}
}
}
}
Usage:
var xx = new ClientModel();
xx.FirstName = "John";
xx.LastName = "Smith";
xx.DateOfBirth = DateTime.Now;
var result = xx.Serialize();
Result:
http://www.w3.org/2001/XMLSchema-instance\"
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">
John Smith
2016-07-11T00:00:00+02:00
EDIT:
This code:
public void Execute(object param)
{
ClientViewModel viewModel = (ClientViewModel)param;
//TODO: Insert XML serialization and save to a file
var xml = Helper.Serialize(param);
//Placeholder to make sure the button works
viewModel.DisplayMessage = "You clicked the button at " + DateTime.Now;
}
Should be replaced by this:
public void Execute(object param)
{
ClientModel model= (ClientModel )param;
//TODO: Insert XML serialization and save to a file
var xml = Helper.Serialize(param);
//Placeholder to make sure the button works
viewModel.DisplayMessage = "You clicked the button at " + DateTime.Now;
}
Make sure, your Param is of type ClientModel.
I also highly recommend you, to get into the basics of how DataBinding works
Edit 2 (The Command-Thingy):
class Save : ICommand
{
public ClientModel Model { get; set; }
public bool CanExecute(object param) { return true; }
public event EventHandler CanExecuteChanged; //Compiler yells at you if you don't implement this from inhereted ICommand
public void Execute(object param)
{
//TODO: Insert XML serialization and save to a file
var xml = Helper.Serialize(this.Model);
//Placeholder to make sure the button works
viewModel.DisplayMessage = "You clicked the button at " + DateTime.Now;
}
}
Usage:
public ICommand SaveCommand
{
get
{
if (btnSave == null)
btnSave = new Save();
btnSave.Model = this.ClientModel;
return btnSave;
}
set { btnSave = value; }
}

After specifying a DataTextField and DataValueField, why doesn't my DropDownList show the elements of my List?

I'm trying to populate a DropDownList, but I have some troubles with the DataTextField and DataValueField. The drop-down doesn't show the elements of the list.
private void llenarProfesionales()
{
List<Profesional> profesionales = daoProfesionales.getAll();
DropDownProfesioanles.DataSource = profesionales;
DropDownProfesioanles.DataTextField = "nombre";
DropDownProfesioanles.DataValueField = "id";
DropDownProfesioanles.DataBind();
}
Here is my class profesional that extends usuario:
public class Profesional: Usuario
{
long idProfesional;
List<Servicio> listaServicios;
Profesion profesion;
Usuario usuar;
Decimal comision;
public Decimal Comision
{
get { return comision; }
set { comision = value; }
}
public Profesional()
{
}
public long IdProfesional
{
get { return idProfesional; }
set { idProfesional = value; }
}
public List<Servicio> ListaServicios
{
get { return listaServicios; }
set { listaServicios = value; }
}
public Profesion Profesion
{
get { return profesion; }
set { profesion = value; }
}
public Usuario Usuar
{
get { return usuar; }
set { usuar = value; }
}
}
Here is the class usuario:
public class Usuario
{
private long id;
private String nombre;
private String apellido;
private String telefono;
private String celular;
private Boolean activo;
private String user;
private String password;
public Usuario()
{
}
public Usuario(string nombre, string apellido, string telefono , string celular, string user, string password ,long id, bool activo) {
this.Id = id;
this.Nombre = nombre;
this.Apellido = apellido;
this.Telefono = telefono;
this.Celular = celular;
this.User = user;
this.password = password;
this.activo = activo;
}
public long Id
{
get { return id; }
set { id = value; }
}
public String Nombre
{
get { return nombre; }
set { nombre = value; }
}
public String Apellido
{
get { return apellido; }
set { apellido = value; }
}
public String Telefono
{
get { return telefono; }
set { telefono = value; }
}
public String Celular
{
get { return celular; }
set { celular = value; }
}
public String Password
{
get { return password; }
set { password = value; }
}
public Boolean Activo
{
get { return activo; }
set { activo = value; }
}
public String User
{
get { return user; }
set { user = value; }
}
}
Specify the public properties, not the private fields:
DropDownProfesioanles.DataTextField = "Nombre";
DropDownProfesioanles.DataValueField = "Id";
Also, there's no reason to define your class like this, where you define a public Usuario property, but also extend the Usuario class (so you'll have access to all of its properties, but they won't have any values since you're using the separate "Usuar" variable).
public class Profesional : Usuario
{
...
Usuario usuar;
...
public Usuario Usuar
{
get { return usuar; }
set { usuar = value; }
}
}
If you're going to use the public property, then don't extend the other class:
public class Profesional
{
...
Usuario usuar;
...
public Usuario Usuar
{
get { return usuar; }
set { usuar = value; }
}
}
thanks for the answers I solved adding this code to the Profesional
public String Nombre
{
get { return usuar.Nombre; }
set { usuar.Nombre = value; }
}

Custom Collection/List To Store Custom Objects

I have a customer object class:
public class customerObject
{
private string _address1;
private string _address2;
private string _address3;
private string _category;
private string _country;
private string _county;
private string _custcode;
private string _fullname;
private string _int_rep_hou;
private string _int_rep_key;
private double _lat;
private double _lng;
private string _postcode;
private string _rep_code;
private string _telephone;
public customerObject()
{
}
public string Address1
{
get { return _address1; }
set { _address1 = value; }
}
public string Address2
{
get
{
return _address2;
}
set { _address2 = value; }
}
public string Address3 { get { return _address3; } set { _address3 = value; } }
public string Category
{
get { return _category; }
set { _category = value; }
}
public string Country { get { return _country; } set { _country = value; } }
public string County { get { return _county; } set { _county = value; } }
public string Custcode
{
get { return _custcode; }
set { _custcode = value; }
}
public string Fullname
{
get { return _fullname; }
set { _fullname = value; }
}
public string Int_rep_hou
{
get { return _int_rep_hou; }
set { _int_rep_hou = value; }
}
public string Int_rep_key
{
get { return _int_rep_key; }
set { _int_rep_key = value; }
}
public double Lat { get { return _lat; } set { _lat = value; } }
public double Lng { get { return _lng; } set { _lng = value; } }
public string Postcode { get { return _postcode; } set { _postcode = value; } }
public string Rep_code
{
get { return _rep_code; }
set { Rep_code = value; }
}
public string Telephone { get { return _telephone; } set { _telephone = value; }
}
}
I have a CustomCollections class
public class CustomerCollection
{
public List<customerObject> Customers { get; set; }
}
My method that loops through dt rows and converts to a customer object
public List<Valueobjects.CustomerCollection> dolist(DataTable temptablename)
{
//Create Collection Object
Valueobjects.CustomerCollection Collection = new Valueobjects.CustomerCollection();
foreach (DataRow row in temptablename.Rows)
{
//Create Customer Object
Valueobjects.customerObject Customer = new Valueobjects.customerObject();
//set values of customer object
Customer.Rep_code = "";
Customer.Int_rep_key = "";
Customer.Int_rep_hou = "";
Customer.Fullname = row["Fullname"].ToString().Trim();
Customer.Custcode = row["Custcode"].ToString().Trim();
Customer.Category = row["Category"].ToString().Trim();
Customer.Address1 = row["Address1"].ToString().Trim();
Customer.Address2 = row["Address2"].ToString().Trim();
Customer.Address3 = row["Address3"].ToString().Trim();
Customer.Postcode = row["Postcode"].ToString().Trim();
Customer.Country = row["Country"].ToString().Trim();
Customer.Telephone = row["Telephone"].ToString().Trim();
Customer.Lat = Convert.ToDouble(row["Lat"]);
Customer.Lng = Convert.ToDouble(row["Lng"]);
Customer.County = row["County"].ToString().Trim();
//add to the collection (list)
Collection.Customers.Add(Customer);
}
temptablename = null;
return Collection;
}
However when I create a new Customer object and a new CustomerCollection object I am getting an error when adding the customer to the collection list.
Error:
Error 32 Cannot implicitly convert type
'Classes.Valueobjects.CustomerCollection' to
'System.Collections.Generic.List'
Your method is returning a List<CustomerCollection>:
public List<Valueobjects.CustomerCollection> dolist(DataTable temptablename)
{
//...
}
But the code is trying to return a CustomerCollection:
return Collection;
Just as the error says, these two types are different.
If a CustomerCollection is already a collection of customers, then semantically what is a List<Valueobjects.CustomerCollection>? A collection of collections? It seems like you're over-pluralizing your objects :)
There are two approaches here. Either return a CustomerCollection from the method:
public CustomerCollection dolist(DataTable temptablename)
{
//...
}
Or use a List<Customer> if you want to use generic lists as your collection containers:
public List<Customer> dolist(DataTable temptablename)
{
//...
var Collection = new List<Customer>();
//...
Collection.Add(Customer);
//...
return Collection;
}
Side note: You may want to stick to C# conventions for variable naming. As you can see from the code highlighting here on Stack Overflow, your variable names can easily be mistaken for classes/types, which can cause confusion when supporting the code.
Return a CustomerCollection instead of a List<Valueobjects.CustomerCollection>:
public Valueobjects.CustomerCollection Dolist(DataTable temptablename)
{
// ...
Your object has a list, it is not a list.
MSDN: Inheritance

C# - Marshall by value problem!

Here is the thing, I have a problem creating a new object using the remote mechanism "marshal by value".
Here is my class:
[Serializable]
internal class Empleado_MBV
{
public Empleado_MBV()
{
Id = 123456789;
Nombres = "NotEntry";
Apellidos = "NotEntry";
FechaNacimiento = DateTime.MinValue;
Direccion = "NotEntry";
Metapreferencias = "NotEntry";
}
private List<Multas> _multas;
internal List<Multas> Multas
{
get { return _multas; }
set { _multas = value; }
}
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _nombres;
public string Nombres
{
get { return _nombres; }
set { _nombres = value; }
}
private string _apellidos;
public string Apellidos
{
get { return _apellidos; }
set { _apellidos = value; }
}
private DateTime _FecNac;
public DateTime FechaNacimiento
{
get { return _FecNac; }
set { _FecNac = value; }
}
private string _direccion;
public string Direccion
{
get { return _direccion; }
set { _direccion = value; }
}
private string _metapreferencias;
public string Metapreferencias
{
get { return _metapreferencias; }
set { _metapreferencias = value; }
}
public string _AppDomainHost
{
get { return AppDomain.CurrentDomain.FriendlyName.ToString(); }
}
}
But when I try to create an object in another "appdomain", the property "_AppDomainHost" of "Empleado" does not show the "appdomain" I had created, but show the "appdomain" by default. Some ideas?
AppDomain ad1 = AppDomain.CreateDomain("NewAppDomain");
//Crear new object in my new AD.
Empleado_MBV mbv_emp = (Empleado_MBV)ad1.CreateInstanceFromAndUnwrap("DEMO_MBV_MBR.exe", "DEMO_MBV_MBR.Empleado_MBV");
Console.WriteLine(AppDomain.CurrentDomain.FriendlyName.ToString());
Console.WriteLine("MBV : {0}",mbv_emp._AppDomainHost.ToString());
Console.ReadLine();
Result:
DEMO_MBV_MBR.vshost.exe
MBV : DEMO_MBV_MBR.vshost.exe
The result that I want:
DEMO_MBV_MBR.vshost.exe
MBV : NewAppDomain
You need to store AppDomain in Empleado_MBV's constructor.
What you are doing right now is displaying current AppDomain using its Current static property. It will return the AppDomain where current code is being executed.
Example:
private string _appDomainHost;
public string _AppDomainHost
{
get { return _appDomainHost; }
}
and in constructor:
_appDomainHost = AppDomain.CurrentDomain.FriendlyName.ToString();

Categories