i am building a dictionary WPF application where you write a word and than the application tells u in what language the word is and also gives you a description of the word. Using MVVM.
Here is how it looks:
I have problem with finding out how to get the language and the description of word from a text file and put them in the text box, i dont mean the binding, but the exact method of getting the info.
Here is my Model:
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
namespace dictionary
{
public class dictionaryModel
{
private string word;
private string language;
private string description;
public string Word
{
get
{
return word;
}
set
{
word = value;
}
}
public string Language
{
get
{
return language;
}
set
{
language = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public dictionaryModel(string describedWord, string WordLanguage, string WordDescription)
{
this.word = describedWord;
this.language = WordLanguage;
this.description = WordDescription;
}
public dictionaryModel()
{ }
}
and here is my View Model, so far:
namespace dictionary
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Markup;
public class dictionaryViewModel : INotifyPropertyChanged
{
private ICommand _getAnswer;
private dictionaryModel m;
private string w;
private string retLanguage;
private string retDescription;
private bool _canExecute;
public dictionaryViewModel()
{
_canExecute = true;
}
public string retLang
{
get
{
return retLanguage;
}
set
{
retLanguage = value;
NotifyPropertyChanged();
}
}
public string retDescr
{
get
{
return retDescription;
}
set
{
retDescription = value;
NotifyPropertyChanged();
}
}
public string word
{
get
{
return w;
}
set
{
w = value;
NotifyPropertyChanged();
}
}
public dictionaryModel model
{
get
{
return m;
}
set
{
m = value;
NotifyPropertyChanged();
}
}
public ICommand getAnswer
{
get
{
return _getAnswer ?? (_getAnswer = new RelayCommand(() => getWholeAnswer(word), _canExecute));
}
}
public dictionaryViewModel(dictionaryModel model, string word, string retLang, string retDescr,
ICommand getAnswer)
{
m = model;
w = word;
retLang = retLanguage;
retDescr = retDescription;
_getAnswer = getAnswer;
}
public ObservableCollection<dictionaryModel> readTxtFile()
{
ObservableCollection<dictionaryModel> dictObj = new ObservableCollection<dictionaryModel>();
string word;
string language;
string description;
var file = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), "dictionary.txt");
StreamReader read = new StreamReader(file);
string line;
string[] item;
while((line=read.ReadLine())!=null)
{
item = line.Split(';');
word = item[0];
language = item[1];
description = item[2];
dictionaryModel object1 = new dictionaryModel(word, language, description);
dictObj.Add(object1);
}
read.Close();
return dictObj;
}
public void getWholeAnswer(string w)
{
string descr, lang;
dictionaryModel obj = null;
ObservableCollection<dictionaryModel> rdF = readTxtFile();
try
{
foreach(dictionaryModel a in rdF)
{
if(w.Equals(a))
{
descr = retDescr;
lang = retLang;
obj = a;
}
obj.Language = retLang;
obj.Description = retDescription;
}
}catch(Exception e)
{
ExceptionInfo();
}
}
private void ExceptionInfo()
{
throw new NotImplementedException();
}
private void NotifyPropertyChanged()
{
throw new NotImplementedException();
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
The method is getWholeAnswer(). You see what i have tried, but no success. If you have any ideas, please help me out...
I think the problem is here:
if(w.Equals(a))
w is a string, while a is dictionaryModel, you are comparing two different kind of types without defining an equality logic.
Maybe you would replace that line with this?
if(string.Compare(w.Trim(), a.word, true) == 0)
string.Compare reference on MSDN
string.Trim reference on MSDN
i found my mistake, i am posting the solution of the method, it could be helpful to someone:
public void getWholeAnswer(string w)
{
dictionaryModel obj = null;
ObservableCollection<dictionaryModel> rdF = readTxtFile();
bool find = false;
try
{
foreach(dictionaryModel a in rdF)
{
if(w.Equals(a.Word))
{
obj = a;
retLang = a.Language;
retDescr = a.Description;
find = true;
break;
}
}
if(false == find)
{
AskTheQuestion();
}
}catch(Exception e)
{
AskTheQuestion();
}
}
Related
In the last month of so I have been trying to learn some C# with the aim of writing some PowerShell modules. I looked at some articles and documentation (Creating a client with C# - Microsoft.Management.Infrastructure) to try and put together a simple CIM cmdlet that would return the local network adapters.
The class library compiles okay, but when I run the command in PowerShell, it shows a format exception.
Show-LocalAdapter : Input string was not in a correct format.
In function based problems, I would normally see an issue with a line in the error reporting, but the error does not point me in the right direction with a cmdlet.
Hopefully someone here can help me as I have exhausted my, admittedly limited, knowledge on debugging this problem.
Here is the code for the cmdlet.
using System.Collections;
using System.Linq;
using System.Management.Automation;
using System.Text.RegularExpressions;
using Microsoft.Management.Infrastructure;
namespace NetTest
{
[Cmdlet(VerbsCommon.Show, "LocalAdapter")]
[OutputType(typeof(NetworkAdapter))]
public class ShowLocalAdapterCmdlet : PSCmdlet
{
private string[] _manufacturer;
private string _name;
private bool? _physicalAdapter;
private int _maxEntries = 100;
[Parameter(Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true)]
[Alias("Vendor")]
public string[] Manufacturer
{
get { return this._manufacturer; }
set { _manufacturer = value; }
}
[Parameter(Position = 1, ValueFromPipelineByPropertyName = true)]
public string Name
{
get { return this._name; }
set { _name = value; }
}
[Parameter(Position = 2, ValueFromPipelineByPropertyName = true)]
public bool? PhysicalAdapter
{
get { return this._physicalAdapter; }
set { _physicalAdapter = value; }
}
[Parameter(Position = 3)]
public int MaxEntries
{
get { return this._maxEntries; }
set { _maxEntries = value; }
}
protected override void BeginProcessing()
{
base.BeginProcessing();
}
protected override void ProcessRecord()
{
CimSession session = CimSession.Create("localHost");
IEnumerable cimResults = session.QueryInstances(#"root\cimv2", "WQL", "SELECT * FROM Win32_NetworkAdapter");
var query = cimResults.Cast<CimInstance>().Select(ReturnNetworkAdapter);
// Filter Name
if (Name != null)
{
query = query.Where(adapter => adapter.Name != null && adapter.Name.StartsWith(Name));
}
// Manufacturer Filter
if (Manufacturer != null)
{
query = query.Where(
adapter =>
adapter.Manufacturer != null &&
Regex.IsMatch(adapter.Manufacturer.ToString(),
string.Format("^(?:{0})", string.Join("|", Manufacturer))));
}
// Physical Adapter: true or false
if (PhysicalAdapter != null)
{
query = query.Where(adapter =>
adapter.PhysicalAdapter == PhysicalAdapter);
}
// Return objects
query.Take(MaxEntries).ToList().ForEach(WriteObject);
}
private static NetworkAdapter ReturnNetworkAdapter(CimInstance item)
{
return new NetworkAdapter
{
Name = item.CimInstanceProperties["Name"].ToString(),
Description = item.CimInstanceProperties["Description"].ToString(),
DeviceId = int.Parse(item.CimInstanceProperties["DeviceId"].ToString()),
Manufacturer = item.CimInstanceProperties["Manufacturer"].ToString(),
NetConnectionId = item.CimInstanceProperties["NetConnectionId"].ToString(),
PhysicalAdapter = bool.Parse(item.CimInstanceProperties["PhysicalAdapter"].ToString())
};
}
}
}
Here is the class for the network adapter object.
namespace NetTest
{
public class NetworkAdapter
{
private string _name;
private string _description;
private int _deviceId;
private string _manufacturer;
private string _netConnectionId;
private bool _physicalAdapter;
public string Name
{
get { return _name; }
set { _name = value; }
}
public string Description
{
get { return _description; }
set { _description = value; }
}
public int DeviceId
{
get { return _deviceId; }
set { _deviceId = value; }
}
public string Manufacturer
{
get { return _manufacturer; }
set { _manufacturer = value; }
}
public string NetConnectionId
{
get { return _netConnectionId; }
set { _netConnectionId = value; }
}
public bool PhysicalAdapter
{
get { return _physicalAdapter; }
set { _physicalAdapter = value; }
}
}
}
Calls like this item.CimInstanceProperties["Name"].ToString() is not what are you expecting. You should look at property Value:
private static NetworkAdapter ReturnNetworkAdapter(CimInstance item)
{
return new NetworkAdapter
{
Name = item.CimInstanceProperties["Name"].Value.ToString(),
Description = item.CimInstanceProperties["Description"].Value?.ToString(),
DeviceId = int.Parse(item.CimInstanceProperties["DeviceId"].Value.ToString()),
Manufacturer = item.CimInstanceProperties["Manufacturer"].Value?.ToString(),
NetConnectionId = item.CimInstanceProperties["NetConnectionId"].Value?.ToString(),
PhysicalAdapter = bool.Parse(item.CimInstanceProperties["PhysicalAdapter"].Value.ToString())
};
}
I'm trying to read a object from a XML doc with C# using the System.XML.
I created that doc with the same application, but when I try to read, I get "System.InvalidOperationException" in System.Xml.dll.
<?xml version="1.0"?>
<PKW xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Fahrzeug>
<Name>Testname</Name>
<Color>Rot</Color>
<Turen>5</Turen>
<Speed>80</Speed>
</Fahrzeug>
<Sitze>3</Sitze>
</PKW>
I try to read this XML with the following code...
System.Xml.Serialization.XmlSerializer reader = new System.Xml.Serialization.XmlSerializer(typeof(Fahrzeug.PKW));
System.IO.StreamReader file = new System.IO.StreamReader(#"Car.xml");
Auto = (Fahrzeug.PKW) reader.Deserialize(file);
file.Close();
Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace XML_test
{
public class Fahrzeug
{
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
private string color;
public string Color
{
get { return color; }
set { color = value; }
}
private int türen;
public int Türen
{
get { return türen; }
set { türen = value; }
}
private double speed;
public double Speed
{
get { return speed; }
set { speed = value; }
}
public Fahrzeug(string name,string color,int türen,double speed)
{
this.color = color;
this.türen= türen;
this.speed = speed;
this.Name = name;
}
private void Output()
{
Console.WriteLine("Color:\t" + this.color);
Console.WriteLine("Türen:\t" + this.Türen);
Console.WriteLine("Speed:\t" + this.speed);
}
public class PKW
{
private Fahrzeug fahrzeug;
public Fahrzeug Fahrzeug
{
get { return fahrzeug; }
set { fahrzeug = value; }
}
public PKW()
{
}
private int sitze;
public int Sitze
{
get { return sitze; }
set { sitze = value; }
}
public PKW(Fahrzeug F, int sitze)
{
this.fahrzeug = F;
this.sitze = sitze;
}
public void Output()
{
Fahrzeug.Output();
Console.WriteLine("Color:\t" + this.sitze);
}
}
}
}
Think if you move the PKW class outside the Fahrzeug class (so it's not an inner class any more) it might work. My guess is that it's not resolving PKW in the xml correctly.
This is my code so far:
using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;
using System.Xml;
namespace Opgaver
{
class OpgaveController
{
static ArrayList _arrAktiveOpgaver = new ArrayList();
public ArrayList arrAktiveOpgaver
{
get { return _arrAktiveOpgaver; }
set { _arrAktiveOpgaver = value; }
}
static ArrayList _arrAfsluttedeOpgaver = new ArrayList();
public ArrayList arrAfsluttedeOpgaver
{
get { return _arrAfsluttedeOpgaver; }
set { _arrAfsluttedeOpgaver = value; }
}
static int _opgavenr = 100;
public int opgavenr
{
get { return _opgavenr; }
set { _opgavenr = value; }
}
public void opretOpgave(string opgavenavn, string opgavebeskrivelse, int opgaveprioritet, DateTime opgaveafsluttetdato)
{
DateTime oprettetdato = new DateTime();
oprettetdato = DateTime.Now;
bool opgaveafsluttet = false;
Opgave opgave = new Opgave(oprettetdato, _opgavenr, opgavenavn, opgavebeskrivelse, opgaveprioritet, opgaveafsluttet, opgaveafsluttetdato);
if (opgave.opgaveAfsluttet == false)
{
_arrAktiveOpgaver.Add(opgave);
}
else
{
_arrAfsluttedeOpgaver.Add(opgave);
}
_opgavenr++;
}
public OpgaveController()
{
}
}
public void test()
{
string outfile = #"C:\Folder\Tester.xml";
XmlSerializer xs;
Serialize<List<Opgave>>(arrAktiveOpgaver, outfile);
arrAktiveOpgaver = <List<Opgave>>(outfile);//deserialize data - Generates this error: Error 2 Using the generic type 'System.Collections.Generic.List<T>' requires 1 type arguments P:\Programmerings opgaver\Opgaver\Opgaver\OpgaveController.cs 107 33 Opgaver
}
private void Serialize<T1>(ArrayList arrAktiveOpgaver, string outfile)
{
throw new NotImplementedException();
}
public static T DeserializeFromXml<T>(string inputFile)
{
XmlSerializer s = new XmlSerializer(typeof(T));
T deserializedObject = default(T);
using (TextReader textReader = new StreamReader(inputFile))
{
deserializedObject = (T)s.Deserialize(textReader);
textReader.Close();
}
return deserializedObject;
}
public static void SerializeToXml<T>(T objToSerialize, string outputFile)
{
XmlSerializer s = new XmlSerializer(objToSerialize.GetType());
using (TextWriter textWriter = new StreamWriter(outputFile))
{
s.Serialize(textWriter, objToSerialize);
textWriter.Close();
}
}
}
}
i need to serialize the arraylist, and deserialize it..
and here is my opgave class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Opgaver
{
[Serializable()] public class Opgave : IComparable
{
DateTime _oprettetDato = new DateTime();
public DateTime oprettetDato
{
get { return _oprettetDato; }
set { _oprettetDato = value; }
}
int _opgavenr;
public int opgavenr
{
get { return _opgavenr; }
set { _opgavenr = value; }
}
string _opgaveNavn;
public string opgaveNavn
{
get { return _opgaveNavn; }
set { _opgaveNavn = value; }
}
string _opgaveBeskrivelse;
public string opgaveBeskrivelse
{
get { return _opgaveBeskrivelse; }
set { _opgaveBeskrivelse = value; }
}
int _opgavePrioritet;
public int opgavePrioritet
{
get { return _opgavePrioritet; }
set { _opgavePrioritet = value; }
}
bool _opgaveAfsluttet = false;
public bool opgaveAfsluttet
{
get { return _opgaveAfsluttet; }
set { _opgaveAfsluttet = value; }
}
DateTime _opgaveAfsluttetDato = new DateTime();
public DateTime opgaveAfsluttetDato
{
get { return _opgaveAfsluttetDato; }
set { _opgaveAfsluttetDato = value; }
}
public Opgave()
{
}
public Opgave(DateTime oprettetdato, int opgavenr, string opgavenavn, string opgavebeskrivelse, int opgaveprioritet, bool opgaveafsluttet, DateTime opgaveafsluttetdato)
{
_oprettetDato = oprettetdato;
_opgavenr = opgavenr;
_opgaveNavn = opgavenavn;
_opgaveBeskrivelse = opgavebeskrivelse;
_opgavePrioritet = opgaveprioritet;
_opgaveAfsluttet = opgaveafsluttet;
_opgaveAfsluttetDato = opgaveafsluttetdato;
}
//Sorterings metode
public int CompareTo(object obj)
{
Opgave Compare = (Opgave)obj;
int result = this.opgavenr.CompareTo(Compare.opgavenr);
if (result == 0)
result = this.opgavenr.CompareTo(Compare.opgavenr);
return result;
}
}
}
Use this static methods whenver you want to serialize or deserialize data:
example:
public void test()
{
string outfile = #"C:\Folder\Tester.xml";
SerializeToXml<List<Opgaver>>(arrAktiveOpgaver, outfile);//serialize data
arrAktiveOpgaver = DeserializeFromXml<List<Opgaver>>(outfile);//deserialize data
}
public static T DeserializeFromXml<T>(string inputFile)
{
XmlSerializer s = new XmlSerializer(typeof(T));
T deserializedObject = default(T);
using (TextReader textReader = new StreamReader(inputFile))
{
deserializedObject = (T)s.Deserialize(textReader);
textReader.Close();
}
return deserializedObject;
}
public static void SerializeToXml<T>(T objToSerialize, string outputFile)
{
XmlSerializer s = new XmlSerializer(objToSerialize.GetType());
using (TextWriter textWriter = new StreamWriter(outputFile))
{
s.Serialize(textWriter, objToSerialize);
textWriter.Close();
}
}
Serialize array of Opgave instead of serializing them in loop.
XmlSerializer xs = new XmlSerializer(arrAktiveOpgaver.GetType());
xs.Serialize(sw, arrAktiveOpgaver);
And then deserialize as array of Opgave.
Goal:
Display Encapsulate field from Player
Problem:
Want to display datamember_id, _name and _bust in class mainform only by using bindingList
Was it suppose to use syntax [] above the encapsulate field?
Class MainForm
dataGridViewPlayers.AutoGenerateColumns=true;
dataGridViewPlayers.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.Fill;
bindingSourcePlayers.Clear();
bindingSourcePlayers.DataSource = _myGameManager.Players;
Class GameManager:
public BindingList<Player> Players
{
get
{
for (int i = 0; i < _myPlayerGUI_list.Count; i++)
{
_player.Add(new Player(_myPlayerGUI_list[i].Player));
}
return _player;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CardGameClassLibrary;
namespace CardGameLib
{
public class Player
{
private int _id;
private string _name;
private Hand _myHand;
private int _win;
private int _lost;
private bool _madeMove = false;
private bool _bust = false;
public int Id
{
get { return _id; }
set { _id = value; }
}
public string Name
{
get { return _name; }
set { _name = value; }
}
public Hand MyHand
{
get { return _myHand; }
set { _myHand = value; }
}
public int Win
{
get { return _win; }
set { _win = value; }
}
public int Lost
{
get { return _lost; }
set { _lost = value; }
}
public bool MadeMove
{
get { return _madeMove; }
set { _madeMove = value; }
}
public bool Bust
{
get { return _bust; }
set { _bust = value; }
}
public Player(int pId)
{
_id = pId;
_myHand = new Hand();
}
public Player(Player pPlayer)
{
_id = pPlayer.Id;
//_name = pPlayer.Name;
_name = "adsf";
}
public Player()
{
}
}
}
You can use Browsable() attribute to prevent specific properties from being shown in the DataGridView when usin BindingList.
Example: if you want to hide MadeMove:
[Browsable(false)]
public bool MadeMove
{
get { return _madeMove; }
set { _madeMove = value; }
}
When I execute the code saveXML below it generates the error above, why??
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Serialization;
using System.IO;
/// <summary>
/// Summary description for Post
/// </summary>
public class Post
{
private int postIDCounter = 0;
private String DateCreated;
public Post()
{
Author = "unknown";
Title = "unkown";
Content = "";
DateCreated = DateTime.Now.ToString();
ID = postIDCounter++;
}
public int ID
{
get { return ID; }
set
{
if (ID != value)
ID = value;
}
}
public string Author
{
get { return Author; }
set
{
if (Author != value)
Author = value;
}
}
public string Title
{
get { return Title; }
set
{
if (Title != value)
Title = value;
}
}
public string Content
{
get { return Content; }
set
{
if (Content != value)
Content = value;
}
}
public void saveXML()
{
XmlSerializer serializer = new XmlSerializer(typeof(Post));
Stream writer = new FileStream("..'\'App_Data'\'posts'\'" + new Guid(ID.ToString()).ToString() + ".xml", FileMode.Create);
serializer.Serialize(writer, this);
writer.Close();
}
}
All your variables are circular reference, that loops for ever and eventually your system stops / crash.
public string Content
{
get { return Content; }
For example, you say here, that get, return the Content, but the return is again the get Content, and get Content, and you understand ? is loop for ever in this line... and in all lines that you have something like that.
Try to do this way.
string inside_Content;
public string Content
{
get { return inside_Content; }
set { inside_Content = value;}
}