Get multiple items in one session - c#

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()];

Related

I have created an inventory System but i dont know how to proceed

I have everything in place, but i have a problem setting the items that are created in the inventory to the actual slots. i made this so that there is a better overview of the items.
this is the code for the inventory:
// Amount of Slots in inventory defined here!!!
[SerializeField]
private Slot[] slots = new Slot[10];
public List<Item> invItems = new List<Item>();
public void CheckSlot(Item item)
{
for (int i = 0; i < slots.Length; i++)
{
if (slots[i].isEmpty == false)
{
//call a method.
if (item.isStackable)
{
slots[i].amount = item.amount;
}
}
if (slots[i].isEmpty == true)
{
//call another method.
//run some code.
slots[i] = new Slot(item);
return;
}
}
}
public void UpdateAmount(Item _item,Slot _slot)
{
_slot.amount = _item.amount;
}
public void CreateItem(Item item)
{
Item invItem1 = new Item();
invItem1 = item.Copy();
invItems.Add(invItem1);
}
public void InventoryAdd(Item item)
{
//check if the item is already in the inventory
//if true check if it is stackable and the new amount is less than maxStackable amount
//if false add the item to the invItems list and set the slot to false
if (invItems.Count != 0)
{
for (int i = 0; i < invItems.Count; i++)
{
if (invItems[i].ItemID == item.ItemID)
{
if (invItems[i].amount + item.amount <= invItems[i].maxStackable)
{
invItems[i].amount += item.amount;
CheckSlot(invItems[i]); //
return;
}
if (invItems[i].amount < invItems[i].maxStackable)
{
if (invItems[i].amount + item.amount > invItems[i].maxStackable)
{
int nextAmount = invItems[i].maxStackable - invItems[i].amount;
invItems[i].amount += nextAmount;
Item invItem1 = new Item();
invItem1 = item.Copy();
invItem1.amount = invItem1.amount - nextAmount;
invItems.Add(invItem1);
return;
}
}
}
}
}
Item invItem = new Item();
invItem = item.Copy();
invItems.Add(invItem);
and the Item script :
public string name;
public int ItemID;
public GameObject prefab;
public Sprite icon;
public int amount = 1;
public bool isStackable;
public int maxStackable = 5;
public Item()
{
}
public Item(string _name, int id,GameObject _prefab, int _amount, bool stackable,int maxStack)
{
name = _name;
ItemID = id;
prefab = _prefab;
amount = _amount;
isStackable = stackable;
maxStackable = maxStack;
}
public Item Copy()
{
Item copy = new Item();
copy.name = this.name;
copy.ItemID = this.ItemID;
copy.prefab = this.prefab;
copy.amount = this.amount;
copy.isStackable = this.isStackable;
copy.maxStackable = this.maxStackable;
return copy;
}
and the code for a slot:
public bool isEmpty = true;
public Slot()
{
}
public Slot(Item _item)
{
this.name = _item.name;
this.ItemID = _item.ItemID;
this.isStackable = _item.isStackable;
this.prefab = _item.prefab;
this.icon = _item.icon;
}
the thing is i do not know how i can set the Items i have created in the inventory to the slot. maybe i need to cleanup my code, and check for each of those things in one go instead of seperate?
What I understand from your description is that you have multiple slots and each slot can hold one or more item.
So,Instead of adding them through constructor like below:
public Slot(Item _item)
{
this.name = _item.name;
this.ItemID = _item.ItemID;
this.isStackable = _item.isStackable;
this.prefab = _item.prefab;
this.icon = _item.icon;
}
Maintain a list of items in slot class and have a special method to add items to slot.
Something like this:
public List<Item> ItemsInSlot {get;set;}
public void AddItems(IEnumerable<Item> items)
{
ItemsInSlot.AddRange(items);
}
I am assuming you already have some mechanic in place to trigger adding items to a slot. Like a button in UI or dragging item(s) to slot.

How to fix System.InvalidCastException: 'Specified cast is not valid.'

I've got a booking system program, and one form lists the bookings already made depending on the date selected. All the times of the bookings made on the selected date were to be shown in the list box. The selected item in the list box would then populate the text boxes below with all the booking data.
However, I'm getting this error:
System.InvalidCastException: 'Specified cast is not valid.'
This is the bookingClass:
public DateTime bookingDate
{
get
{
return myDate;
}
set
{
myDate = value;
}
}
public string bookingTime
{
get
{
return myTime;
}
set
{
myTime = value;
}
}
public int bookingID
{
get
{
return myID;
}
set
{
myID = value;
}
}
public int customerID
{
get
{
return myCust;
}
set
{
myCust = value;
}
}
public string bookingTicket
{
get
{
return myTicket;
}
set
{
myTicket = value;
}
}
public int bookingQuantity
{
get
{
return myNum;
}
set
{
myNum = value;
}
}
public decimal bookingTotal
{
get
{
return myTotal;
}
set
{
myTotal = value;
}
}
//A SortedList of booking times is returned for a given Date
public SortedList GetBookingsByDate(DateTime bookingDate)
{
newCon = new System.Data.SqlClient.SqlConnection();
String firstConStr = "Data Source=.\\SQLEXPRESS;AttachDbFilename=";
String pathToDB = "F:\\Level 5\\Object Oriented Programs\\Programs\\assignmentPractice\\assignmentPractice\\assignmentDB.mdf;";
String lastConStr = "Integrated Security=True;Connect Timeout=30;User Instance=True";
newCon.ConnectionString = firstConStr + pathToDB + lastConStr;
newCon.Open();
SqlCommand cmBookList = new SqlCommand();
cmBookList.Connection = newCon;
cmBookList.CommandType = CommandType.Text;
cmBookList.CommandText = "Select bookingID, bookingTime from Booking where bookingDate = '" + bookingDate.ToLongDateString() + "'";
SqlDataReader drBookList = cmBookList.ExecuteReader();
//This is a sorted list of key/value pairs
SortedList BookList = new SortedList();
//drBookList[0] is the key (Booking ID) and drBookList[1] is the value (Booking Time)
while (drBookList.Read())
{
BookList.Add(drBookList[0], drBookList[1]);
}
drBookList.Close();
newCon.Close();
return BookList;
}
}
This is the form:
public bookingSearch()
{
InitializeComponent();
}
private SortedList BookList;
private bookingClass objBooking;
private void btnList_Click(object sender, EventArgs e)
{
lstBook.Items.Clear();
bookingClass objBooking = new bookingClass();
BookList = objBooking.GetBookingsByDate(DateTime.Parse(dtpDate.Text));
//Populate the ListBox with the Booking times
if (BookList.Count == 0)
{
lstBook.Items.Add("No Records");
return;
}
foreach (DictionaryEntry book in BookList)
{
lstBook.Items.Add(book.Value);
}
lstBook.SelectedIndex = 0;
}
private void lstBook_SelectedIndexChanged(object sender, EventArgs e)
{
if (BookList.Count > 0) //Don't process if 'No Records'
{
//Get the Booking details for a particular selected time in the list
//The SelectedIndex is used to read the Key value from the
//SortedList which holds the bookingID
objBooking.GetBookingsByDate((DateTime)BookList.GetKey(lstBook.SelectedIndex));
txtID.Text = objBooking.bookingID.ToString();
txtCust.Text = objBooking.customerID.ToString();
txtTime.Text = objBooking.bookingTime;
txtTicket.Text = objBooking.bookingTicket;
txtNum.Text = objBooking.bookingQuantity.ToString();
txtTotal.Text = objBooking.bookingTotal.ToString();
}
}
}
It's highlighting this line when I get the error:
objBooking.GetBookingsByDate((DateTime)BookList.GetKey(lstBook.SelectedIndex))
Any help is much appreciated.

