generic abstract class for hierarchical structured - c#

I would like to create an abstract class for hierarchical structured objects.
Here is what I already use, but now I want to make it generic
public class EventBase
{
private EventBase _Parent;
virtual public EventBase Parent
{
get
{
return _Parent;
}
set
{
_Parent = value;
}
}
[ForeignKey("Parent")]
private ICustomList<EventBase> _ChildList = new CustomList<EventBase>();
virtual public ICustomList<EventBase> ChildList
{
get
{
return _ChildList;
}
set
{
_ChildList = value;
}
}
}
something like this:
public class EventBaseGeneric
{
private GenericTypeThatIsSetInTheInheritingClass _Parent;
virtual public GenericTypeThatIsSetInTheInheritingClass Parent
{
get
{
return _Parent;
}
set
{
_Parent = value;
}
}
[ForeignKey("Parent")]
private ICustomList<GenericTypeThatIsSetInTheInheritingClass> _ChildList = new CustomList<GenericTypeThatIsSetInTheInheritingClass>();
virtual public ICustomList<GenericTypeThatIsSetInTheInheritingClass> ChildList
{
get
{
return _ChildList;
}
set
{
_ChildList = value;
}
}
}
Thanks a lot for any idea on how to achiv this !
Best regards,
Fabianus

It would look as follows:
// T generic parameter must inherit EventBase<T>
public class EventBase<T>
where T : EventBase<T>
{
public virtual T Parent { get; set; }
[ForeignKey("Parent")]
public virtual ICustomList<T> ChildList { get; set; } = new CustomList<T>()
}

