Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Problem:
A List<> variable is passing a reference check even though there is no accessible data in the list.
Solution:
The Save() function finished executing before the save thread had finished causing the thread to abort.
added threadrunning = true before starting the thread.
Code:
Thread saveThread;
public string filepath;
public string rootElementName;
public string objectElementName;
public int objectsSaved;
public SaveData saveData;
public List<SavedObject> datasets;
public bool threadRunning = false;
public bool syncingData = false;
public void StartSaveThread()
{
bool warned = false;
//The "error" is here
//The reference returns true but none of the data is accessible, there is nothing in the list
while(datasets != saveData.objects)
{
if(warned == false)
{
Debug.Log("Waiting for data to sync");
syncingData = true;
warned = true;
}
}
syncingData = false;
saveThread = new Thread(SaveData);
saveThread.Start();
}
public void SaveData()
{
bool saveComplete = false;
threadRunning = true;
while (threadRunning && saveComplete == false)
{
objectsSaved = 0;
XmlDocument saveFile = new XmlDocument();
XmlElement documentRoot = saveFile.CreateElement(rootElementName);
foreach (SavedObject dataset in datasets)
{
XmlElement savedObjectElement = saveFile.CreateElement(objectElementName);
foreach (SavedElement savedValue in dataset.data.savedElements)
{
XmlElement newElement = saveFile.CreateElement(savedValue.name);
newElement.InnerText = savedValue.value;
savedObjectElement.AppendChild(newElement);
}
documentRoot.AppendChild(savedObjectElement);
objectsSaved++;
}
saveFile.AppendChild(documentRoot);
saveFile.Save(filepath);
saveComplete = true;
}
threadRunning = false;
}
More of the code can be found bellow if you want to reproduce the error.
SavedObject Class (Simplified):
//this class is in SavedObject.cs
public int id = 0;
public string name = "";
public string objectPath = "";
public bool saveData;
public bool loadData;
public bool savePosition;
public bool saveRotation;
public bool saveScale;
public SavedObjectData data = new SavedObjectData();
public GameObject parent;
public List<SavedElement> savedElements = new List<SavedElement>();
public void StoreData()
{
data.id = id;
data.name = name;
data.objectPath = objectPath;
data.saveData = saveData;
data.loadData = loadData;
data.savePosition = savePosition;
data.saveRotation = saveRotation;
data.saveScale = saveScale;
Vector3 position = transform.position;
data.position = position;
Vector3 rotation = transform.rotation.eulerAngles;
data.rotation = rotation;
Vector3 scale = transform.localScale;
data.scale = scale;
}
public void LoadData()
{
id = data.id;
name = data.name;
objectPath = data.objectPath;
saveData = data.saveData;
loadData = data.loadData;
savePosition = data.savePosition;
saveRotation = data.saveRotation;
saveScale = data.saveScale;
if (savePosition) { transform.position = data.position; }
if (saveRotation) { transform.eulerAngles = data.rotation; }
if (saveScale) { transform.localScale = data.scale; }
savedElements = data.savedElements;
}
SavedObjectData Class(simplified):
//this class is in SavedObject.cs
public int id;
public string name;
public string objectPath;
public bool saveData;
public bool loadData;
public bool savePosition;
public bool saveRotation;
public bool saveScale;
public Vector3 position;
public Vector3 rotation;
public Vector3 scale;
public List<SavedElement> savedElements = new List<SavedElement>();
public string BoolToString(bool value)
{
string result = "";
if (value)
{
result = "t";
}
else
{
result = "f";
}
return result;
}
public bool StringToBool(string value)
{
bool result;
if (value == "t")
{
result = true;
}
else
{
result = false;
}
return result;
}
public void StoreValues()
{
savedElements = new List<SavedElement>();
savedElements.Add(new SavedElement() { name = "ID", value = id.ToString() });
savedElements.Add(new SavedElement() { name = "Name", value = name });
savedElements.Add(new SavedElement() { name = "Path", value = objectPath });
savedElements.Add(new SavedElement() { name = "SD", value = BoolToString(saveData) });
savedElements.Add(new SavedElement() { name = "LD", value = BoolToString(loadData) });
savedElements.Add(new SavedElement() { name = "SP", value = BoolToString(savePosition) });
savedElements.Add(new SavedElement() { name = "SR", value = BoolToString(saveRotation) });
savedElements.Add(new SavedElement() { name = "SS", value = BoolToString(saveScale) });
if (savePosition) { savedElements.Add(new SavedElement() { name = "P", value = "x:" + position.x + "|y:" + position.y + "|z:" + position.z }); }
if (saveRotation) { savedElements.Add(new SavedElement() { name = "R", value = "x:" + rotation.x + "|y:" + rotation.y + "|z:" + rotation.z }); }
if (saveScale) { savedElements.Add(new SavedElement() { name = "S", value = "x:" + scale.x + "|y:" + scale.y + "|z:" + scale.z }); }
}
public void LoadValues()
{
foreach (SavedElement savedElement in savedElements)
{
string[] sectionedData;
switch (savedElement.name)
{
default:
break;
case "ID":
id = int.Parse(savedElement.value);
break;
case "Name":
name = savedElement.value;
break;
case "Path":
objectPath = savedElement.value;
break;
case "SD":
saveData = StringToBool(savedElement.value);
break;
case "LD":
loadData = StringToBool(savedElement.value);
break;
case "SP":
savePosition = StringToBool(savedElement.value);
break;
case "SR":
saveRotation = StringToBool(savedElement.value);
break;
case "SS":
saveScale = StringToBool(savedElement.value);
break;
case "P":
sectionedData = savedElement.value.Split('|');
position = new Vector3(float.Parse(sectionedData[0].Split(':')[1]), float.Parse(sectionedData[1].Split(':')[1]), float.Parse(sectionedData[2].Split(':')[1]));
break;
case "R":
sectionedData = savedElement.value.Split('|');
rotation = new Vector3(float.Parse(sectionedData[0].Split(':')[1]), float.Parse(sectionedData[1].Split(':')[1]), float.Parse(sectionedData[2].Split(':')[1]));
break;
case "S":
sectionedData = savedElement.value.Split('|');
scale = new Vector3(float.Parse(sectionedData[0].Split(':')[1]), float.Parse(sectionedData[1].Split(':')[1]), float.Parse(sectionedData[2].Split(':')[1]));
break;
}
}
}
SavedElement Class (simplified):
//this class is in SavedObject.cs
public string name;
public string value;
SaveData Class (simplified):
//this class is in SaveData.cs
private IEnumerator SaveObjects(string path, string rootElementName, string objectElementName, GameObject savedObjects){
objects = new List<SavedObject>();
//Compiles List
foreach (Transform savedObject in savedObjects.transform)
{
if(savedObject.gameObject.GetComponent<SavedObject>() != null)
{
objects.add(savedObject.gameObject.GetComponent<SavedObject>())
}
}
//Creates new instance of SaveSystem
saveSystem = new SaveSystem
{
filepath = path,
rootElementName = rootElementName,
objectElementName = objectElementName,
saveData = this,
datasets = objects
};
//checks if saveSystem.datasets == objects then starts the thread to save the data
//PLEASE NOTE: the reference is true but none of the data is updated and accessible
saveSystem.StartSaveThread();
while (saveSystem.threadRunning || saveSystem.syncingData)
{
yield return null;
}
}
SaveSystem Class (simplified):
//this class is in SaveSystem.cs
public SaveData saveData;
public string filepath;
public string rootElementName;
public string objectElementName;
public int objectsSaved;
public List<SavedObject> datasets;
Thread saveThread;
public volatile bool threadRunning = false;
public volatile bool syncingData = false;
public void SaveData()
{
bool saveComplete = false;
threadRunning = true;
while (threadRunning && saveComplete == false)
{
objectsSaved = 0;
XmlDocument saveFile = new XmlDocument();
XmlElement documentRoot = saveFile.CreateElement(rootElementName);
foreach (SavedObject dataset in datasets)
{
XmlElement savedObjectElement = saveFile.CreateElement(objectElementName);
foreach (SavedElement savedValue in dataset.data.savedElements)
{
XmlElement newElement = saveFile.CreateElement(savedValue.name);
newElement.InnerText = savedValue.value;
savedObjectElement.AppendChild(newElement);
}
documentRoot.AppendChild(savedObjectElement);
objectsSaved++;
}
saveFile.AppendChild(documentRoot);
saveFile.Save(filepath);
saveComplete = true;
}
threadRunning = false;
}
public void StartSaveThread()
{
bool warned = false;
//The error is here
//The reference returns true but none of the data is accessible
while(datasets != saveData.objects)
{
if(warned == false)
{
Debug.Log("Waiting for data to sync");
syncingData = true;
warned = true;
}
}
syncingData = false;
saveThread = new Thread(SaveData);
saveThread.Start();
}
I'd first make it easily reproducible, for example, start the thread, wait a second, and then assign the List variable so that you can reproduce the race condition constantly, by just letting the thread run first.
Perhaps change your logic so that you don't start your thread until after you know for certain the variable has been set, or you can use a https://msdn.microsoft.com/en-us/library/system.threading.manualresetevent(v=vs.110).aspx object where the thread calls WaitOne(), which will block that thread on that line, until your List code path assigns the value and then calls the Set() event on the ManualResetEvent.
Related
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.
I'm creating an application in Unity3d that communicates with python's websockets library. My python script is as following:
from __future__ import division
import asyncio
import websockets
import time
import os
from threading import Thread
from random import randint
from read import CustOPCLib
import socket
from jsonsocket import Client,Server
class SubHandler(object):
def data_change(self, handle, node, val, attr):
print("Python: New data change event", handle, node, val, attr)
def datachange_notification(self, node, val, data):
print("Data received: ",val)
def event(self, handle, event):
print("Python: New event", handle, event)
p = CustOPCLib()
async def hello(websocket, path):
p.connect() #my own custom library
while True:
datastring = p.opcjson() #this is a jsonstring
await websocket.send(datastring)
#print("> {}".format(datastring))
time.sleep(1)
if __name__ == '__main__':
start_server = websockets.serve(hello, '127.0.0.1', 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
my json string is as following:
{
"Index": 709953575,
"Moto": true,
"Start": false,
"StartWINCC": false,
"Stop": false,
"StopWINCC": false,
"Tag1": true,
"Tag2": false
}
This is the string i want to send to Unity. In Unity3d I've made the following script that used the Concurrentqueue from mono. The script works accordingly, the problem i have however, is that i get alot of null values from the websocket.
my Unity3d script:
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Threading;
public class ConcurrentQueue<T> : IEnumerable<T>, ICollection, ISerializable, IDeserializationCallback
{
class Node
{
public T Value;
public Node Next;
}
Node _head = new Node();
Node _tail;
int _count;
/// <summary>
/// </summary>
public ConcurrentQueue()
{
_tail = _head;
}
public ConcurrentQueue(IEnumerable<T> enumerable)
: this()
{
foreach (T item in enumerable)
Enqueue(item);
}
public void Enqueue(T item)
{
var node = new Node { Value = item };
Node oldTail = null;
bool update = false;
while (!update)
{
oldTail = _tail;
var oldNext = oldTail.Next;
// Did tail was already updated ?
if (_tail == oldTail)
{
if (oldNext == null)
{
// The place is for us
update = Interlocked.CompareExchange(ref _tail.Next, node, null) == null;
}
else
{
// another Thread already used the place so give him a hand by putting tail where it should be
Interlocked.CompareExchange(ref _tail, oldNext, oldTail);
}
}
}
// At this point we added correctly our node, now we have to update tail. If it fails then it will be done by another thread
Interlocked.CompareExchange(ref _tail, node, oldTail);
Interlocked.Increment(ref _count);
}
/// <summary>
/// </summary>
/// <returns></returns>
public bool TryDequeue(out T value)
{
value = default(T);
bool advanced = false;
while (!advanced)
{
Node oldHead = _head;
Node oldTail = _tail;
Node oldNext = oldHead.Next;
if (oldHead == _head)
{
// Empty case ?
if (oldHead == oldTail)
{
// This should be false then
if (oldNext != null)
{
// If not then the linked list is mal formed, update tail
Interlocked.CompareExchange(ref _tail, oldNext, oldTail);
}
value = default(T);
return false;
}
else
{
value = oldNext.Value;
advanced = Interlocked.CompareExchange(ref _head, oldNext, oldHead) == oldHead;
}
}
}
Interlocked.Decrement(ref _count);
return true;
}
/// <summary>
/// </summary>
/// <returns></returns>
public bool TryPeek(out T value)
{
if (IsEmpty)
{
value = default(T);
return false;
}
Node first = _head.Next;
value = first.Value;
return true;
}
public void Clear()
{
_count = 0;
_tail = _head = new Node();
}
IEnumerator IEnumerable.GetEnumerator()
{
return InternalGetEnumerator();
}
IEnumerator<T> IEnumerable<T>.GetEnumerator()
{
return InternalGetEnumerator();
}
public IEnumerator<T> GetEnumerator()
{
return InternalGetEnumerator();
}
IEnumerator<T> InternalGetEnumerator()
{
Node myHead = _head;
while ((myHead = myHead.Next) != null)
{
yield return myHead.Value;
}
}
void ICollection.CopyTo(Array array, int index)
{
T[] dest = array as T[];
if (dest == null)
return;
CopyTo(dest, index);
}
public void CopyTo(T[] dest, int index)
{
IEnumerator<T> e = InternalGetEnumerator();
int i = index;
while (e.MoveNext())
{
dest[i++] = e.Current;
}
}
public T[] ToArray()
{
T[] dest = new T[_count];
CopyTo(dest, 0);
return dest;
}
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
throw new NotImplementedException();
}
bool ICollection.IsSynchronized
{
get { return true; }
}
public void OnDeserialization(object sender)
{
throw new NotImplementedException();
}
readonly object _syncRoot = new object();
object ICollection.SyncRoot
{
get { return _syncRoot; }
}
public int Count
{
get
{
return _count;
}
}
public bool IsEmpty
{
get
{
return _count == 0;
}
}
}
public class test : MonoBehaviour
{
class OpcJson
{
public int Index { get; set; }
public bool Moto { get; set; }
public bool Start { get; set; }
public bool StartWINCC { get; set; }
public bool Stop { get; set; }
public bool StopWINCC { get; set; }
public bool Tag1 { get; set; }
public bool Tag2 { get; set; }
}
//variables
static readonly ConcurrentQueue<string> queue = new ConcurrentQueue<string>();
public string receivedFromServer;
WebSocket w = new WebSocket(new Uri("ws://127.0.0.1:8765"));
public Text testert;
public Image moto;
public Image start;
public Image startwincc;
public Image stop;
public Image stopwincc;
public Image tag1;
public Image tag2;
// Use this for initialization
IEnumerator StartWebsocket()
{
yield return StartCoroutine(w.Connect());
//w.SendString("Hi there");
//int i = 0;
while (true)
{
string reply = w.RecvString();
if (reply != null)
{
//Debug.Log(reply);
queue.Enqueue(reply);
//receivedFromServer = reply;
//Debug.Log("Received: " + reply);
//w.SendString("Hi there" + i++);
}
if (w.error != null)
{
Debug.LogError("Error: " + w.error);
break;
}
yield return 0;
}
w.Close();
}
private void OnApplicationQuit()
{
StopAllCoroutines();
w.Close();
}
IEnumerator JsonObjectSetter(float waitforsecods)
{
while (true)
{
queue.TryDequeue(out receivedFromServer);
//string s = receivedFromServer;
//Debug.Log(s);
if(receivedFromServer == null)
{
Debug.Log("I'm null");
}
else
{
var results = JsonConvert.DeserializeObject<OpcJson>(receivedFromServer);
testert.text = results.Index.ToString();
if (results.Moto == true)
{
moto.GetComponent<Image>().color = Color.green;
}
else
{
moto.GetComponent<Image>().color = Color.red;
}
if (results.Start == true)
{
start.GetComponent<Image>().color = Color.green;
}
else
{
start.GetComponent<Image>().color = Color.red;
}
if (results.StartWINCC == true)
{
startwincc.GetComponent<Image>().color = Color.green;
}
else
{
startwincc.GetComponent<Image>().color = Color.red;
}
if (results.Stop == true)
{
stop.GetComponent<Image>().color = Color.green;
}
else
{
stop.GetComponent<Image>().color = Color.red;
}
if (results.StopWINCC == true)
{
stopwincc.GetComponent<Image>().color = Color.green;
}
else
{
stopwincc.GetComponent<Image>().color = Color.red;
}
if (results.Tag1 == true)
{
tag1.GetComponent<Image>().color = Color.green;
}
else
{
tag1.GetComponent<Image>().color = Color.red;
}
if (results.Tag2 == true)
{
tag2.GetComponent<Image>().color = Color.green;
}
else
{
tag2.GetComponent<Image>().color = Color.red;
}
}
yield return new WaitForSeconds(waitforsecods);
}
}
private void Start()
{
StartCoroutine(StartWebsocket());
StartCoroutine(JsonObjectSetter(1));
}
}
as you can see, I've made an if/else statement in my JsonObjectSetter method. Everytime the string is null after a dequeue, it prints out "I'm null", and if its not null, it gets used to set an image to a color according to the value.
How can i make it so I won't get any nulls anymore?
Edit 1: during a 7-minute test I've counted 49 nulls. This is quite a big issue to be honest...
Fixed it!
The problem was that my python script had a time.sleep() which lasts 1 second, changed it to 0.1, and changed the WaitForSecods in the Unityscript to 0.25f. This totally fixed my problem. Kind of stupid that I didn't think of this before posting it on Stackoverflow.
I have this code. I've edited the classes somewhat. I've verified that it all works as expected, only the LINQ fails.
public class SANSwitch
{
public bool HasWWN(string wwn)
{
bool test = false;
if (wwn.StartsWith("55")) { test = VirtualWWNList.Values.Contains(wwn); }
else { test= SwitchWWPN.Contains(wwn.Substring(0,20)); }
return test;
}
}
public class SANFabric
{
// dictionary of switch WWPNs and SANSwitch objects
public Dictionary<string, SANSwitch> MemberSwitches = new Dictionary<string, SANSwitch>();
public bool IsFabricMember(string wwn)
{
var found = MemberSwitches.Values.Where(t => t.HasWWN(wwn)).ToList();
if (found.Count() > 0) { return true; }
else { return false; }
}
}
List<SANFabric> Fabrics = new List<SANFabric();
string wwn = String.Empty;
// pretend there's code here and we have a list of fabrics
// and wwn has been assigned a value
Here's what works. That is when a switch that has a WWN that matches the string is a member of the fabric, tester gets set to true
bool tester = false;
//find out if the switch is a member of the fabric
{
foreach (SANFabric f in fabrics)
{
tester = f.IsFabricMember(wwn);
}
}
Here's what doesn't work. ismember is always empty, even when it's run against the same collection.
var ismember = fabrics.Where(t => t.IsFabricMember(wwn));
where IsMember() is defined as
public bool IsFabricMember(string wwn)
{
var found = MemberSwitches.Values.Where(t => t.HasWWN(wwn)).ToList();
if (found.Count() > 0) { return true; }
else { return false; }
}
IsMember() always returns false because found.Count is always 0. I've stepped through the debugger and HasWWN is working correctly.
public bool IsFabricMember(string wwn)
{
if (MemberSwitches.Where(x => x.Value.HasWWN(wwn)).Count() > 0)
return true;
else
return false;
}
or
public bool IsFabricMember(string wwn)
{
if (MemberSwitches.Any(x => x.Value.HasWWN(wwn))) { return true; }
else { return false; }
}
or
public bool IsFabricMember(string wwn)
{
return MemberSwitches.Any(x => x.Value.HasWWN(wwn));
}
Your code works, based on how I filled up missing pieces.
class Program
{
static void Main(string[] args)
{
List<SANFabric> Fabrics = new List<SANFabric>() ;
Dictionary<string,SANSwitch> _swDict=new Dictionary<string,SANSwitch>();
_swDict.Add("A", new SANSwitch() { SwitchWWPN = new List<string>() { "CDEFGHIJKLMNOPQRSTUVWXYZ", "CDEFGHIJKLMNOPQRSTUVWXYZ12333" },
VirtualWWNList = new Dictionary<string, string>() {
{"ABC","55555555"},
{"DEF","993383838"}
}
}
);
_swDict.Add("B", new SANSwitch()
{
SwitchWWPN = new List<string>() { "KGBIFBGKLMPQUERREE", "CDEFGHIKGBIFBGKLMPQUERREEXYZ12333" },
VirtualWWNList = new Dictionary<string, string>() {
{"GHI","8888383"},
{"JKL","00933939"}
}
});
Fabrics.Add(new SANFabric()
{
MemberSwitches = _swDict
});
var f1 = Fabrics.Where(t => t.IsFabricMember("55555555")).ToList();
var f2 = Fabrics.Where(t => t.IsFabricMember("CDEFGHIJKLMNOPQRSTUV")).ToList();
Console.WriteLine("# of items to be member: {0},{1}",f1.Count,f2.Count);
Console.ReadKey();
}
}
public class SANSwitch
{
public Dictionary<string,string> VirtualWWNList {get;set;}
public List<string> SwitchWWPN {get;set;}
public bool HasWWN(string wwn)
{
bool test = false;
if (wwn.StartsWith("55")) { test = VirtualWWNList.Values.Contains(wwn); }
else { test = SwitchWWPN.Contains(wwn.Substring(0, 20)); }
return test;
}
}
public class SANFabric
{
// dictionary of switch WWPNs and SANSwitch objects
public Dictionary<string, SANSwitch> MemberSwitches { get; set; }
public bool IsFabricMember(string wwn)
{
var found = MemberSwitches.Values.Where(t => t.HasWWN(wwn)).ToList();
if (found.Count() > 0) { return true; }
else { return false; }
}
}
In public static void ammount() I get an error saying:
"The name 'mps' does not exist in the current context"
How do I fix this error?
struct mp3players{
private int ID;
private string Make;
private string Model;
private int MBSize;
private double Price;
private int vr;
public int id
{
get { return this.ID; }
set { this.ID = value; }
}
public string make
{
get { return this.Make; }
set { this.Make = value; }
}
public string model
{
get { return this.Model; }
set { this.Model = value; }
}
public int mbsize
{
get { return this.MBSize; }
set { this.MBSize = value; }
}
public double price
{
get { return this.Price; }
set { this.Price = value; }
}
public int VR
{
get { return this.vr; }
set { this.vr = value; }
}
}
public static void mp3()
{
mp3players mp1 = new mp3players();
mp1.id = 1;
mp1.make = "GET technologies .inc";
mp1.model = "HF 410 ";
mp1.mbsize = 4096;
mp1.price = 129.95;
mp1.VR = 500;
mp3players mp2 = new mp3players();
mp2.id = 2;
mp2.make = "Far & Loud";
mp2.model = "XM 600 ";
mp2.mbsize = 8192;
mp2.price = 224.95;
mp2.VR = 500;
mp3players mp3 = new mp3players();
mp3.id = 3;
mp3.make = "Innotivative";
mp3.model = "Z3 ";
mp3.mbsize = 512;
mp3.price = 79.95;
mp3.VR = 500;
mp3players mp4 = new mp3players();
mp4.id = 4;
mp4.make = "Resistance S.A.";
mp4.model = "3001 ";
mp4.mbsize = 4096;
mp4.price = 124.95;
mp4.VR = 500;
mp3players mp5 = new mp3players();
mp5.id = 5;
mp5.make = "CBA";
mp5.model = "NXT volume ";
mp5.mbsize = 2048;
mp5.price = 159.05;
mp5.VR = 500;
ArrayList mps = new ArrayList();
mps.Add(mp1);
mps.Add(mp2);
mps.Add(mp3);
mps.Add(mp4);
mps.Add(mp5);
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Make: " + value.make);
Console.WriteLine("Model: " + value.model);
Console.WriteLine("MBSize: " + value.mbsize);
Console.WriteLine("Price: " + value.price);
Console.WriteLine();
}
}
This is where the error occurs.
I tried a couple of ways but did not find what I was searching for.
public static void ammount()
{
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Model: " + value.model);
Console.WriteLine();
}
}
I am not very good in C# so an explanation what I did wrong is also very welcome!
public static void ammount()
{
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Model: " + value.model);
Console.WriteLine();
}
}
this code has knowledge of mps.
you would add a parameter the method so public static void ammount() looks like public static void ammount(mp3players[] mps). that will fix this error but cause another
you will have to pass mps into the method.
mps is a local variable inside mp3() method. It is not a global variable, so its not accessible in ammount() method.
I got your point , you are getting compilation error The name 'mps' does not exist in the current context. So to fix this, you have to make mps as global variable and set that value in mp3() method, and use that in other methods as well.
struct mp3players
{
private int ID;
private string Make;
private string Model;
private int MBSize;
private double Price;
private int vr;
public int id
{
get { return this.ID; }
set { this.ID = value; }
}
public string make
{
get { return this.Make; }
set { this.Make = value; }
}
public string model
{
get { return this.Model; }
set { this.Model = value; }
}
public int mbsize
{
get { return this.MBSize; }
set { this.MBSize = value; }
}
public double price
{
get { return this.Price; }
set { this.Price = value; }
}
public int VR
{
get { return this.vr; }
set { this.vr = value; }
}
}
private static ArrayList mps;
public static void mp3()
{
mp3players mp1 = new mp3players();
mp1.id = 1;
mp1.make = "GET technologies .inc";
mp1.model = "HF 410 ";
mp1.mbsize = 4096;
mp1.price = 129.95;
mp1.VR = 500;
mp3players mp2 = new mp3players();
mp2.id = 2;
mp2.make = "Far & Loud";
mp2.model = "XM 600 ";
mp2.mbsize = 8192;
mp2.price = 224.95;
mp2.VR = 500;
mp3players mp3 = new mp3players();
mp3.id = 3;
mp3.make = "Innotivative";
mp3.model = "Z3 ";
mp3.mbsize = 512;
mp3.price = 79.95;
mp3.VR = 500;
mp3players mp4 = new mp3players();
mp4.id = 4;
mp4.make = "Resistance S.A.";
mp4.model = "3001 ";
mp4.mbsize = 4096;
mp4.price = 124.95;
mp4.VR = 500;
mp3players mp5 = new mp3players();
mp5.id = 5;
mp5.make = "CBA";
mp5.model = "NXT volume ";
mp5.mbsize = 2048;
mp5.price = 159.05;
mp5.VR = 500;
mps = new ArrayList();
mps.Add(mp1);
mps.Add(mp2);
mps.Add(mp3);
mps.Add(mp4);
mps.Add(mp5);
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Make: " + value.make);
Console.WriteLine("Model: " + value.model);
Console.WriteLine("MBSize: " + value.mbsize);
Console.WriteLine("Price: " + value.price);
Console.WriteLine();
}
}
public static void ammount()
{
foreach (mp3players value in mps)
{
Console.WriteLine("ID: " + value.id);
Console.WriteLine("Model: " + value.model);
Console.WriteLine();
}
}
The variable 'mps' declared inside the function public static void mp3() and you are trying to access the same from another function public static void ammount() which can't be feasible due to the scope.
To access the 'mps' you have to remove the declaration from the mp3() function and move it directly uder you so defined class:
public class MySongColl
{
private static ArrayList mps = new ArrayList();
struct mp3players
{
....
....
}
public static void mp3()
{
....
....
}
public static void ammount()
{
....
....
}
}
NOTE:
Use proper Naming convention while you write code. e.g: Speeling mistake in Function name ammount() should be amount(). And use camel case while declaring the names like struct mp3players should be Mp3Players etc. These are not necessary to build the code but essential for a developer.
I am storing multiple items into one session variable: which is 4 different words.
I need to be able to take those 4 different wordsin the one session, and store them into separate variables so i can use them, is this possible? and if so how?
_application just holds text from a series of text from text boxes.
Here is my session class.
public class JobApplicantSession
{
public JobApplication ApplicationSession
{
get {if (HttpContext.Current.Session["Application"] != null)
return (JobApplication)HttpContext.Current.Session["Application"];
return null; }
set{ HttpContext.Current.Session["Application"] = value; }
}
Job application: Job application holds information from a list of textboxes thats it.
JobApplication _application;
_application = new JobApplication(jobID);
if (i < _applicant.Fields.Count)
_applicant.AddAnswer((_controlsList[i] as TextBox).Text);
else
_application.AddAnswer((_controlsList[i] as TextBox).Text);
add to the session:
_sessions.ApplicationSession = _application;
I can get the session:
JobApplication application;
var jas = new JobApplicantSession();
application = jas.ApplicationSession;
Job application:
public class JobApplication
{
private int _jobID = -1;
public JobApplication(int jobID)
{
_jobID = jobID;
}
List<String> _answers = new List<String>();
List<JobApplicationField> _fields = new List<JobApplicationField>();
public List<JobApplicationField> Fields
{
get { return _fields; }
}
public int JobID()
{
return _jobID;
}
public List<String> Answers
{
get { return _answers; }
set { _answers = value; }
}
public void AddAnswer(String answer)
{
_answers.Add(answer);
}
public void AddField(JobApplicationField field)
{
if (field.HasFieldID)
{
for (int i = 0; i < _fields.Count(); i++)
{
if (_fields[i].FieldID == field.FieldID)
{
_fields[i] = field;
return;
}
}
}
_fields.Add(field);
}
public void PopulateFromDatabase()
{
JobPositionSystemDAL dal = new JobPositionSystemDAL();
DataSet data = dal.OpenJobOpeningByID(_jobID);
foreach (DataRow row in data.Tables[0].Rows)
{
JobApplicationField field = new JobApplicationField(Convert.ToInt32(row["QUESTIONID"]), row["QUESTIONTEXT"].ToString(), Convert.ToBoolean(row["HASCORRECTANSWER"]), row["CORRECTANSWER"].ToString(), Convert.ToBoolean(row["ISREQUIRED"]));
AddField(field);
}
}
public bool Verify()
{
if (_fields.Count != Answers.Count)
throw new Exception("Number of answers != number of fields");
for (int i = 0; i < _fields.Count; i++)
{
if (_fields[i].HasCorrectAnswer == true && _fields[i].CorrectAnswer != _answers[i])
return false;
}
return true;
}
public void Save()
{
JobPositionSystemDAL database = new JobPositionSystemDAL();
foreach(JobApplicationField field in _fields)
{
field.Save(_jobID, ref database);
}
//reload to get the Field/question ID for any new fields
Reload();
}
public void Reload()
{
_fields = new List<JobApplicationField>();
Load(_jobID);
}
public void Load(int jobID)
{
_jobID = jobID;
DataSet ds = DB.OpenJobOpeningByID(jobID);
DataTable table = ds.Tables[0];
foreach (DataRow row in table.Rows)
{
int questionID = 0;
object obj = row["QUESTIONID"];
Int32.TryParse(obj.ToString(), out questionID);
//int jobApplicationID = Int32.Parse(row["JOBAPPLICATIONID"] as String);
string questionText = row["QUESTIONTEXT"] as String;
int type = Int32.Parse(row["TYPEID"].ToString());
bool hasCorrectAnswer = (row["HASCORRECTANSWER"] as String == "0") ? false : true;
string correctAnswer = row["CORRECTANSWER"] as String;
bool required = ((row["ISREQUIRED"] as String) == "0") ? false : true;
JobApplicationField field = new JobApplicationField(questionID, questionText, hasCorrectAnswer, correctAnswer, required);
AddField(field);
}
}
private JobPositionSystemDAL _db;
private JobPositionSystemDAL DB
{
get
{
if (null == _db)
_db = new JobPositionSystemDAL();
return _db;
}
}
}
}
How can i loop through and store each item into its own variable?
i will need 4 variables.
Hope it is what you are asking. If you want to store array of objects in session state you can either sotre array directly:
HttpContext.Current.Session["data"] = new int[32];
or dynamically create names based on element index (strange, but possible):
var data = new int[3];
HttpContext.Current.Session["data" + 0.ToString()] = data[0];
HttpContext.Current.Session["data" + 1.ToString()] = data[1];
HttpContext.Current.Session["data" + 2.ToString()] = data[2];
Read in reverse order:
var dataArray = (int[])(HttpContext.Current.Session["data"]);
or
var data = new int[3];
data[0] = (int)HttpContext.Current.Session["data" + + 0.ToString()];