Unity console not showing Debug upon pressing play - c#

I am creating a small login page example and upon pressing play I am not getting any of the Debug messages I am expected if the email/password/confirm password is not according to the conditions set.
Here is the whole code:
Packages
using System.Collections;
using System.Collections.Generic;
using UnityEngine.UI;
using UnityEngine;
using System;
using System.Text.RegularExpressions;
Class definition
public class Register : MonoBehaviour
{
public GameObject username;
public GameObject email;
public GameObject password;
public GameObject confPassword;
private string Username;
private string Email;
private string Password;
private string ConfPassword;
private string form;
private bool EmailValid = false;
private string[] Characters = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z",
"A","B","C","D","E","F","G","H","I","J","K","L","M","O","N","P","Q","R","S","T","U","V","W","X","Y","Z",
"1","2","3","4","5","6","7","8","9","0","_","-" };
Initiation and setting conditions for username, email, password and confirm password.
// Start is called before the first frame update
void Start()
{
}
public void RegisterButton()
{
print("Registration Successful");
bool UN = false;
bool EM = false;
bool PW = false;
bool CPW = false;
if (Username != "")
{
if (!System.IO.File.Exists(#"E:/UnityTestFolder/" + Username + ".txt"))
{
UN = true;
}
else
{
Debug.LogWarning("Username Taken");
}
}
else
{
Debug.LogWarning("Username field empty");
}
if (Email != "")
{
EmailValidation();
if (EmailValid)
{
if (Email.Contains("#"))
{
if (Email.Contains("."))
{
EM = true;
}
else
{
Debug.LogWarning("Email is incorrect");
}
}
else
{
Debug.LogWarning("Email is incorrect");
}
}
else
{
Debug.LogWarning("Email is incorrect");
}
}
else
{
Debug.LogWarning("Email field empty ");
}
if (Password != "")
{
if (Password.Length > 5)
{
PW = true;
}
else
{
Debug.LogWarning("Pass must be at least 6 characters long!");
}
}
else
{
Debug.LogWarning("Password field empty");
}
if (ConfPassword != "")
{
if (ConfPassword == Password)
{
CPW = true;
}
else
{
Debug.LogWarning("Passwords do not match!");
}
}
else
{
Debug.LogWarning("Confirm password field empty");
}
if (UN == true &&EM == true &&PW == true &&CPW == true)
{
bool Clear = true;
int i = 1;
foreach (char c in Password)
{
if (Clear)
{
Password = "";
Clear = false;
}
i++;
char Encrypted = (char)(c * i);
Password += Encrypted.ToString();
}
form = (Username + "\n" + Email + "\n" + Password);
System.IO.File.WriteAllText(#"E:/ UnityTestFolder / " + Username + ".txt", form);
username.GetComponent<InputField>().text = "";
email.GetComponent<InputField>().text = "";
password.GetComponent<InputField>().text = "";
confPassword.GetComponent<InputField>().text = "";
print("Registration complete");
}
}
Calling update - pressing tab button to navigate between the various placeholders.
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
if (username.GetComponent<InputField>().isFocused)
{
email.GetComponent<InputField>().Select();
}
if (email.GetComponent<InputField>().isFocused)
{
password.GetComponent<InputField>().Select();
}
if (password.GetComponent<InputField>().isFocused)
{
confPassword.GetComponent<InputField>().Select();
}
}
if (Input.GetKeyDown(KeyCode.Return))
{
if (Password != ""&&Email != ""&&Password != ""&&ConfPassword != "")
{
RegisterButton();
}
}
Username = username.GetComponent<InputField>().text;
Email = email.GetComponent<InputField>().text;
Password = password.GetComponent<InputField>().text;
ConfPassword = confPassword.GetComponent<InputField>().text;
}
void EmailValidation()
{
bool SW = false;
bool EW = false;
for (int i = 0; i < Characters.Length; i++)
{
if (Email.StartsWith(Characters[i]))
{
SW = true;
}
}
for (int i = 0; i < Characters.Length; i++)
{
if (Email.EndsWith(Characters[i]))
{
EW = true;
}
}
if (SW = true &&EW == true)
{
EmailValid = true;
}
else
{
EmailValid = false;
}
}
}
Thanks for the help.

Add [ExecuteInEditMode] attribute here:
[ExecuteInEditMode]
public class Register : MonoBehaviour

I have resolved it, it was a stupid mistake, I just had the wrong GameObject in the "On Click" component.
Thanks for all help again.

