ObservableCollection empty itself in foreach loop for no reason - c#

As the title says, my empty itself in middle of code.
I do not do any background/thread work so it couldn't empty itself in middle of executing code. It empty itself on one particular point every time.
ObservableCollection is proizvod.GrupeIPodgrupe in my case
Here is where it happens:
private void NamestiGrupeIPodgrupe()
{
foreach (TreeNode n in treeView1.Nodes)
{
if (proizvod.GrupeIPodGrupe.Grupe.Any(g => g.Id == (int)n.Tag))
{
n.Checked = true;
foreach (TreeNode n1 in n.Nodes) //Here it empty
{
if (proizvod.GrupeIPodGrupe.Podgrupe.Any(pg => pg.PodGrupaId == (int)n1.Tag))
{
n1.Checked = true;
}
}
}
else
n.Checked = false;
}
}
Here are images when I debug it step by step:
Here is full code of my Form class where this problem is happening:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Magacin.Sajt;
namespace Magacin
{
public partial class Sajt_Proizvod : Form
{
private Proizvod proizvod;
private Komercijalno.Roba roba;
public Sajt_Proizvod(int proizvodID)
{
InitializeComponent();
UcitajGrupeIPodgrupe();
this.roba = new Komercijalno.Roba(proizvodID);
UcitajProizvod(proizvodID);
k_jm_txt.Text = roba.Jm;
k_katBr_txt.Text = roba.KatBr;
k_naziv_txt.Text = roba.Naziv;
k_pdv_txt.Text = String.Format("{0:#.00}%", roba.Pdv);
k_robaid_txt.Text = roba.RobaId.ToString();
NamestiGrupeIPodgrupe();
}
private void PodesiPremaPravima()
{
if (!Korisnik.ImaPravo(200103))
{
w_naziv_txt.Enabled = false;
w_naziv_txt.BackColor = SystemColors.Info;
slika_txt.Enabled = false;
slika_txt.BackColor = SystemColors.Info;
w_opis_rtxt.Enabled = false;
w_opis_rtxt.BackColor = SystemColors.Info;
akcijskiArtikal_cb.Enabled = false;
akcijskiArtikal_cb.BackColor = SystemColors.Info;
aktivan_cb.Enabled = false;
aktivan_cb.BackColor = SystemColors.Info;
button2.BackColor = SystemColors.Info;
}
else
{
w_naziv_txt.Enabled = true;
w_naziv_txt.BackColor = SystemColors.Window;
slika_txt.Enabled = true;
slika_txt.BackColor = SystemColors.Window;
w_opis_rtxt.Enabled = true;
w_opis_rtxt.BackColor = SystemColors.Window;
akcijskiArtikal_cb.Enabled = true;
akcijskiArtikal_cb.BackColor = SystemColors.Window;
aktivan_cb.Enabled = true;
aktivan_cb.BackColor = SystemColors.Window;
}
}
private void NamestiGrupeIPodgrupe()
{
foreach (TreeNode n in treeView1.Nodes)
{
if (proizvod.GrupeIPodGrupe.Grupe.Any(g => g.Id == (int)n.Tag))
{
n.Checked = true;
foreach (TreeNode n1 in n.Nodes)
{
if (proizvod.GrupeIPodGrupe.Podgrupe.Any(pg => pg.PodGrupaId == (int)n1.Tag))
{
n1.Checked = true;
}
}
}
else
n.Checked = false;
}
}
private void UcitajProizvod()
{
proizvod = new Proizvod(proizvod.PROIZVODID);
w_proizvodId_txt.Text = proizvod.PROIZVODID.ToString();
w_naziv_txt.Text = proizvod.NAZIV.ToString();
w_katBr_txt.Text = proizvod.KATBR.ToString();
w_pdv_txt.Text = String.Format("{0}%", proizvod.PDV);
w_jm_txt.Text = proizvod.JM.ToString();
slika_txt.Text = proizvod.SLIKA.ToString();
kratakOpis_txt.Text = proizvod.KratakOpis;
w_opis_rtxt.Text = proizvod.OPIS;
akcijskiArtikal_cb.Checked = (proizvod.AKCIJSKI_ARTIKAL == 1) ? true : false;
aktivan_cb.Checked = (proizvod.AKTIVAN == 1) ? true : false;
}
private void UcitajProizvod(int poizvodId)
{
proizvod = new Proizvod(poizvodId);
w_proizvodId_txt.Text = proizvod.PROIZVODID.ToString();
w_naziv_txt.Text = proizvod.NAZIV.ToString();
w_katBr_txt.Text = proizvod.KATBR.ToString();
w_pdv_txt.Text = String.Format("{0}%", proizvod.PDV);
w_jm_txt.Text = proizvod.JM.ToString();
slika_txt.Text = proizvod.SLIKA.ToString();
kratakOpis_txt.Text = proizvod.KratakOpis;
w_opis_rtxt.Text = proizvod.OPIS;
akcijskiArtikal_cb.Checked = (proizvod.AKCIJSKI_ARTIKAL == 1) ? true : false;
aktivan_cb.Checked = (proizvod.AKTIVAN == 1) ? true : false;
}
private void UcitajGrupeIPodgrupe()
{
List<Grupa> grupe = Grupa.ListaSvihGrupa();
foreach(Grupa gp in grupe)
{
TreeNode tn = new TreeNode(gp.Naziv);
List<PodGrupa> pg = PodGrupa.ListaSvihPodgrupa(gp.Id);
if(pg != null && pg.Count > 0)
{
foreach(PodGrupa pgp in pg)
{
TreeNode tn1 = new TreeNode(pgp.Naziv);
tn1.Tag = pgp.PodGrupaId;
tn1.ToolTipText = "PodGrupa";
tn.Nodes.Add(tn1);
}
}
tn.Tag = gp.Id;
tn.ToolTipText = "Grupa";
treeView1.Nodes.Add(tn);
}
}
private void sacuvaj_btn_Click(object sender, EventArgs e)
{
if (Korisnik.ImaPravo(200103))
{
proizvod.Update();
MessageBox.Show(proizvod.errorMessage);
}
else
{
MessageBox.Show("Nemate pravo pristupa modulu [ 200103 ] ");
}
}
private void odbaci_btn_Click(object sender, EventArgs e)
{
UcitajProizvod();
}
private void novi_btn_Click(object sender, EventArgs e)
{
using (Sajt_NoviProizvod np = new Sajt_NoviProizvod())
{
np.ShowDialog();
}
}
private void w_naziv_txt_TextChanged(object sender, EventArgs e)
{
proizvod.NAZIV = w_naziv_txt.Text;
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void w_jm_txt_TextChanged(object sender, EventArgs e)
{
proizvod.JM = w_jm_txt.Text;
}
private void w_opis_rtxt_TextChanged(object sender, EventArgs e)
{
proizvod.OPIS = w_opis_rtxt.Text;
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void akcijskiArtikal_cb_CheckedChanged(object sender, EventArgs e)
{
proizvod.AKCIJSKI_ARTIKAL = Convert.ToInt32(akcijskiArtikal_cb.Checked);
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void aktivan_cb_CheckedChanged(object sender, EventArgs e)
{
proizvod.AKTIVAN = Convert.ToInt32(aktivan_cb.Checked);
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void button2_Click(object sender, EventArgs e)
{
using (Sajt_Paketi sp = new Sajt_Paketi(proizvod.PROIZVODID))
{
sp.ShowDialog();
}
}
private void slika_txt_TextChanged(object sender, EventArgs e)
{
proizvod.SLIKA = slika_txt.Text;
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void kratakOpis_txt_TextChanged(object sender, EventArgs e)
{
proizvod.KratakOpis = kratakOpis_txt.Text;
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void treeView1_AfterCheck(object sender, TreeViewEventArgs e)
{
if (e.Node.Parent != null)
{
if (e.Node.Parent.Parent != null)
{
e.Node.Parent.Parent.Checked = true;
}
e.Node.Parent.Checked = true;
}
if (e.Node.Tag.ToString() == "Grupa")
{
foreach (TreeNode tn in e.Node.Nodes)
{
tn.Checked = false;
}
}
ProveriGrupeIPodgrupe();
sacuvaj_btn.Enabled = true;
odbaci_btn.Enabled = true;
}
private void ProveriGrupeIPodgrupe()
{
proizvod.GrupeIPodGrupe.Reset();
foreach (TreeNode tn in treeView1.Nodes)
{
if (tn.Checked)
{
foreach (TreeNode tn1 in tn.Nodes)
{
if (tn1.Checked)
{
proizvod.GrupeIPodGrupe.Podgrupe.Add(new PodGrupa { PodGrupaId = Convert.ToInt32(tn1.Tag), GrupaId = Convert.ToInt32(tn.Tag) });
}
}
}
}
}
private void odbaci_btn_EnabledChanged(object sender, EventArgs e)
{
if (odbaci_btn.Enabled)
odbaci_btn.BackColor = Color.White;
else
odbaci_btn.BackColor = Color.DimGray;
}
private void sacuvaj_btn_EnabledChanged(object sender, EventArgs e)
{
if (sacuvaj_btn.Enabled)
sacuvaj_btn.BackColor = Color.White;
else
sacuvaj_btn.BackColor = Color.DimGray;
}
}
}
Here is my Proizvod class
public class Proizvod
{
#region Variables
public int PROIZVODID { get { return _PROIZVODID; } set { _PROIZVODID = value; } }
public string NAZIV { get { return _NAZIV; } set { _NAZIV = value; } }
public string OPIS { get { return _OPIS; } set { _OPIS = value; } }
public string JM { get { return _JM; } set { _JM = value; } }
public int AKCIJSKI_ARTIKAL { get { return _AKCIJSKI_ARTIKAL; } set { _AKCIJSKI_ARTIKAL = value; } }
public int AKTIVAN { get { return _AKTIVAN; } set { _AKTIVAN = value; } }
public string KATBR { get { return _KATBR; } set { _KATBR = value; } }
public double PDV { get { return _PDV; } set { _PDV = value; } }
public string SLIKA { get { return _SLIKA; } set { _SLIKA = value; } }
public string KratakOpis { get { return _KratakOpis; } set { _KratakOpis = value; } }
public GrupeIPodgrupe GrupeIPodGrupe { get { return _GrupeIPodGrupe; } }
public List<Paket> Paketi { get { return _Paketi; } }
public string errorMessage { get { return _errorMessage; } }
private int _PROIZVODID;
private string _NAZIV;
private string _OPIS;
private string _JM;
private int _AKCIJSKI_ARTIKAL;
private int _AKTIVAN;
private string _KATBR;
private double _PDV;
private string _SLIKA;
private string _KratakOpis;
private GrupeIPodgrupe _GrupeIPodGrupe;
private List<Paket> _Paketi;
private string fileNameSlika;
private string pathSlika;
string _errorMessage = "Sve je ok!";
#endregion
#region classes
public class GrupeIPodgrupe
{
public ReadOnlyCollection<Grupa> Grupe
{
get
{
return _Grupe.AsReadOnly();
}
}
public ObservableCollection<PodGrupa> Podgrupe
{
get
{
return _PodGrupe;
}
set
{
_PodGrupe = value;
}
}
private List<Grupa> _Grupe;
private ObservableCollection<PodGrupa> _PodGrupe;
private void HandleChange(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (PodGrupa pg in e.NewItems)
{
if (_Grupe.Count < 1 || !_Grupe.Any(g => g.Id == pg.GrupaId))
{
_Grupe.Add(new Grupa { Id = pg.GrupaId });
}
}
}
}
public GrupeIPodgrupe()
{
_PodGrupe = new ObservableCollection<PodGrupa>();
_PodGrupe.CollectionChanged += HandleChange;
}
public GrupeIPodgrupe(int proizvodId)
{
this._Grupe = Grupa.ListaGrupaProizvoda(proizvodId);
if(this.Grupe.Count > 0)
{
this.Podgrupe = PodGrupa.ListaPodgrupaProizvoda(Grupe[0].Id, proizvodId);
}
}
public GrupeIPodgrupe(TreeView treeView)
{
_Grupe = new List<Grupa>();
_PodGrupe = new ObservableCollection<PodGrupa>();
_PodGrupe.CollectionChanged += HandleChange;
foreach (TreeNode n in treeView.Nodes)
{
if(n.Checked)
{
foreach(TreeNode n1 in n.Nodes)
{
if(n1.Checked)
_PodGrupe.Add(new PodGrupa { GrupaId = (int)n.Tag, PodGrupaId = (int)n1.Tag });
}
}
}
}
public void Reset()
{
_Grupe = new List<Grupa>();
_PodGrupe = new ObservableCollection<PodGrupa>();
}
}
public class Paket
{
public int PaketId;
public int ProizvodId;
public double CenaBezPdv;
public double Kolicina;
}
#endregion
private Proizvod()
{
}
/// <summary>
/// Kreira klasu sa podacima proizvoda sa web-a
/// </summary>
/// <param name="ROBAID">Unikatni ID za stavku/proizvod/robu</param>
public Proizvod(int ROBAID)
{
if(ROBAID == null ) { throw new Exception("ROBAID ne moze biti NULL!"); }
string url = "censoredLink";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
_errorMessage = "Proizvod nije pronadjen u web bazi!";
break;
default:
Proizvod p = JsonConvert.DeserializeObject<Proizvod>(resp);
if(p == null)
{
MessageBox.Show("Unhandled error!");
return;
}
this._PROIZVODID = p.PROIZVODID;
this._NAZIV = p.NAZIV;
this._OPIS = p.OPIS;
this._JM = p.JM;
this._AKCIJSKI_ARTIKAL = p.AKCIJSKI_ARTIKAL;
this._AKTIVAN = p.AKTIVAN;
this._KATBR = p.KATBR;
this._PDV = p.PDV;
this._SLIKA = p.SLIKA;
this._KratakOpis = p.KratakOpis;
this._GrupeIPodGrupe = new GrupeIPodgrupe(p.PROIZVODID);
break;
}
}
public Proizvod(int RobaId, string Naziv, string Opis, string Jm, bool AkcijskiArtikal, bool Aktivan, string KatBr, double PDV, string Slika, string KratakOpis, GrupeIPodgrupe gip, List<Paket> paketi, string fileNameSlika, string filePathSlika)
{
this._PROIZVODID = RobaId;
this._NAZIV = Naziv;
this._OPIS = Opis;
this._JM = Jm;
this._AKCIJSKI_ARTIKAL = (AkcijskiArtikal) ? 1 : 0;
this._AKTIVAN = (Aktivan) ? 1 : 0;
this._KATBR = KatBr;
this._PDV = PDV;
this._SLIKA = Slika;
this._KratakOpis = KratakOpis;
this._GrupeIPodGrupe = gip;
this._Paketi = paketi;
this.fileNameSlika = fileNameSlika;
this.pathSlika = filePathSlika;
}
/// <summary>
/// Updateuje trenutne vrednosti proizvoda na sajt!
/// </summary>
public void Update()
{
#region Proizvod table
string url = String.Format("censoredLink");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
_errorMessage = "Doslo je do greske!";
break;
case "1":
_errorMessage = "Uspesno updateovan prozvod na WEB-u";
break;
case "2":
_errorMessage = "Proizvod sa tim ID-em nije pronadjen u bazi!";
break;
default:
break;
}
#endregion
DeGrupisi();
Grupisi();
}
public void Publish()
{
PublishProizvod();
Grupisi();
PublishPakete();
Thread t = new Thread(PublishSliku);
t.Start();
}
public static List<Proizvod> SviProizvodi()
{
List<Proizvod> list = new List<Proizvod>();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string url = "censoredLink";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
break;
default:
list = JsonConvert.DeserializeObject<List<Proizvod>>(resp);
break;
}
return list;
}
/// <summary>
/// Skida proizvodu bilo kakvu grupu i podgrupu
/// </summary>
private void DeGrupisi()
{
string url = "censoredLink";
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0":
_errorMessage = "Doslo je do greske prilikom brisanja proizvoda iz grupa i podgrupa";
break;
case "1":
_errorMessage = "Uspesno degrupisani proizvodi!";
break;
default:
_errorMessage = "Unhandled error";
break;
}
}
private void Grupisi()
{
foreach(PodGrupa pg in GrupeIPodGrupe.Podgrupe)
{
string url = string.Format("censoredLink");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0":
_errorMessage = "Doslo je do greske prilikom grupisanja proizvoda";
break;
case "1":
_errorMessage = "Proizvod je uspesno grupisan!";
break;
case "2":
_errorMessage = "Proizvod je vec u grupi!";
break;
default:
_errorMessage = "Unhandled error";
break;
}
}
}
private void PublishProizvod()
{
string url = string.Format("censoredLink");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0":
_errorMessage = "Doslo je do greske prilikom kreiranja proizvoda";
break;
case "1":
_errorMessage = "Proizvod je uspesno kreiran!";
break;
case "2":
_errorMessage = "Proizvod vec postoji u web bazi!";
break;
default:
_errorMessage = "Unhandled error";
break;
}
}
private void PublishPakete()
{
foreach (Proizvod.Paket p in Paketi)
{
string url = string.Format("censoredLink");
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0":
_errorMessage = "Doslo je do greske prilikom dodavanja paketa";
break;
case "1":
_errorMessage = "Paketi uspesno dodati!";
break;
default:
_errorMessage = "Unhandled error";
break;
}
}
}
private void PublishSliku()
{
if (!string.IsNullOrWhiteSpace(_SLIKA))
{
M.preventClosing = true;
MessageBox.Show("Dodavanje slike ce potrajati i zavisi od brzine interneta koju imate i nece vam dozvoliti zatvaranje programa!\nDodavanje slike se vrsi u pozadini te mozete nastaviti sa radom u programu!");
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential("username", "password");
client.UploadFile("censoredLink");
}
M.preventClosing = false;
}
}
}

