Dependency Injection in WPF on .NET Core 6 - c#

I'm trying to implement dependency injection and EF 6 in a WPF on .NET Core 6 project. Part of my code on App.xaml.cs is:
public partial class App : MvxApplication
{
public static IHost? AppHost { get; private set; }
public App()
{
AppHost = Host
.CreateDefaultBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddSingleton<MainWindow>();
services.AddSingleton<SuperheroContext>();
services.AddSingleton<IUnitOfWork, UnitOfWork>();
services.AddSingleton<IMethodsBusinessLogic, MethodsBusinessLogic>();
IConfiguration configuration;
configuration = new ConfigurationBuilder()
.AddJsonFile(#"appsettings.json")
.Build();
services.AddDbContext<SuperheroContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("Default")));
})
.Build();
}
protected override async void OnStartup(StartupEventArgs e)
{
await AppHost!.StartAsync();
var startupForm = AppHost.Services.GetRequiredService<MainWindow>();
startupForm.Show();
base.OnStartup(e);
}
protected override async void OnExit(ExitEventArgs e)
{
await AppHost!.StopAsync();
base.OnExit(e);
}
protected override void RegisterSetup()
{
this.RegisterSetupType<MvxWpfSetup<_App.App>>();
}
}
I have a view model for navigation purposes and my goal is the CRUD operation.
So I have a CreateViewModel:
public class CreateHeroViewModel : MvxViewModel
{
private readonly IMvxNavigationService navigator;
public CreateHeroViewModel(IMvxNavigationService navigator)
{
this.navigator = navigator;
BackToNavigationManagerCommand = new
MvxCommand(BackToNavigationManager);
CreateTheNewHeroCommand = new MvxCommand(CreateTheNewHero);
}
public ICommand BackToNavigationManagerCommand { get; set; }
public void BackToNavigationManager()
{
navigator.Navigate<NavigationManagerViewModel>();
}
public ICommand CreateTheNewHeroCommand { get; set; }
public async void CreateTheNewHero()
{
//await methodsBusinessLogic.CreateHero(SuperheroModel);
}
private SuperheroModel _superheroModel = new SuperheroModel();
public SuperheroModel SuperheroModel
{
get { return _superheroModel; }
set
{
SetProperty(ref _superheroModel, value);
RaiseAllPropertiesChanged();
}
}
private string _heroName;
private string _heroImage;
private string _firstName;
private string _lastName;
private string _location;
private string _rank;
private string _numberOfFriends;
public string HeroName
{
get { return _heroName; }
set
{
SetProperty(ref _heroName, value);
RaisePropertyChanged(SuperheroModel.HeroName);
}
}
public string HeroImage
{
get { return _heroImage; }
set
{
SetProperty(ref _heroImage, value);
RaisePropertyChanged(SuperheroModel.HeroImage);
}
}
public string FirstName
{
get { return _firstName; }
set
{
SetProperty(ref _firstName, value);
RaisePropertyChanged(SuperheroModel.FirstName);
}
}
public string LastName
{
get { return _lastName; }
set
{
SetProperty(ref _lastName, value);
RaisePropertyChanged(SuperheroModel.LastName);
}
}
public string Location
{
get { return _location; }
set
{
SetProperty(ref _location, value);
RaisePropertyChanged(SuperheroModel.Location);
}
}
public string Rank
{
get { return _rank; }
set
{
SetProperty(ref _rank, value);
RaisePropertyChanged(SuperheroModel.Rank);
}
}
public string NumberOfFriends
{
get { return _numberOfFriends; }
set
{
SetProperty(ref _numberOfFriends, value);
RaisePropertyChanged(SuperheroModel.NumberOfFriends);
}
}
}
The problem arises when I'm trying to inject to the constructor one of my configured services, for example the SuperheroContext.
I've searched to many places but couldn't find out why it's not working.
Any help is welcome!

Related

Using ServerManager to list virtual directories separated by type

