Problem getting a string from a Combobox into a class variable [C#] - c#

The button function, should take whatever text is in the combo box and place it within sleeper.traintype
private void Btn_Apply_Click(object sender, RoutedEventArgs e)
{
try
{
sleeper.trainType = CmbBox_TrainType.Text;
if (CmbBox_TrainType.Text == "Sleeper")
{
// instantiate the sleeper train
sleeper.trainType = CmbBox_TrainType.Text;
}
}
My sleeper train class (inheriting from overall train class)
public class Sleeper : Train
{
private string _intermediate, _intermediate1, _intermediate2, _intermediate3;
private bool _cabin;
public string intermediate
{
get
{
return _intermediate;
}
set
{
_intermediate = value;
}
}
public string intermediate1
{
get
{
return _intermediate1;
}
set
{
_intermediate1 = value;
}
}
public string intermediate2
{
get
{
return _intermediate2;
}
set
{
_intermediate2 = value;
}
}
public string intermediate3
{
get
{
return _intermediate3;
}
set
{
_intermediate3 = value;
}
}
The train class:
public class Train
{
private string _trainID, _departureDay, _departureStation, _destinationStation, _departureTime, _trainType;
private bool _firstClass;
public string timePunctuation = ":";
public string dayPunctuation = "/";
public string trainID
{
get
{
return _trainID;
}
set
{
// check if the vlaue has letters & numbers and that the length is correct
if(value.Length == 4 && Regex.IsMatch(value, "[A-Z][0-9]"))
{
_trainID = value;
}
else
{
throw new FormatException("That train ID is not valid! (Example: AA11)");
}
}
}
public string departureDay
{
get
{
return _departureDay;
}
set
{
if(value.Length == 0)
{
throw new FormatException("You need to choose a departure day!");
} else
{
_departureDay = value;
}
}
}
public string departureTime
{
get
{
return _departureTime;
}
set
{
if(value.Length != 5 || value.Contains(timePunctuation) == false)
{
throw new FormatException("The time must be in this format: (11:11 or 03:22)");
} else
{
_departureTime = value;
}
}
}
public string departureStation
{
get
{
return _departureStation;
}
set
{
if(value.Length == 0)
{
throw new FormatException("You must enter a departure station!");
} else
{
_departureStation = value;
}
}
}
public string destinationStation
{
get
{
return _destinationStation;
}
set
{
if(value.Length == 0)
{
throw new FormatException("You must enter a destination!");
} else
{
_departureStation = value;
}
}
}
public string trainType
{
get
{
return _trainType;
}
set
{
value = _trainType;
}
}
}
I'm using a combobox with three options "Sleeper", "Stopping" and "Express". When using breakpoints next to sleeper.trainType = CmbBox_TrainType.Text; it creates my class but states that my sleeper.trainType variable is null. But it says that
CmbBox_TrainType = "Sleeper"
Instantiate sleeper at the start with Sleeper sleeper = new Sleeper();
but have also tried to put it in the if and just before sleeper.trainType = CmbBox_TrainType.Text;

Related

I want to update a property in my primaryviewmodel from the viewmodel that I use in my usercontrol

I am trying to update my treeview in primary viewmodel everytime I add an object to my database in my usercontrol viewmodel.
This is the code in my primary viewmodel
public class RechtbankenRechtersViewModel : Basis
{
IUnitOfWork uow = new UnitOfWork(new RechtContext());
private ObservableCollection<Rechtbank> _rechtbanken;
private IntroRechtbankenEnRechters intro = new IntroRechtbankenEnRechters();
private UserControl _control;
private ObservableCollection<TreeViewItem> _tree;
private TreeViewItem _treeItem;
public TreeViewItem TreeItem
{
get
{
return _treeItem;
}
set
{
_treeItem = value;
NotifyPropertyChanged();
}
}
public string Title { get; set; }
public UserControl Control
{
get
{
return _control;
}
set
{
_control = value;
NotifyPropertyChanged();
}
}
public ObservableCollection<TreeViewItem> Tree
{
get
{
return _tree;
}
set
{
_tree = value;
NotifyPropertyChanged();
}
}
public ObservableCollection<Rechtbank> Rechtbanken
{
get
{
return _rechtbanken;
}
set
{
_rechtbanken = value;
BouwBoom();
NotifyPropertyChanged();
}
}
public override string this[string columnName] => throw new NotImplementedException();
public RechtbankenRechtersViewModel()
{
Title = "Rechtbanken en rechters";
Tree = new ObservableCollection<TreeViewItem>();
TreeItem = new TreeViewItem();
Rechtbanken = new ObservableCollection<Rechtbank>(uow.RechtbankRepo.Ophalen(x => x.Rechters));
IntroRechtbankenEnRechters intro = new IntroRechtbankenEnRechters();
Control = intro;
}
//gaat de lijst van Tree opvullen met treeviewitems
public void BouwBoom()
{
foreach (var rechtbank in Rechtbanken)
{
TreeViewItem parent = new TreeViewItem() { Header = rechtbank.Naam, Tag = rechtbank.RechtbankID, Name="Rechtbank"};
foreach (var rechter in rechtbank.Rechters)
{
parent.Items.Add(new TreeViewItem() { Header = "Rechter - " + rechter.Voornaam + " " + rechter.Achternaam, Tag = rechter.RechterID, Name = "Rechter" });
}
Tree.Add(parent);
}
}
The Method BouwBoom is what fills my treeview since I struggled with it in the xaml(not much of a designer)
when opening the usercontrol i pass through the tag so that i can load the correct data into an object
my usercontrol viewmodel looks like this
public class OperatiesRechterViewModel : Basis
{
private RechtersRechtbanken context = (RechtersRechtbanken)Application.Current.Windows[1];
private Rechtbank _selectedRechtbank;
private ObservableCollection<Rechtbank> _rechtbanken;
private Rechter _rechter;
IUnitOfWork uow = new UnitOfWork(new RechtContext());
public override string this[string columnName] => throw new NotImplementedException();
public Rechter Rechter
{
get
{
return _rechter;
}
set
{
_rechter = value;
NotifyPropertyChanged();
}
}
public Rechtbank SelectedRechtbank
{
get
{
return _selectedRechtbank;
}
set
{
_selectedRechtbank = value;
NotifyPropertyChanged();
}
}
public ObservableCollection<Rechtbank> Rechtbanken
{
get
{
return _rechtbanken;
}
set
{
_rechtbanken = value;
}
}
public OperatiesRechterViewModel()
{
Rechter = new Rechter();
Rechtbanken = new ObservableCollection<Rechtbank>(uow.RechtbankRepo.Ophalen());
}
public OperatiesRechterViewModel(int id)
{
Rechter = uow.RechterRepo.ZoekOpPK(id);
Rechtbanken = new ObservableCollection<Rechtbank>(uow.RechtbankRepo.Ophalen());
SelectedRechtbank = uow.RechtbankRepo.Ophalen(x => x.RechtbankID == Rechter.RechtbankID).SingleOrDefault();
}
public override bool CanExecute(object parameter)
{
switch (parameter.ToString())
{
case "Toevoegen":
if (Rechter.RechterID <= 0)
{
return true;
}
return false;
case "Wijzigen":
if (Rechter.RechterID > 0)
{
return true;
}
return false;
case "Verwijderen":
if (Rechter.RechterID > 0)
{
return true;
}
return false;
}
return false;
}
public string FoutmeldingInstellen()
{
string melding = "";
if (SelectedRechtbank == null)
{
}
return melding;
}
public void Toevoegen()
{
if (SelectedRechtbank != null)
{
Rechter.RechtbankID = SelectedRechtbank.RechtbankID;
if (Rechter.Voornaam != "")
{
if (Rechter.Achternaam != "")
{
uow.RechterRepo.Toevoegen(Rechter);
int ok = uow.Save();
if (ok > 0)
{
MessageBox.Show("Rechter is toegevoegd!");
///refresh view in principe
context.DataContext = new RechtbankenRechtersViewModel();
}
}
else
{
//
}
}
else
{
//foutmelding maken
}
}
else
{
//foutmelding maken
}
}
public override void Execute(object parameter)
{
switch (parameter.ToString())
{
case "Toevoegen":
Toevoegen();
break;
}
}
}
}
As you can see here, I use the application.current.windows method to get the activated window and then I update it's datacontext when toevoegen(add) is pressed.
However I don't know if this is allowed in mvvm.
Can somebody help me?
Solved it!
for those who want to do the same thing just pass on the function to the constructor of the usercontrol viewmodel as an action then inside the uc viewmodel you can invoke it

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

LinQ Count based on element in child class

I have a JSON class which I used to deserialize my object to :-
public class Response
{
private Meta _meta;
private Result _result;
private Output _output;
public Meta meta
{
set
{
if (this._meta == null)
{
this._meta = new Meta();
}
this._meta = value;
}
get
{
return this._meta;
}
}
public Output output
{
set
{
if (this._output == null)
{
this._output = new Output();
}
this._output = value;
}
get
{
return this._output;
}
}
}
Which inherit
public class Output
{
...
public Verified verified{
get
{
return this._verified;
}
set
{
if (this._verified == null)
{
this._verified = new Verified();
}
this._verified = value;
}
}
in which has sub class of
public class Verified
{
...
public Address Address
{
set
{
if (this.address == null)
{
this.address = new Address();
}
this.address = value;
}
get
{
return this.address;
}
}
public Age Age
{
get
{
return this.age;
}
set
{
if (this.age == null)
{
this.age = new Age();
}
this.age = value;
}
}
public City City
{
get
{
return this.city;
}
set
{
if (this.city == null)
{
this.city = new City();
}
this.city = value;
}
}
...
All the attribute in City, Age, and Address are the same such as
public class Address
{
public int code { get; set; }
public string text { get; set; }
}
I have manage to count how many attribute in the Verified by using
TotalQuestion = response.output.verified.GetType().GetProperties()
.Where(p => !p.PropertyType.IsGenericType
&& !p.PropertyType.IsArray)
.Count();
, and that is only half of my concern. I have to also count now many of the attribute "code" in each of the class in Address, City, Age which has value as 3.
I did tried to add .GetType().GetProperty("code") at the back of the same LinQ I used to query the total amount of question inside, but I got lost in mind how to complete it.
I hope that anyone would be able to advice on possible LinQ solution (hopefully one-liner) type.
Thanks.
Simon
I think this is what you are looking for -
var result = resp.output.verified.GetType().GetProperties().Where(
child => {
var prop = child.GetValue(resp.output.verified, null);
return (int)prop.GetType().GetProperty("code").GetValue(prop, null) == 3;
}).ToList();

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