Your code is calling:
proizvod.GrupeIPodGrupe.Reset()
which is emptying the ObservableCollection.

Related

Xamarin : Different behaviour Android / iOS (static class ?)

I'm taking over a project on Xamarin.
It work on android and I want it to work on iOS.
Initially, it have been done for that so I expected it work with maybe only settings ?
Anyway it work on Android but not on iOS.
I have this code :
public App()
{
Debug.WriteLine(Current.Properties); //return default value
try
{
ViewModelLocator.MainViewModel.RestoreState(Current.Properties);
BindingContext = ViewModelLocator.MainViewModel;
MainTabPage = new SGC400Tab();
MainPage = MainTabPage;
}
catch (Exception ex)
{
Debug.WriteLine(ex);
}
}
public static class ViewModelLocator
{
private static GlobalViewModel _myViewModel = new GlobalViewModel();
public static GlobalViewModel MainViewModel
{
get
{
return _myViewModel;
}
}
}
public class GlobalViewModel : INotifyPropertyChanged
{
public void RestoreState(IDictionary<string, object> dictionary)
{
Thing1.SelectedUnitySystem_Presure = GetDictionaryEntry(dictionary, "SavedUnitySystem_Pression", "Bars");
Thing1.SelectedUnitySystem_Flow = GetDictionaryEntry(dictionary, "SavedUnitySystem_Debit", "m3/h");
Thing1.SelectedUnitySystem_Temperature = GetDictionaryEntry(dictionary, "SavedUnitySystem_Temperature", "°C");
Thing1.SelectedLanguageKey = GetDictionaryEntry(dictionary, "SavedLanguage", "en");
}
}
Which return an error :
System.NullReferenceException on line :
private static GlobalViewModel _myViewModel = new GlobalViewModel();
I'm a bit puzzled by the fact it work on android... but not on iOS...
I have to tell I'm pretty new on Xamarin, may you give me some pointer ?
Thank you in advance !
PS : Class GlobalViewModel here :
public class GlobalViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
//#####################################
//Enneigeur
public Enneigeur _Enneigeur1 = new Enneigeur();
public Enneigeur Enneigeur1
{
get { return _Enneigeur1; }
set
{
_Enneigeur1 = value;
}
}
//Com
public ComSGC400 _comSGC400 = new ComSGC400();
public ComSGC400 ComSGC400
{
get { return _comSGC400; }
set { _comSGC400 = value; }
}
public const int TIMOUT_COM_MS = 500;
public const int DELAI_ENTRE_TRAME_MS = 1000;
//#####################################
//Bluetooth
public ObservableCollection<string> ListOfDevices { get; set; } = new ObservableCollection<string>();
public string inputBuffer;
public string SelectedBthDevice { get;set; } = "";
private bool _isConnected { get; set; } = false;
public bool IsConnected {
get { return _isConnected; }
set
{
_isConnected = value;
if (_isConnected == true)
{
((App)Application.Current).AddPages();
} else
{
((App)Application.Current).RemovePages();
}
}
}
private bool _isSelectedBthDevice { get { if (string.IsNullOrEmpty(SelectedBthDevice)) return false; return true; }}
public bool IsConnectEnabled { get { if (_isSelectedBthDevice == false) return false; return !IsConnected; }}
public bool IsDisconnectEnabled { get { if (_isSelectedBthDevice == false) return false; return IsConnected; } }
public Color ConnectBackgroundcolor { get { if (IsConnectEnabled) return Color.Green; return Color.FromRgb(48, 48, 48); } }
public Color DisconnectBackgroundColor { get { if (IsDisconnectEnabled) return Color.Red; return Color.FromRgb(48, 48, 48); } }
public bool IsConnectionInit { get { if (EtatGrafcet_loop < 2 || IsConnected == false ) return false; return true; } }
public bool IsModeManuOK { get { if (EtatGrafcet_loop >= 2 && IsConnected == true && _Enneigeur1.Manu == true) return true; return false; } }
public bool IsBoutonRotaOK { get { if (EtatGrafcet_loop >= 2 && IsConnected == true && ( _Enneigeur1._VersionSGC400 > 10213 || _Enneigeur1.Manu == true)) return true; return false; } }
public bool IsPickerEnabled { get { return !IsConnected; }}
public bool IsBalayageDispo { get { if (EtatGrafcet_loop < 2 || IsConnected == false || _Enneigeur1.OptionBalayageDispo == false) return false; return true; } }
public LocalizedResources Resources { get; private set;}
public Color Mode_Manu_Button_Text_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.Gray;
else
return Color.White;
}
}
public Color Mode_Manu_Button_Color {
get {
if (EtatGrafcet_loop < 2)
return Color.FromRgb(48, 48, 48);
else
{
if (_Enneigeur1.ModeMarche == 1) return Color.Green; return Color.Black;
}
}
}
public Color Mode_Stop_Button_Text_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.Gray;
else
return Color.White;
}
}
public Color Mode_Stop_Button_Color {
get
{
if (EtatGrafcet_loop < 2)
return Color.FromRgb(48, 48, 48);
else
{
if (_Enneigeur1.ModeMarche == 2) return Color.Green; return Color.Black;
}
}
}
public Color Mode_Forcage_Button_Text_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.Gray;
else
return Color.White;
}
}
public Color Mode_Forcage_Button_Color
{
get
{
if (EtatGrafcet_loop < 2)
return Color.FromRgb(48, 48, 48);
else
{
if (_Enneigeur1.ModeMarche == 0) return Color.Green; return Color.Black;
}
}
}
private CancellationTokenSource _ct { get; set; }
private int EtatGrafcet_loop { get; set; }
private DateTime timer_send = DateTime.Now;
private bool envoiContinu = false;
private string envoiWrite = "";
private async Task Loop()
{
string bufferEnvoi = "";
bool res;
int erreur_cryptage = 0;
EtatGrafcet_loop = 0;
int reponseLen = 0;
_Enneigeur1.ResetValues();
_ct = new CancellationTokenSource();
ComSGC400.AddrSGC400 = Convert.ToUInt16(SelectedBthDevice.Substring(5));
while (_ct.IsCancellationRequested == false)
{
switch (EtatGrafcet_loop)
{
case 0://Envoi trame clé crypté
if (DateTime.Now > timer_send.AddMilliseconds(DELAI_ENTRE_TRAME_MS)) //Temps entre trames
{
//Test d'echange de clé de cryptage
inputBuffer = "";
reponseLen = ComSGC400.Create_Trame_getKey(ref bufferEnvoi);
if (bufferEnvoi.Length > 0)
{
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", bufferEnvoi);
timer_send = DateTime.Now;
EtatGrafcet_loop = 1;
}
}
break;
case 1: //attente reception clé crypté
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)){ EtatGrafcet_loop = 0; break; } //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= reponseLen)
{
inputBuffer = inputBuffer.Substring(0, reponseLen);
res = ComSGC400.Update_ProtectionKey( inputBuffer);
if (res == true)
{
//cle cryptage OK
bufferEnvoi = "";
EtatGrafcet_loop = 2;
erreur_cryptage = 0;
}
else
{
//cle cryptage non ok
bufferEnvoi = "";
EtatGrafcet_loop = 0;
}
inputBuffer = "";
}
}
break;
case 2: //envoi trame readMain
if (envoiWrite != "")
EtatGrafcet_loop = 10; //envoi write
else
{
if (DateTime.Now > timer_send.AddMilliseconds(DELAI_ENTRE_TRAME_MS)) //Temps entre trames
{
reponseLen = ComSGC400.Create_Trame_ReadMain(ref bufferEnvoi);
if (bufferEnvoi.Length > 0)
{
inputBuffer = "";
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", bufferEnvoi);
timer_send = DateTime.Now;
EtatGrafcet_loop = 3;
}
}
}
break;
case 3: //attente reponse trame readMain
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)) {
EtatGrafcet_loop = 20; break;
} //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= reponseLen)
{
inputBuffer = inputBuffer.Substring(0, reponseLen);
res = ComSGC400.Update_Enneigeur( inputBuffer, ref _Enneigeur1);
if (res == true)
{
//Message OK
bufferEnvoi = "";
EtatGrafcet_loop = 4;//Passage readCom
erreur_cryptage = 0;
_Enneigeur1.LastRead = DateTime.Now;
}
else
{
//Message NON OK
EtatGrafcet_loop = 20;
}
inputBuffer = "";
}
}
break;
case 4: //envoi trame readCom
if (envoiWrite != "")
EtatGrafcet_loop = 10; //envoi write
else
{
if (DateTime.Now > timer_send.AddMilliseconds(50)) //Temps entre trames
{
reponseLen = ComSGC400.Create_Trame_ReadCom(ref bufferEnvoi);
if (bufferEnvoi.Length > 0)
{
inputBuffer = "";
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", bufferEnvoi);
timer_send = DateTime.Now;
EtatGrafcet_loop = 5;
}
}
}
break;
case 5: //attente reponse trame readCom
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)) {
EtatGrafcet_loop = 21; break;
} //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= reponseLen)
{
inputBuffer = inputBuffer.Substring(0, reponseLen);
res = ComSGC400.Update_Enneigeur( inputBuffer, ref _Enneigeur1);
if (res == true)
{
//Message OK
bufferEnvoi = "";
EtatGrafcet_loop = 2; //Retour read main
erreur_cryptage = 0;
_Enneigeur1.LastRead = DateTime.Now;
if (_Enneigeur1.Reset)
Send_value_bluetooth("reset", false);
}
else
{
//Message NON OK
EtatGrafcet_loop = 21;
}
inputBuffer = "";
}
}
break;
case 10: //envoi trame Write
inputBuffer = "";
Xamarin.Forms.MessagingCenter.Send<App, string>((App)Xamarin.Forms.Application.Current, "WriteDatas", envoiWrite);
timer_send = DateTime.Now;
EtatGrafcet_loop =11;
break;
case 11: //attente reponse trame Write
if (DateTime.Now > timer_send.AddMilliseconds(TIMOUT_COM_MS)) { EtatGrafcet_loop = 20; break; } //timeout
if (inputBuffer != null)
{
ComSGC400.Trame_RechercheDebutTrame(ref inputBuffer);
if (inputBuffer.Length >= 16)
{
bufferEnvoi = "";
if (envoiContinu)
{
EtatGrafcet_loop = 10; //envoi continu
}
else
{
envoiWrite = "";
EtatGrafcet_loop = 2; //Retour read main
}
erreur_cryptage = 0;
_Enneigeur1.LastWrite = DateTime.Now;
inputBuffer = "";
}
}
break;
case 20://Erreur de reception trame readMain
bufferEnvoi = "";
erreur_cryptage = erreur_cryptage + 1;
envoiWrite = "";
if (erreur_cryptage > 3)
{
_Enneigeur1.ResetValues();
erreur_cryptage = 0;
EtatGrafcet_loop = 0;
}
else
{
EtatGrafcet_loop = 2;
}
break;
case 21://Erreur de reception trame readCom
bufferEnvoi = "";
erreur_cryptage = erreur_cryptage + 1;
envoiWrite = "";
if (erreur_cryptage > 3)
{
_Enneigeur1.ResetValues();
erreur_cryptage = 0;
EtatGrafcet_loop = 0;
}
else
{
EtatGrafcet_loop = 4;
}
break;
default:
EtatGrafcet_loop = 0;
break;
}
await Task.Delay(10);
}
EtatGrafcet_loop = 0;
}
public void Send_value_bluetooth(string nom_param, bool value)
{
if (value == true) Send_value_bluetooth( nom_param, 1); else Send_value_bluetooth(nom_param, 0);
}
public void Send_value_bluetooth(string nom_param, double value)
{
//la modif de Enneigeur1 entraine l'envoi d'une trame WRITE en bluetooth (si la liaison est OK)
string bufferEnvoi = "";
if (EtatGrafcet_loop >= 2)
{
switch(nom_param.ToLower())
{
Cases...
}
}
}
public void ExitApp()
{
// Disconnect from bth device
DependencyService.Get<IBtInterface>().Disconnect();
MessagingCenter.Unsubscribe<App, string>(this, "ReadDatas");
IsConnected = false;
if (_ct != null)
{
System.Diagnostics.Debug.WriteLine("Send a cancel to task!");
_ct.Cancel();
}
}
public GlobalViewModel()
{
Resources = new LocalizedResources(typeof(AppResources), Enneigeur1._SelectedLanguageKey
);
MessagingCenter.Subscribe<App>(this, "Sleep", (obj) =>
{
// When the app "sleep", I close the connection with bluetooth
if (IsConnected)
DependencyService.Get<IBtInterface>().Disconnect();
});
MessagingCenter.Subscribe<App>(this, "Resume", (obj) =>
{
// When the app "resume" I try to restart the connection with bluetooth
if (IsConnected)
DependencyService.Get<IBtInterface>().Connect(SelectedBthDevice);
});
this.InitCommand = new Command(() =>
{
// Try to connect to a bth device
DependencyService.Get<IBtInterface>().Init();
});
this.ConnectCommand = new Command(() =>
{
EtatGrafcet_loop = 0;
// Try to connect to a bth device
IsConnected = DependencyService.Get<IBtInterface>().Connect(SelectedBthDevice);
//second essai
if (IsConnected == false) IsConnected = DependencyService.Get<IBtInterface>().Connect(SelectedBthDevice);
if (IsConnected == true)
{
// initialisation des echange de données
MessagingCenter.Subscribe<App, string>(this, "ReadDatas", (sender, arg) =>
{
//inputBuffer = inputBuffer + arg;
inputBuffer = inputBuffer + arg;
});
Task.Run(async () => Loop());
}else
{
//erreur aux 2 tentatives de connection
//Task.Run(async () => ((App)Application.Current).OpenTextBoxDialog());
((App)Application.Current).OpenTextBoxDialog();
}
});
this.DisconnectCommand = new Command(() =>
{
EtatGrafcet_loop = 0;
ExitApp();
});
this.RefreshListDeviceCommand = new Command(() =>
{
try
{
ListOfDevices = DependencyService.Get<IBtInterface>().PairedDevices();
}
catch (Exception ex)
{
Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
}
});
// At startup, I load all paired devices
try
{
ListOfDevices = DependencyService.Get<IBtInterface>().PairedDevices();
}
catch (Exception ex)
{
Application.Current.MainPage.DisplayAlert("Attention", ex.Message, "Ok");
}
}
private object Await(App current)
{
throw new NotImplementedException();
}
public ICommand InitCommand { get; protected set; }
public ICommand ConnectCommand { get; protected set; }
public ICommand DisconnectCommand { get; protected set; }
public ICommand RefreshListDeviceCommand { get; protected set; }
public void SaveState(IDictionary<string, object> dictionary)
{
dictionary["SavedLanguage"] = Enneigeur1._SelectedLanguageKey;
dictionary["SavedUnitySystem_Pression"] = Enneigeur1.SelectedUnitySystem_Presure;
dictionary["SavedUnitySystem_Debit"] = Enneigeur1.SelectedUnitySystem_Flow;
dictionary["SavedUnitySystem_Temperature"] = Enneigeur1.SelectedUnitySystem_Temperature;
}
public void RestoreState(IDictionary<string, object> dictionary)
{
Enneigeur1.SelectedUnitySystem_Presure = GetDictionaryEntry(dictionary, "SavedUnitySystem_Pression", "Bars");
Enneigeur1.SelectedUnitySystem_Flow = GetDictionaryEntry(dictionary, "SavedUnitySystem_Debit", "m3/h");
Enneigeur1.SelectedUnitySystem_Temperature = GetDictionaryEntry(dictionary, "SavedUnitySystem_Temperature", "°C");
Enneigeur1.SelectedLanguageKey = GetDictionaryEntry(dictionary, "SavedLanguage", "en");
}
public T GetDictionaryEntry<T>(IDictionary<string, object> dictionary,
string key, T defaultValue)
{
if (dictionary.ContainsKey(key))
return (T)dictionary[key];
return defaultValue;
}
}