I'm using ServerManager (Microsoft.Web.Administration.dll) to create an Application to manage my web servers, All of my server are running IIS 7 and above. Majority of the site is complete, i can manage servers, sites, FTP, SSL etc.
Here is my issue,
I am able to create virtual directories and applications, but having an issue with listing them separately when viewing the site information as you can do in IIS. I am able to list the all together as Virtual Directories by just getting item.VirtualDirectories[0].PhysicalPath but would like to show Applications in one column and basic virtual directories in the second column. I'm sure i need to be looking for if root application path is siteid, or if it has an AppPool somehow but having a hard time figuring how. Any help would be appreciated.
My Code:
SiteVirtualDirectory.cs
private string anonymousUsername;
private string anonymousUserPassword;
private string contentPath;
private bool enableWritePermissions;
private bool enableParentPaths;
private bool enableDirectoryBrowsing;
private bool enableAnonymousAccess;
private bool enableWindowsAuthentication;
private bool enableBasicAuthentication;
private bool enableDynamicCompression;
private bool enableStaticCompression;
private string defaultDocs;
private string httpRedirect;
private HttpError[] httpErrors;
private HttpErrorsMode errorMode;
private HttpErrorsExistingResponse existingResponse;
private MimeMap[] mimeMaps;
private HttpHeader[] httpHeaders;
private bool aspInstalled;
private string aspNetInstalled;
private string phpInstalled;
private bool perlInstalled;
private bool pythonInstalled;
private bool coldfusionInstalled;
private bool cgiBinInstalled;
private string applicationPool;
private bool dedicatedApplicationPool;
private string parentSiteName;
private bool redirectExactUrl;
private bool redirectDirectoryBelow;
private bool redirectPermanent;
private bool sharePointInstalled;
private bool iis7;
private string consoleUrl;
private string php5VersionsInstalled;
public string AnonymousUsername
{
get { return anonymousUsername; }
set { anonymousUsername = value; }
}
public string AnonymousUserPassword
{
get { return anonymousUserPassword; }
set { anonymousUserPassword = value; }
}
public string ContentPath
{
get { return contentPath; }
set { contentPath = value; }
}
public string HttpRedirect
{
get { return httpRedirect; }
set { httpRedirect = value; }
}
public string DefaultDocs
{
get { return defaultDocs; }
set { defaultDocs = value; }
}
public MimeMap[] MimeMaps
{
get { return mimeMaps; }
set { mimeMaps = value; }
}
public HttpError[] HttpErrors
{
get { return httpErrors; }
set { httpErrors = value; }
}
public HttpErrorsMode ErrorMode
{
get { return errorMode; }
set { errorMode = value; }
}
public HttpErrorsExistingResponse ExistingResponse
{
get { return existingResponse; }
set { existingResponse = value; }
}
public string ApplicationPool
{
get { return this.applicationPool; }
set { this.applicationPool = value; }
}
public bool EnableParentPaths
{
get { return this.enableParentPaths; }
set { this.enableParentPaths = value; }
}
public HttpHeader[] HttpHeaders
{
get { return this.httpHeaders; }
set { this.httpHeaders = value; }
}
public bool EnableWritePermissions
{
get { return this.enableWritePermissions; }
set { this.enableWritePermissions = value; }
}
public bool EnableDirectoryBrowsing
{
get { return this.enableDirectoryBrowsing; }
set { this.enableDirectoryBrowsing = value; }
}
public bool EnableAnonymousAccess
{
get { return this.enableAnonymousAccess; }
set { this.enableAnonymousAccess = value; }
}
public bool EnableWindowsAuthentication
{
get { return this.enableWindowsAuthentication; }
set { this.enableWindowsAuthentication = value; }
}
public bool EnableBasicAuthentication
{
get { return this.enableBasicAuthentication; }
set { this.enableBasicAuthentication = value; }
}
public bool EnableDynamicCompression
{
get { return this.enableDynamicCompression; }
set { this.enableDynamicCompression = value; }
}
public bool EnableStaticCompression
{
get { return this.enableStaticCompression; }
set { this.enableStaticCompression = value; }
}
public bool AspInstalled
{
get { return this.aspInstalled; }
set { this.aspInstalled = value; }
}
public string AspNetInstalled
{
get { return this.aspNetInstalled; }
set { this.aspNetInstalled = value; }
}
public string PhpInstalled
{
get { return this.phpInstalled; }
set { this.phpInstalled = value; }
}
public bool PerlInstalled
{
get { return this.perlInstalled; }
set { this.perlInstalled = value; }
}
public bool PythonInstalled
{
get { return this.pythonInstalled; }
set { this.pythonInstalled = value; }
}
public bool ColdFusionInstalled
{
get { return this.coldfusionInstalled; }
set { this.coldfusionInstalled = value; }
}
public bool DedicatedApplicationPool
{
get { return this.dedicatedApplicationPool; }
set { this.dedicatedApplicationPool = value; }
}
public string ParentSiteName
{
get { return this.parentSiteName; }
set { this.parentSiteName = value; }
}
public bool RedirectExactUrl
{
get { return this.redirectExactUrl; }
set { this.redirectExactUrl = value; }
}
public bool RedirectDirectoryBelow
{
get { return this.redirectDirectoryBelow; }
set { this.redirectDirectoryBelow = value; }
}
public bool RedirectPermanent
{
get { return this.redirectPermanent; }
set { this.redirectPermanent = value; }
}
public bool CgiBinInstalled
{
get { return this.cgiBinInstalled; }
set { this.cgiBinInstalled = value; }
}
public bool SharePointInstalled
{
get { return this.sharePointInstalled; }
set { this.sharePointInstalled = value; }
}
public bool IIs7
{
get { return this.iis7; }
set { this.iis7 = value; }
}
public string ConsoleUrl
{
get { return consoleUrl; }
set { consoleUrl = value; }
}
public string Php5VersionsInstalled
{
get { return php5VersionsInstalled; }
set { php5VersionsInstalled = value; }
}
[XmlIgnore]
public string VirtualPath
{
get
{
// virtual path is rooted
if (String.IsNullOrEmpty(ParentSiteName))
return "/"; //
else if (!Name.StartsWith("/"))
return "/" + Name;
//
return Name;
}
}
[XmlIgnore]
public string FullQualifiedPath
{
get
{
if (String.IsNullOrEmpty(ParentSiteName))
return Name;
else if (Name.StartsWith("/"))
return ParentSiteName + Name;
else
return ParentSiteName + "/" + Name;
}
}
Get Virtual Directories:
public class GetVirtualDirectories(ServerManager iismanager, string siteId)
{
if (!SiteExists(iismanager, siteId))
return new SiteVirtualDirectory[] { };
var vdirs = new List<SiteVirtualDirectory>();
var iisObject = iismanager.Sites[siteId];
//
foreach (var item in iisObject.Applications)
{
// do not list root Virtual Directory
if (item.Path == "/")
continue;
//
vdirs.Add(new SiteVirtualDirectory
{
Name = ConfigurationUtility.GetNonQualifiedVirtualPath(item.Path),
ContentPath = item.VirtualDirectories[0].PhysicalPath
});
}
//
return vdirs.ToArray();
}