Related

Custom Textbox Even not running

I wrote a custom textbox for a program that is designed to give me database values without a lot of converts or checks and to have custom text input. It had a few different modes, such as an auto formatting date box and SSN. It worked great in VB.NET, but now that I'm learning C# and I'm remaking the program in C# for practice, I'm hitting a snag with the conversion. None of the events will fire.
using System;
using System.ComponentModel;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
public class DBTextBox : TextBox {
private void InitializeComponent() {
SuspendLayout();
Enter += new EventHandler(DBTextBox_Enter);
KeyPress += new KeyPressEventHandler(On_Key_Press);
KeyUp += new KeyEventHandler(On_Key_Up);
Leave += new EventHandler(Control_Leave);
ResumeLayout(false);
}
public enum StyleTypes {
DateBox,
SSNBox,
PhoneBox,
TextBox,
IntegerBox,
DecimalBox
}
private StyleTypes Type { get; set; }
public StyleTypes StyleType {
get { return Type; }
set { Type = value; }
}
private string _Default_Value { get; set; }
public string Default_Value {
get { return _Default_Value; }
set { _Default_Value = value; }
}
private bool _AutoUpperCase = false;
public bool AutoUpperCase {
get { return _AutoUpperCase; }
set { _AutoUpperCase = value; }
}
private bool _AutoUpperCaseFirstCharOnly = false;
public bool AutoUpperCaseFirstCharOnly {
get { return _AutoUpperCaseFirstCharOnly; }
set { _AutoUpperCaseFirstCharOnly = value; }
}
private void On_Key_Up(object sender, KeyEventArgs e) {
if (e.KeyCode != Keys.Back) {
if (Type == StyleTypes.DateBox) {
if (TextLength == 2 && Text.Contains("//") == false) {
Text = Text + "/";
SelectionStart = Text.Length + 1;
}
if (TextLength == 4 && Text.Substring(1, 1) == "//" && Text.Substring(3, 1) != "//" && CharCount('/') <= 1) {
Text = Text + "/";
SelectionStart = Text.Length + 1;
}
if (TextLength == 5 && Text.Substring(2, 1) == "//" && CharCount('/') <= 1) {
Text = Text + "/";
SelectionStart = Text.Length + 1;
}
if (Text.Contains("//")) {
Text = Text.Replace(#"//", #"/");
SelectionStart = Text.Length + 1;
}
}
if (Type == StyleTypes.SSNBox) {
MaxLength = 11;
if (TextLength == 3 || TextLength == 6) {
Text = Text + "-";
SelectionStart = Text.Length + 1;
}
}
if (Type == StyleTypes.PhoneBox) {
MaxLength = 14;
if (TextLength == 3 && Text.Contains('(') == false) {
Text = "(" + Text + ") ";
SelectionStart = Text.Length + 1;
}
if (TextLength == 9) {
Text = Text + "-";
SelectionStart = Text.Length + 1;
}
}
}
}
private void Control_Leave(object sender, EventArgs e) {
if (Type == StyleTypes.DateBox) {
if (DateTime.TryParse(Text, out DateTime i)) {
BackColor = Color.FromKnownColor(KnownColor.Window);
Text = Convert.ToDateTime(Text).ToShortDateString();
} else if (string.IsNullOrWhiteSpace(Text)) {
BackColor = Color.FromKnownColor(KnownColor.Window);
Text = string.Empty;
} else {
BackColor = Color.Salmon;
}
}
}
private void On_Key_Press(object sender, KeyPressEventArgs e) {
if (Type == StyleTypes.DateBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false) {
if (e.KeyChar == '/' && CharCount('/') <= 1) { } else { e.Handled = true; }
}
}
if (Type == StyleTypes.PhoneBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false && e.KeyChar != '-' && e.KeyChar != '(' && e.KeyChar != ' ') {
e.Handled = true;
}
}
if (Type == StyleTypes.SSNBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false && e.KeyChar != '-') {
e.Handled = true;
}
}
if (Type == StyleTypes.DecimalBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false) {
if ((e.KeyChar == '.' && CharCount('.') < 1) || (e.KeyChar == '-' && CharCount('-') < 1)) { } else { e.Handled = true; }
}
}
if (Type == StyleTypes.IntegerBox) {
if (char.IsNumber(e.KeyChar) == false && char.IsControl(e.KeyChar) == false) {
e.Handled = true;
}
}
}
private int CharCount(char Character) {
char[] Chars = Text.ToCharArray();
int Count = 0;
foreach (var Item in Chars) {
if (Item == Character) {
Count += 1;
}
}
return Count;
}
[Description("The Text in the box, returns null if Empty or White spaces")]
public string DBText {
get { if (string.IsNullOrWhiteSpace(Text)) { return null; } else { return Text; } }
set { if (string.IsNullOrWhiteSpace(value)) { Text = null; } else { Text = value; } }
}
[Description("The returned Date if the Text is a date.")]
public DateTime? DBDate {
get { if (DateTime.TryParse(Text, out DateTime i)) { return Convert.ToDateTime(Text); } else { return null; } }
set { Convert.ToDateTime(value).ToShortDateString(); }
}
public decimal? DBDecimal {
get { if (decimal.TryParse(Text, out decimal i)) { return Convert.ToDecimal(Text); } else { return null; } }
set { Text = value.ToString(); }
}
public int? DBInt {
get { if (int.TryParse(Text, out int i) && Convert.ToInt32(Text) > int.MinValue && Convert.ToInt32(Text) < int.MaxValue) { return Convert.ToInt32(Text); } else { return null; } }
set { Text = value.ToString(); }
}
public short? DBShort {
get { if (short.TryParse(Text, out short i)) { return Convert.ToInt16(Text); } else { return null; } }
set { Text = value.ToString(); }
}
private string UppercaseFirstLetter(string Input) {
if (string.IsNullOrEmpty(Input)) { return Input; }
char[] array = Input.ToCharArray();
array[0] = char.ToUpper(array[0]);
bool UpperCaseNextLetter = true;
int LastCharPos = array.Count() - 1;
if (_AutoUpperCaseFirstCharOnly) { LastCharPos = 1; }
for (int i = 0; i <= LastCharPos; i++) {
if (UpperCaseNextLetter == true) {
array[i] = char.ToUpper(array[i]);
UpperCaseNextLetter = false;
} else {
array[i] = char.ToLower(array[i]);
}
if (array[i] == ' ') {
UpperCaseNextLetter = true;
}
}
return new string(array);
}
private void DBTextBox_Enter(object sender, EventArgs e) {
if (Type == StyleTypes.DateBox) {
if (DateTime.TryParse(Text, out DateTime i)) {
SelectionStart = 0;
SelectionLength = Text.Length;
}
}
if (Type == StyleTypes.TextBox && Text.Length > 0 && _Default_Value.Length > 0) {
if (Text == _Default_Value) {
SelectionStart = 0;
SelectionLength = Text.Length;
}
}
}
}
What do I need to do to get the events to fire?
Edit: Here it is on the Debug Form I created to test it;
partial class frmDebug {
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing) {
if (disposing && (components != null)) {
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent() {
this.txtDate = new DBTextBox();
this.cmdSet = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// txtDate
//
this.txtDate.AutoUpperCase = false;
this.txtDate.AutoUpperCaseFirstCharOnly = false;
this.txtDate.DBDate = null;
this.txtDate.DBDecimal = null;
this.txtDate.DBInt = null;
this.txtDate.DBShort = null;
this.txtDate.DBText = null;
this.txtDate.Default_Value = null;
this.txtDate.Location = new System.Drawing.Point(72, 52);
this.txtDate.Name = "txtDate";
this.txtDate.Size = new System.Drawing.Size(100, 20);
this.txtDate.StyleType = DBTextBox.StyleTypes.DateBox;
this.txtDate.TabIndex = 0;
//
// cmdSet
//
this.cmdSet.Location = new System.Drawing.Point(68, 128);
this.cmdSet.Name = "cmdSet";
this.cmdSet.Size = new System.Drawing.Size(75, 23);
this.cmdSet.TabIndex = 1;
this.cmdSet.Text = "Set";
this.cmdSet.UseVisualStyleBackColor = true;
this.cmdSet.Click += new System.EventHandler(this.cmdSet_Click);
//
// frmDebug
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 261);
this.Controls.Add(this.cmdSet);
this.Controls.Add(this.txtDate);
this.Name = "frmDebug";
this.Text = "frmDebug";
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.Button cmdSet;
public DBTextBox txtDate;
}
I don't have any code on the Form so this is what it looks like;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public partial class frmDebug : Form {
public frmDebug() {
InitializeComponent();
}
}
LarsTech has a better and more correct solution:
You don't call InitializeComponent from inside the TextBox. But a
class doesn't have to listen to their own events. Use the overrides
instead, example: protected override void OnKeyUp(KeyEventArgs e)
{...}
My original answer:
It looks like you'll probably just need to add a constructor for the DBTextBox class that will call your private InitializeComponent() method. It should look something like this:
public DBTextBox()
{
InitializeComponent();
}