Class creator enters multiple class constructors

I have code like this:
public class Paket
{
public int PaketID { get { return _PaketID; } set { _PaketID = value; } }
public int ProizvodID { get { return _ProizvodID; } set { _ProizvodID = value; } }
public double Kolicina { get { return _Kolicina; } set { _Kolicina = value; } }
public double CenaBezPdv { get { return _CenaBezPdv; } set { _CenaBezPdv = value; } }
private int _PaketID;
private int _ProizvodID;
private double _Kolicina;
private double _CenaBezPdv;
public string _errorMessage { get; set; }
private Paket()
{
}
public Paket(int proizvodID)
{
if (proizvodID == null) { throw new Exception("ProizvodID ne moze biti NULL!"); }
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string url = "https://www.new.termodom.rs/Php/Proizvodi/Paketi/GetOne.php?proizvodid=" + proizvodID;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
_errorMessage = "Paket nije pronadjen u web bazi!";
break;
default:
Paket p = JsonConvert.DeserializeObject<Paket>(resp);
this._PaketID = p.PaketID;
this._ProizvodID = p.ProizvodID;
this._Kolicina = p.Kolicina;
this._CenaBezPdv = p.CenaBezPdv;
break;
}
}
public static List<Paket> SviPaketi(int ProizvodID)
{
List<Paket> list = new List<Paket>();
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;
string url = "https://www.new.termodom.rs/Php/Proizvodi/Paketi/GetAll.php?proizvodid=" + ProizvodID;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string resp = new StreamReader(response.GetResponseStream()).ReadToEnd();
switch (resp)
{
case "0": //Nije pronadjen proizvod
break;
default:
list = JsonConvert.DeserializeObject<List<Paket>>(resp);
break;
}
return list;
}
}
When i run function like this List<Proizvod> myList = Proizvod.SviPaketi(139) i am getting some error (i do not know now which one it was but it is not important for my question).
When i started debugging i saw that JsonConvert.DeserializeObject<List<Paket>>(resp); doesn't enter only private Paket() which is empty but public Paket(int proizvodID) which has some code inside it.
So my question is why did JsonConvert.DeserializeObject<List<Paket>>(resp); triggered public Paket(int proizvodID) when i haven't passed any parameter to it?
JSON de-serializer will prefer a public constructor. You can however make it use the private constructor using a ConstructorHandling. Check this example