Tuple cannot be serialized because it does not have a parameterless constructor

I am trying to serialize an instance of the QDatatables class provided below, but I am getting error :
An exception of type 'System.InvalidOperationException' occurred in System.Xml.dll but was not handled in user code
Additional information: There was an error reflecting type 'System.Collections.ObjectModel.ObservableCollection`1[DataRetrieval.Model.QDatatable]'.
StackTrace: at System.Xml.Serialization.XmlReflectionImporter.InitializeStructMembers(StructMapping mapping, StructModel model, Boolean openModel, String typeName, RecursionLimiter limiter)
at System.Xml.Serialization.XmlReflectionImporter.ImportStructLikeMapping(StructModel model, String ns, Boolean openModel, XmlAttributes a, RecursionLimiter limiter)
at System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(TypeModel model, String ns, ImportContext context, String dataType, XmlAttributes a, Boolean repeats, Boolean openModel, RecursionLimiter limiter)
InnerException: {"System.Tuple`2[System.String,System.String] cannot be serialized because it does not have a parameterless constructor."}
Can anyone help to find what is missing?
My serlializing function:
public string serialize()
{
StringWriter sw = new StringWriter();
XmlSerializer s = new XmlSerializer(this.GetType());
s.Serialize(sw, this);
return sw.ToString();
}
QDatatables class:
[Serializable()]
public class QDatatables : BindableBase
{
private ObservableCollection<QDatatable> _list;
public ObservableCollection<QDatatable> List
{
get { return _list ?? (_list=new ObservableCollection<QDatatable>()); }
set { SetProperty(ref _list, value); }
}
public string serialize()
{
StringWriter sw = new StringWriter();
XmlSerializer s = new XmlSerializer(typeof(ObservableCollection<QDatatable>));
s.Serialize(sw, List);
return sw.ToString();
}
}
QDatatable Class
[Serializable()]
public class QDatatable : BindableBase
{
private int _id;
public int ID
{
get { return _id; }
set { SetProperty(ref _id, value); }
}
private String _name;
public String Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
private WhereParams _params;
public WhereParams Params
{
get { return _params; }
set { SetProperty(ref _params, value); }
}
private bool _isexpanded;
public bool IsExpanded
{
get { return _isexpanded; }
set { SetProperty(ref _isexpanded, value); }
}
}
WhereParam Class:
public class WhereParams : BindableBase
{
private Dictionary<int, WhereParam> _dictionaryIdToWhereParam;
private ObservableCollection<WhereParam> _list;
public ObservableCollection<WhereParam> List
{
get { return _list ?? (_list = new ObservableCollection<WhereParam>()); }
set { SetProperty(ref _list, value); }
}
public WhereParam GetById(int id)
{
return List.First(w => w.ID == id);
}
public string serialize()
{
StringWriter sw = new StringWriter();
XmlSerializer s = new XmlSerializer(this.GetType());
s.Serialize(sw, this);
return sw.ToString();
}
}
[Serializable()]
public class WhereParam:BindableBase
{
private int _id;
public int ID
{
get { return _id; }
set { SetProperty(ref _id, value); }
}
private string _name;
public string Name
{
get { return _name; }
set { SetProperty(ref _name, value); }
}
private ParamType _type;
public ParamType Type
{
get { return _type; }
set { SetProperty(ref _type, value); }
}
}
ParamType Class:
[XmlInclude(typeof(DateTimeType))]
[XmlInclude(typeof(StringType))]
[XmlInclude(typeof(IntType))]
[XmlInclude(typeof(FloatgType))]
[XmlInclude(typeof(BoolType))]
[XmlInclude(typeof(NullableBoolType))]
[XmlInclude(typeof(ListMulti))]
[XmlInclude(typeof(ListSingle))]
[XmlInclude(typeof(StringMulti))]
public class ParamType: BindableBase
{
private int _typeID;
public int TypeID
{
get { return _typeID; }
set { SetProperty(ref _typeID, value); }
}
private ParamTypeEnum _typeName;
public ParamTypeEnum TypeName
{
get { return _typeName; }
set { SetProperty(ref _typeName, value); }
}
}
public class DateTimeType : ParamType
{
private DateTime? _datefrom;
public DateTime? Datefrom
{
get { return _datefrom; }
set { SetProperty(ref _datefrom, value); }
}
private DateTime? _dateTo;
public DateTime? DateTo
{
get { return _dateTo; }
set {
SetProperty(ref _dateTo, value); }
}
}
public class StringType : ParamType
{
private string _stringContent;
public string StringContent
{
get { return _stringContent; }
set {
SetProperty(ref _stringContent, value); }
}
}
public class IntType : ParamType
{
private int _intContent;
public int IntContent
{
get { return _intContent; }
set { SetProperty(ref _intContent, value); }
}
}
public class FloatgType : ParamType
{
private float _floatContent;
public float FloatContent
{
get { return _floatContent; }
set { SetProperty(ref _floatContent, value); }
}
}
public class BoolType : ParamType
{
private bool _boolTypeValue;
public bool BoolTypeValue
{
get { return _boolTypeValue; }
set { SetProperty(ref _boolTypeValue, value); }
}
}
public class NullableBoolType : ParamType
{
private bool? _nullableBoolTypeValue;
public bool? NullableBoolTypeValue
{
get { return _nullableBoolTypeValue; }
set { SetProperty(ref _nullableBoolTypeValue, value); }
}
}
public class ListMulti : ParamType
{
private ObservableCollection<Tuple<string, string>> _listMultiItems;
public ObservableCollection<Tuple<string, string>> ListMultiItems
{
get { return _listMultiItems; }
set { SetProperty(ref _listMultiItems, value); }
}
private ObservableCollection<Tuple<string, string>> _selectedListMulti;
public ObservableCollection<Tuple<string, string>> SelectedItemsListMulti
{
get { return _selectedListMulti ?? (_selectedListMulti = new ObservableCollection<Tuple<string,string>>()); }
set {
SetProperty(ref _selectedListMulti, value); }
}
}
public class ListSingle : ParamType
{
private ObservableCollection<Tuple<string, string>> _listSingleItems;
public ObservableCollection<Tuple<string, string>> ListSingleItems
{
get { return _listSingleItems; }
set { SetProperty(ref _listSingleItems, value); }
}
//private ObservableCollection<Tuple<string, string>> _listSingleItems;
//public ObservableCollection<Tuple<string, string>> ListSingleItems
//{
// get { return _listSingleItems; }
// set { SetProperty(ref _listSingleItems, value); }
//}
}
public class StringMulti : ParamType
{
private string _listMultiCollection;
public string ListMultiCollection
{
get { return _listMultiCollection; }
set { SetProperty(ref _listMultiCollection, value); }
}
}
public enum ParamTypeEnum
{
boolType,
nullableboolType,
intType,
floatType,
stringType,
datetimeType,
listmultiType,
stringlistmultiType,
};
The problem is that the class Tuple<T1, T2>, used by your class ListMulti among others, does not have a default constructor, as tuples can only be publicly created via Tuple.Create(). XmlSerializer, however, requires classes to have parameterless default constructors and will throw an exception if it encounters a type without a default constructor. This is the exception you are seeing.
One workaround is to add proxy properties to your class that repackage and return its data in a form that can be serialized. Then, mark the "real" properties with XmlIgnore. For the collections of string tuples held by ListMulti, a string [][] proxy property would make sense:
public class ListMulti : ParamType
{
[XmlArray("ListMultiItems")]
[XmlArrayItem("Pair")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string[][] SerializableListMultiItems
{
get
{
return ListMultiItems.ToPairArray();
}
set
{
ListMultiItems.SetFromPairArray(value);
}
}
[XmlArray("SelectedItemsListMulti")]
[XmlArrayItem("Pair")]
[Browsable(false), EditorBrowsable(EditorBrowsableState.Never), DebuggerBrowsable(DebuggerBrowsableState.Never)]
public string[][] SerializableSelectedItemsListMulti
{
get
{
return SelectedItemsListMulti.ToPairArray();
}
set
{
SelectedItemsListMulti.SetFromPairArray(value);
}
}
private ObservableCollection<Tuple<string, string>> _listMultiItems = new ObservableCollection<Tuple<string, string>>();
[XmlIgnore]
public ObservableCollection<Tuple<string, string>> ListMultiItems
{
get { return _listMultiItems; }
set { SetProperty(ref _listMultiItems, value); }
}
private ObservableCollection<Tuple<string, string>> _selectedListMulti;
[XmlIgnore]
public ObservableCollection<Tuple<string, string>> SelectedItemsListMulti
{
get { return _selectedListMulti ?? (_selectedListMulti = new ObservableCollection<Tuple<string, string>>()); }
set
{
SetProperty(ref _selectedListMulti, value);
}
}
}
Using the extension methods:
public static class TupleExtensions
{
public static T[][] ToPairArray<T>(this IEnumerable<Tuple<T, T>> collection)
{
return collection == null ? null : collection.Select(t => new[] { t.Item1, t.Item2 }).ToArray();
}
public static void SetFromPairArray<T>(this ICollection<Tuple<T, T>> collection, T[][] array)
{
if (collection == null)
throw new ArgumentNullException();
collection.Clear();
foreach (var pair in array)
{
if (pair.Length != 2)
throw new ArgumentException("Inner array did not have length 2");
collection.Add(Tuple.Create(pair[0], pair[1]));
}
}
}
You'll need to make a similar fix to ListSingle.

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 .

Creating connection string with dependency injection using MVVM Light

I'm writing login window using WPF, MVVM and dependency injection patterns. My problem is that I must create connection string using login and password which user writes in my login form and I don't know how to do it according to good practice. Object is created by SimpleIoc class and I pass part of connection string like database adress and port during initialization. When user write his login and password I need to pass this data to database manager to create full connection string. I don't want to pass login and password every time when some function is called to connect part of connection string with user and password. I can create function in interface like Initialize but in my point of view that it isn't good idea and I think there is better way to do it.
Here is sample how I do it:
public interface ILoginService
{
bool SomeAction(string parameter);
}
public class LoginService : ILoginService
{
private string _connectionString;
public LoginService(string connectionStringPart)
{
_connectionString = connectionStringPart;
}
public bool SomeAction(string parameter)
{
//Create connection, execute query etc.
return true;
}
}
public class MainViewModel : ViewModelBase
{
private ILoginService _loginService;
private string _login;
public string Login
{
get { return _login; }
set
{
_login = value;
RaisePropertyChanged("Login");
}
}
private string _password;
public string Password
{
get { return _password; }
set
{
_password = value;
RaisePropertyChanged("Password");
}
}
public MainViewModel(ILoginService loginService)
{
_loginService = loginService;
}
private RelayCommand _loginCommand;
public ICommand LoginCommand
{
get { return _loginCommand ?? (_loginCommand = new RelayCommand(ExecuteLogin)); }
}
private void ExecuteLogin()
{
//And here I must add login and password to _loginService but I don't want to do it by passing them to SomeAction method
_loginService.SomeAction("some parameter");
}
}
public class ViewModelLocator
{
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<ILoginService>(()=>{return new LoginService("Server=myServerAddress;Database=myDataBase;");});
SimpleIoc.Default.Register<MainViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
How About:
public interface ILoginService
{
bool SomeAction(string parameter);
string Password {set; }
string UserName {set; }
}
public class LoginService : ILoginService
{
private System.Data.SqlClient.SqlConnectionStringBuilder builder = new System.Data.SqlClient.SqlConnectionStringBuilder();
private string _connectionString
{
get
{ return builder.ConnectionString;}
}
public LoginService(string connectionStringPart)
{
_connectionString = connectionStringPart;
}
public string Password
{
set { builder["Password"] =value; }
}
public string UserName
{
set { builder["user"] =value; }
}
public bool SomeAction(string parameter)
{
//Create connection, execute query etc.
return true;
}
}
public class MainViewModel : ViewModelBase
{
private ILoginService _loginService;
private string _login;
public string Login
{
get { return _login; }
set
{
_login = value;
_loginService.UserName = value;
RaisePropertyChanged("Login");
}
}
private string _password;
public string Password
{
get { return _password; }
set
{
_password = value;
_loginService.Password= value;
RaisePropertyChanged("Password");
}
}
public MainViewModel(ILoginService loginService)
{
_loginService = loginService;
}
private RelayCommand _loginCommand;
public ICommand LoginCommand
{
get { return _loginCommand ?? (_loginCommand = new RelayCommand(ExecuteLogin)); }
}
private void ExecuteLogin()
{
_loginService.SomeAction("some parameter");
}

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