DbContext disposed error - c#

I have tried the internet, but could not find a good answer. Here is the code which is having the problem
private void LoadRecords()
{
var data = from record in model.Records
where record.TimeStamp >= oldestRecordVisible
orderby record.TimeStamp descending
select record;
dataGridView1.DataSource = data.ToList();
}
I am using mySql server for the database. And here's the code from the context.cs
using System.Data.Entity;
namespace MilThicknessMonitor3.Models
{
public class DataModel : DbContext
{
public DataModel()
: base("name=DataConnection")
{
}
public DbSet<Record> Records { get; set; }
public DbSet<CaptureSource> CaptureSources { get; set; }
public DbSet<PlcConfiguration> PlcConfigurations { get; set; }
public DbSet<Configuration> Configurations { get; set; }
}
}
Any help will appreciated
Below is the Data Model
using MilThicknessMonitor3.Analytics;
using System;
using System.ComponentModel;
namespace MilThicknessMonitor3.Models
{
public class Record
{
public int Id { get; set; }
[DisplayName("Date/Time")]
public DateTime TimeStamp { get; set; }
[DisplayName("Average Measure (Mils)")]
public double AvgMeasure { get; set; }
[DisplayName("Average Measure (Millimetres)")]
public double AvgMilli { get { return AvgMeasure / 39.37; } }
[DisplayName("Minimum Measure (Mils)")]
public double MinMeasure { get; set; }
[DisplayName("Minimum Measure (Millimetres)")]
public double MinMilli { get { return MinMeasure / 39.37; } }
[DisplayName("Maximum Measure (Mils)")]
public double MaxMeasure { get; set; }
[DisplayName("Maximum Measure (Millimetres)")]
public double MaxMilli { get { return MaxMeasure / 39.37; } }
[DisplayName("Notes")]
public string Notes { get; set; }
#region Testing Fields, Properties, and Methods
private DataLine offset;
internal DataLine Offset
{
get { return offset; }
}
private DataLine baseline;
internal DataLine Baseline
{
get { return baseline; }
}
private float[] results;
public int[] OffsetValues
{
get
{
int[] values = new int[offset.Size];
int index = 0;
foreach (ImageColumn c in offset)
{
values[index] = c.Ys.Count;
index++;
}
return values;
}
}
public int[] BaselineValues
{
get
{
int[] values = new int[baseline.Size];
int index = 0;
foreach (ImageColumn c in baseline)
{
values[index] = c.Ys.Count;
index++;
}
return values;
}
}
public int[] ResultValues
{
get
{
int[] values = new int[results.Length];
for (int i = 0; i < results.Length; i++)
values[i] = (int)Math.Round(results[i]);
return values;
}
}
internal void AddOffset(DataLine offset) { this.offset = offset; }
internal void AddBaseLine(DataLine baseline) { this.baseline = baseline; }
internal void AddResults(float[] results) { this.results = results; }
#endregion
}
}

You need to give some more information on the model object. Where is it created?
Try something like this.
using(var context = new DataModel())
{
//Prepare your Model
var model = RecordsRepository.GetQueryableObject();
//Call LoadRecords
return LoadRecords(model);
}

Well I found the solution for the problem. Basically one of my object was taking up wrong configuration from a table, failing it to initialize and throwing exception and eventually disposing the context.
Thanks everyone for your support.

Related

Polymorphism and Interfaces in C#