raspberry pi not sending to windowsform

Any idea why my visual studio doesn't send to windowsform from pi but it does send when i'm using my school's visual studio ( same version ). Do I have to download any specific thing or whatsoever to make it work? Please help.
Here's my code in case too. Would be cool if some1 can go through it and help me with it ( school's project ) Much appreciated !
string strConnectionString =
ConfigurationManager.ConnectionStrings["DataCommsDBConnection"].ConnectionString;
DataComms dataComms;
public delegate void myprocessDataDelegate(string strData);
private void saveWaterSensorDataToDB(string strTime, string strWaterValue, string strStatus)
{
SqlConnection myConnect = new SqlConnection(strConnectionString);
string strCommandText = "INSERT MySensor (TimeOccurred, SensorValue, SensorStatus) +" +
"VALUES (#time, #value, #status)";
SqlCommand updateCmd = new SqlCommand(strCommandText, myConnect);
updateCmd.Parameters.AddWithValue("#time", strTime);
updateCmd.Parameters.AddWithValue("#value", strWaterValue);
updateCmd.Parameters.AddWithValue("#status", strStatus);
myConnect.Open();
int result = updateCmd.ExecuteNonQuery();
myConnect.Close();
}
private string extractStringValue(string strData, string ID)
{
string result = strData.Substring(strData.IndexOf(ID) + ID.Length);
return result;
}
private float extractFloatValue(string strData, string ID)
{
return (float.Parse(extractStringValue(strData, ID)));
}
private void handleWaterSensorData(string strData, string strTime, string ID)
{
string strWaterValue = extractStringValue(strData, ID);
txtWaterValue.Text = strWaterValue;
txtWaterLevel.Text = strWaterValue;
float fWaterValue = extractFloatValue(strData, ID);
string status = "";
if (fWaterValue <= 500)
status = "Dry";
else
status = "Wet";
txtRoomStatus.Text = status;
}
private void handleButtonData(string strData, string strTime, string ID)
{
string strbuttonValue = extractStringValue(strData, ID);
txtButtonValue.Text = strbuttonValue;
txtDoorBell.Text = strbuttonValue;
}
private void extractSensorData(string strData, string strTime)
{
if (strData.IndexOf("WaterLevel=") != -1)
handleWaterSensorData(strData, strTime, "WaterLevel=");
else if (strData.IndexOf("BUTTON=") != -1)
handleButtonData(strData, strTime, "BUTTON=");
}
public void handleSensorData(string strData)
{
string dt = DateTime.Now.ToString();
extractSensorData(strData, dt);
string strMessage = dt + ":" + strData;
lbDataComms.Items.Insert(0, strMessage);
}
public void processDataReceive(string strData)
{
myprocessDataDelegate d = new myprocessDataDelegate(handleSensorData);
lbDataComms.Invoke(d, new object[] { strData });
}
public void commsDataReceive(string dataReceived)
{
processDataReceive(dataReceived);
}
public void commsSendError(string errMsg)
{
MessageBox.Show(errMsg);
processDataReceive(errMsg);
}
private void InitComms()
{
dataComms = new DataComms();
dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);
dataComms.dataSendErrorEvent += new DataComms.DataSendErrorDelegate(commsSendError);
}
public frmDataComms()
{
InitializeComponent();
}
private void frmDataComms_Load(object sender, EventArgs e)
{
InitComms();
}
private void btnClear_Click(object sender, EventArgs e)
{
lbDataComms.Items.Clear();
}
private void btnSendLight_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDWATER");
}
private void btnSendButton_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDBUTTON");
}
private void btnCmd_Click(object sender, EventArgs e)
{
dataComms.sendData(txtCmd.Text);
}
private void btnSendAll_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDALL");
}
private void btnSendTemp_Click(object sender, EventArgs e)
{
dataComms.sendData("SENDTEMP");
}
}
Form ***
namespace DataCommsRpi
{
public sealed class StartupTask : IBackgroundTask
{
const int MODE_SENDWATER = 1;
const int MODE_SENDBUTTON = 2;
const int MODE_SENDALL = 3;
const int MODE_SENDTEMP = 4;
static int curMode;
Pin waterPin = Pin.AnalogPin2;
IButtonSensor button = DeviceFactory.Build.ButtonSensor(Pin.DigitalPin4);
Pin tempPin = Pin.AnalogPin0;
DataComms dataComms;
string strDataReceived = "";
private bool buttonPressed = false;
private bool prevButtonStatus = false;
int moistureAdcValue = 800;
double tempDegree = 20;
private bool moistureWet = false;
private bool moistureDry = false;
private bool tempHot = false;
private bool tempCold = false;
private void Sleep(int NoOfMs)
{
Task.Delay(NoOfMs).Wait();
}
private async void startWaterMonitoring()
{
int iPrevAdcValue = 800, iReadAdcValue, iDiff;
await Task.Delay(100);
while (true)
{
Sleep(500);
iReadAdcValue = DeviceFactory.Build.GrovePi().AnalogRead(waterPin);
if (iPrevAdcValue > iReadAdcValue)
iDiff = iPrevAdcValue - iReadAdcValue;
else
iDiff = iReadAdcValue - iPrevAdcValue;
iPrevAdcValue = iReadAdcValue;
if (iDiff < 100)
moistureAdcValue = iReadAdcValue;
}
}
private async void startTempMonitoring()
{
await Task.Delay(100);
int adcValue; double tempCalculated = 0, R;
while (true)
{
Sleep(1000);
adcValue = DeviceFactory.Build.GrovePi().AnalogRead(tempPin);
int B = 4250, R0 = 100000;
R = 100000 * (1023.0 - adcValue) / adcValue;
tempCalculated = 1 / (Math.Log(R / R0) / B + 1 / 298.15) - 273.15;
if (!Double.IsNaN(tempCalculated))
tempDegree = tempCalculated;
}
}
private async void startButtonMonitoring()
{
await Task.Delay(100);
while(true)
{
Sleep(100);
string buttonState = button.CurrentState.ToString();
if (buttonState.Equals("On"))
{
Sleep(100);
buttonState = button.CurrentState.ToString();
if(buttonState.Equals("On"))
{
buttonPressed = true;
}
}
}
}
private void commsDataReceive(string dataReceived)
{
strDataReceived = dataReceived;
Debug.WriteLine("Data Received : " + strDataReceived);
}
private void sendDataToWindows(string strDataOut)
{
try
{
dataComms.sendData(strDataOut);
Debug.WriteLine("Sending Msg : " + strDataOut);
}
catch(Exception)
{
Debug.WriteLine("ERROR. Did you forget to initComms()?");
}
}
private void initComms()
{
dataComms = new DataComms();
dataComms.dataReceiveEvent += new DataComms.DataReceivedDelegate(commsDataReceive);
}
private void handleModeSendWater()
{
if (moistureAdcValue <= 500)
moistureWet = true;
else
moistureWet = false;
if (moistureAdcValue <= 500 && moistureDry != moistureWet)
sendDataToWindows("WaterLevel=" + moistureAdcValue + " wet");
if (moistureAdcValue > 500 && moistureDry != moistureWet)
sendDataToWindows("WaterLevel=" + moistureAdcValue + " dry");
moistureDry = moistureWet;
if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON===");
}
else if (strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
strDataReceived = "";
}
private void handleModeSendTemperature()
{
if (tempDegree <= 31)
tempCold = true;
else
tempCold = false;
if (tempDegree <= 31 && tempCold != tempHot)
{
Sleep(3000);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : cold");
}
else if (tempDegree >= 32 && tempCold != tempHot)
{
Sleep(3000);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2") + " : hot");
}
if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON===");
}
else if (strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
}
}
private void handleModeSendButton()
{
if(buttonPressed != prevButtonStatus)
{
sendDataToWindows("BUTTON=" + buttonPressed);
}
prevButtonStatus = buttonPressed;
buttonPressed = false;
if(strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
}
else if(strDataReceived.Equals("SENDALL"))
{
curMode = MODE_SENDALL;
Debug.WriteLine("===Entering MODE_SENDALL");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
}
private void handleModeSendAll()
{
Sleep(5000);
sendDataToWindows("Water Level=" + moistureAdcValue);
sendDataToWindows("Temperature = " + tempDegree.ToString("N2"));
if (strDataReceived.Equals("SENDWATER"))
{
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER");
}
else if (strDataReceived.Equals("SENDBUTTON"))
{
curMode = MODE_SENDBUTTON;
Debug.WriteLine("===Entering MODE_SENDBUTTON");
}
else if (strDataReceived.Equals("SENDTEMP"))
{
curMode = MODE_SENDTEMP;
Debug.WriteLine("===Entering MODE_SENDTEMP");
}
}
public void Run(IBackgroundTaskInstance taskInstance)
{
//
// TODO: Insert code to perform background work
//
// If you start any asynchronous methods here, prevent the task
// from closing prematurely by using BackgroundTaskDeferral as
// described in http://aka.ms/backgroundtaskdeferral
//
initComms();
startButtonMonitoring();
startWaterMonitoring();
startTempMonitoring();
curMode = MODE_SENDWATER;
Debug.WriteLine("===Entering MODE_SENDWATER===");
while (true)
{
Sleep(300);
if (curMode == MODE_SENDWATER)
handleModeSendWater();
else if (curMode == MODE_SENDBUTTON)
handleModeSendButton();
else if (curMode == MODE_SENDALL)
handleModeSendAll();
else if (curMode == MODE_SENDTEMP)
handleModeSendTemperature();
else
Debug.WriteLine("ERROR: Invalid Mode. Please check your logic");
}
}
}
}

