i want to add items in a sql database to a dictionary but the values enter as null in the object reference heres the code im using atm
public static Dictionary<string, prizedbinfo> dbprizes = new Dictionary<string, prizedbinfo>();
private void LoadData(string dataloc)
{
if (!File.Exists(dataloc))
{
MessageBox.Show(dataloc + " not found.");
return;
}
var connection = new SQLiteConnection("Data Source=" + dataloc);
connection.Open();
var datacommand = new SQLiteCommand("SELECT prizeID, createdOn, expiresOn, modifiedOn, status, redeemedOn, giftedOn, claimedOn FROM mySnackData", connection);
List<string[]> datas = ExecuteStringCommand(datacommand, 9);
foreach (string[] row in datas)
{
if (!Program.dbprizes.ContainsKey(row[0]))
{
Program.dbprizes.Add(row[0], new prizedbinfo(row));
}
}
connection.Close();
}
and the prizedbinfo object is
class prizedbinfo
{
public prizedbinfo(string[] dbdata)
{
string prizeID = dbdata[0];
string createdOn = dbdata[1];
string expiresOn = dbdata[2];
string modifiedOn = dbdata[3];
string status = dbdata[4];
string redeemedOn = dbdata[5];
string giftedOn = dbdata[6];
string claimedOn = dbdata[7];
string name = dbdata[8];
}
public string prizeID { get; set; }
public string createdOn { get; set; }
public string expiresOn { get; set; }
public string modifiedOn { get; set; }
public string status { get; set; }
public string redeemedOn { get; set; }
public string giftedOn { get; set; }
public string claimedOn { get; set; }
public string name { get; set; }
}
i have tested it with breakpoints and all the data is correctly added to datas and row but not to the prizedbinfo object for some reason
Remove the string keyword from all your variables in the prizedbinfo constructor. You're creating local variables that immediately go out of scope, so you're losing your values.
public prizedbinfo(string[] dbdata)
{
prizeID = dbdata[0];
createdOn = dbdata[1];
expiresOn = dbdata[2];
modifiedOn = dbdata[3];
status = dbdata[4];
redeemedOn = dbdata[5];
giftedOn = dbdata[6];
claimedOn = dbdata[7];
name = dbdata[8];
}
Related
I have list in class
public List<Igrac> Igraci { get; set; } = new List<Igrac>();
The class:
class Igrac
{
public string Ime { get; set; }
public string Prezime { get; set; }
public string Pozicija { get; set; }
public int Godine { get; set; }
public Igrac(string Ime, string Prezime, string Pozicija, int Godine)
{
this.Ime = Ime;
this.Prezime = Prezime;
this.Pozicija = Pozicija;
this.Godine = Godine;
}
}
Added new list elements:
noviklb.DodavanjeIgraca(new Igrac("Petar", "Petrovic", "Krilo", 1992));
noviklb.DodavanjeIgraca(new Igrac("Badr", "Hari", "Napad", 1993));
The method for adding is working OK. The problem is that when I use Console.WriteLine I get an error like this:
System.Collections.Generic.List`1[zadatak.Program+Igrac]
I Googled and foreach is solution but I cant do it right. Do I need to write foreach as method?
class Igrac
{
public string Ime { get; }
public string Prezime { get; }
public string Pozicija { get; }
public int Godine { get; }
public Igrac(string Ime, string Prezime, string Pozicija, int Godine)
{
this.Ime = Ime;
this.Prezime = Prezime;
this.Pozicija = Pozicija;
this.Godine = Godine;
}
}
public override string ToString()
{
return $"{Ime} {Prezime} {Pozicija} {Godine}";
}
Now you can use.
string myStringDate = new Igrac("Petar", "Petrovic", "Krilo", 1992).ToString();
ALSO NOTE: It would be good to make you properties get only.
Working link:
https://dotnetfiddle.net/zMNiln
use this code:
public void showList(List<Igrac> noviklb)
{
foreach (var item in noviklb)
{
Console.WriteLine("Ime : " + item.Ime);
Console.WriteLine("Prezime : " + item.Prezime);
Console.WriteLine("Pozicija : " + item.Pozicija);
Console.WriteLine("Godine : " + item.Godine);
Console.WriteLine("Get New Record****************** ");
}
}
I'm trying to change a Dataset into a List of objects. For some reason, I have this error " Error CS7036: There is no argument given that corresponds to the required formal parameter" but I really don't know why...
What am I missing?
Thx in advance
automate.cs
public class Automate
{
private string SrtAutomate { get; set; }
public string AutomateId { get; set; }
public string MachineName { get; set; }
public DateTime LastUpdate { get; set; }
public DateTime LastTreatment { get; set; }
public bool AskStop { get; set; }
public bool AskPause { get; set; }
public string ListeningConfiguration { get; set; }
public string Informations { get; set; }
public Automate(string srtAutomate, string automateId, string machineName,
DateTime lastUpdate, DateTime lastTreatment, bool askStop, bool askPause, string informations, string listeningConfiguration)
{
SrtAutomate = srtAutomate;
AutomateId = automateId;
MachineName = machineName;
LastUpdate = lastUpdate;
LastTreatment = lastTreatment;
AskStop = askStop;
AskPause = askPause;
ListeningConfiguration = listeningConfiguration;
Informations = informations;
}
}
checkTable.cs
public static class CheckTable
{
public static List<Automate> GetAutomaton()
{
DataSet dsAutomate;
List<Automate> lstAutomate = new List<Automate>();
using (var databaseConnexion = new DatabaseConnexion(Parameters.DbSrtServer, Parameters.DbSrtName, Parameters.DbSrtUser, Parameters.DbSrtPassword))
{
string request = "SELECT * FROM SrtAutomateStatus";
//CONNEXION A BDD
try { databaseConnexion.Open(); }
catch (Exception ex) { throw new Exception($"Impossible détablir une connexion à la base : {Parameters.DbSrtName}"); }
DatabaseParamQuery paramQuery = new DatabaseParamQuery(request);
//RECUPERATION DES AUTOMATES
try { dsAutomate = databaseConnexion.GetQueryResults(paramQuery); }
catch (Exception ex) { throw new Exception($"Impossible de récuperer la liste des automates : {ex.Message}"); }
}
lstAutomate = dsAutomate.Tables[0].AsEnumerable().Select(dataRow => new Automate
{
SrtAutomate = dataRow.Field<string>("srtAutomate"),
AutomateId = dataRow.Field<string>("automateId"),
MachineName = dataRow.Field<string>("machineName"),
LastUpdate = dataRow.Field<DateTime>("lastUpdate"),
LastTreatment = dataRow.Field<DateTime>("lastTreatment"),
AskStop = dataRow.Field<bool>("askStop"),
AskPause = dataRow.Field<bool>("askPause"),
Informations = dataRow.Field<string>("informations"),
ListeningConfiguration = dataRow.Field<string>("isteningConfiguration")
}).toList();
return lstAutomate;
}
}
In my MdiForm I have a menubar that has btnSave on it. I would like to save the data created in my childform that is active by clicking the btnSave on the midForm menubar. I have these classes to save the data to the database:
StudentBal.cs
internal class StudentBal
{
public string DateAdded { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string CityAddress { get; set; }
public string HomeAddress { get; set; }
public string Nationality { get; set; }
public string MaritalStatus { get; set; }
public string DateOfBirth { get; set; }
public string PlaceOfBirth { get; set; }
public string TelNo { get; set; }
public string Father { get; set; }
public string Mother { get; set; }
public string ParentsAddress { get; set; }
public string EmployersName { get; set; }
public string EmplyerTelNo { get; set; }
public string GuardiansName { get; set; }
public string GuradiansAddress { get; set; }
public byte[] StudentImage { get; set; }
public string WorkAddress { get; set; }
public int InsertStudent(StudentBal bal)
{
var dal = new StudentDal();
return dal.InsertStudent(bal);
}
StudentDal.cs
public int InsertStudent(StudentBal bal)
{
const string query =
#"INSERT INTO students VALUES(#DateAdded, #FirstName, #MiddleName, #LastName, #CityAddress, #HomeAddress, #Nationality,
#MaritalStatus, #DateOfBirth, #PlaceOfBirth, #TelNo, #Father, #Mother,
#ParentsAddress, #EmployersName, #EmployersTelNo, #GuardiansName,
#GuardiansAddress, #StudentImage, #WorkAddress)";
using (_cmd = new SqlCommand(query, _cn))
{
_cmd.Parameters.AddWithValue("#DateAdded", Convert.ToDateTime(bal.DateAdded).ToShortDateString());
_cmd.Parameters.AddWithValue("#FirstName", bal.FirstName);
_cmd.Parameters.AddWithValue("#MiddleName", bal.MiddleName);
_cmd.Parameters.AddWithValue("#LastName", bal.LastName);
_cmd.Parameters.AddWithValue("#CityAddress", bal.CityAddress);
_cmd.Parameters.AddWithValue("#HomeAddress", bal.HomeAddress);
_cmd.Parameters.AddWithValue("#Nationality", bal.Nationality);
_cmd.Parameters.AddWithValue("#MaritalStatus", bal.MaritalStatus);
_cmd.Parameters.AddWithValue("#DateOfBirth", bal.DateOfBirth);
_cmd.Parameters.AddWithValue("#PlaceOfBirth", bal.PlaceOfBirth);
_cmd.Parameters.AddWithValue("#TelNo", bal.TelNo);
_cmd.Parameters.AddWithValue("#Father", bal.Father);
_cmd.Parameters.AddWithValue("#Mother", bal.Mother);
_cmd.Parameters.AddWithValue("#ParentsAddress", bal.ParentsAddress);
_cmd.Parameters.AddWithValue("#EmployersName", bal.EmployersName);
_cmd.Parameters.AddWithValue("#EmployersTelNo", bal.EmplyerTelNo);
_cmd.Parameters.AddWithValue("#GuardiansName", bal.GuardiansName);
_cmd.Parameters.AddWithValue("#GuardiansAddress", bal.GuradiansAddress);
_cmd.Parameters.AddWithValue("#StudentImage", bal.StudentImage);
_cmd.Parameters.AddWithValue("#WorkAddress", bal.WorkAddress);
_cn.Open();
return(_cmd.ExecuteNonQuery());
}
}
This is in my AddStudent Form
private void btnSaveInformation_Click(object sender, EventArgs e)
{
var stream = new MemoryStream();
pictureBox2.Image.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] pic = stream.ToArray();
if (!CheckTextBox()) return;
var bal = new StudentBal
{
CityAddress = string.IsNullOrWhiteSpace(txtCityAddress.Text) ? "N/A" : txtCityAddress.Text,
DateAdded = DateTime.Now.ToShortDateString(),
DateOfBirth = txtDateOfBirth.Text,
EmployersName = string.IsNullOrWhiteSpace(txtEmployersName.Text) ? "N/A" : txtEmployersName.Text,
EmplyerTelNo = string.IsNullOrWhiteSpace(txtEmpContactNumber.Text) ? "N/A" : txtEmpContactNumber.Text,
Father = string.IsNullOrWhiteSpace(txtFathersName.Text) ? "N/A" : txtFathersName.Text,
FirstName = txtFirstName.Text,
GuardiansName = string.IsNullOrWhiteSpace(txtGuardiansName.Text) ? "N/A" : txtGuardiansName.Text,
GuradiansAddress = string.IsNullOrWhiteSpace(txtGuardiansAddress.Text) ? "N/A" : txtGuardiansAddress.Text,
HomeAddress = txtHomeAddress.Text,
LastName = txtLastName.Text,
MaritalStatus = txtMaritalStatus.Text,
MiddleName = string.IsNullOrWhiteSpace(txtMiddleName.Text) ? "N/A" : txtMiddleName.Text,
Mother = txtMothersName.Text,
Nationality = txtNationality.Text,
ParentsAddress = txtParentsAddress.Text,
PlaceOfBirth = txtPlaceOfBirth.Text,
TelNo = string.IsNullOrWhiteSpace(txtTelNo.Text) ? "N/A" : txtTelNo.Text,
StudentImage = pic,
WorkAddress = string.IsNullOrWhiteSpace(txtWorkAddress.Text) ? "N/A" : txtWorkAddress.Text,
};
var result = bal.InsertStudent(bal);
if (result > 0)
{
MessageBox.Show(#"Data successfully added.");
}
var obj = (MdiForm)Application.OpenForms["MdiForm"];
if (obj != null) obj.FillComboBox();
}
I would need to pass all the information from my childform(AddStudent) to the parentform(MdiFOrm) so I can save all the details by clicking on the btnSave in the menubar. I tried creating a public method (SaveDetails()) that can be invoked in the parent form like so:
AddStudent add = new AddStudent();
add.SaveDetails();
But doing the code above will create a new instance and will not save the active childform that has the values to be saved. If there is a way to call a method in the active childform without instantiating (var addStudent = new AddStudent();) that will be great.
Making the method public static won't work in this scenario.
Thank you for your help.
This is the abstract example of doing a callback:
public class Parent
{
public void CreateChild()
{
Child childNew = new Child(this); //here you give over the parents reverence
}
public void SaveStuff(int number)
{
//here you can save the number
}
}
class Child
{
private Parent parent;
public Child(Parent parent)
{
this.parent = parent;
}
public void PressOkButton()
{
this.parent.SaveStuff(4); //here you are doing the callback
}
}
This question already has answers here:
SQLite .NET performance, how to speed up things?
(2 answers)
Closed 7 years ago.
I am having a hard time trying to save the data faster, to a local DB.
Even though this is a one time saving, when the app runs for the first time, it takes like 90 seconds, in a Lumia 920, to save "only" the "map tables".
What I do:
1) I call an API, where I receive all the grids, with its Xs, Ys, Map Id, etc.
2) I deserialize the info based on a class I have defined.
3) For each item, in that info, I save the "misc" info (since I will use it)
4) I save, in a GRIDS table, each grid inside the previous item.
This code snipet is what I use to deserialize the info, and call the function to save in the DB
public class Maps
{
public string id { get; set; }
public string name { get; set; }
public string height { get; set; }
public string width { get; set; }
public string tile { get; set; }
public string shopping_id { get; set; }
public string url { get; set; }
public string updated_at { get; set; }
public string created_at { get; set; }
public GridFirst gridFirst { get; set; }
public GridLast gridLast { get; set; }
public List<Grid> grid { get; set; }
public class GridFirst
{
public string id { get; set; }
public string x { get; set; }
public string y { get; set; }
public string maps_id { get; set; }
public string value { get; set; }
}
public class GridLast
{
public string id { get; set; }
public string x { get; set; }
public string y { get; set; }
public string maps_id { get; set; }
public string value { get; set; }
}
public class Grid
{
public string id { get; set; }
public string x { get; set; }
public string y { get; set; }
public string maps_id { get; set; }
public string value { get; set; }
}
public void deserializeAndConvert(string aaa)
{
JObject myGeneral = JObject.Parse(aaa);
IList<JToken> results = myGeneral["resp"].Children().ToList();
// serialize JSON results into .NET objects
IList<Maps> searchResults = new List<Maps>();
foreach (JToken result in results)
{
Maps searchResult = JsonConvert.DeserializeObject<Maps>(result.ToString());
searchResults.Add(searchResult);
}
var respuesta = from data in searchResults
select new
{
id = data.id,
name = data.name,
height = data.height,
width = data.width,
tile = data.tile,
url = data.url,
lastX = data.gridLast.x,
lastY = data.gridLast.y,
grid = data.grid
};
foreach (var a in respuesta)
{
Database_Controller.getReadyToSaveData("mapinfo", 8, a.id, a.name, a.height, a.width, a.tile, a.url, a.lastX, a.lastY, "", "", "", "", "", "", "");
foreach (var data in a.grid)
{
Database_Controller.getReadyToSaveData("mapgrid", 5, data.id, data.x, data.y, data.maps_id, data.value, "", "", "", "", "", "", "", "", "", "");
}
}
}
}
And these are the functions that save the data, in the DB
public static void getReadyToSaveData(string dbName, int numberOfParams, string param1, string param2, string param3, string param4, string param5, string param6, string param7, string param8, string param9, string param10, string param11, string param12, string param13, string param14, string param15)
{
List<string> myParams = new List<string>();
myParams.Add(param1);
myParams.Add(param2);
myParams.Add(param3);
myParams.Add(param4);
myParams.Add(param5);
myParams.Add(param6);
myParams.Add(param7);
myParams.Add(param8);
myParams.Add(param9);
myParams.Add(param10);
myParams.Add(param11);
myParams.Add(param12);
myParams.Add(param13);
myParams.Add(param14);
myParams.Add(param15);
List<string> myParamsToDB = new List<string>();
for (var i = 0; i < numberOfParams; i++)
{
myParamsToDB.Add(myParams[i]);
}
insertData(dbName, myParamsToDB);
}
public static void insertData(string dbName, List<string> paramsToGo)
{
try
{
using (var connection = new SQLiteConnection("Unicenter.sqlite"))
{
if (dbName == "mapgrid")
{
using (var statement = connection.Prepare(#"INSERT INTO mapgrid (ID,X,Y,MAPS_ID,VALUE)
VALUES(?, ?,?,?,?);"))
{
statement.Bind(1, paramsToGo[0]);
statement.Bind(2, paramsToGo[1]);
statement.Bind(3, paramsToGo[2]);
statement.Bind(4, paramsToGo[3]);
statement.Bind(5, paramsToGo[4]);
// Inserts data.
statement.Step();
statement.Reset();
statement.ClearBindings();
}
}
if (dbName == "mapinfo")
{
using (var statement = connection.Prepare(#"INSERT INTO mapinfo (ID,NAME,HEIGHT,WIDTH,TILE,URL,LASTX,LASTY)
VALUES(?, ?,?,?,?,?,?,?);"))
{
statement.Bind(1, paramsToGo[0]);
statement.Bind(2, paramsToGo[1]);
statement.Bind(3, paramsToGo[2]);
statement.Bind(4, paramsToGo[3]);
statement.Bind(5, paramsToGo[4]);
statement.Bind(6, paramsToGo[5]);
statement.Bind(7, paramsToGo[6]);
statement.Bind(8, paramsToGo[7]);
// Inserts data.
statement.Step();
statement.Reset();
statement.ClearBindings();
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Exception\n" + ex.ToString());
}
}
***Edit: As a kind reminder, in case some people does not see the tags (and mark this question as duplicated), this is FOR WINDOWS PHONE 8.1, so, the functions, references and classes ARE different from plain c#
Any idea on how to make it faster? ... What am I doing wrong?
you can use parallel.for loop which is more faster if you have large data or you can easily check each loop how much time it takes to execute in VS-2015
In my controller I'm looping through items and saving them to my db. The problem is that it saves the first item, but none of the others. I put a breakpoint on the "SaveItem()" line in the loop and it hits it every time, but what seems odd to me is that it only goes through to the method for the 1st item.
What am I doing wrong?
public void SubmitItem(Cart cart, ShippingDetails shippingDetails, ProcessedItems processedItem, string orderID)
{
var cartItems = cart.Lines;
//CartIndexViewModel cartIndex = new CartIndexViewModel();
//var customID = cartIndex.OrderID;
foreach(var item in cartItems)
{
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
}
public class EFProcessedItemsRepository : IProcessedItems
{
private EFDbContext context = new EFDbContext();
public IQueryable<ProcessedItems> ProcessedItem
{
get { return context.ProcessedItems; }
}
public void SaveItem(ProcessedItems processedItem)
{
if(processedItem.ProcessedID == 0)
{
try
{
context.ProcessedItems.Add(processedItem);
context.SaveChanges();
}
catch (Exception)
{
throw;
}
}
else
{
context.Entry(processedItem).State = EntityState.Modified;
}
}
public void DeleteItem(ProcessedItems processedItem)
{
context.ProcessedItems.Remove(processedItem);
context.SaveChanges();
}
}
here is the class for the processedItem:
public class ProcessedItems
{
[Key]
public int ProcessedID { get; set; }
public string OrderID { get; set; }
public int ProductID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public string Category { get; set; }
public string ImageName { get; set; }
public string Image2Name { get; set; }
public string Image3Name { get; set; }
public string Status { get; set; }
//shipping
public string BuyerName { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
public string Country { get; set; }
}
Interface:
public interface IProcessedItems
{
IQueryable<ProcessedItems> ProcessedItem { get; }
void SaveItem(ProcessedItems processedItem);
void DeleteItem(ProcessedItems processedItem);
}
try calling context.SaveChanges() after adding all of the items, I think it should persist them all in one go.
Another thing to try:
Refactor your code so that SaveItem accepts only one item to save, Add it and call SaveChanges()
Loop through the cart items outside the method and call the method with one item to save at a time.
// set orderID, shippingDetails above
foreach(var item in cartItems)
{
ProcessedItems processedItem = new ProcessedItems();
processedItem.OrderID = orderID;
processedItem.ProductID = item.Product.ProductID;
processedItem.Name = item.Product.Name;
processedItem.Description = item.Product.Description;
processedItem.Price = item.Product.Price;
processedItem.Category = item.Product.Category;
processedItem.ImageName = item.Product.ImageName;
processedItem.Image2Name = item.Product.Image2Name;
processedItem.Image3Name = item.Product.Image3Name;
processedItem.BuyerName = shippingDetails.Name;
processedItem.Line1 = shippingDetails.Line1;
processedItem.Line2 = shippingDetails.Line2;
processedItem.Line3 = shippingDetails.Line3;
processedItem.City = shippingDetails.City;
processedItem.State = shippingDetails.State;
processedItem.Zip = shippingDetails.Zip;
processedItem.Country = shippingDetails.Country;
SubmitItem(processedItem);
}
public void SubmitItem(ProcessedItems processedItem)
{
processedItem.Status = "Submitted";
processedItems.SaveItem(processedItem);
}
I think it is because processedItem is the same instance for each loop iteration. So after it has been through SaveItem once, it has its ProcessedID set and therefore won't get processed again.
My first guess is that you always store one entity, which is stored in processedItem, which is a input parameter. Try to create new Entity on each loop and then save it. In other words, you assign values to input parameter
processedItem.OrderID = orderID;
and then store same entity each time, but with changed fields
processedItems.SaveItem(processedItem);