So, I'm making a small version of library inventory manager. I have a method that should call the database, take one DateTime values and compare it with today's date. I have a table with rented books and in every row there is a "rented_till" value. My loop should go through every row and my method should compare those values. The problem is that it doesn't work and even my flags are not working
I tried to use breaking points but even their I can see that compailer skips my code.
This is something new for me, since I never done that some maybe I'm doing something completley wrong. I couldn't find a similary problem. You can see my method below.
public void CheckBooks()
{
OverdueBooksDAL obDAL = new OverdueBooksDAL();
DataTable dt = new DataTable();
dt = obDAL.RentedBooks();
int rows = dt.Rows.Count;
DateTime today = DateTime.Now;
for (int i = 0; i < rows; i++)
{
DateTime rented_till = Convert.ToDateTime(dt.Rows[i]["rented_till"]);
int result = DateTime.Compare(today, rented_till);
if (result > 0)
{
OverdueBook OB = new OverdueBook();
OB.Id = Int32.Parse(dt.Rows[i]["id"].ToString());
OB.Title = dt.Rows[i]["title"].ToString();
OB.Rented_Till = Convert.ToDateTime(dt.Rows[i]["rented_till"]);
string fullname = dt.Rows[i]["name"].ToString() + dt.Rows[i]["surname"].ToString();
OB.Rented_By = fullname;
OverdueBooksDAL obeDAL = new OverdueBooksDAL();
if (obeDAL.InsertOverduebooks(OB))
{
MessageBox.Show("There are new books overdue");
}
}
}
Program compiles and every other part of it works. I've checked the tables and they're getting the data from the data base.
Related
Working on a windows form application that reads in data from csv files and adds the data to a Datagridview. I ran into an issue with all of the rows being added to the datable and being displayed on the datagridview. The datagridview displays the datarows from the first two if conditions and OneRow if condition only. It will not add the rows from the twoRow if condition if the datable and datagridview rows are populated with the OneRow if condition rows. But i want the rows from both OneRow and TwoRow to be displyed. Also the rows from TwoRow do populate the datatable and datagridview when I comment(/**/) out the OneRow if condition. But I need both to populate the table. Thanks in advance!
Construct.MainDataTable.Columns.Add("Date", typeof(DateTime));
Construct.MainDataTable.Columns.Add("Time");
Construct.MainDataTable.Columns.Add("Serial");
Construct.MainDataTable.Columns.Add("Type");
Construct.MainDataTable.Columns.Add("level");
Construct.MainDataTable.Columns.Add("price");
Construct.MainDataTable.Columns.Add(" Limit");
Construct.MainDataTable.Columns.Add("last Limit");
Construct.MainDataTable.Columns.Add("Data");
..........................
...............................................
DataRow oneRow = Construct.MainDataTable.NewRow();
DataRow twoRow = Construct.MainDataTable.NewRow();
dataGridView2.AllowUserToAddRows = false;
if (line.Split(',')[2].Equals("Time"))
{
time = line.Split(',')[3];
date = line.Split(',')[1];
}
if (line.Split(',')[2].Equals("Level"))
{
level = line.Split(',')[3];
}
//OneROw(IF condition)
if ((Convert.ToDecimal(line.Split(',')[8])) < (Convert.ToDecimal (line.Split(',')[12])))
{
type = line.Split(',')[1];
serial = line.Split(',')[7];
price = line.Split(',')[3];
Limit = line.Split(',')[8];
lastLimit = line.Split(',')[10];
Data = line.Split(',')[12];
oneRow["Date"] = date;
oneRow["Time"] = time;
oneRow["Serial"] = serial;
oneRow["Type"] = type;
oneRow["level"] = level;
oneRow["price"] = price;
oneRow[" Limit"] = Limit;
oneRow["last Limit"] = lastlimit;
oneRow["Data"] = Data;
Construct.MainDataTable.Rows.Add(oneRow);
}
//TwoROw(IF condition)
if ((line.Contains('"')) && ((line.Contains("NG"))))
{
price = line.Split(',')[3];
type = line.Split(',')[1];
serial = line.Split(',')[7];
Limit = line.Split('"')[7];
var valLimit = Limit.Split(',').Select(a => Convert.ToInt32(a, 16));
var limitJoin = String.Join(",", valLimit);
lastlimit = line.Split('"')[1];
var vallastLimit = lastlimit.Split(',').Select(d => Convert.ToInt32(d, 16));
var lastJoin = String.Join(",", vallastLimit);
Data = line.Split('"')[5];
var valDatas = Data.Split(',').Select(s => Convert.ToInt32(s, 16));
var dataJoin = String.Join(",", valDatas);
twoRow["Date"] = date;
twoRow["Time"] = time;
twoRow["Serial"] = serial;
twoRow["Type"] = type;
twoRow["level"] = level;
twoRow["price"] = price;
twoRow["Limit"] = limitJoin;
twoRow["last Limit"] = lastJoin;
twoRow["Data"] = dataJoin;
Construct.MainDataTable.Rows.Add(twoRow);
}
dataGridView2.DataSource = Construct.MainDataTable;
Can't add a comment because I don't have enough karma so I ask my questions here: So, if I understood your problem you can't add data from one .csv file if it have more then one row? Why are you using 2 different if conditions for row in .csv file?
If you have empty data in row never mind you can still place them to your DataTable column, so you can use loop to add data from .csv to your DataTable. Try some thing like this:
public static DataTable CsvToDataTable(string csv)
{
DataTable dt = new DataTable();
string[] lines = csv.Split(new[] { "\r\n", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
Regex onlyDeimiterComma = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
for (int i = 0; i < lines.Length; i++)
{
DataRow row = dt.NewRow();
string[] cells = onlyDeimiterComma.Split(lines[i]);
for (int j = 0; j < cells.Length; j++)
{
if (i == 0)
{
if (j == 0)
{
dt.Columns.Add(cells[j], typeof(DateTime));
}
else
{
dt.Columns.Add(cells[j]);
}
}
else
{
row[j] = cells[j];
}
}
dt.Rows.Add(row);
}
return dt;
}
Just call this method anywhere in your code and give it string read from your .csv file.
You can try to compile this code here and see how it works on .csv data with different data (empty columns, quoted text, quoted commas)
UPD: If you need to fill DataTable from two different .csv files you can still use code above. Just call it twice for both files and then Merge two DataTable, like this:
DataTable dt = CsvToDataTable(csvFileOne);
DataTable dtTwo = CsvToDataTable(csvFileTwo);
dt.Merge(dtTwo);
I am currently working on a project that processing a file and create a datatble and create a "excel" look data grid view for the processed results.
The flow is open a new file and click process. After that, the datagridview will show a table with processed data. The following is the function to create a table and input the values for each columns.
public DataTable createDataTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Date Time");
dt.Columns.Add("CAT Protocol");
dt.Columns.Add("Display");
//dt.Columns.Add("Command ID");
dt.Columns.Add("Command Description");
List<string> timeList = time();
List<string> catList = read(userSelectedFilePath);
List<string> displayList = translate(catList);
List<string> idList = commandID(catList);
List<string> descList = commandDescription(idList);
int rows = catList.Count();
for (int i = 0; i < rows; i++)
{
DataRow _myRow = dt.NewRow();
_myRow["Date Time"] = timeList.ElementAt(i);
_myRow["CAT Protocol"] = catList.ElementAt(i);
_myRow["Display"] = displayList.ElementAt(i);
//_myRow["Command ID"] = idList.ElementAt(i);
_myRow["Command Description"] = descList.ElementAt(i);
dt.Rows.Add(_myRow);
}
return dt;
}
Then the user can use "Find" function which will refresh the results based on the users' input. When user choose Find, a textbox will pop out. When user press enter, the datatable will be refreshed based on Command Description.
I think I need to write some code in this function.
private void TextBoxKeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
//write something here
}
}
Here is the screenshot of my interface.
My question is how to implement find function in this application. I will really appreciate all kinds of help. Thanks!
You could use LINQ to get all your indices of the corresponding lines:
var indices = descList.Select((desc, index) => new { desc, index = index }).Where(item => item .desc.Contains(SearchTextBox.Text)).Select(item => item.index).ToList();
Then clear your DataGridViewand readd all those items with the indices, you get.
for (int i = 0; i < indices.Count; i++)
{
DataRow _myRow = dt.NewRow();
_myRow["Date Time"] = timeList.ElementAt(indices[i]);
_myRow["CAT Protocol"] = catList.ElementAt(indices[i]);
_myRow["Display"] = displayList.ElementAt(indices[i]);
//_myRow["Command ID"] = idList.ElementAt(indices[i]);
_myRow["Command Description"] = descList.ElementAt(indices[i]);
dt.Rows.Add(_myRow);
}
Furthermore I'd suggest you build a class for each row:
public class LogLine{
public DateTime Date {get;set;} //maybe Convert to DateTime or change to string
public string Protocol {get;set;}
public string Display {get;set;}
public string Command {get;set;}
}
Later you can simply use List<LogLine> to populate your DataGridView.
This will make your code cleaner, and will simplify much of the code.
This is the first time I am using DataSet. Below is my code
var transactionSet = new ModelExecutionContext()
{
TransactionSet = new DataSet()
{
Tables = { new DataTable()
{
TableName = "transaction_history"
}
}
}
};
transactionSet.TransactionSet.Tables["transaction_history"].Columns.Add().ColumnName = "retailer_reference_id";
var retailerReferenceIdRow = transactionSet.TransactionSet.Tables["transaction_history"].NewRow();
retailerReferenceIdRow["retailer_reference_id"] = 8;
transactionSet.TransactionSet.AcceptChanges();
I am unit testing a method in a class which has the datasets. I am trying to mock those datasets. I thought transactionSet.TransactionSet.AcceptChanges(); will save the changes into the DataSet, but in the execution, I am getting context?.TransactionSet?.Tables["transaction_history"]?.Rows.Count = 0
Is anything incorrect with my code?
After you created object of row you need to add row to table.
transactionSet.TransactionSet.Tables["transaction_history"].Rows.Add(retailerReferenceIdRow);
I have been working on a website and for the first time started using Entity Framework 6. The application is MVC4, C#.
The issue I am having is that EF not always pulls data from the table. For example I will load a page and get an empty result. But if I refresh the page then the data from database will be shown. If I refresh again it goes empty again.
Basically, it's been pulling data every second time (and been very consistent in this behaviour).
I'm really at lost, I even tried to pull data from view instead of the table, but the behaviour stayed consistent.
Here is the relevant code from my application
#region returns list of new files uploaded in the last 24 hours
[HttpPost]
[InitializeSimpleMembership]
public ActionResult LastUploadedFiles()
{
var path = Server.MapPath("~/" + this.uploadPath + "/");
FileListModel filesList = new FileListModel();
using (CCGFileShareEntities db = new CCGFileShareEntities())
{
db.Configuration.AutoDetectChangesEnabled = false;
db.Configuration.ValidateOnSaveEnabled = false;
DateTime daydiff = DateTime.Now.AddHours(-24);
filesList.files = (from r in db.viewFileUploads
where r.file_upload_date >= daydiff && r.file_deleted == 0
//orderby r.file_upload_date descending
select new FileModels()
{
id = r.id,
fileName = r.file_name,
file_description = (r.file_description == null ? "" : r.file_description),
upload_extention = r.upload_extention,
upload_folder = r.upload_folder,
file_upload_date = r.file_upload_date,
upload_owner_id = r.upload_owner_id.ToString(),
file_size = r.file_size.ToString(),
description_is_visible = false
}).ToList();
//get owner and convert date
FileHelpers fhelpers = new FileHelpers();
for (int i = 0; i < filesList.files.Count(); i++)
{
filesList.files[i].file_upload_date_string = filesList.files[i].file_upload_date.ToString("MMM dd, yyyy");
int ownerID = int.Parse(filesList.files[i].upload_owner_id);
filesList.files[i].fileOnwerName = fhelpers.getUserName(ownerID);
}
filesList.currentUserID = WebSecurity.GetUserId(User.Identity.Name);
//public string upload_owner_id { get; set; }
}
return Json(filesList);
}
I've no idea why it doesn't pull data every single time as it supposed to do.
I'm really at loss and would appreciate your help.
Thanks in advance,
I am getting the error
"An item with the same key has already been added"
in production randomly.if i execute the below code in local i am not getting the issue.please suggestion needed to solve this issue.
//check for whether Midas.DAB is Enabled in the App.Config File
if (ProcessMidasDab)
{
var dvFilteredMidasDabDetails = new DataView(dtMidasDabandSurgDetails) {
RowFilter = "not (LastReceivedOnForDAB is null)" };
dtCmMidasDabAlerts.Columns.Add("ClientID");
dtCmMidasDabAlerts.Columns.Add("LastFileReceivedDate");
dtCmMidasDabAlerts.Columns.Add("SendingSystem");
//Get the Cut-off time for Midas.DAB from the App.config.
var timeStamp = ConfigurationManager.AppSettings["TimeLapseforMidasDABinhrs"];
//Logic to check the Feed for Midas.DAB
foreach (DataRowView dv in dvFilteredMidasDabDetails)
{
midasDabClientList.Add(Convert.ToInt32(dv["ClientID"]));
var timeDifference =
(DateTime.Now - Convert.ToDateTime(dv["LastReceivedOnForDAB"])).TotalHours;
if (timeDifference > Convert.ToDouble(timeStamp))
{
var drNewRow = dtCmMidasDabAlerts.NewRow();
drNewRow["ClientID"] = dv["ClientID"];
drNewRow["LastFileReceivedDate"] = dv["LastReceivedOnForDAB"];
drNewRow["SendingSystem"] = "Midas.DAB";
dtCmMidasDabAlerts.Rows.Add(drNewRow);
}
}
dabclients = midasDabClientList;
}
You have two time assign this
drNewRow["Clientid"] = 12;
drNewRow["ClientID"] = dv["ClientID"];
Please remove this one
drNewRow["Clientid"] = 12;
and also you have two time assigned this
dtCmMidasDabAlerts.Columns.Add("ClientID");