How to delete datagridview item that is bound to variable and then update

I was just wondering, how do I delete the selected datagridview item, therefore deleting the item member in the variable and therefore updating the table and textfile?
frmMainPage:
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Windows.Forms;
using AForge.Video;
using AForge.Imaging;
using AForge.Imaging.Filters;
using AForge;
using AForge.Video.DirectShow;
using System.Drawing.Imaging;
namespace BusinessSoftware
{
public partial class frmMainPage : Form
{
private FilterInfoCollection VideoCaptureDevices;
private VideoCaptureDevice FinalVideoSource;
Bitmap image;
int currentlySelectedRow;
string currentlySelectedName;
int currentlySelectedId;
int currentlySelectedAuthority;
bool isCurrentlyUserLoginPage;
bool isCurrentlyAdminLoginPage;
bool isCurrentlyForgotPasswordPage;
bool isCurrentlyViewEmployeesPage;
bool isCurrentlyScanBarcodePage;
bool isCurrentlyEmployeeFoundPage;
bool isCurrentlyEditEmployeeDetailsPage;
DataTable table = new DataTable();
bool isCurrentlyControlPanelPage;
string txtUsernameFieldPlaceholder;
string btnLoginValue;
string employeeDetailsFileContents;
string userLoginDetailsFileContents;
string[] employeeDetails;
string[] userLoginDetails;
string[] employeeInformationElements;
List<string> employeeDetailElements = new List<string>();
string[] userLoginInformationElements;
List<string> userLoginDetailElements = new List<string>();
string isAUser;
string enteredPassword;
string usernameOfForgottenUser;
string passwordOfForgottenUser;
public frmMainPage()
{
InitializeComponent();
}
private void frmMainPage_Load(object sender, EventArgs e)
{
HideEverything();
btnForgotPassword.Show();
txtUsernameField.Text = txtUsernameFieldPlaceholder;
txtPasswordField.Text = "Password";
FormBorderStyle = FormBorderStyle.None;
WindowState = FormWindowState.Maximized;
GlobalVariables.emailSent = false;
btnLoginValue = "Login";
btnLogin.Text = btnLoginValue;
lblLoginTypePage.Text = "User Login";
isCurrentlyUserLoginPage = true;
isCurrentlyAdminLoginPage = false;
isCurrentlyForgotPasswordPage = false;
txtUsernameFieldPlaceholder = "Username";
txtUsernameField.Text = txtUsernameFieldPlaceholder;
GetAndStoreEmployeeInformation();
GetAndStoreUserInformation();
btnFocusOnThis.Text = "";
btnFocusOnThis.Focus();
}
private void btnLoginTypePage_Click(object sender, EventArgs e)
{
if (isCurrentlyUserLoginPage)
{
AdminLoginPage();
}
else if (isCurrentlyAdminLoginPage)
{
UserLoginPage();
}
else
{
UserLoginPage();
}
}
private void txtUsernameField_Leave(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(txtUsernameField.Text))
{
txtUsernameField.Text = txtUsernameFieldPlaceholder;
}
}
private void txtUsernameField_Enter(object sender, EventArgs e)
{
txtUsernameField.Text = "";
}
private void txtPasswordField_Leave(object sender, EventArgs e)
{
if (String.IsNullOrWhiteSpace(txtPasswordField.Text))
{
txtPasswordField.PasswordChar = '\0';
txtPasswordField.Text = "Password";
}
}
private void txtPasswordField_Enter(object sender, EventArgs e)
{
txtPasswordField.Text = "";
txtPasswordField.PasswordChar = '*';
}
private void frmMainPage_MouseClick(object sender, MouseEventArgs e)
{
if (txtPasswordField.Focused || txtUsernameField.Focused)
{
btnFocusOnThis.Focus();
}
}
private void frmLoginPage_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyValue == 13 && (txtPasswordField.Focused || txtUsernameField.Focused))
{
btnLogin.PerformClick();
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
if (isCurrentlyAdminLoginPage)
{
if (txtUsernameField.Text == "admin" && txtPasswordField.Text == "password")
{
}
}
else if (isCurrentlyUserLoginPage)
{
enteredPassword = txtPasswordField.Text;
isAUser =
(from p in GlobalVariables.users
where p.Username == txtUsernameField.Text
select p.Password).SingleOrDefault();
if (isAUser != null)
{
if (isAUser == enteredPassword)
{
GlobalVariables.currentUser = txtUsernameField.Text;
ControlPanelPage();
}
else
{
MessageBox.Show("Incorrect Password");
}
}
else
{
MessageBox.Show("User not found!");
}
}
else
{
usernameOfForgottenUser =
(from p in GlobalVariables.users
where p.Email == txtUsernameField.Text
select p.Username).SingleOrDefault();
passwordOfForgottenUser =
(from p in GlobalVariables.users
where p.Email == txtUsernameField.Text
select p.Password).SingleOrDefault();
if (passwordOfForgottenUser != null && usernameOfForgottenUser != null)
{
SendEmail();
}
else
{
MessageBox.Show("Email not registered to user!");
}
}
}
public void AdminLoginPage()
{
btnForgotPassword.Show();
btnFocusOnThis.Focus();
btnLoginTypePage.Text = "User Login";
txtUsernameField.Text = "Username";
lblLoginTypePage.Text = "Administrator Login";
btnLoginValue = "Login";
btnLogin.Text = btnLoginValue;
isCurrentlyUserLoginPage = false;
isCurrentlyAdminLoginPage = true;
isCurrentlyForgotPasswordPage = false;
txtPasswordField.Show();
}
public void ForgotPasswordPage()
{
isCurrentlyForgotPasswordPage = true;
isCurrentlyAdminLoginPage = false;
isCurrentlyUserLoginPage = false;
btnForgotPassword.Hide();
lblLoginTypePage.Text = "Forgot Password";
btnLoginTypePage.Text = "User Login";
btnLoginValue = "Send Email";
btnLogin.Text = btnLoginValue;
txtUsernameFieldPlaceholder = "Email";
txtUsernameField.Text = txtUsernameFieldPlaceholder;
isCurrentlyUserLoginPage = false;
isCurrentlyAdminLoginPage = false;
isCurrentlyForgotPasswordPage = true;
txtPasswordField.Hide();
}
public void UserLoginPage()
{
lblLoginTypePage.Text = "User Login";
btnLoginTypePage.Text = "Admin Login";
txtPasswordField.PasswordChar = '\0';
txtPasswordField.Text = "Password";
btnFocusOnThis.Focus();
btnForgotPassword.Show();
txtUsernameField.Show();
txtPasswordField.Show();
btnLogin.Show();
btnForgotPassword.Show();
btnLoginTypePage.Show();
btnQuit.Show();
lblLoginTypePage.Show();
txtUsernameFieldPlaceholder = "Username";
txtUsernameField.Text = txtUsernameFieldPlaceholder;
btnLoginValue = "Login";
btnLogin.Text = btnLoginValue;
isCurrentlyUserLoginPage = true;
isCurrentlyAdminLoginPage = false;
isCurrentlyForgotPasswordPage = false;
txtPasswordField.Show();
}
public void GetAndStoreEmployeeInformation()
{
employeeDetailsFileContents = System.IO.File.ReadAllText(#"EmployeeDetails.txt");
employeeDetails = employeeDetailsFileContents.Split("\n\r".ToArray(), StringSplitOptions.RemoveEmptyEntries);
GlobalVariables.employees.Clear();
foreach (string line in employeeDetails)
{
employeeInformationElements = line.Split(',');
List<string> employeeDetailElements = new List<string>();
foreach (string element in employeeInformationElements)
{
employeeDetailElements.Add(element);
}
GlobalVariables.employees.Add(new Employee
{
Name = employeeDetailElements[0],
Id = Convert.ToInt32(employeeDetailElements[1]),
Authority = Convert.ToInt32(employeeDetailElements[2])
});
}
}
public void GetAndStoreUserInformation()
{
userLoginDetailsFileContents = System.IO.File.ReadAllText(#"UserLoginDetails.txt");
userLoginDetails = userLoginDetailsFileContents.Split("\n\r".ToArray(), StringSplitOptions.RemoveEmptyEntries);
foreach (string line in userLoginDetails)
{
userLoginInformationElements = line.Split(',');
List<string> userLoginDetailElements = new List<string>();
foreach (string element in userLoginInformationElements)
{
userLoginDetailElements.Add(element);
}
GlobalVariables.users.Add(new User
{
Username = userLoginDetailElements[0],
Email = userLoginDetailElements[1],
Password = userLoginDetailElements[2]
});
}
}
private void btnForgotPassword_Click(object sender, EventArgs e)
{
ForgotPasswordPage();
}
public void SendEmail()
{
string fromaddr = "exampleCompany#gmail.com";
string toaddr = txtUsernameField.Text;
string password = "founder1971";
MailMessage msg = new MailMessage();
msg.Subject = "Username & Password";
msg.From = new MailAddress(fromaddr);
msg.Body = "Your username is: " + usernameOfForgottenUser + "\n" + "Your password is: " + passwordOfForgottenUser + "\n\nRegards,\nThe IT Team.";
msg.To.Add(new MailAddress(toaddr));
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.UseDefaultCredentials = false;
smtp.EnableSsl = true;
NetworkCredential nc = new NetworkCredential(fromaddr, password);
smtp.Credentials = nc;
frmAlertBox frm = new frmAlertBox();
frm.Show();
smtp.Send(msg);
GlobalVariables.emailSent = true;
UserLoginPage();
}
public void HideLogin()
{
txtUsernameField.Hide();
txtPasswordField.Hide();
btnLogin.Hide();
btnForgotPassword.Hide();
btnLoginTypePage.Hide();
btnQuit.Hide();
lblLoginTypePage.Hide();
isCurrentlyUserLoginPage = false;
isCurrentlyAdminLoginPage = false;
isCurrentlyForgotPasswordPage = false;
}
public void ControlPanelPage()
{
HideLogin();
HideEverything();
isCurrentlyViewEmployeesPage = false;
isCurrentlyScanBarcodePage = false;
isCurrentlyEmployeeFoundPage = false;
isCurrentlyEditEmployeeDetailsPage = false;
isCurrentlyControlPanelPage = true;
btnLogOut.Show();
btnScanBarcode.Show();
btnViewEmployees.Show();
}
public void HideEverything()
{
btnDelete.Hide();
btnEditEmployeeDetails.Hide();
btnCancelUpdate.Hide();
btnAdd.Hide();
btnCancel.Hide();
btnEditDetails.Hide();
lblEmployeeName.Hide();
lblEmployeeId.Hide();
lblEmployeeAuthority.Hide();
btnForgotPassword.Hide();
btnScanBarcode.Hide();
btnViewEmployees.Hide();
btnLogOut.Hide();
dgvViewEmployees.Hide();
btnBack.Hide();
picScanBarcode.Hide();
txtAuthority.Hide();
txtId.Hide();
txtName.Hide();
lblName.Hide();
picEmployeeFoundImage.Hide();
lblId.Hide();
lblAuthority.Hide();
btnSaveAndUpdate.Hide();
txtScanBarcode.Hide();
picEmployeeImage.Hide();
btnCaptureNewImage.Hide();
txtEmployeeAuthority.Hide();
txtEmployeeId.Hide();
txtEmployeeName.Hide();
btnCaptureNewEmployeeImage.Hide();
}
private void btnQuit_Click(object sender, EventArgs e)
{
this.Close();
Application.Exit();
}
private void btnLogOut_Click(object sender, EventArgs e)
{
HideEverything();
UserLoginPage();
}
private void btnViewEmployees_Click(object sender, EventArgs e)
{
ViewEmployees();
}
public void ViewEmployees()
{
HideEverything();
btnDelete.Show();
btnAdd.Show();
btnEditEmployeeDetails.Show();
txtName.Enabled = false;
txtId.Enabled = false;
txtAuthority.Enabled = false;
btnCaptureNewImage.Show();
dgvViewEmployees.Show();
btnBack.Show();
dgvViewEmployees.DataSource = null;
dgvViewEmployees.Rows.Clear();
dgvViewEmployees.Columns.Clear();
picEmployeeImage.Show();
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Id", typeof(string));
table.Columns.Add("Authority", typeof(string));
int x = 0;
Employee employee;
while (x < GlobalVariables.employees.Count())
{
employee = GlobalVariables.employees[x];
table.Rows.Add(employee.Name, employee.Id, employee.Authority);
x++;
}
dgvViewEmployees.DataSource = table;
txtAuthority.Show();
txtId.Show();
txtName.Show();
lblName.Show();
lblId.Show();
lblAuthority.Show();
}
public void ScanBarcode()
{
HideEverything();
picScanBarcode.Show();
btnBack.Show();
txtScanBarcode.Show();
}
public void EmployeeFound(string employeeId)
{
isCurrentlyEmployeeFoundPage = true;
HideEverything();
btnEditDetails.Show();
picEmployeeFoundImage.Show();
btnBack.Show();
lblEmployeeName.Show();
lblEmployeeId.Show();
lblEmployeeAuthority.Show();
txtEmployeeName.Show();
txtEmployeeId.Show();
txtEmployeeAuthority.Show();
string src = "Images\\" + employeeId + ".bmp";
picEmployeeFoundImage.Image = System.Drawing.Image.FromFile(src);
string EmployeeName =
(from x in GlobalVariables.employees
where x.Id == Convert.ToInt32(employeeId)
select x.Name).SingleOrDefault();
int EmployeeAuthority =
(from x in GlobalVariables.employees
where x.Id == Convert.ToInt32(employeeId)
select x.Authority).SingleOrDefault();
txtEmployeeName.Text = EmployeeName;
txtEmployeeId.Text = employeeId;
txtEmployeeAuthority.Text = Convert.ToString(EmployeeAuthority);
}
public void EditEmployeeDetails()
{
HideEverything();
}
private void btnBack_Click(object sender, EventArgs e)
{
HideEverything();
try {
FinalVideoSource.Stop();
} catch
{
}
ControlPanelPage();
isCurrentlyEmployeeFoundPage = false;
}
private void btnScanBarcode_Click(object sender, EventArgs e)
{
ScanBarcode();
}
private void dgvViewEmployees_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e)
{
if (e.StateChanged != DataGridViewElementStates.Selected) return;
dgvViewEmployees.Rows.GetRowCount(DataGridViewElementStates.Selected);
Int32 selectedRowCount =
dgvViewEmployees.Rows.GetRowCount(DataGridViewElementStates.Selected);
if (selectedRowCount > 0)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
currentlySelectedRow = dgvViewEmployees.SelectedRows[0].Index;
currentlySelectedName = Convert.ToString(dgvViewEmployees.Rows[currentlySelectedRow].Cells[0].Value);
currentlySelectedId = Convert.ToInt32(dgvViewEmployees.Rows[currentlySelectedRow].Cells[1].Value);
currentlySelectedAuthority = Convert.ToInt32(dgvViewEmployees.Rows[currentlySelectedRow].Cells[2].Value);
}
txtName.Text = currentlySelectedName;
txtId.Text = Convert.ToString(currentlySelectedId);
txtAuthority.Text = Convert.ToString(currentlySelectedAuthority);
try
{
string src = "Images\\" + currentlySelectedId + ".bmp";
picEmployeeImage.Image = System.Drawing.Image.FromFile(src);
picEmployeeImage.Size = new System.Drawing.Size(picEmployeeImage.Width, 300);
}
catch
{
picEmployeeImage.Image = null;
}
}
private void btnSaveAndUpdate_Click(object sender, EventArgs e)
{
SaveAndUpdate();
btnEditEmployeeDetails.Show();
btnSaveAndUpdate.Hide();
}
public void SaveAndUpdate()
{
int currentIndex = dgvViewEmployees.SelectedRows[0].Index;
dgvViewEmployees.Rows[currentIndex].Cells[0].Value = txtName.Text;
dgvViewEmployees.Rows[currentIndex].Cells[1].Value = txtId.Text;
dgvViewEmployees.Rows[currentIndex].Cells[2].Value = txtAuthority.Text;
string fileContents = "";
GlobalVariables.employees[currentIndex].Name = txtName.Text;
GlobalVariables.employees[currentIndex].Id = Convert.ToInt32(txtId.Text);
GlobalVariables.employees[currentIndex].Authority = Convert.ToInt32(txtAuthority.Text);
foreach (Employee employee in GlobalVariables.employees)
{
fileContents = fileContents + employee.Name + "," + employee.Id + "," + employee.Authority + Environment.NewLine;
}
File.Delete(#"EmployeeDetails.txt");
File.WriteAllText(#"EmployeeDetails.txt", fileContents);
GetAndStoreEmployeeInformation();
// ViewEmployees();
}
private void txtScanBarcode_TextChanged(object sender, EventArgs e)
{
if (txtScanBarcode.Text.Length == 6)
{
string isEmployeeFound =
(from x in GlobalVariables.employees
where x.Id == Convert.ToInt32(txtScanBarcode.Text)
select x.Name).SingleOrDefault();
if (isEmployeeFound != null)
{
EmployeeFound(txtScanBarcode.Text);
}
}
}
void VideoShow()
{
VideoCaptureDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice);
FinalVideoSource = new VideoCaptureDevice(VideoCaptureDevices[0].MonikerString);
FinalVideoSource.NewFrame += new NewFrameEventHandler(FinalVideoSource_NewFrame);
FinalVideoSource.Start();
}
void FinalVideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
{
image = (Bitmap)eventArgs.Frame.Clone();
image = CropBitmap(image, 150, 100, 300, 200);
if (isCurrentlyEmployeeFoundPage == true)
{
picEmployeeFoundImage.Image = image;
} else
{
picEmployeeImage.Image = image;
}
}
private void btnCaptureNewImage_Click(object sender, EventArgs e)
{
if (btnCaptureNewImage.Text == "Capture New Image")
{
VideoShow();
btnCaptureNewImage.Text = "Take Photo";
}
else
{
FinalVideoSource.Stop();
TakePhoto();
btnCaptureNewImage.Text = "Capture New Image";
}
}
public Bitmap CropBitmap(Bitmap bitmap, int cropX, int cropY, int cropWidth, int cropHeight)
{
Rectangle rect = new Rectangle(cropX, cropY, cropWidth, cropHeight);
Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
return cropped;
}
public void TakePhoto()
{
Bitmap bm = new Bitmap(picEmployeeImage.Width, picEmployeeImage.Height);
bm = (Bitmap)picEmployeeImage.Image;
Bitmap bmp = new Bitmap(bm.Width, bm.Height);
Graphics g = Graphics.FromImage(bmp);
g.DrawImage(bm, 0, 0, bmp.Width, bmp.Height);
if (currentlySelectedId != 0)
{
bmp.Save(#"Images\\" + currentlySelectedId + ".bmp", ImageFormat.Bmp);
}
}
private void picEmployeeFoundImage_Click(object sender, EventArgs e)
{
}
private void btnEditDetails_Click(object sender, EventArgs e)
{
if (btnEditDetails.Text == "Save Details")
{
txtEmployeeName.Enabled = false;
txtEmployeeId.Enabled = false;
txtEmployeeAuthority.Enabled = false;
btnCancel.Hide();
btnEditDetails.Text = "Edit Details";
btnCaptureNewEmployeeImage.Hide();
}
else
{
txtEmployeeName.Enabled = true;
txtEmployeeId.Enabled = true;
txtEmployeeAuthority.Enabled = true;
btnCancel.Show();
btnEditDetails.Text = "Save Details";
btnCaptureNewEmployeeImage.Show();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
txtEmployeeName.Enabled = false;
txtEmployeeId.Enabled = false;
txtEmployeeAuthority.Enabled = false;
btnCancel.Hide();
btnEditDetails.Text = "Edit Details";
}
private void btnCaptureNewEmployeeImage_Click(object sender, EventArgs e)
{
if (btnCaptureNewImage.Text == "Capture New Image")
{
VideoShow();
btnCaptureNewImage.Text = "Take Photo";
}
else
{
FinalVideoSource.Stop();
TakePhoto();
btnCaptureNewImage.Text = "Capture New Image";
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
currentlySelectedAuthority = 0;
currentlySelectedId = 0;
currentlySelectedName = "";
//this.dgvViewEmployees.Rows.Add("five", "six", "seven");
btnAdd.Text = "Create";
txtEmployeeName.Enabled = true;
txtEmployeeId.Enabled = true;
txtEmployeeAuthority.Enabled = true;
}
private void btnEditEmployeeDetails_Click(object sender, EventArgs e)
{
btnCancelUpdate.Show();
txtName.Enabled = true;
txtId.Enabled = true;
txtAuthority.Enabled = true;
btnEditEmployeeDetails.Hide();
btnSaveAndUpdate.Show();
}
private void btnCancelUpdate_Click(object sender, EventArgs e)
{
btnCancelUpdate.Hide();
btnEditEmployeeDetails.Show();
btnSaveAndUpdate.Hide();
txtName.Enabled = false;
txtId.Enabled = false;
txtAuthority.Enabled = false;
}
private void btnDelete_Click(object sender, EventArgs e)
{
foreach (DataGridViewCell oneCell in dgvViewEmployees.SelectedCells)
{
string nameToDelete = dgvViewEmployees.Rows[dgvViewEmployees.SelectedRows[0].Index].Cells["Name"].Value.ToString();
}
}
}
}
Classes:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BusinessSoftware
{
public class Employee
{
public string Name;
public int Id;
public int Authority;
}
public class User
{
public string Username;
public string Password;
public string Email;
}
public static class GlobalVariables
{
public static List<Employee> employees = new List<Employee>();
public static List<User> users = new List<User>();
public static string currentUser;
public static bool emailSent;
}
}

How to prevent duplicated random generated numbers

I have put random numbers into arrays but now I want to prevent it from being shown double in the Listbox. I already got a beginning to start with:
private bool InArray(int getal, int[] getallen, int aantal)
{
}
I think the solution is something like when the number is already in it return true and else just keep going with the code, but I can't think of how I can do this.
This is my code:
namespace Trekking
{
public partial class Form1 : Form
{
private Trekking trekking;
public Form1()
{
InitializeComponent();
btnLaatZien.Enabled = false;
btnSerie.Enabled = false;
btnSorteer.Enabled = false;
btnStart.Enabled = true;
btnStop.Enabled = false;
btnTrek.Enabled = false;
}
private void btnStart_Click(object sender, EventArgs e)
{
int AantalGewenst = Convert.ToInt32(tbInvoerAantalGewenst.Text);
int Maxwaarde = Convert.ToInt32(tbInvoerMaxwaarde.Text);
trekking = new Trekking(Maxwaarde, AantalGewenst);
btnTrek.Enabled = true;
btnStop.Enabled = true;
btnStart.Enabled = false;
if (Maxwaarde > 90)
{
MessageBox.Show("Uw getal mag niet boven de 90 zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (Maxwaarde < 0)
{
MessageBox.Show("Dit aantal is niet mogelijk!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (AantalGewenst > 45)
{
MessageBox.Show("Uw getal mag niet boven de 45 zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
if (AantalGewenst < 1)
{
MessageBox.Show("Dit aantal is niet mogelijk!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else if (Maxwaarde / AantalGewenst < 2)
{
MessageBox.Show("Uw maxwaarde moet minstens het dubbele van Aantal Gewenst zijn!");
btnStart.Enabled = true;
btnTrek.Enabled = false;
btnStop.Enabled = false;
}
else
{
if (AantalGewenst <= 45)
btnStart.Enabled = false;
btnTrek.Enabled = true;
btnStop.Enabled = true;
}
}
public void getSingleNumber(int hoeveel)
{
int Getal = trekking.GeefGetal(hoeveel);
lbResultaat.Items.Add(Getal);
}
public void getTrekkingData()
{
for (int p = 0; p < trekking.AantalGewenst; p++)
{
int alleGetallen = trekking.GeefGetal(p);
lbResultaat.Items.Add(alleGetallen);
}
}
int count = 0;
private void btnTrek_Click(object sender, EventArgs e)
{
int gewenst = trekking.AantalGewenst;
label3.Text = Convert.ToString(count);
btnStop.Enabled = true;
btnSerie.Enabled = false;
trekking.TrekGetal();
getSingleNumber(count);
count++;
if (count == trekking.AantalGewenst)
{
MessageBox.Show("Alle gewenste trekkingen zijn uitgevoerd");
btnTrek.Enabled = false;
btnStop.Enabled = true;
btnSerie.Enabled = false;
}
}
private void btnStop_Click(object sender, EventArgs e)
{
lbResultaat.Items.Clear();
btnLaatZien.Enabled = false;
btnSerie.Enabled = false;
btnSorteer.Enabled = false;
btnStart.Enabled = true;
btnStop.Enabled = false;
btnTrek.Enabled = false;
tbInvoerAantalGewenst.Enabled = true;
tbInvoerMaxwaarde.Enabled = true;
count = 0;
}
private void tbInvoerMaxwaarde_KeyPress(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' '));
}
private void k(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
e.Handled = !(Char.IsDigit(ch) || (ch == '-') || (ch < ' '));
}
private bool InArray(int getal, int[] getallen, int aantal)
{
}
}
}
The class:
namespace Trekking
{
class Trekking
{
//attributes
private Random random;
private int[] getallen;
//properties
public int Maxwaarde { get; private set; } //maximum waarde van te trekken getal
public int AantalGetrokken { get; private set; } //aantal getrokken getallen
public int AantalGewenst { get; private set; } //aantal te trekken getallen
public bool IsTenEinde { get; private set; } //true als alle getallen gerokken
//constructor en methoden
public Trekking(int Maxwaarde, int AantalGewenst)
{
this.Maxwaarde = Maxwaarde;
this.AantalGewenst = AantalGewenst;
AantalGetrokken = 0;
IsTenEinde = false;
random = new Random();
getallen = new int[AantalGewenst];
}
//methods
public void TrekGetal()
{
int erbijArray;
for (int i = 0; i < AantalGewenst; i++)
{
erbijArray = random.Next(1, Maxwaarde);
getallen[i] = erbijArray;
AantalGetrokken++;
}
}
public int GeefGetal(int number)
{
return getallen[number];
}
//sorteert getrokken getallen in array "getallen"
public void Sort()
{
Array.Sort(getallen);
}
}
}
I simplified your problem (leaving out min, max, max number etc).
Basically, you can keep a list of things you already encountered:
public class Lottery
{
public HashSet<int> _previousNumbers = new HashSet<int>();
private Random random = new Random();
public int GetNextNumber()
{
int next;
do
{
next = random.Next();
}
while (_previousNumbers.Contains(next));
_previousNumbers.Add(next);
return next;
}
}
A set does not contain duplicates and is efficient in its Contains implementation.

Categories

Resources