Create three small classes unrelated by inheritance—classes Building, Car and Bicycle. Write an interface ICarbonFootprint with a GetCarbonFootprint method. Have each of your classes implement that interface, so that its GetCarbonFootprint method calculates an appropriate carbon footprint for that class (check out a few websites that explain how to calculate carbon footprints). Write an app that creates objects of each of the three classes, places references to those objects in List, then iterates through the List, polymorphically invoking each object’s GetCarbonFootprint method. Constructor of Car initialize “gallon of gas”, and the Building constructor will initialize buiding-square-footage.
how to calculate carbon-footprint
One gallon of gas yields 20 pounds of CO2 for a car
Multiply the square footage by 50 for a building
None for a bicycle
My instructor's code:
public static void Main(string[] args)
{
ICarbonFootprint[] list = new ICarbonFootprint[3];
// add elements to list
list[0] = new Bicycle();
list[1] = new Building(2500);
list[2] = new Car(10);
// display carbon footprint of each object
for (int i = 0; i < list.Length; i++)
list[i].GetCarbonFootprint();
} // end Main
}
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Miller
{
class Program
{
static void Main(string[] args)
{
Bicycle bike = new Bicycle();
Building b = new Building();
Car car = new Car();
List<ICarbonFootprint> list = new List<ICarbonFootprint>();
list.Add(bike);
list.Add(b);
list.Add(car);
int totalCarbon = 0;
foreach (var item in list)
{
totalCarbon += item.GetCarbonFootprint();
Console.WriteLine("{0} has a footprint of: {1}", item, item.GetCarbonFootprint());
}
Console.WriteLine("Total footprint is: {0}", totalCarbon);
Console.ReadKey();
}
}
public class Bicycle : ICarbonFootprint
{
private string _make;
private string _model;
public string Make
{
get { return _make; }
set { _make = value; }
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public int GetCarbonFootprint()
{
return 10;
}
public override string ToString()
{
return string.Format("Bike");
}
}
public class Building : ICarbonFootprint
{
private string _address;
public string Address
{
get { return _address; }
set { _address = value; }
}
public int GetCarbonFootprint()
{
return 2000;
}
public override string ToString()
{
return string.Format("Building");
}
}
public class Car : ICarbonFootprint
{
private string _make;
private string _model;
public string Make
{
get { return _make; }
set { _make = value; }
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public int GetCarbonFootprint()
{
return 1500;
}
public override string ToString()
{
return string.Format("Car");
}
}
public interface ICarbonFootprint
{
int GetCarbonFootprint();
}
}
Me integrating my instructor's code (lines 12-23 changed AKA class Program was the only thing changed):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Miller
{
class Program
{
public static void Main(string[] args)
{
ICarbonFootprint[] list = new ICarbonFootprint[3];
// add elements to list
list[0] = new Bicycle();
list[1] = new Building(2500);
list[2] = new Car(10);
// display carbon footprint of each object
for (int i = 0; i < list.Length; i++)
list[i].GetCarbonFootprint();
} // end Main
}
public class Bicycle : ICarbonFootprint
{
private string _make;
private string _model;
public string Make
{
get { return _make; }
set { _make = value; }
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public int GetCarbonFootprint()
{
return 10;
}
public override string ToString()
{
return string.Format("Bike");
}
}
public class Building : ICarbonFootprint
{
private string _address;
public string Address
{
get { return _address; }
set { _address = value; }
}
public int GetCarbonFootprint()
{
return 2000;
}
public override string ToString()
{
return string.Format("Building");
}
}
public class Car : ICarbonFootprint
{
private string _make;
private string _model;
public string Make
{
get { return _make; }
set { _make = value; }
}
public string Model
{
get { return _model; }
set { _model = value; }
}
public int GetCarbonFootprint()
{
return 1500;
}
public override string ToString()
{
return string.Format("Car");
}
}
public interface ICarbonFootprint
{
int GetCarbonFootprint();
}
}
So, replacing my code for class Program with my instructor's code, I received the following errors:
Program.cs(51,23,51,41): error CS1729: 'Miller.Building' does not contain a constructor that takes 1 arguments
Program.cs(52,23,52,34): error CS1729: 'Miller.Car' does not contain a constructor that takes 1 arguments
Now, because the last two days before Spring break were cancelled due to the weather (snow), we weren't able to discuss. My code seems to do what the directions ask, but I would like to get my instructor's code for class Program working with my code. Could someone help me with these errors possibly?
There are a few issues with your code.
First up you need to include the constructors to make the code compile.
For Building this would look like:
private int squareFootage;
public Building(int squareFootage)
{
this.squareFootage = squareFootage;
}
And for Car this would look like:
private int gasGallons;
public Car(int gasGallons)
{
this.gasGallons = gasGallons;
}
Next, you're not following the rules for calculating the carbon footprint.
They should be:
//Bicycle
public int GetCarbonFootprint()
{
return 0;
}
//Building
public int GetCarbonFootprint()
{
return 50 * squareFootage;
}
//Car
public int GetCarbonFootprint()
{
return 20 * gasGallons;
}
Finally, your instructor's code doesn't actually display any results. The code in the for loop should be changed to be Console.WriteLine(list[i].GetCarbonFootprint()); if this is a console app.
So, all up the code should look like this:
public static void Main(string[] args)
{
ICarbonFootprint[] list = new ICarbonFootprint[3];
// add elements to list
list[0] = new Bicycle();
list[1] = new Building(2500);
list[2] = new Car(10);
// display carbon footprint of each object
for (int i = 0; i < list.Length; i++)
Console.WriteLine(list[i].GetCarbonFootprint());
}
public class Bicycle : ICarbonFootprint
{
public string Make { get; set; }
public string Model { get; set; }
public int GetCarbonFootprint()
{
return 0;
}
}
public class Building : ICarbonFootprint
{
private int squareFootage;
public Building(int squareFootage)
{
this.squareFootage = squareFootage;
}
public string Address { get; set; }
public int GetCarbonFootprint()
{
return 50 * squareFootage;
}
}
public class Car : ICarbonFootprint
{
private int gasGallons;
public Car(int gasGallons)
{
this.gasGallons = gasGallons;
}
public string Make { get; set; }
public string Model { get; set; }
public int GetCarbonFootprint()
{
return 20 * gasGallons;
}
}
public interface ICarbonFootprint
{
int GetCarbonFootprint();
}
I've opted to short-cut the property definitions rather than implement them with fields.
The output is:
0
125000
200
You should write constructors for Building and Car like next:
public Building(int MyValue)
{
...
}
and your code will work fine.
Suggestion: Car and Bicycle shares properties, and the ICarbonFootprint implementation, so you can create a base class with an abstract method. Also the GetCarbonFootprint from ICarbonFootprint interface must be type of System.Double.
public interface ICarbonFootprint
{
int GetCarbonFootprint();
}
public class Building : ICarbonFootprint
{
public int BuildingSquareFootage { get; set; }
public string Address { get; set; }
public Building(int buildingSquareFootage, string address)
{
BuildingSquareFootage = buildingSquareFootage;
Address = address;
}
public int GetCarbonFootprint()
{
return BuildingSquareFootage * 50;
}
public override string ToString()
{
return string.Format("Building");
}
}
public abstract class CarBicycleBase : ICarbonFootprint
{
public string Make { get; set; }
public string Model { get; set; }
protected CarBicycleBase(string make, string model)
{
Make = make;
Model = model;
}
public abstract int GetCarbonFootprint();
}
public class Bicycle : CarBicycleBase
{
public Bicycle(string make, string model)
: base(make, model) { }
public override int GetCarbonFootprint()
{
return 0;
}
public override string ToString()
{
return string.Format("Bike");
}
}
public class Car : CarBicycleBase
{
public int GallonOfGas { get; set; }
public Car(int gallonOfGas, string make, string model)
: base(make, model)
{
GallonOfGas = gallonOfGas;
}
public override int GetCarbonFootprint()
{
return GallonOfGas * 20;
}
public override string ToString()
{
return string.Format("Car");
}
}
Example:
...
var list = new List<ICarbonFootprint>(3)
{
new Car(10, "...", "..."),
new Bicycle("...", "..."),
new Building(20, "...")
};
foreach (ICarbonFootprint item in list)
item.GetCarbonFootprint();
...
I hope it helps.

What is NZEC error in C# and where it is in following code snippet

This is the first time I am getting NZEC error. I don't understand this error, I just found that it stands for "Non Zero Exit Code". But what does this means. When we get this error. I am getting this error on one of online coding challenge websites and not in Visual Studio.
I am real need of help. Please check following code snippet where I am getting this error and please suggest what I am doing wrong.
using System;
using System.Collections.Generic;
using System.Linq;
namespace PractiseConsoleApplication
{
internal class Program
{
private static void Main(string[] args)
{
//Get input
var stringInput = Console.ReadLine();
var numberOfRooms = Convert.ToInt32(Console.ReadLine());
var endOfInput = Convert.ToInt32(Console.ReadLine());
var customers = stringInput.ToArray();
var hotel = new Hotel(numberOfRooms);
foreach (var customerName in customers)
{
hotel.CheckInCheckoutCustomer(customerName);
}
Console.WriteLine(Convert.ToString(hotel.CustomersLeftWithoutStayingInHotel.Count));
}
}
internal class Hotel
{
public bool IsRoomAvailable { get; private set; }
public List<HotelRoom> Rooms { get; private set; }
public List<char> CustomersLeftWithoutStayingInHotel { get; private set; }
private Hotel()
{
Rooms = new List<HotelRoom>();
CustomersLeftWithoutStayingInHotel = new List<char>();
}
public Hotel(int numberOfRooms)
: this()
{
for (int i = 1; i <= numberOfRooms; i++)
{
Rooms.Add(new HotelRoom(i));
}
}
public void CheckInCheckoutCustomer(char customer)
{
if (CustomersLeftWithoutStayingInHotel.Any(f => f == customer))
{
return;
}
var existingCustomer = Rooms.FirstOrDefault(f => f.IsRoomAllocatedToCustomer && f.CustomerName == customer);
//Already room allocated to this customer
if (existingCustomer != null)
{
//checkout him
existingCustomer.CustomerCheckout();
}
else
{
//Get empty rooms
var emptyRoom = Rooms.FirstOrDefault(f => f.IsRoomAllocatedToCustomer == false);
if (emptyRoom != null)
{
emptyRoom.AllocateRoomToCustomer(customer);
}
else
{
CustomersLeftWithoutStayingInHotel.Add(customer);
}
}
}
}
internal class HotelRoom
{
public int RoomNumber { get; private set; }
public char? CustomerName { get; private set; }
public HotelRoom(int roomNumber)
{
RoomNumber = roomNumber;
CustomerName = null;
}
public bool IsRoomAllocatedToCustomer
{
get
{
return CustomerName.HasValue;
}
}
public void AllocateRoomToCustomer(char customerDetails)
{
CustomerName = customerDetails;
}
public void CustomerCheckout()
{
CustomerName = null;
}
}
internal class Customer
{
public char CustomerName { get; private set; }
public Customer(char name)
{
CustomerName = name;
}
}
}
as Tony Hopkinson says in the comments, main should return an int.
place this statement in the end of main method:
return 0;
this will exit with zero code(thus the Non Zero Exit Code error)

operator to access other classes's objects

I need help with this code. If you run the code you'll get in the last 7 lines (which is for...loop for Order object) Exercise.OrderItem.The problem is that I would like to access the OrderItem objects with for...loop but all I get are the last 7 lines representing OrderItem objects.How can I access them in for...loop so that I get the same as in foreach...loop? I think it has something to do with the indexer.Thank You.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace Exercise
{
interface IPricing
{
//read/write property
double Price
{
get;
set;
}
double Discount
{
get;
set;
}
}
public class Order:IPricing
{
private string name;
private double price;
private static int OrderNo;
//private ArrayList m_items = new ArrayList();
private ArrayList m_items;
//static constructor
static Order()
{
OrderNo = 0;
}
//default constructor
public Order()
{
name = null;
price = 0;
OrderNo++;
m_items = new ArrayList();
}
//constructor with parameters
public Order(string name, double price)
{
this.name = name;
this.price = price;
OrderNo++;
this.m_items = new ArrayList();
}
//copy constructor
public Order(Order order)
{
this.name = order.name;
this.price = order.price;
this.m_items = order.m_items;
}
public string Name
{
get { return name; }
set { name = value; }
}
public IEnumerable Items
{
get { return m_items; }
private set { }
}
public void AddItem(OrderItem orderItem)
{
orderItem.Order = name;
m_items.Add(orderItem);
}
public static Order operator +(Order o1, Order o2)
{
Order o3 = new Order(o1.name+", "+o2.name,o1.price+o2.price);
o3.m_items.AddRange(o1.m_items);
o3.m_items.AddRange(o2.m_items);
return o3;
}
//indexer
public object this[int index]
{
get
{
m_items[index] = this.m_items[index];
return m_items[index];
}
set { m_items[index] = value; }
}
public double ItemCount
{
get { return m_items.Count; }
private set{}
}
public virtual void Print()
{
Console.WriteLine("*********************Order No. {0}***********************", OrderNo);
Console.WriteLine("Details");
Console.WriteLine("Name: {0}", name);
Console.WriteLine("Price: {0}", price);
}
public double Price
{
get { return price - Discount; }
set { price = value; }
}
public virtual double Discount
{
get { return 0; }
set { ;}
}
public void PrintItems()
{
Console.WriteLine("Items in this order: ");
Console.WriteLine();
foreach(OrderItem itm in this.m_items)
{
Console.WriteLine("Item name: {0,4};\tPart of order: {1}", itm.Name, itm.Order);
}
}
}
public class OrderItem
{
private string m_name; //name of the item in order
private string m_order; //name of the order whose parts are items with names m_name
//default constructor
public OrderItem()
{
m_order = null;
}
//parameter constructor
public OrderItem(string name)
{
this.m_name = name;
this.m_order = null;
}
//copy constructor
public OrderItem(OrderItem orderItem)
{
this.m_name = orderItem.m_name;
this.m_order = orderItem.m_order;
}
//Name read/write property
public string Name
{
get { return m_name; }
set { m_name = value; }
}
//Order read/write property
public string Order
{
get { return m_order; }
set { m_order = value; }
}
}
public class MainProgram
{
static void Main(string[] args)
{
string order1 = "Desktop PC";
Order desktopPC = new Order(order1,25000);
desktopPC.AddItem(new OrderItem("pc mouse"));
desktopPC.AddItem(new OrderItem("keyboard"));
desktopPC.AddItem(new OrderItem("monitor"));
desktopPC.AddItem(new OrderItem("pc"));
desktopPC.Print();
desktopPC.PrintItems();
Console.WriteLine();
string order2 = "Notebook";
Order notebook = new Order(order2, 54000);
notebook.AddItem(new OrderItem("mouse"));
notebook.AddItem(new OrderItem("bag"));
notebook.AddItem(new OrderItem("notebook"));
notebook.Print();
notebook.PrintItems();
Console.WriteLine();
Order total = desktopPC + notebook;
total.Print();
total.PrintItems();
Console.WriteLine();
Console.WriteLine("Getting the items via for loop");
for (int k = 0; k < total.ItemCount; k++)
{
Console.WriteLine(total[k]);
}
Console.ReadKey();
}
}
}
for (int k = 0; k < total.ItemCount; k++)
{
var x = total[k] as OrderItem;
if (x == null) continue;
Console.WriteLine(x.Name);
Console.WriteLine(x.Order);
}

How to save a reference of an instance of an object in XML

EDIT:
Got an answer, I changed the list Inv in player to a list of int, and imported the items on initial load of the game into a Dictionary like so:
public static class InitLoad
{
static List<ItemEquipmentWeapon> weapons;
public static Dictionary<int, Item> ItemIDList = new Dictionary<int, Item>();
public static void PreLoading()
{
string path, filePath,
weaponFile = #"\WeaponsItem.aid";
XmlSerializer SerializerObj;
FileStream ReadFileStream;
path = string.Format(#"{0}\AwesomeRPG\Data\Items",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
filePath = string.Format(#"{0}\{1}", path, weaponFile);
SerializerObj = new XmlSerializer(typeof(ItemEquipmentWeapon));
ReadFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
weapons = (List<ItemEquipmentWeapon>)SerializerObj.Deserialize(ReadFileStream);
foreach (Item item in weapons)
{
ItemIDList.Add(item.ID, item);
}
}
}
Meaning I can then do this with my player class:
[Serializable()]
public class Player : Entity
{
public string Name { get; set; }
public int MaxHP { get; set; }
public int Level { get; set; }
public int XP { get; set; }
public int Str { get; set; }
public int End { get; set; }
public int Dex { get; set; }
public int Agi { get; set; }
public int Wis { get; set; }
public int Int { get; set; }
//Create a list of Item Id's for inventory
public List<int> Inv { get; set; }
private int lHand;
private int rHand;
public int LHand
{
get
{ return lHand; }
set
{
if (!value.THand)
{
lHand = value;
}
else lHand = null;
}
}
public int RHand
{
get
{ return rHand; }
set
{ rHand = value; }
}
internal Player() { }
public Player(string name, int maxhp, int hp, int lvl, int exp, int str, int end, int dex, int agi, int wis, int inte)
: base(true, hp)
{
Name = name;
MaxHP = maxhp;
Level = lvl;
XP = exp;
Str = str;
End = end;
Dex = dex;
Agi = agi;
Wis = wis;
Int = inte;
Inv = new List<int>();
}
public List<string> GetInv()
{
List<string> val = new List<string>();
Item item;
foreach (int i in Inv)
{
InitLoad.ItemIDList.TryGetValue(i, out item);
val.Add(item.Name);
}
return val;
}
public void AddItem(Item i, int amt)
{
for (int j = 0; j < amt; j++)
{
Inv.Add(i.ID);
}
}
public void AddItem(Item i){
AddItem(i, 1); }
public void RemoveItem(Item i, int amt)
{
int count = 0;
foreach (int item in Inv)
{
if (item == i.ID)
{
Inv.Remove(item);
count++;
}
if (count == amt)
{
break;
}
}
}
public void RemoveItem(Item i){
RemoveItem(i, 1); }
public bool HasItem(Item i, int amt)
{
int count = 0;
foreach (int item in Inv)
{
if (item == i.ID)
{
count++;
}
}
return count >= amt;
}
public bool HasItem(Item i){
return HasItem(i, 1); }
}
Hope this helps anybody else!
Original Question:
So, I'm making a silly little RPG game with windows forms to test my skills, and I'm sorting out saving. At the moment it saves to an XML file, which a custom extention (.asd)
Here's my save/load code:
public static class SaveGame
{
public static void Save(Player player)
{
string myfile = string.Format(#"{1}\AwesomeRPG\Saves\{0}Save.asd", player.Name, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
//Delete file if it already exists
if (File.Exists(myfile)) System.IO.File.Delete(myfile);
//Create/Write to the file
FileStream outFile = File.Create(myfile);
XmlSerializer Serializer = new XmlSerializer(typeof(Player));
Serializer.Serialize(outFile, player);
outFile.Close();
}
public static Player Load(string FileName)
{
string myfile = string.Format(#"{1}\AwesomeRPG\Saves\{0}Save.asd", FileName, Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
if (!File.Exists(myfile)) return null;
XmlSerializer Serializer = new XmlSerializer(typeof(Player));
FileStream ReadFileStream = new FileStream(myfile, FileMode.Open, FileAccess.Read, FileShare.Read);
return (Player)Serializer.Deserialize(ReadFileStream);
}
}
As you can imagine, this saves all the details of any item in the Inv list.
However, I want all items that exist to be loaded (instances of them to be created) when the game starts, and I need a way for the save file to hold references to those instances, rather than making new instances.
The instances loaded when the game starts are also held in XML files, and then loaded into separate lists based on the item type, eg all ItemEquipmentWeapon instances (Inherits ItemEquipment which inherits Item) are in a WeaponItem.aid file, which is in XML format, and is loaded into a List
Is there any way I can save and load the Inv contents to and from the player save file by reference so I can have them use the existing instances setup during initial loading?
EDIT:
Just thought, it might help some to see how the Player class is coded, so here it is:
[Serializable()]
public class Player : Entity
{
public string Name { get; set; }
public int MaxHP { get; set; }
public int Level { get; set; }
public int XP { get; set; }
public int Str { get; set; }
public int End { get; set; }
public int Dex { get; set; }
public int Agi { get; set; }
public int Wis { get; set; }
public int Int { get; set; }
public List<Item> Inv { get; set; }
private ItemEquipmentWeapon lHand;
private ItemEquipmentWeapon rHand;
public ItemEquipmentWeapon LHand
{
get
{ return lHand; }
set
{
if (!value.THand)
{
lHand = value;
}
else lHand = null;
}
}
public ItemEquipmentWeapon RHand
{
get
{ return rHand; }
set
{ rHand = value; }
}
internal Player() { }
public Player(string name, int maxhp, int hp, int lvl, int exp, int str, int end, int dex, int agi, int wis, int inte)
: base(true, hp)
{
Name = name;
MaxHP = maxhp;
Level = lvl;
XP = exp;
Str = str;
End = end;
Dex = dex;
Agi = agi;
Wis = wis;
Int = inte;
Inv = new List<Item>();
}
public List<string> GetInv()
{
List<string> val = new List<string>();
foreach (Item item in Inv)
{
val.Add(item.Name);
}
return val;
}
public void AddItem(Item i, int amt)
{
for (int j = 0; j < amt; j++)
{
Inv.Add(i);
}
}
public void AddItem(Item i){
AddItem(i, 1); }
public void RemoveItem(Item i, int amt)
{
int count = 0;
foreach (Item item in Inv)
{
if (item == i)
{
Inv.Remove(item);
count++;
}
if (count == amt)
{
break;
}
}
}
public void RemoveItem(Item i){
RemoveItem(i, 1); }
public bool HasItem(Item i, int amt)
{
int count = 0;
foreach (Item item in Inv)
{
if (item == i)
{
count++;
}
}
return count >= amt;
}
public bool HasItem(Item i){
return HasItem(i, 1); }
}
Obviously the code that loads the item instances from XML on game load would also be very useful, but I haven't coded that yet, I'm not 100% sure how I would go about doing it.
So far though, I have this:
public static class InitLoad
{
static List<ItemEquipmentWeapon> weapons;
public static void PreLoading()
{
string path, filePath,
weaponFile = #"\WeaponsItem.aid";
XmlSerializer SerializerObj;
FileStream ReadFileStream;
path = string.Format(#"{0}\AwesomeRPG\Data\Items",
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData));
filePath = string.Format(#"{0}\{1}", path, weaponFile);
SerializerObj = new XmlSerializer(typeof(ItemEquipmentWeapon));
ReadFileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
weapons = (List<ItemEquipmentWeapon>)SerializerObj.Deserialize(ReadFileStream);
}
}
Thanks in advance for any help!
Is there any way I can save and load the Inv contents to and from the player save file by reference so I can have them use the existing instances setup during initial loading?
Here is one way to solve this issue:
1. Add to your Item class int field Id or something of the kind, and assign for each unique item appropriate unique value.
2. During initial loading create a global cache of all the unique items in your game. For this matter I'd suggest using Dictionary<int, Item> where the key would be Id of the item and value would be the item itself.
3. In your Player class you should store only Id's of the items, so during loading you can obtain instances of Item from the global cache mentioned previously.
Furthermore, you might want to read about flyweight pattern, which is pretty much about sharing instances.

Stack overflow error in singleton pattern

I have implemented Single Pattern. Here is my code i am getting the an error when i call the Test.BuildData() function. Please help
public class WordDataItem
{
public string Word { get; set; }
public string Definition { get; set; }
public int WordGroupKey { get; set; }
}
public class WordDataGroup
{
public List<WordDataItem> listItem = new List<WordDataItem>();
public int GroupKey { get; set; }
}
public sealed class WordDataSource
{
private static WordDataSource _dataSoruce;
private List<WordDataGroup> listGroup = new List<WordDataGroup>();
public List<WordDataGroup> ListGroup
{
get { return listGroup; }
set { listGroup = value; }
}
private WordDataSource() { }
public static WordDataSource Instance
{
get
{
if (Instance == null)
{
_dataSoruce = new WordDataSource();
}
return _dataSoruce;
}
}
}
public static class Test
{
public static void BuildData()
{
WordDataSource.Instance.ListGroup.Add(new WordDataGroup() { GroupKey = 8, listItem = new List<WordDataItem>() { new WordDataItem() {Word = "Hello", Definition="Greetings", WordGroupKey = 8}} });
}
}
I get an error of stack over flow when i call the Test.BuildData() function.
Your Instance property is recursively calling into itself when you check if it is null.
Try this:
public static WordDataSource Instance
{
get
{
if (_dataSoruce == null)
{
_dataSoruce = new WordDataSource();
}
return _dataSoruce;
}
}

Categories