Network Map with full detail and hierarchy

I wrote a piece of code to run from the first IP address to the last and retrieve the MAC and Hostname of devices in my network.
But, i do not know how to get the hierachy of then. Information like what router is the device conected (via Cable of WiFi also). And some routers are not managed (they don't have IP - they are just "switchs").
First, i didn't think it was possible, since a "tracert" on the CMD does not show then, but when i call the "Network Complete Map" on Windows Control Panel, they get all the information i need - so there is a way. See the image below:
The "switchs" circled in red have no IP, the "TL-xxxx" are routers with DHCP turned of. The "gateway" is a server that has the DHCP and provides connection to the internet.
Thus far, i wrote the following code:
using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using System.Net;
using System.Runtime.InteropServices;
namespace Network
{
[Serializable] public sealed class Map
{
private bool mMARKED = true;
private long mDB = 0L;
private string mIP = string.Empty;
private string mMAC = string.Empty;
private string mBRAND = string.Empty;
private string mNAME = string.Empty;
public bool Save { get { return this.mMARKED; } set { this.mMARKED = value; } }
public long DBId { get { return this.mDB; } set { this.mDB = value; } }
public string IP { get { return this.mIP; } set { this.mIP = value; } }
public string MAC { get { return this.mMAC; } set { this.mMAC = value; } }
public string BRAND { get { return this.mBRAND; } set { this.mBRAND = value; } }
public string NAME { get { return this.mNAME; } set { this.mNAME = value; } }
}
[Serializable] public sealed class Scanner
{
public const string WebOUIFile = "http://standards-oui.ieee.org/oui.txt";
public const string LocalOUIFileName = "oui.txt";
private const long MaxOUIAge = (TimeSpan.TicksPerDay * 90L);
internal Dictionary<string, string> OUIList;
private List<Map> mDevices = new List<Map>(50);
public List<Map> Devices { get { return this.mDevices; } }
public static Scanner Scan;
public Thread Worker;
public bool AutoSave { get; set; }
private string Node;
private byte mInitial;
public static string UploadPath { get; set; }
public byte Initial { get { return this.mInitial; } set { this.mInitial = value; } }
public byte Current { get; private set; }
public byte Limit { get; set; }
public bool Working { get; private set; }
public string Errors;
public string Message { get; private set; }
public bool UpdatingOUI { get; private set; }
public void Interrupt()
{
this.Working = false;
if (this.Worker != null)
{
this.Worker.Abort();
this.Worker = null;
}
this.Node = string.Empty;
this.Initial = 0;
this.Current = 0;
this.Limit = 0;
this.Working = false;
}
public void ToDestroy()
{
this.Interrupt();
this.Errors = string.Empty;
this.Message = string.Empty;
}
public void Stop(bool immediate) { if (immediate) { this.Interrupt(); } }
[DllImport("iphlpapi.dll", SetLastError = true, CharSet = CharSet.Auto)] private static extern int SendARP(int DestIP, int SrcIP, out long pMacAddr, ref int PhyAddrLen);
public void ToBegin() { }
public void Stop() { this.Stop(true); }
private static int IPToInt(string Expression)
{
try
{
byte[] IPAddress = System.Net.IPAddress.Parse(Expression).GetAddressBytes();
return (Convert.ToInt32(IPAddress[3]) << 24) | (Convert.ToInt32(IPAddress[2]) << 16) | (Convert.ToInt32(IPAddress[1]) << 8) | Convert.ToInt32(IPAddress[0]);
} catch { return 0; }
}
private Map GetBasics(string IPString)
{
int res = Scanner.IPToInt(IPString);
if (res > 0)
{
long mem = 0L;
int PhyAddrLen = 6;
if (Scanner.SendARP(res, 0, out mem, ref PhyAddrLen) == 0)
{
Map dev = new Map();
byte[] macbytes = BitConverter.GetBytes(mem);
dev.IP = IPString;
string Tmp = BitConverter.ToString(macbytes, 0, 3);
if (this.OUIList != null && this.OUIList.ContainsKey(Tmp)) { dev.BRAND = this.OUIList[Tmp]; }
dev.MAC = Tmp + "-" + BitConverter.ToString(macbytes, 3, 3);
try { dev.NAME = Dns.GetHostEntry(IPString).HostName.ToLower(); } catch { dev.NAME = "unknow"; }
return dev;
}
}
return null;
}
private static void GetNode(ref string IP, ref string Node, ref byte Device)
{
string[] NodeComp = IP.Split('.');
Node = NodeComp[0] + "." + NodeComp[1] + "." + NodeComp[2] + ".";
Device = Convert.ToByte(NodeComp[3]);
}
public static Dictionary<string, string> DonwloadOUTFile(bool ForceUpdate = true)
{
Dictionary<string, string> List = null;
try
{
string Aux = Scanner.UploadPath;
if (Aux == null) { Aux = string.Empty; }
else if (Aux != string.Empty)
{
string Tmp = Aux + "~" + Scanner.LocalOUIFileName;
Aux += Scanner.LocalOUIFileName;
bool FileExists = File.Exists(Aux);
if (FileExists && ((DateTime.UtcNow.Ticks - (new FileInfo(Aux)).CreationTimeUtc.Ticks) > Scanner.MaxOUIAge))
{
File.Delete(Aux);
ForceUpdate = true;
}
string Aux2 = string.Empty;
if (ForceUpdate)
{
List = new Dictionary<string, string>(25000);
using (WebClient Downloader = new WebClient()) { Downloader.DownloadFile(Scanner.WebOUIFile, Tmp); }
using (StreamReader Reader = new StreamReader(Tmp))
using (StreamWriter Writer = new StreamWriter(Aux))
{
do
{
Aux = Reader.ReadLine();
if (Aux.ToLower().Contains("(hex)"))
{
Aux2 = Aux.Substring(0, 8).ToUpper();
Aux = Aux.Substring(Aux.LastIndexOf('\t') + 1);
if (!List.ContainsKey(Aux2))
{
List.Add(Aux2, Aux);
Writer.WriteLine(Aux2 + "\t" + Aux);
}
}
} while (Reader.Peek() >= 0);
Reader.Close();
Writer.Close();
}
try { File.Delete(Tmp); } catch { /* NOTHING */ }
}
else if (FileExists)
{
List = new Dictionary<string, string>(25000);
using (StreamReader Reader = new StreamReader(Aux))
{
do
{
Aux = Reader.ReadLine();
if (Aux != null && Aux.Length > 9)
{
Aux2 = Aux.Substring(0, 8);
if (!List.ContainsKey(Aux2)) { List.Add(Aux2, Aux.Substring(9)); }
}
} while (Reader.Peek() >= 0);
Reader.Close();
}
}
}
}
catch
{
if (List != null) { List.Clear(); }
List = null;
}
return List;
}
private void ReadScaner()
{
this.UpdatingOUI = true;
try { this.OUIList = Scanner.DonwloadOUTFile(ForceUpdate: false); } catch { /* NOTHING */ }
this.UpdatingOUI = false;
if (this.OUIList == null || this.OUIList.Count == 0) { this.Errors += "\nErrorOUIFileDownload"; }
Map Dev = null;
this.Current = this.Initial;
if (this.Limit < this.Initial)
{
Dev = this.GetBasics(this.Node + this.Initial.ToString());
if (Dev != null) { this.Devices.Add(Dev); }
}
else
{
bool ToAdd = true;
while (this.Current <= this.Limit)
{
Dev = this.GetBasics(this.Node + this.Current.ToString());
this.Current += 1;
if (Dev != null)
{
ToAdd = true;
foreach (Map iDev in this.Devices)
{
if (iDev.MAC == Dev.MAC)
{
ToAdd = false;
break;
}
}
if (ToAdd) { this.Devices.Add(Dev); }
}
}
}
this.Message = "Finished!";
this.Interrupt();
}
public void GetRange(string IPInitial, byte Limit, bool AutoSave = true)
{
if (!this.Working)
{
this.AutoSave = AutoSave;
this.Working = true;
Scanner.GetNode(ref IPInitial, ref this.Node, ref this.mInitial);
this.Limit = Limit;
this.Worker = new Thread(this.ReadScaner);
this.Worker.IsBackground = true;
this.ToBegin();
this.Worker.Start();
}
}
public static void GetRange(bool AutoSave, string IPInitial, byte Limit)
{
if (Scanner.Scan == null)
{
Scanner.Scan = new Scanner();
Scanner.Scan.GetRange(IPInitial, Limit, AutoSave: AutoSave);
}
}
~Scanner()
{
if (this.OUIList != null)
{
this.OUIList.Clear();
this.OUIList = null;
}
}
}
}
How do i make that code able to get the hierarchy like windows does?

String does contain a definition for isnullorwhitespace

Please help me in my system. I don't know whats the problem with isnullorwhitespace:
My error for this is:
"string does contain a definition for isnullorwhitespace"
What is my other option for isnullorwhitespace?
private void btnAdd_Click(object sender, EventArgs e)
{
int age = int.Parse(txtage.Text);
if (string.IsNullOrWhiteSpace(txtfname.Text))
{
MessageBox.Show("Please input your firstname!");
}
else if(string.IsNullOrWhiteSpace(txtlname.Text))
{
MessageBox.Show("Please input your lastname!");
}
else if(string.IsNullOrWhiteSpace(cbgender.SelectedItem.ToString()))
{
MessageBox.Show("Please specify your gender!");
}
else if(string.IsNullOrWhiteSpace(txtage.Text) || age <= 0 )
{
MessageBox.Show("Please assign your birthdate to know your age!");
}
else if(string.IsNullOrWhiteSpace(txtcontact.Text))
{
MessageBox.Show("Please input your contact number!");
}
else if(string.IsNullOrWhiteSpace(txtAddress.Text))
{
MessageBox.Show("Please input your address!");
}
else if(string.IsNullOrWhiteSpace(txtUsername.Text))
{
MessageBox.Show("Please input your username!");
}
else if(string.IsNullOrWhiteSpace(txtPass.Text))
{
MessageBox.Show("Please input your password!");
}
else if(string.IsNullOrWhiteSpace(cbxQuest.SelectedItem.ToString()))
{
MessageBox.Show("Please specify your secret question!");
}
else if(string.IsNullOrWhiteSpace(txtAsnwer.Text))
{
MessageBox.Show("Please input your answer!");
}
else
{
//Insert 7
ui.fname = txtfname.Text;
ui.lname = txtlname.Text;
ui.gender = cbgender.SelectedItem.ToString();
ui.age = int.Parse(txtage.Text);
ui.bdate = dtpBdate.Value;
ui.contactNo = txtcontact.Text;
ui.Adress = txtAddress.Text;
//Insert 4
us.username = txtUsername.Text;
us.passwordHash = txtPass.Text;
us.secretQuestion = cbxQuest.SelectedItem.ToString();
us.secretAnswer = txtAsnwer.Text;
StoredProcedure.Insert(ui, us);
dgData.DataSource = StoredProcedure.View();
Clear();
}
String.IsNullOrWhiteSpace has been introduced in .NET 4. If you are not targeting .NET 4 you could easily write your own:
public static class StringExtensions
{
public static bool IsNullOrWhiteSpace(string value)
{
if (value != null)
{
for (int i = 0; i < value.Length; i++)
{
if (!char.IsWhiteSpace(value[i]))
{
return false;
}
}
}
return true;
}
}
which could be used like this:
if (StringExtensions.IsNullOrWhiteSpace(txtfname.Text))
{
// do something
}

ListBox doesnt show any results

I'm trying to add an array of strings that holds information about people to a ListBox but i cant get it to show anything and i really dont know why.
This is the first class that is called when the button to add contacts to the list is clicked.
public partial class MainForm : Form
{
private ContactManager m_contacts;
public MainForm()
{
InitializeComponent();
m_contacts = new ContactManager();
InitializeGUI();
}
private void InitializeGUI()
{
txtFirstName.Text = string.Empty;
txtLastName.Text = string.Empty;
txtStreet.Text = string.Empty;
txtCity.Text = string.Empty;
txtZipCode.Text = string.Empty;
cmbCountry.Items.AddRange(Enum.GetNames(typeof(Countries)));
cmbCountry.DropDownStyle = ComboBoxStyle.DropDownList;
cmbCountry.SelectedIndex = (int)Countries.Sverige;
UpdateGUI();
}
private bool ReadInput(out Contact contact)
{
// skapar ett lokalt objekt av Contact-klassen
contact = new Contact();
// Lägger in ReadAdress till ett objekt i klassen Adress.
Address adr = ReadAddress();
contact.AddressData = adr; // skickar adress till contact-objekt
//bool readNameOK = ReadName();
// ReadName är OK så skickas det till AddContact.
if (ReadName())
{
m_contacts.AddContact(contact);
}
return ReadName();
} // ReadInput
private bool ReadName()
{
Contact contact = new Contact();
contact.FirstName = txtFirstName.Text;
contact.LastName = txtLastName.Text;
bool firstname = false;
bool lastname = false;
if (!InputUtility.ValidateString(contact.FirstName))
{
MessageBox.Show("You must enter a first name with atleast one character (not a blank)", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtFirstName.Focus();
txtFirstName.Text = " ";
txtFirstName.SelectAll();
firstname = false;
}
else if (!InputUtility.ValidateString(contact.LastName))
{
MessageBox.Show("You must enter a last name with atleast one character (not a blank)", "Error!",
MessageBoxButtons.OK, MessageBoxIcon.Error);
txtLastName.Focus();
txtLastName.Text = " ";
txtLastName.SelectAll();
lastname = false;
}
return firstname && lastname;
}
private Address ReadAddress()
{
Address address = new Address();
address.Street = txtStreet.Text;
address.City = txtCity.Text;
address.ZipCode = txtZipCode.Text;
address.Country = (Countries)cmbCountry.SelectedIndex;
return address;
}
private void button1_Click(object sender, EventArgs e)
{
Contact contact;
if (ReadInput(out contact))
{
UpdateGUI();
}
}
private void UpdateGUI()
{
lstContacts.Items.Clear();
lstContacts.Items.AddRange(m_contacts.GetContactsInfo());
lblCount.Text = m_contacts.Count().ToString();
}
private void lstContacts_SelectedIndexChanged(object sender, EventArgs e)
{
UpdateContactInfoFromRegistry();
}
private void UpdateContactInfoFromRegistry()
{
Contact contact = m_contacts.GetContact(lstContacts.SelectedIndex);
cmbCountry.SelectedIndex = (int)contact.AddressData.Country;
txtFirstName.Text = contact.FirstName;
txtLastName.Text = contact.LastName;
txtCity.Text = contact.AddressData.City;
txtStreet.Text = contact.AddressData.Street;
txtZipCode.Text = contact.AddressData.ZipCode;
}
}
This class then calls this class
public class ContactManager
{
private List<Contact> m_contactRegistry;
public ContactManager()
{
m_contactRegistry = new List<Contact>();
}
public int Count()
{
int count = m_contactRegistry.Count();
return count;
}
public bool CheckIndex(int index)
{
if (index >= 0 && index < m_contactRegistry.Count())
return true;
else return false;
}
public bool AddContact(string firstName, string lastName, Address addressIn)
{
Contact contactObj = new Contact();
bool result = false;
if (!result)
{
contactObj.FirstName = firstName;
contactObj.LastName = lastName;
contactObj.AddressData = addressIn;
m_contactRegistry.Add(contactObj);
result = true;
}
return result;
}
public bool AddContact(Contact contactIn)
{
if (contactIn == null)
{
return false;
}
else
{
m_contactRegistry.Add(contactIn);
return true;
}
}
public bool changeContact(Contact contactIn, int index)
{
if (CheckIndex(index))
{
Contact contact = (Contact)m_contactRegistry[index];
//contact.ToString = contactIn;
return true;
}
else return false;
}
public bool DeleteContact(int index)
{
if (CheckIndex(index))
{
m_contactRegistry.RemoveAt(index);
return true;
}
else return false;
}
public Contact GetContact(int index)
{
if (!CheckIndex(index))
return null;
else return m_contactRegistry[index];
}
public string[] GetContactsInfo()
{
string[] strInfoStrings = new string[m_contactRegistry.Count];
int i = 0;
foreach (Contact contactObj in m_contactRegistry)
{
strInfoStrings[i++] = contactObj.ToString();
}
return strInfoStrings;
}
}
Any help regarding why the arrays wont show up in the listbox would be much appriciated, thanks.
Your ReadName() always returns false, there for it never adds the contacts.
EDIT:
A clearer code
private Contact ReadInput()
{
Contact contact = new Contact();
contact.FirstName = txtFirstName.Text;
contact.LastName = txtLastName.Text;
contact.AddressData = new Address
{
Street = txtStreet.Text,
City = txtCity.Text,
ZipCode = txtZipCode.Text,
Country = (Countries) cmbCountry.SelectedIndex
};
return contact;
}
private bool ValidateContact(Contact contact)
{
if ( !InputUtility.ValidateString( contact.FirstName ) )
{
MessageBox.Show( "You must enter a first name with atleast one character (not a blank)", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error );
txtFirstName.Focus();
txtFirstName.Text = " ";
txtFirstName.SelectAll();
return false;
}
else if ( !InputUtility.ValidateString( contact.LastName ) )
{
MessageBox.Show( "You must enter a last name with atleast one character (not a blank)", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error );
txtLastName.Focus();
txtLastName.Text = " ";
txtLastName.SelectAll();
return false;
}
return true;
}
private void button1_Click( object sender, EventArgs e )
{
Contact contact = ReadInput();
if ( ValidateContact( contact ) )
{
m_contacts.AddContact(contact);
UpdateGUI();
}
}

How to only run methods when called?

I have a bunch of code below. However, I am hitting some bugs because the methods Move() and Genius() are running logic too much. I only want to two methods to run if they are being called by the submit click method. How can I do this?
namespace ShotgunApp
{
public partial class SingleGame : PhoneApplicationPage
{
public static class AmmoCount
{
public static int userAmmo = startVars.startAmmo;
public static int geniusAmmo = startVars.startAmmo;
}
public static class Global
{
public static int lives = 1;
public static string GeniusMove;
public static string UserMove;
}
public SingleGame()
{
InitializeComponent();
GeniusAmmo.Text = "ammo: " + AmmoCount.geniusAmmo;
UserAmmo.Text = "ammo: " + AmmoCount.userAmmo;
}
private void submit_Click(object sender, RoutedEventArgs e)
{
if (((String)submit.Content) == "Submit")
{
Move();
submit.Content = "Wait for Genius...";
uReload.IsEnabled = false;
uFire.IsEnabled = false;
uShield.IsEnabled = false;
Genius();
}
else if (((String)submit.Content) == "Go!")
{
GeniusSpeak.Text = "";
OutcomeDesc.Text = "You have " + Move() + " and Genius has " + Genius();
Outcome.Text = "ANOTHER ROUND...";
submit.Content = "Continue";
}
else if (((String)submit.Content) == "Continue")
{
uReload.IsEnabled = true;
uFire.IsEnabled = true;
uShield.IsEnabled = true;
OutcomeDesc.Text = "";
Outcome.Text = "";
submit.Content = "Submit";
}
}
public string Move()
{
if (uReload.IsChecked.HasValue && uReload.IsChecked.Value == true)
{
UserAmmo.Text = "ammo: " + ++AmmoCount.userAmmo;
Global.UserMove = "reloaded";
}
else if (uShield.IsChecked.HasValue && uShield.IsChecked.Value == true)
{
Global.UserMove = "shielded";
}
else if (uFire.IsChecked.HasValue && uFire.IsChecked.Value == true)
{
UserAmmo.Text = "ammo: " + --AmmoCount.userAmmo;
Global.UserMove = "fired";
}
else
{
submit.Content = "Enter a move!";
}
return Global.UserMove;
}
public string Genius()
{
GeniusSpeak.Text = "Genius has moved";
submit.Content = "Go!";
Random RandomNumber = new Random();
int x = RandomNumber.Next(0, 3);
if (x == 0)
{
Global.GeniusMove = "reloaded";
GeniusAmmo.Text = "ammo: " + ++AmmoCount.geniusAmmo;
}
else if (x == 1)
{
Global.GeniusMove = "shielded";
}
else if (x == 2)
{
Global.GeniusMove = "fired";
GeniusAmmo.Text = "ammo: " + ++AmmoCount.geniusAmmo;
}
return Global.GeniusMove;
}
}
}
Store the last results in data members:
private string lastMoveResult = string.Empty;
private string lastGeniusResult = string.Empty;
private void submit_Click(object sender, RoutedEventArgs e)
{
if (((String)submit.Content) == "Submit")
{
lastMoveResult = Move();
submit.Content = "Wait for Genius...";
uReload.IsEnabled = false;
uFire.IsEnabled = false;
uShield.IsEnabled = false;
lastGeniusResult = Genius();
}
else if (((String)submit.Content) == "Go!")
{
GeniusSpeak.Text = "";
OutcomeDesc.Text = "You have " + lastMoveResult + " and Genius has " + lastGeniusResult ;
Outcome.Text = "ANOTHER ROUND...";
submit.Content = "Continue";
}

Categories