I found the answer:
public abstract class PersistentObjectBaseWithNameHierarchical <T>
{
private T _Parent;
virtual public T Parent
{
get
{
return _Parent;
}
set
{
_Parent = value;
UpdatePropertiesInHierachy();
}
}
[ForeignKey("Parent")]
private ICustomList<T> _ChildList = new CustomList<T>();
virtual public ICustomList<T> ChildList
{
get
{
return _ChildList;
}
set
{
_ChildList = value;
UpdatePropertiesInHierachy();
}
}

could it be that it has to go like this ?
public abstract class PersistentObjectBaseWithNameHierarchical<T> : PersistentObjectBaseWithName where T : PersistentObjectBaseWithNameHierarchical<T>
{
private PersistentObjectBaseWithNameHierarchical<T> _Parent;
virtual public PersistentObjectBaseWithNameHierarchical<T> Parent
{
get
{
return _Parent;
}
set
{
_Parent = value;
UpdatePropertiesInHierachy();
}
}
[ForeignKey("Parent")]
private ICustomList<PersistentObjectBaseWithNameHierarchical<T>> _ChildList = new CustomList<PersistentObjectBaseWithNameHierarchical<T>>();
virtual public ICustomList<PersistentObjectBaseWithNameHierarchical<T>> ChildList
{
get
{
return _ChildList;
}
set
{
_ChildList = value;
UpdatePropertiesInHierachy();
}
}
public void AddChild(PersistentObjectBaseWithNameHierarchical<T> child)
{
if (ChildList.Count() != 0)
child.OrderPosition = ChildList.Max(e => e.OrderPosition) + 1;
ChildList.Add(child);
}
public void OrderChildList()
{
foreach (var e in ChildList)
{
e.OrderChildList();
}
ChildList.Sort((s1, s2) => s1.OrderPosition.CompareTo(s2.OrderPosition));
}
public int Level
{
get
{
if (Parent != null)
{
return Parent.Level + 1;
}
else
{
return 1;
}
}
}
private double _OrderPosition;
virtual public double OrderPosition
{
get
{
if (_OrderPosition == 0)
{
// We use the Id as OrderPosition to keep creation order by default
_OrderPosition = Id;
}
return _OrderPosition;
}
set
{
_OrderPosition = value;
Parent?.ChildList.Sort((s1, s2) => s1.OrderPosition.CompareTo(s2.OrderPosition));
UpdatePropertiesInHierachy();
}
}
public void UpdatePropertiesInHierachy()
{
PersistentObjectBaseWithNameHierarchical<T> r = GetRoot(this);
DuringUpdatePropertiesInHierachy();
}
Because otherwise I get an error here:
GetRoot(this)
telling
Argument 1: cannot convert from 'HostSystems.Models.PersistentObjectBaseWithNameHierarchical' to 'T'
Thanks for any further advice !
Regards,
Fabianus

Related

Refresh datagrid when changes to database are made

I'm writing a wpf application, where I have music albums and corresponding songs. I can add albums and corresponding songs. But now I want to to refresh the view when a change to the database is made. I found many possible solutions, but as I'm new to wpf and c# I don't know which one would suite my code.
In my MainView have an album list and a add button which opens another window where I can add data with a textbox.
AlbumListViewModel
#region Constants
IWindowManager addAlbum = new WindowManager();
IWindowManager addSong = new WindowManager();
private AlbumViewModel _selectedAlbum;
private SongViewModel _selectedSong;
#endregion
#region Constructor
public AlbumListViewModel()
{
Albums = new ObservableCollection<AlbumViewModel>(GetAlbumList());
AddAlbumCommand = new RelayCommand(x => AddAlbum());
AddSongCommand = new RelayCommand(x => AddSong());
}
#endregion
#region Properties
public ICommand AddAlbumCommand { get; private set; }
public ICommand AddSongCommand { get; private set; }
public ObservableCollection<AlbumViewModel> Albums { get; set; }
public AlbumViewModel SelectedAlbum
{
get
{
return _selectedAlbum;
}
set
{
if (_selectedAlbum != value)
{
_selectedAlbum = value;
}
NotifyPropertyChanged("SelectedAlbum");
}
}
public SongViewModel SelectedSong
{
get
{
return _selectedSong;
}
set
{
if (_selectedSong != value)
{
_selectedSong = value;
}
NotifyPropertyChanged("SelectedSong");
}
}
#endregion
#region Methods
public List<AlbumViewModel> GetAlbumList()
{
var controller = new BandManagerController();
return controller.GetAlbumList()
.Select(a => new AlbumViewModel(a))
.ToList();
}
private void AddAlbum()
{
addAlbum.ShowDialog(new AlbumViewModel(new AlbumData()));
}
private void AddSong()
{
addSong.ShowDialog(new SongViewModel(new SongData { AlbumID = SelectedAlbum.AlbumID }));
}
It opens the AlbumView where I add albums to the database.
public class AlbumViewModel : Screen
{
#region Constants
private AlbumData _data;
#endregion
#region Constructor
public AlbumViewModel(AlbumData data)
{
_data = data;
SongListVM = new SongListViewModel(data.AlbumID);
SaveAlbumToDatabase = new RelayCommand(x => AlbumToDatabase(data));
}
#endregion
#region Properties
public SongListViewModel SongListVM { get; set; }
public ICommand SaveAlbumToDatabase { get; private set; }
public string AlbumName
{
get
{
return _data.AlbumName;
}
set
{
if (_data.AlbumName != value)
{
_data.AlbumName = value;
NotifyOfPropertyChange("AlbumName");
}
}
}
public int AlbumID
{
get
{
return _data.AlbumID;
}
set
{
if (_data.AlbumID != value)
{
_data.AlbumID = value;
NotifyOfPropertyChange("AlbumID");
}
}
}
public string AlbumYear
{
get
{
return _data.AlbumYear;
}
set
{
if (_data.AlbumYear != value)
{
_data.AlbumYear = value;
NotifyOfPropertyChange("AlbumYear");
}
}
}
#endregion
#region Methods
public AlbumData AddAlbumEntry(AlbumData albumData)
{
var controller = new BandManagerController();
return controller.AddAlbumEntry(albumData);
}
public void ExecuteCancelCommand()
{
(GetView() as Window).Close();
}
public void AlbumToDatabase(AlbumData data)
{
AddAlbumEntry(data);
ExecuteCancelCommand();
}
#endregion
}
The AddAlbumEntry Method in the ALbumView is in a different class which is the connections to my database. I already use an ObservableCollection but don't know how to tell it the Database was updated.
Thanks in advance!
Just want to answer my question. I just changed my AddAlbum method to use a Deactivated event, to reload the Collection after the Dialog closes like:
private void AddAlbum()
{
var vm = new AlbumViewModel(new AlbumData());
vm.Deactivated += (s, e) => GetAlbumList();
addAlbum.ShowDialog(vm);
}

Generic Class Polymorphisim

If I have the following:
public abstract class Parameter<T>
{
protected T value;
public virtual T Value
{
get { return value; }
set { this.value = value; }
}
protected Parameter(T startingValue)
{
value = startingValue;
}
}
public class FloatParameter : Parameter<float>
{
public FloatParameter(float startingValue) : base(startingValue){}
}
public class IntParameter : Parameter<int>
{
public override int Value
{
get { return value; }
set { this.value = value > 100 ? 100 : value; }
}
public IntParameter(int startingValue) : base (startingValue) {}
}
Is there any way to create some List<Parameter> that can contain any of the derived types? For example, something like:
// no type specified in Parameter
List<Parameter> storedParameters = new List<Parameter>();
storedParameters.Add(new FloatParameter(2f));
storedParameters.Add(new IntParameter(7));
foreach(Parameter p in storedParameters)
{
DoSomethingWithValue(p.Value);
}
Or, alternatively, if this implementation is flawed, is there a better way to do this? What I have here feels slightly naive.
The only way I see to manage such case is to have and Interface that you use to manage the generic types, something like this should work:
public interface IParameter
{
void DoSomething();
}
public abstract class Parameter<T>
{
protected T value;
public T Value
{
get { return value; }
set { this.value = value; }
}
protected Parameter(T startingValue)
{
value = startingValue;
}
}
public class FloatParameter : Parameter<float>, IParameter
{
public FloatParameter(float startingValue) : base(startingValue) { }
public void DoSomething()
{
Console.WriteLine(value);
}
}
public class IntParameter : Parameter<int>, IParameter
{
public IntParameter(int startingValue) : base(startingValue) { }
public void DoSomething()
{
Console.WriteLine(value);
}
}
Ont his case you would be able to create a List of the Interface IParameter and add there specific instances:
var list = new List<IParameter>();
list.Add(new FloatParameter(1F));
list.Add(new IntParameter(1));
foreach (var item in list)
{
item.DoSomething();
}
Try to add nongeneric interface. Here is an example:
public class Program
{
static void Main(string[] args)
{
try
{
List<IParameter> storedParameters = new List<IParameter>();
storedParameters.Add(new FloatParameter(2f));
storedParameters.Add(new IntParameter(7));
foreach (IParameter p in storedParameters)
{
Console.WriteLine(p.ToString());
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
public interface IParameter
{
object value { get; }
}
public class Parameter<T> : IParameter
{
public object value { get; protected set; }
public virtual T Value
{
get { return (T)value; }
set { this.value = value; }
}
protected Parameter(T startingValue)
{
value = startingValue;
}
}
public class FloatParameter : Parameter<float>
{
public FloatParameter(float startingValue) : base(startingValue){ }
}
public class IntParameter : Parameter<int>
{
public override int Value
{
get { return (int)value; }
set { this.value = value > 100 ? 100 : value; }
}
public IntParameter(int startingValue) : base (startingValue) { }
}
No, it's not possible to do it.
What you are trying to do is to have an interface (or base class) that expose a property of an undefined type, to be able to then retrieve that value and dispatch it dynamically to the proper override of DoSomethingWithValue.
What you are after is achievable defining the property as dynamic, instead of using generics.
public class Parameter
{
protected dynamic value;
public dynamic Value
{
get { return value; }
set { this.value = value; }
}
public Parameter(dynamic startingValue)
{
value = startingValue;
}
}
public class MyStuff {
public void DoStuff()
{
List<Parameter> storedParameters = new List<Parameter>();
storedParameters.Add(new Parameter(2f));
storedParameters.Add(new Parameter(7));
foreach (Parameter p in storedParameters)
{
DoSomethingWithValue(p.Value);
}
}
}
Otherwise you should look into implementing a Double dispatch.
You can do it by defining a common interface and using the visitor pattern.
public interface IParameterVisitor
{
void VisitInt(int value);
void VisitFloat(float value);
}
public interface IParameter
{
void Accept(IParameterVisitor visitor);
}
The previous implementation has to be modified a bit:
public abstract class Parameter<T> : IParameter
{
protected T value;
public virtual T Value
{
get { return value; }
set { this.value = value; }
}
protected Parameter(T startingValue)
{
value = startingValue;
}
public abstract void Accept(IParameterVisitor visitor);
}
FloatParameter will VisitFloat, and IntParameter will VisitInt
public class FloatParameter : Parameter<float>
{
public FloatParameter(float startingValue) : base(startingValue) { }
public override void Accept(IParameterVisitor visitor)
{
visitor.VisitFloat(this.value);
}
}
public class IntParameter : Parameter<int>
{
public override int Value
{
get { return value; }
set { this.value = value > 100 ? 100 : value; }
}
public override void Accept(IParameterVisitor visitor)
{
visitor.VisitInt(this.value);
}
public IntParameter(int startingValue) : base(startingValue) { }
}
And our visitor for example:
public class MyVisitor : IParameterVisitor
{
public void VisitInt(int value)
{
Console.WriteLine($"Visiting an int: {value}");
}
public void VisitFloat(float value)
{
Console.WriteLine($"Visiting a float: {value}");
}
}
Finally, the usage:
var parameters =
new List<IParameter> {new FloatParameter(0.5f), new IntParameter(1)};
var visitor = new MyVisitor();
foreach (IParameter parameter in parameters) {
parameter.Accept(visitor);
}
If you change the value to an object you will be able to set the value to whatever type you like:
class Program
{
static void Main(string[] args)
{
// no type specified in Parameter
var storedParameters = new List<ParameterBase>();
storedParameters.Add(new FloatParameter(3.5F));
storedParameters.Add(new IntParameter(7));
foreach (var p in storedParameters)
{
Console.WriteLine(p.Value);
}
}
}
public class ParameterBase
{
protected object value;
public virtual object Value
{
get { return value; }
set { this.value = value; }
}
}
public class FloatParameter : ParameterBase
{
public FloatParameter(float value)
{
Value = value;
}
}
public class IntParameter : ParameterBase
{
public IntParameter(int value)
{
Value = value;
}
}
UPDATED: Use object instead of dynamic and removed ValueType as suggested by #Pieter Witvoet

objectcontext instance is not null but its disposed even if i declare it and give it same value

i know that this question have asked many times but i havent find any answer that can help me
the problem is
the-objectcontext-instance-has-been-disposed-and-can-no-longer-be-used-for-operations-that-require-a-connection
after i declare copy of entity object that have linked to other entity with 1 to many relation
this is the class
using System;
using System.Linq;
using School.Component;
using System.Windows.Input;
using DataAccess;
using System.Collections.ObjectModel;
using DataAccess.Repository;
using Microsoft.Practices.Prism.Commands;
using System.Collections.Generic;
namespace School.WpfApp.ViewModels
{
public class LevelsPerYearNewVM : ViewModelBase
{
SchAvaiLevelsPerYear _CurrentLevelsPerYear;
SchAvaiLevelsPerYear _old;
private bool _isnew = false;
bool _IsEnabled = false;
StudyYearRepository _Repository = new StudyYearRepository();
SchoolSettingRepository _SRepository = new SchoolSettingRepository();
ObservableCollection<StageLevel> _AllStageLevel;
StageLevel _SelectrdStageLevel;
ObservableCollection<SchAvaiLevelsPerYear> _allSchAvaiLevelsPerYear;
ObservableCollection<CoursesLevelsPerStYear> _AllCoursesLevelsPerStYear;
private string errorMasseg;
public LevelsPerYearNewVM(SchAvaiLevelsPerYear f, ObservableCollection<SchAvaiLevelsPerYear> _list)
: base()
{
_old = (f);
CurrentLevelsPerYear = new SchAvaiLevelsPerYear()
{
Avalible = f.Avalible,
CoursCount = f.CoursCount,
YearID = f.YearID,
ID = f.ID,
SchoolID = f.SchoolID,
UserID = f.UserID,
StageLevelID = f.StageLevelID,
};
InitVars();
CreateCommands();
ErrorMasseg = "";
if (_CurrentLevelsPerYear.ID > 0)
{
this.Title = "تعديل بيانات المستوى الدراسي";
}
else
{ this.Title = "اضافة مستوى دراسي"; IsEnabled = true; _isnew = true; }
_allSchAvaiLevelsPerYear = _list;
}
protected override async void InitVars()
{
AllStageLevel = await _SRepository.GetAllStageLevelsIncludeCourses();
if(!isnew)
AllCoursesLevelsPerStYear = await _SRepository.GetAllAllCoursesLevelsPerStYearBySchAvaiLevelsPerYearID( _CurrentLevelsPerYear.ID);
}
protected override void CreateCommands()
{
SaveCommand = new RelayCommand(o =>
{
Save();
}
, o => Valdite());
CanselCommand = new DelegateCommand(() =>
{
if (Closed != null)
{
_CurrentLevelsPerYear = null;
Closed(_CurrentLevelsPerYear);
}
}
, () => true);
}
private void Save()
{
SchAvaiLevelsPerYear a = null;
string masseg = "";
if (Valdite())
{
a = _allSchAvaiLevelsPerYear.FirstOrDefault(i => i.ID != CurrentLevelsPerYear.ID && i.StageLevelID == _CurrentLevelsPerYear.StageLevelID);
if (a == null)
{
_CurrentLevelsPerYear.CoursCount = _AllCoursesLevelsPerStYear.Where(cc=>cc.Avalible).Count();
_CurrentLevelsPerYear.UserID = Session.SessionData.CurrentUser.UserID;
_CurrentLevelsPerYear.ID = _Repository.SaveSchAvaiLevelsPerYear(_CurrentLevelsPerYear);
CoursesLevelsPerStYear v;
foreach (CoursesLevelsPerStYear c in _AllCoursesLevelsPerStYear)
{
if (_isnew)
c.SALByYearID = _CurrentLevelsPerYear.ID;
c.UserID = Session.SessionData.CurrentUser.UserID;
v = (CoursesLevelsPerStYear)MyDataAccessTools.Clone<CoursesLevelsPerStYear>(c);
c.ID= _Repository.SaveCoursesLevelsPerStYearDirctliy(v);
}
///// the error massage aaper her when i use break point to know what are the changes that have been done
_CurrentLevelsPerYear.CoursesLevelsPerStYears = _AllCoursesLevelsPerStYear
//////
/////
}
else
masseg = "يوجد مستوى دراسي مماثل";
}
if (string.IsNullOrWhiteSpace(masseg))
Closed(a);
else
ErrorMasseg = masseg;
}
private bool Valdite()
{
bool result = false;
if (_CurrentLevelsPerYear != null && _CurrentLevelsPerYear.StageLevelID>0 )
result = true;
return result;
}
public override void Reset()
{
}
public SchAvaiLevelsPerYear CurrentLevelsPerYear
{
get { return _CurrentLevelsPerYear; }
set
{
if (_CurrentLevelsPerYear != value)
{
_CurrentLevelsPerYear = value;
NotifyPropertyChanged("CurrentLevelsPerYear");
}
}
}
public ObservableCollection<StageLevel> AllStageLevel
{
get { return _AllStageLevel; }
set
{
if (_AllStageLevel != value)
{
_AllStageLevel = value;
NotifyPropertyChanged("AllStageLevel");
}
}
}
public StageLevel SelectrdStageLevel
{
get { return _SelectrdStageLevel; }
set
{
if (_SelectrdStageLevel != value)
{
_SelectrdStageLevel = value;
NotifyPropertyChanged("SelectrdStageLevel");
if (_isnew)
{
ObservableCollection<CoursesLevelsPerStYear> allcby = new ObservableCollection<CoursesLevelsPerStYear>();
CoursesLevelsPerStYear cby;
foreach (CoursesByLevel cbl in _SelectrdStageLevel.CoursesByLevels)
{
cby = new CoursesLevelsPerStYear() {StartDate = Session.SessionData.CurrentYear.StartDate, Avalible =true
, CoursByLevelID = cbl.ID , CoursesByLevel= cbl, UserID = Session.SessionData.CurrentUser.UserID,
MaxLecturePerWeak = cbl.MaxLecturePerWeak,MinLecturePerWeak = cbl.MinLecturePerWeak,
SchAvaiLevelsPerYear = _CurrentLevelsPerYear
};
allcby.Add(cby);
}
AllCoursesLevelsPerStYear = allcby;
}
}
}
}
public ObservableCollection<CoursesLevelsPerStYear> AllCoursesLevelsPerStYear
{
get { return _AllCoursesLevelsPerStYear; }
set
{
if (_AllCoursesLevelsPerStYear != value)
{
_AllCoursesLevelsPerStYear = value;
NotifyPropertyChanged("AllCoursesLevelsPerStYear");
}
}
}
public bool IsEnabled
{
get { return _IsEnabled; }
set
{
if (_IsEnabled != value)
{
_IsEnabled = value;
NotifyPropertyChanged("IsEnabled");
}
}
}
public string ErrorMasseg
{
get { return errorMasseg; }
private set
{
if (value != errorMasseg)
{
errorMasseg = value;
NotifyPropertyChanged("ErrorMasseg");
}
}
}
public event Action<SchAvaiLevelsPerYear> Closed;
public ICommand SaveCommand
{
private set;
get;
}
public DelegateCommand CanselCommand
{
private set;
get;
}
}
}
this the entity
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DataAccess
{
using System;
using System.Collections.ObjectModel;
public partial class SchAvaiLevelsPerYear : BaseModel
{
public SchAvaiLevelsPerYear()
{
this.CoursesLevelsPerStYears = new ObservableCollection<CoursesLevelsPerStYear>();
this.StduyYearLevelFrogs = new ObservableCollection<StduyYearLevelFrog>();
}
private int _iD;
public int ID
{
get { return _iD; }
set { SetProperty(ref _iD, value); }
}
private int _yearID;
public int YearID
{
get { return _yearID; }
set { SetProperty(ref _yearID, value); }
}
private int _stageLevelID;
public int StageLevelID
{
get { return _stageLevelID; }
set { SetProperty(ref _stageLevelID, value); }
}
private int _schoolID;
public int SchoolID
{
get { return _schoolID; }
set { SetProperty(ref _schoolID, value); }
}
private bool _avalible;
public bool Avalible
{
get { return _avalible; }
set { SetProperty(ref _avalible, value); }
}
private int _coursCount;
public int CoursCount
{
get { return _coursCount; }
set { SetProperty(ref _coursCount, value); }
}
private byte[] _timestamp;
public byte[] Timestamp
{
get { return _timestamp; }
set { SetProperty(ref _timestamp, value); }
}
private int _userID;
public int UserID
{
get { return _userID; }
set { SetProperty(ref _userID, value); }
}
public virtual Branch Branch { get; set; }
public virtual ObservableCollection<CoursesLevelsPerStYear> CoursesLevelsPerStYears { get; set; }
public virtual StageLevel StageLevel { get; set; }
public virtual StudyYear StudyYear { get; set; }
public virtual ObservableCollection<StduyYearLevelFrog> StduyYearLevelFrogs { get; set; }
}
}
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DataAccess
{
using System;
using System.Collections.ObjectModel;
public partial class CoursesLevelsPerStYear : BaseModel
{
public CoursesLevelsPerStYear()
{
this.CourseGroups = new ObservableCollection<CourseGroup>();
this.Teachers = new ObservableCollection<Teacher>();
}
private int _iD;
public int ID
{
get { return _iD; }
set { SetProperty(ref _iD, value); }
}
private int _coursByLevelID;
public int CoursByLevelID
{
get { return _coursByLevelID; }
set { SetProperty(ref _coursByLevelID, value); }
}
private int _sALByYearID;
public int SALByYearID
{
get { return _sALByYearID; }
set { SetProperty(ref _sALByYearID, value); }
}
private int _maxLecturePerWeak;
public int MaxLecturePerWeak
{
get { return _maxLecturePerWeak; }
set { SetProperty(ref _maxLecturePerWeak, value); }
}
private int _minLecturePerWeak;
public int MinLecturePerWeak
{
get { return _minLecturePerWeak; }
set { SetProperty(ref _minLecturePerWeak, value); }
}
private bool _haveGroup;
public bool HaveGroup
{
get { return _haveGroup; }
set { SetProperty(ref _haveGroup, value); }
}
private bool _avalible;
public bool Avalible
{
get { return _avalible; }
set { SetProperty(ref _avalible, value); }
}
private Nullable<int> _holeID;
public Nullable<int> HoleID
{
get { return _holeID; }
set { SetProperty(ref _holeID, value); }
}
private bool _hasHole;
public bool HasHole
{
get { return _hasHole; }
set { SetProperty(ref _hasHole, value); }
}
private System.DateTime _startDate;
public System.DateTime StartDate
{
get { return _startDate; }
set { SetProperty(ref _startDate, value); }
}
private Nullable<System.DateTime> _stopDate;
public Nullable<System.DateTime> StopDate
{
get { return _stopDate; }
set { SetProperty(ref _stopDate, value); }
}
private byte[] _timestamp;
public byte[] Timestamp
{
get { return _timestamp; }
set { SetProperty(ref _timestamp, value); }
}
private int _userID;
public int UserID
{
get { return _userID; }
set { SetProperty(ref _userID, value); }
}
public virtual ObservableCollection<CourseGroup> CourseGroups { get; set; }
public virtual CoursesByLevel CoursesByLevel { get; set; }
public virtual Hole Hole { get; set; }
public virtual SchAvaiLevelsPerYear SchAvaiLevelsPerYear { get; set; }
public virtual ObservableCollection<Teacher> Teachers { get; set; }
}
}
namespace DataAccess
{
partial class CoursesLevelsPerStYear : BaseModel
{
private bool _CanEdit;
public bool CanEdit
{
get { return _CanEdit; }
set
{
SetProperty(ref _CanEdit, value);
}
}
private bool _EditMode;
public bool EditMode
{
get { return _EditMode; }
set
{
SetProperty(ref _EditMode, value);
}
}
string _EditButtonVisibility = "";
public string EditButtonVisibility
{
get
{
return _EditButtonVisibility;
}
set { SetProperty(ref _EditButtonVisibility, value); }
}
}
}
this only relation that Have problem like this . yes i have forget to mention that i change the DBContext of the entity framework using this and this
and i am using entity framework 6.2
excuse my english i am not a good english writer .

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();

Execute is always called even when CanExecute is false,Is this correct?

I am using a delegate command .
I have noticed that regardless CanExecute is true or false execute is always called.
Is this correct?
I would have assumed that Execute would have been called only if CanExecute is true.
Could you clarify?
Thanks a lot
EDITED test shows that Save is always called
[TestFixture]
public class Can_test_a_method_has_been_called_via_relay_command
{
[Test]
public void Should_be_able_to_test_that_insert_method_has_been_called_on_repository()
{
var mock = new Mock<IEmployeeRepository>();
var employeeVm = new EmployeeVM(mock.Object) {Age = 19};
employeeVm.SaveCommand.Execute(null);
mock.Verify(e=>e.Insert(It.IsAny<Employee>()));
}
[Test]
public void Should_be_able_to_test_that_insert_method_has_not_been_called_on_repository()
{
var mock = new Mock<IEmployeeRepository>();
var employeeVm = new EmployeeVM(mock.Object) { Age = 15 };
employeeVm.SaveCommand.Execute(null);
mock.Verify(e => e.Insert(It.IsAny<Employee>()),Times.Never());
}
}
public class EmployeeVM:ViewModelBase
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeVM(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
private bool _hasInserted;
public bool HasInserted
{
get { return _hasInserted; }
set
{
_hasInserted = value;
OnPropertyChanged("HasInserted");
}
}
private int _age;
public int Age
{
get { return _age; }
set
{
_age = value;
OnPropertyChanged("Age");
}
}
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
OnPropertyChanged("Name");
}
}
private RelayCommand _saveCommand;
public ICommand SaveCommand
{
get
{
return _saveCommand ?? (_saveCommand = new RelayCommand(x => Save(), x => CanSave));
}
}
private bool CanSave
{
get
{
return Age > 18;
}
}
private void Save()
{
Insert();
HasInserted = true;
}
private void Insert()
{
_employeeRepository.Insert(new Employee{Age = Age,Name = Name});
}
}
public interface IEmployeeRepository
{
void Insert(Employee employee);
}
public class Employee
{
public string Name { get; set; }
public int Age { get; set; }
}
}
Your test methods are not testing what WPF will be doing run-time.
WPF will first determine if CanExecute evaluates to true - if it is not, the Button/MenuItem/InputBinding etc. is disabled and thus cannot be fired.
As I mentioned in my comment - this is only enforced by convention.

Categories