Memory exception HashSet

I get an memory exception while loading a 4GB file. i have to do that twice but i have enougth memmory to load them. the memmory exception occures when i have 3gb left or more.:(.
Method:
public TableModel LoadTable(string path) {
TableModel model = new TableModel();
using (FileStream filestream = new FileStream(path, FileMode.Open, FileAccess.Read)) {
using (StreamReader reader = new StreamReader(filestream, Encoding.UTF8)) {
string line = "";
bool isHeader = true;
int counter = 0;
List<string> rows = new List<string>();
while ((line = reader.ReadLine()) != null) {
if (isHeader) {
model.Columns = line.Split(new string[] { "\t" }, StringSplitOptions.RemoveEmptyEntries);
isHeader = false;
continue;
} else {
if (Settings.Default.RonudSet != 0) {
rows.Add(RoundDecimals(line));
} else {
rows.Add(line);
}
}
counter++;
}
model.RowCount = counter;
model.ColumnsCount = model.Columns.Length;
model.Keys = new HashSet<string>(rows);
}
}
return model;
}
Exception:
System.OutOfMemoryException was unhandled
The function evaluation was disabled because of an out of memory exception.
TableModel:
class TableModel {
private string tableName;
private string[] columns;
private HashSet<string> keys;
public int ColumnsCount { get; set; }
public int RowCount { get; set; }
public string TableName { get { return tableName; } set { this.tableName = value; } }
public string[] Columns { get { return columns; } set { this.columns = value; } }
public HashSet<string> Keys { get { return keys; } set { this.keys = value; } }
}
Start Compare:
if (newFile.Name.Equals(currFile.Name)) {
FileLoader loader = new FileLoader();
TableModel newModel = loader.LoadTable(newFile.ToString());
TableModel currentModel = loader.LoadTable(currFile.ToString());
newModel.TableName = newFile.Name;
currentModel.TableName = currFile.Name;
new Compare(newModel, currentModel, currFile.Directory.Name);
break;
}
Compare:
private void CheckColumns() {
bool sameColumnCount = CheckColumnsCount();
int counter = 0;
currentContent = new HashSet<string>(currentModel.Columns);
newContent = new HashSet<string>(newModel.Columns);
foreach (string header in currentContent) {
if (!newContent.Contains(header)) {
headersNotFoundInN.Add(header);
}
}
foreach (string header in newContent) {
if (!currentContent.Contains(header)) {
headersNotFoundInC.Add(header);
}
}
if (currentModel.ColumnsCount == newModel.ColumnsCount) {
for (int i = 0; i < currentModel.ColumnsCount; i++) {
if (currentModel.Columns[i] == newModel.Columns[i]) {
counter++;
}
}
if (counter == currentModel.ColumnsCount) {
headerSequence = true;
} else {
headerSequence = false;
}
} else {
headerSequence = false;
}
bool emptyNotFoundIn = false;
if (headersNotFoundInC.Count == 0 && headersNotFoundInN.Count == 0) {
emptyNotFoundIn = true;
}
ReportContent(sameColumnCount, headerSequence, emptyNotFoundIn);
}
private void CheckRows() {
bool sameRowCount = CheckRowCount();
currentContent = new HashSet<string>(currentModel.Keys);
newContent = new HashSet<string>(newModel.Keys);
foreach (string key in currentContent) {
if (!newContent.Contains(key)) {
rowNotFoundInN.Add(key);
}
}
foreach (string key in newContent) {
if (!currentContent.Contains(key)) {
rowNotFoundInC.Add(key);
}
}
bool emptyNotFoundIn = false;
if (rowNotFoundInC.Count == 0 && rowNotFoundInN.Count == 0) {
emptyNotFoundIn = true;
}
ReportContent(sameRowCount, emptyNotFoundIn);
}
Its a table with many rows that i have to compare with a similar table. at the end i have to give a report about the diffrences. but i fail here where i have to load this massive file.
try using BufferedStream
using (BufferedStream bs = new BufferedStream(filestream))
{
}

asp.net - How to load values from database in user control?

I want to load values from database in user control
I could add more user control but I cant't able to load values in user control
Code:
Add.aspx.cs
Below code is for adding more than one user control and retain the previous control values
public List<string> NoOfControls
{
get
{
return ViewState["NoOfControls"] == null ? new List<string>() : (List<string>)ViewState["NoOfControls"];
}
set
{
ViewState["NoOfControls"] = value;
}
}
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
GenerateControls();
}
private void GenerateControls()
{
foreach (string i in NoOfControls)
{
VisaUserControl ctrl = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");
ctrl.ID = i;
this.rpt1.Controls.Add(ctrl);
}
}
protected void btnAddVisa_Click(object sender, EventArgs e)
{
List<string> temp = null;
var uc = (VisaUserControl)this.LoadControl(#"VisaUserControl.ascx");
string id = Guid.NewGuid().ToString();
uc.ID = id;
temp = NoOfControls;
temp.Add(id);
NoOfControls = temp;
rpt1.Controls.Add(uc);
}
Edit.aspx.cs
Below code is for loading values from database in user control
using (OleDbCommand cmd = new OleDbCommand("Select * from visa_details where emp_id = '"+ empid +"'", DbConnection))
using (OleDbDataAdapter da = new OleDbDataAdapter(cmd))
{
OleDbDataReader DR1 = cmd.ExecuteReader();
while(DR1.Read())
{
//Here I can get values
string visaNumb = DR1[2].ToString();
string visaCountry = DR1[3].ToString();
string visaType = DR1[4].ToString();
string visaEntry = DR1[5].ToString();
string expiryDate = DR1[6].ToString();
for (int i = 0; i < y; i++)
{
VisaUserControl userconrol = (VisaUserControl)Page.LoadControl("VisaUserControl.ascx");
userconrol.TextVisaNumber = visaNumb;
userconrol.VisaCountry = visaCountry;
userconrol.VisaType = visaType;
userconrol.VisaEntry = visaEntry;
userconrol.ExpiryDate = expiryDate;
repeater1.Controls.Add(userconrol);
}
}
}
.ascx.cs
Here values are there but when it is loading all values are removed
protected void Page_Load(object sender, EventArgs e)
{
txtUser.Text = Request.Form[txtUser.UniqueID];
dropCountry.SelectedValue = Request.Form[dropCountry.UniqueID];
dropVisa.SelectedValue = Request.Form[dropVisa.UniqueID];
dropEntry.SelectedValue = Request.Form[dropEntry.UniqueID];
txtDate.Text = Request.Form[txtDate.UniqueID];
}
public string TextVisaNumber
{
get { return txtUser.Text; }
set { txtUser.Text = value; }
}
public string VisaCountry
{
get { return dropCountry.SelectedValue; }
set { dropCountry.SelectedValue = value; }
}
public string VisaType
{
get { return dropVisa.SelectedValue; }
set { dropVisa.SelectedValue = value; }
}
public string VisaEntry
{
get { return dropEntry.SelectedValue; }
set { dropEntry.SelectedValue = value; }
}
public string ExpiryDate
{
get
{
return txtDate.Text;
}
set
{
txtDate.Text = value;
}
}
Any ideas? Thanks in advance
Instead of adding the control in the page's controls collection, you should keep an set the data in some existing control's inner HTML.

How to use PagedDataSource CopyTo()?

I get an error when ReadInDataFromRssAndReturnArrayWithTheDataStatic is called because that the DataSource can't be stored in the array specified in the CopyTo-method.
I wonder how I should find which array-type that I should use.
Here follows some of my code:
public static class StillingslisteStatic
{
public static string RssSourceStatic { get; set; }
public static string StillingssideStatic { get; set; }
//This contains all of the data from the rss-file!!
public static PagedDataSource PgdsPositionsStatic { get; set; }
//This function is written by Anders Branderud
public static DataView[] ReadInDataFromRssAndReturnArrayWithTheDataStatic(PageData ledigeStillingerPage)
{
DataView[] myObjArray = null; //I also tried with DataTable
if (ledigeStillingerPage["Stillingsside"] != null)
StillingssideStatic = ledigeStillingerPage["Stillingsside"].ToString();
if (ledigeStillingerPage["RssSource"] != null) RssSourceStatic = (string)ledigeStillingerPage["RssSource"];
if (!string.IsNullOrEmpty(RssSourceStatic))
{
FilterTableStatic(LoadFeedStatic(RssSourceStatic, ledigeStillingerPage), 100); //This initializes PgdsPositionsStatic
myObjArray = new DataView[PgdsPositionsStatic.Count]; //one DataTable is one item
PgdsPositionsStatic.CopyTo(myObjArray, 0);
}
return myObjArray;
}
private static DataTable LoadFeedStatic(string url, PageData ledigeStillingerPage)
{
var reader = new XmlTextReader(url);
var ds = new DataSet();
ds.ReadXml(reader);
foreach (DataTable table in ds.Tables)
{
if (table.TableName == "item")
{
return table;
}
}
return null;
}
private static void FilterTableStatic(DataTable table2Filter, int count)
{
PgdsPositionsStatic = new PagedDataSource();
if (table2Filter == null) return;
int counter = 1;
var deleteItems = new DataRow[table2Filter.Rows.Count];
foreach (DataRow row in table2Filter.Rows)
{
if (counter > count)
deleteItems[counter - count] = row; ;
counter++;
}
for (int i = 0; i < (counter - count); i++)
{
var row = (DataRow)deleteItems[i];
if (row == null)
continue;
table2Filter.Rows.Remove(row);
}
PgdsPositionsStatic.DataSource = table2Filter.DefaultView;
}
Error message:
{"Message":"Object cannot be stored in an array of this type.","StackTrace":" at System.Array.InternalSetValue(Void* target, Object value)\r\n at System.Array.SetValue(Object value, Int32 index)\r\n at System.Web.UI.WebControls.PagedDataSource.CopyTo(Array array, Int32 index)\r\n at

Categories

Resources