C# Exception not being handled - c#

Currently working on a small project, which includes a Registry form, where users can Sign up log in. I have error providers which tell the user if the information they have entered is incorrect or not. For some reason the exceptions are no longer being handled, even though they were a while back.
Here is the code for when the user presses the 'Register Button'
private void btnRegister_Click(object sender, EventArgs e)
{
//Try - Catch Statements
//Try to set the forename
try
{
player1.Forename = txtForename.Text;
player2.Forename = txtForename.Text;
errForename.Icon = Properties.Resources.Correct;
errForename.SetError(txtForename, "OK");
}
catch (NewException exc)
{
errForename.SetError(txtForename, exc.MessageM);
}
It then does this for other details, e.g surname, username.
Here is the User class getters and setters
public string Forename
{
get
{
return forename;
}
set
{
bool okChar = OnlyChars(value, "Forename");
if (okChar == true)
forename = value;
else
{
throw new NewException(errorMessage);
forename = null;
}
}
}
And finally here is the NewException class that I wrote
namespace Colludia
{
class NewException : Exception
{
private string messageM;
public NewException() : base()
{
}
public NewException(string message) : base(message)
{
messageM = message;
}
public string MessageM
{
get { return messageM; }
set { messageM = value; }
}
}
}

This is working code for you.
I think its issue of namespace
using System;
class Player
{
string forename = "";
string errorMessage = "";
public string Forename
{
get
{
return forename;
}
set
{
bool okChar = OnlyChars(value, "Forename");
if (okChar == true)
forename = value;
else
{
throw new NewException(errorMessage);
}
}
}
private bool OnlyChars(string value, string p)
{
if (value == p)
return true;
else
{
errorMessage = "Err";
return false;
}
}
}
class NewException : Exception
{
private string messageM;
public NewException()
: base()
{
}
public NewException(string message)
: base(message)
{
messageM = message;
}
public string MessageM
{
get { return messageM; }
set { messageM = value; }
}
}
class Program
{
static void Main(string[] args)
{
try
{
var player1 = new Player();
var player2 = new Player();
player1.Forename = "asdfg";
player2.Forename = "qwerty";
}
catch (NewException exc)
{
bool error = true;
}
}
}

Related

c# using other class method

Thanks to NHMountainGoat for an answer!
Implementing Interface looks a good choice so we have only the 'needed' method instanciated.
It looks like this now:
EDIT
class Machine
{
//REM: MachineConnexion is a link to the main server where asking the data
internal linkToPLC LinkToPLC;
public IlinkToPLC ILinkPLC;
public interface IlinkToPLC//Interface to linkPLC
{
Int16 MachineNumIS { get; set; }
}
internal class linkToPLC : IlinkToPLC
{
private Int16 Act_MachineNum;
private List<string> genlnkPLCCanvas;
private List<string> genlnkPLCworkingwith;
static private List<string> ListSymbolNoExist;
private string[] ListToPLClnk = {
"GlobalFolder.PMachine[{0}].",
"GlobalFolder.PMachine[{0}].STATE.",
"GlobalFolder.Machine[{0}].",
"GlobalFolder.Machine[{0}].STATE.",
};
public linkToPLC()//ctor
{
genlnkPLCCanvas = new List<string>(ListToPLClnk);
genlnkPLCworkingwith = new List<string>(ListToPLClnk);
ListSymbolNoExist = new List<string>();
Act_MachineNum = MachineNumIS;
}
public Int16 MachineNumIS { get { return (Int16)ReadWriteMachine("data"); } set { ReadWriteMachine("data", value); } }
public string ValueExist(string ValueToreach, bool WorkingDATA = false)
{
if (!WorkingDATA)
{
for (int inc = 0; inc < genlnkPLCworkingwith.Count; inc++)
{
string StrValueToReach = genlnkPLCworkingwith[inc] + ValueToreach;
if (MachineConnexion.SymbolExists(StrValueToReach))
{
ListSymbolNoExist.Clear();
return StrValueToReach;
}
else ListSymbolNoExist.Add(genlnkPLCworkingwith[inc] + ValueToreach);
}
}
else if (WorkingDATA)
{
string StrValueToReach = genlnkPLCworkingwith[10] + ValueToreach;
if (MachineConnexion.SymbolExists(StrValueToReach))
{
ListSymbolNoExist.Clear();
return StrValueToReach;
}
else ListSymbolNoExist.Add(genlnkPLCworkingwith[10] + ValueToreach);
}
if (ListSymbolNoExist.Count != 0)
{
string ErrorList = "";
for (int inc = 0; inc < ListSymbolNoExist.Count; inc++)
{
ErrorList = string.Concat(ErrorList + "Num: " + inc.ToString() + " " + ListSymbolNoExist[inc].ToString() + "\n");
}
Console.WriteLine("Error" + ErrorList);
}
return null;
}
public object ReadWriteMachine(string VariableName, object DataToWrite = null, bool WorkingDATA = false)
{
string valueToFind = "";
if (ValueExist(VariableName) != "FALSE")
{
if (DataToWrite != null) { MachineConnexion.WriteSymbol(valueToFind, DataToWrite); }
return MachineConnexion.ReadSymbol(valueToFind);
}
return VariableName;
}
}
public Machine() //constructor
{
LinkToPLC = new linkToPLC();
}
}
And It doesn't work telling me that the reference object is not defined to an instance of the object..... in the line : Machine() LinkToPLC = new linkToPLC();//REM I found the bug, it was me ;o)) 24112016
//REM 24112016
What are the main differences between those two concept: static Instance and Interface?
Example:
class Program
{
static void Main(string[] args)
{
ITestInterface InterInstance = new TestInterface();
//test Interface
bool value1 = true;
value1 = InterInstance.invert(value1);
InterInstance.print(value1);
//test Instance static
TestStaticInstance staticInstance = new TestStaticInstance();
staticInstance.Instance.invert(value1);
staticInstance.Instance.print(value1);
Console.ReadKey();
}
}
class TestInterface : ITestInterface
{
public bool invert(bool value)
{
return !value;
}
public void print(bool value)
{
Console.WriteLine(value.ToString()+"\n");
}
private void methodX()
{ }
}
interface ITestInterface
{
bool invert(bool value);
void print(bool value);
}
public class TestStaticInstance
{
public TestStaticInstance Instance;
public TestStaticInstance()
{
Instance = this;
}
internal bool invert(bool value)
{
return !value;
}
internal void print(bool value)
{
Console.WriteLine(value.ToString());
}
}
Thanks
Can you structure your other classes to take an instance of the link class? See:
/// <summary>
/// just a stub to demonstrate the model
/// </summary>
internal class Machine
{
public string ReadData() { return "this is data"; }
public void WriteData(string data) { Console.WriteLine(data); }
}
internal interface IMachineDataAccessor
{
string Read();
void Write(string data);
}
class LinkClass : IMachineDataAccessor
{
protected Machine _machine;
public LinkClass(Machine machine)
{
_machine = machine;
}
public void DoMyWork()
{
// insert work somewhere in here.
string dataFromMachine = Read();
Write("outbound data");
}
public string Read()
{
return _machine.ReadData();
}
public void Write(string data)
{
_machine.WriteData(data);
}
}
class PersistentClass
{
IMachineDataAccessor _machineImpl;
public PersistentClass(IMachineDataAccessor machineAccessImplementation)
{
_machineImpl = machineAccessImplementation;
}
public void DoMyWork()
{
string dataFromMachine = _machineImpl.Read();
// insert work here. Or anywhere, actually..
_machineImpl.Write("outbound data");
}
}
class StateClass
{
IMachineDataAccessor _machineImpl;
public StateClass(IMachineDataAccessor machineAccessImplementation)
{
_machineImpl = machineAccessImplementation;
}
public void DoMyWork()
{
string dataFromMachine = _machineImpl.Read();
// insert work here. Or anywhere, actually..
_machineImpl.Write("outbound data");
}
}
static void Main(string[] args)
{
LinkClass link = new LinkClass(new Machine());
PersistentClass persistent = new PersistentClass(link as IMachineDataAccessor);
StateClass state = new StateClass(link as IMachineDataAccessor);
persistent.DoMyWork();
state.DoMyWork();
link.DoMyWork();
}

C# How to load data to messagebox

I have:
private void Tab2KsiazkiBTSzczegoly_Click(object sender, EventArgs e)
{
string KodKsiazki;
KodKsiazki = DataWyszukajKsiazki.Rows[DataWyszukajKsiazki.CurrentCell.RowIndex].Cells[2].Value.ToString();
TSzczegolyDb _szczegoly = new TSzczegolyDb();
Global.listSzczegoly = _szczegoly.GetSZCZEGOLY(KodKsiazki);
//StringBuilder sb = new StringBuilder();
//foreach (DataGridViewCell cell in DataWyszukajKsiazki.SelectedCells)
//{
// sb.AppendLine(cell.Value.ToString());
//}
//MessageBox.Show(sb.ToString());
//}
MessageBox.Show(_szczegoly.ToString());
}
class like that:
public class TSzczegolyDb : Core.CoreMSSQL
{
static string connectionString = TconStrDb.GetConectionString();
public TSzczegolyDb()
: base(connectionString)
{
}
public List<TSzczegolyDto> GetSZCZEGOLY(string co)
{
List<TSzczegolyDto> list = null;
list = new List<TSzczegolyDto>();
SqlCommand command = new SqlCommand();
command.CommandText = "SELECT Tytul, Autorzy, ISBN10, ISBN13, IlStron, Wydawnictwo, Gatunek, Opis FROM dbo.TKsiazki WHERE dbo.TKsiazki.KodKsiazki = '" + co + "'";
SqlDataReader reader = ExecuteQuery(command);
while (reader.Read())
{
TSzczegolyDto message = new TSzczegolyDto();
if (!reader.IsDBNull(0))
{
message.Tytuł = reader.GetString(0);
}
if (!reader.IsDBNull(1))
{
message.Autorzy = reader.GetString(1);
}
if (!reader.IsDBNull(2))
{
message.ISBN10 = reader.GetString(2);
}
if (!reader.IsDBNull(3))
{
message.ISBN13 = reader.GetString(3);
}
if (!reader.IsDBNull(4))
{
message.IlStron = reader.GetInt32(4);
}
if (!reader.IsDBNull(5))
{
message.Wydawnictwo = reader.GetString(5);
}
if (!reader.IsDBNull(6))
{
message.Gatunek = reader.GetString(6);
}
if (!reader.IsDBNull(7))
{
message.Opis = reader.GetString(7);
}
list.Add(message);
}
return list;
}
and second:
public class TSzczegolyDto
{
private string _tytul;
public string Tytuł
{
get { return _tytul; }
set { _tytul = value; }
}
private string _autorzy;
public string Autorzy
{
get { return _autorzy; }
set { _autorzy = value; }
}
private string _ISBN10;
public string ISBN10
{
get { return _ISBN10; }
set { _ISBN10 = value; }
}
private string _ISBN13;
public string ISBN13
{
get { return _ISBN13; }
set { _ISBN13 = value; }
}
private long _ilstron;
public long IlStron
{
get { return _ilstron; }
set { _ilstron = value; }
}
private string _wydawnictwo;
public string Wydawnictwo
{
get { return _wydawnictwo; }
set { _wydawnictwo = value; }
}
private string _gatunek;
public string Gatunek
{
get { return _gatunek; }
set { _gatunek = value; }
}
private string _opis;
public string Opis
{
get { return _opis; }
set { _opis = value; }
}
}
I want show _szczegoly on MessageBox but when I try to MessageBox.Show(_szczegoly.ToString()); then is wrong. In _szczegoly I have string and long type data.
How to create messagebox with this data?
I think you are trying to show an Object with a MessageBox, you need to override the ToString() method to show propertly:
class TSzczegolyDb
{
public override string ToString()
{
return this.Property1 + this.Property2 /*....*/;
}
}

Why my ICollection is always empty?

I am trying to reach a foreach but my program never gets inside because my ICollection Coletores is always empty even if I put a lot of stuff in there.
The code where I want to get inside and it is always empty (I want to get inside the second foreach):
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (NavigationContext.QueryString.TryGetValue("email", out email))
{
//MessageBox.Show(email);
List<HyperlinkButton> listaLinks = new List<HyperlinkButton>();
AppDataContext db = new AppDataContext();
int i = 0;
HyperlinkButton aux = new HyperlinkButton();
foreach (Pessoa pessoa in db.Pessoas)
{
if (pessoa.Email == email)
{
foreach (Coletor coletor in pessoa.Coletores)
{
aux.Content = "Coletor " + (i + 1).ToString();
aux.FontSize = 24;
aux.NavigateUri = new Uri("/OcorrenciasPage.xaml?coletorId=" + coletor.Id.ToString(), UriKind.RelativeOrAbsolute);
listaLinks.Add(aux);
i++;
}
}
}
ListBox coletores = new ListBox();
coletores.ItemsSource = listaLinks;
stcList.Children.Add(coletores);
}
base.OnNavigatedTo(e);
}
Now the code that I am adding data:
if (txtLat.Text != "" && txtLong.Text != "" && rdNorte.IsChecked == true || rdSul.IsChecked == true && rdLeste.IsChecked == true || rdOeste.IsChecked == true)
{
foreach (var pessoa in db.Pessoas)
{
if (pessoa.Email == email)
{
pessoa.Coletores.Add(coletor);
}
}
db.Coletores.InsertOnSubmit(coletor);
db.SubmitChanges();
NavigationService.Navigate(new Uri("/ColetoresPage.xaml?email=" + email, UriKind.RelativeOrAbsolute));
}
Now, my Pessoa class:
public class Pessoa : INotifyPropertyChanged
{
private int _id;
[Column(IsDbGenerated = true, IsPrimaryKey = true)]
public int Id {
get { return _id;}
set { _id = value;
OnPropertyChanged("Id");
}
}
private string _nome;
[Column]
public string Nome
{
get { return _nome; }
set { _nome = value;
OnPropertyChanged("Nome");
}
}
private string _email;
[Column]
public string Email
{
get { return _email; }
set { _email = value;
OnPropertyChanged("Email");
}
}
private string _senha;
[Column]
public string Senha { get { return _senha; }
set { _senha = value;
OnPropertyChanged("Senha");
}
}
private string _profissao;
[Column]
public string Profissao { get { return _profissao; }
set { _profissao = value;
OnPropertyChanged("Profissao");
}
}
private int _idade;
[Column]
public int Idade { get { return _idade; }
set { _idade = value;
OnPropertyChanged("Idade");
}
}
private string _endereco;
[Column]
public string Endereco { get { return _endereco; }
set { _endereco = value;
OnPropertyChanged("Endereco");
}
}
private string _cidade;
[Column]
public string Cidade { get { return _cidade; }
set { _cidade = value;
OnPropertyChanged("Cidade");
}
}
private string _estado;
[Column]
public string Estado { get { return _estado; }
set { _estado = value;
OnPropertyChanged("Estado");
}
}
private EntitySet<Coletor> _coletores = new EntitySet<Coletor>();
[Association(Name = "FK_Coletores_PessoaColetores", Storage = "_coletores", ThisKey = "Id", OtherKey = "pessoaId")]
public ICollection<Coletor> Coletores
{
get { return _coletores; }
set { _coletores.Assign(value); }
}
private EntitySet<PessoaColetor> _pessoaColetores = new EntitySet<PessoaColetor>();
[Association(Name = "FK_PessoaColetores_Pessoas", Storage = "_pessoaColetores", OtherKey = "pessoaId", ThisKey = "Id")]
private ICollection<PessoaColetor> PessoaColetores
{
get { return _pessoaColetores; }
set { _pessoaColetores.Assign(value); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
The Coletores property on the Pessoa class looks alright. There is also a PessoaColetores property. Are you sure there has been no confusion between the two? Especially with intellisense one might dot or tab the wrong one.
Have you put a break point on the line that actually adds coletors (second code snippet)? Maybe stuff is added to the wrong collection.
Cheers, B.

ConfigurationProperty(typeof(CCfgElement).ToString())

Why is it not possible to have this ?
[ConfigurationProperty(typeof(CCfgElement).ToString())]
I get the error:
Error 1 An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type
here is my code
public class CConfigElement<T> : ConfigurationElement
{
}
public class CConfigSection<CCfgElement> : ConfigurationSection where CCfgElement : CConfigElement<CCfgElement>
{
// Create a element.
[ConfigurationProperty(typeof(CCfgElement).ToString())]
public CCfgElement Element
{
get { return (CCfgElement)this[typeof(CCfgElement).ToString()]; }
set { this[typeof(CCfgElement).ToString()] = value; }
}
}
I do not think there is any workarounds but
can anybody tell me how to add a section lement with code?
Søren
I found a kind of solution my self
here is my code
// create the DataModel in your MainWindow or App
// CTestDataModel t = new CTestDataModel();
public class CTestDataModel
{
CTestValues _Cfg;
// Create values to save in cofig
public class CTestValues : ConfigurationElement
{
[ConfigurationProperty("Param", DefaultValue = 11, IsRequired = true)]
public int Param
{
get { return (int)this["Param"]; }
set { this["Param"] = value; }
}
[ConfigurationProperty("Param1", DefaultValue = "22", IsRequired = true)]
public double Param1
{
get { return (double)this["Param1"]; }
set { this["Param1"] = value; }
}
[ConfigurationProperty("Time", IsRequired = true)]
public DateTime Time
{
get { return (DateTime)this["Time"]; }
set { this["Time"] = value; }
}
}
public CTestDataModel()
{
// load config
_Cfg = CConfiguration.Element<CTestValues>();
// Use values
int t = _Cfg.Param;
_Cfg.Param = 5;
_Cfg.Param1 = 6;
_Cfg.Time = new DateTime(1962, 10, 10);
}
}
public class CConfigSection<CCfgElement> : ConfigurationSection where CCfgElement : ConfigurationElement
{
// Create a element.
[ConfigurationProperty("Element")]
public CCfgElement Element
{
get { return (CCfgElement)this["Element"]; }
set { this["Element"] = value; }
}
}
public static class CConfiguration
{
static Configuration config = null;
static AppSettingsSection appSettings = null;
static CConfiguration()
{
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
appSettings = config.AppSettings;
AppDomain.CurrentDomain.ProcessExit += CConfiguration_Dtor;
}
private static void CConfiguration_Dtor(object sender, EventArgs e)
{
config.Save(ConfigurationSaveMode.Modified, true);
}
// Uses sections
private static String MakeSectionName(String name)
{
return name.Replace('+', '.');
}
public static void RemoveSection(Type T)
{
try
{
String name = MakeSectionName(T.ToString());
config.Sections.Remove(name);
}
catch (Exception)
{
return;
}
}
public static T Element<T>() where T : ConfigurationElement
{
try
{
return Section<T>().Element;
}
catch (Exception ex)
{
Debug.WriteLine(typeof(T).ToString()+" error: "+ex.Message);
throw ex;
}
}
public static CConfigSection<T> Section<T>() where T : ConfigurationElement
{
try
{
return Section(typeof(T).ToString(), new CConfigSection<T>()) as CConfigSection<T>;
}
catch (Exception ex)
{
Debug.WriteLine(typeof(T).ToString()+" error: "+ex.Message);
throw ex;
}
}
public static ConfigurationSection Section(String name, ConfigurationSection section)
{
try
{
name = MakeSectionName(name);
ConfigurationSection cs = config.Sections.Get(name);
if (cs == null)
{
config.Sections.Add(name, section);
return section;
}
else
return cs;
}
catch (Exception)
{
config.Sections.Remove(name);
config.Sections.Add(name, section);
return section;
}
}
// Uses AppSettings
public static bool Exist(String key)
{
return appSettings.Settings[key] != null;
}
public static string Read(String key, string Default = "")
{
if (Exist(key))
return appSettings.Settings[key].Value;
return Default;
}
public static void Write(string key, string value)
{
if (Exist(key))
appSettings.Settings.Remove(key);
appSettings.Settings.Add(key, value);
}
public static void Remove(string key)
{
if (Exist(key))
appSettings.Settings.Remove(key);
}
public static new string ToString()
{
StringBuilder sb = new StringBuilder();
// Get the settings collection (key/value pairs).
if (appSettings.Settings.Count != 0)
{
foreach (string key in appSettings.Settings.AllKeys)
{
string value = appSettings.Settings[key].Value;
sb.Append(String.Format("Key: {0} Value: {1}\r\n", key, value));
}
}
return sb.ToString();
}
}

C# XmlSerializer has error while reflecting type

To transfer data, I'm using XmlSerializer. But I get a runtime error at following line:
XmlSerializer serializer = new XmlSerializer(typeof(Packets.Wrapper));
The error is "Additional information: Error reflecting type 'Packets.Wrapper'.". MSDN says that I have to use an empty contructor, but it doesn't fix the error.
The class looks like this:
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace Packets
{
[Serializable]
public class Wrapper
{
int _sID = 0;
int _sSession = 0;
PacketType _sType = PacketType.None;
AuthRequest _sAuthRequest = null;
AuthResponse _sAuthResponse = null;
ProxyRequest _sProxyRequest = null;
ProxyResponse _sProxyResponse = null;
public Wrapper()
{
}
public int ID
{
get { return _sID; }
set { _sID = value; }
}
public int Session
{
get { return _sSession; }
set { _sSession = value; }
}
public PacketType Type
{
get { return _sType; }
set { _sType = value; }
}
public AuthRequest AuthRequest
{
get { return _sAuthRequest; }
set { _sAuthRequest = value; }
}
public AuthResponse AuthResponse
{
get { return _sAuthResponse; }
set { _sAuthResponse = value; }
}
public ProxyRequest ProxyRequest
{
get { return _sProxyRequest; }
set { _sProxyRequest = value; }
}
public ProxyResponse ProxyResponse
{
get { return _sProxyResponse; }
set { _sProxyResponse = value; }
}
}
[Serializable]
public enum PacketType
{
AuthRequest,
AuthResponse,
ProxyRequest,
ProxyResponse,
None
}
[Serializable]
public enum AuthResult
{
Accepted,
Denied,
Error
}
[Serializable]
public enum ProxyAction
{
Send,
Response,
Connect,
Close
}
[Serializable]
public enum ProxyResult
{
Connected,
Sent,
Revieved,
Error
}
[Serializable]
public class AuthRequest
{
string username = null;
string password = null;
public AuthRequest()
{
}
public string Username
{
get { return username; }
set { username = value; }
}
public string Password
{
get { return password; }
set { password = value; }
}
}
[Serializable]
public class AuthResponse
{
AuthResult authResult = AuthResult.Denied;
public AuthResponse()
{
}
public AuthResult AuthResult
{
get { return authResult; }
set { authResult = value; }
}
}
[Serializable]
public class ProxyRequest
{
ProxyAction _sAction;
string _sIP = null;
int _sPort = 0;
TcpClient _sClient = null;
public ProxyRequest()
{
}
public ProxyAction Action
{
get { return _sAction; }
set { _sAction = value; }
}
public string IP
{
get { return _sIP; }
set { _sIP = value; }
}
public int Port
{
get { return _sPort; }
set { _sPort = value; }
}
public TcpClient Client
{
get { return _sClient; }
set { _sClient = value; }
}
}
[Serializable]
public class ProxyResponse
{
public ProxyResult _sResult = ProxyResult.Error;
public StringBuilder _sError = new StringBuilder();
public StringBuilder _sRecieved = new StringBuilder();
public TcpClient _sClient = null;
public ProxyResponse()
{
}
public ProxyResult Result
{
get { return _sResult; }
set { _sResult = value; }
}
public StringBuilder Error
{
get { return _sError; }
set { _sError = value; }
}
public StringBuilder Recieved
{
get { return _sRecieved; }
set { _sRecieved = value; }
}
public TcpClient Client
{
get { return _sClient; }
set { _sClient = value; }
}
}
}
I hope you can help me and thank you for your time.
I got it.
TcpClient isn't serializable.

Categories

Resources