I have created a simple code that reads in data from a csv file then transfers that data to a datatable. the datatable is displayed on a datagridview. I would like to display two columns from my datable to a line chart. the application works but no chart appears. What am i doing wrong.
namespace WindowsFormsApp6
{
public partial class Form1 : Form
{
public static class Construct
{
public static DataTable MainDataTable = new DataTable();
public static List<string> fileDirectories = new List<string>();
public static List<string> pathList = new List<string>();
}
public class datalist
{
public decimal DataLimit { get; set; }
public DateTime Date1 { get; set; }
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Construct.MainDataTable.Dispose();
Construct.MainDataTable.Columns.Clear();
Construct.MainDataTable.Rows.Clear();
Construct.fileDirectories.Clear();
chart1.Series.Clear();
chart1.ChartAreas.Clear();
GC.Collect();
string earliestdate = dateTimePicker1.Value.ToString("yyyy-MM-dd");
string latestdate = dateTimePicker2.Value.ToString("yyyy-MM-dd");
DateTime EarlyTime = dateTimePicker1.Value.Date;
DateTime LateTime = dateTimePicker2.Value.Date;
List<string> fileDirectories = new List<string>();
if (1 == 1)
{
fileDirectories.Add(#"C:\Users\999\Downloads\x");
}
foreach (string selectedPath in fileDirectories)
{
string[] level1 = Directory.GetFiles(#selectedPath, "*.csv", SearchOption.AllDirectories);
foreach (string level2 in level1)
{
DateTime lastModDate = File.GetLastWriteTime(#level2);
if (lastModDate >= Convert.ToDateTime(earliestdate) && lastModDate < Convert.ToDateTime(latestdate).AddDays(1))
{
Construct.pathList.Add(level2);
}
}
}
chart1.Visible = false;
DateTime beginDate = dateTimePicker1.Value;
DateTime endDate = dateTimePicker2.Value;
Construct.MainDataTable.Columns.Add("Date",typeof(DateTime));
Construct.MainDataTable.Columns.Add("Time");
Construct.MainDataTable.Columns.Add("TestNo");
Construct.MainDataTable.Columns.Add("Lower Limit");
Construct.MainDataTable.Columns.Add("Upper Limit");
Construct.MainDataTable.Columns.Add("Data", typeof(decimal));
foreach (string x in Construct.pathList)
{
using (FileStream stream = File.Open(x, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader reader = new StreamReader(stream))
{
string LowLimit = "";
string Upplimit = "";
string testNo = "";
string date = "";
string time = "";
string Data = "";
while (!reader.EndOfStream)
{
try
{
var line = reader.ReadLine();
string[] values = line.Split(',');
if (line.Split(',')[0].Equals("Date"))
{
date = line.Split(',')[1];
time = line.Split(',')[3];
}
if (line.IndexOf("7u883", StringComparison.CurrentCultureIgnoreCase) >= 0)
{
DataRow allShiftRow = Construct.MainDataTable.NewRow();
Data = line.Split(',')[12];
testNo = line.Split(',')[3];
Upplimit = line.Split(',')[8];
LowLimit = line.Split(',')[10];
allShiftRow["Date"] = date;
allShiftRow["Time"] = time;
allShiftRow["TestNo"] = testNo;
allShiftRow["Upper Limit"] = Upplimit;
allShiftRow["Lower Limit"] = LowLimit;
allShiftRow["Data"] = Data;
Construct.MainDataTable.Rows.Add(allShiftRow);
dataGridView1.DataSource = Construct.MainDataTable;
List<datalist> DAList = new List<datalist>();
DAList = (from DataRow dr in Construct.MainDataTable.Rows
select new datalist()
{
DataLimit = Convert.ToDecimal(dr["Data"]),
}).ToList();
List<datalist> DATEList = new List<datalist>();
DATEList = (from DataRow dr in Construct.MainDataTable.Rows
select new datalist()
{
Date1 = Convert.ToDateTime(dr["Date"]),
}).ToList();
var series1 = new Series
{
Name = "Series1",
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Line
};
//chart1.Series[0].XValueType = ChartValueType.DateTime;
chart1.ChartAreas[0].AxisX.LabelStyle.Format = "yyyy-MM-dd";
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Weeks;
chart1.ChartAreas[0].AxisX.IntervalOffset = 1;
chart1.Series[0].XValueType = ChartValueType.DateTime;
chart1.ChartAreas[0].AxisX.Minimum = EarlyTime.ToOADate();
chart1.ChartAreas[0].AxisX.Maximum = LateTime.ToOADate();
chart1.ChartAreas[0].AxisY.Interval = .25;
chart1.ChartAreas[0].AxisY.Minimum = 0;
chart1.ChartAreas[0].AxisX.Maximum = 4;
chart1.Series.Add(series1);
series1.Points.AddXY(DATEList, DAList);
}
}
catch
{
Console.WriteLine("over.");
}
chart1.Visible = true;
}
}
}
}
}
}
}
Thank you in advanced!!
Related
I'm making a journal application for myself in c# where i can make journals with dates attached to it.
I'm using a foreach statement to let the data display in the textboxes. I can't figure out how to display the journals in order (old->new) with the dates in Textbox3 (t3). I live in Europe so It's DD/MM/YYYY. I hope it's clear, thanks.
string[] journalfolder = Directory.GetDirectories(#"D:\panel\Journal\", "*");
foreach (string file in journalfolder)
{
Color grey = new Color();
TextBox t1 = new TextBox();
t1.Name = "t1_" + (t1.Controls.Count + 1);
t1.Location = new Point(265, 20);
grey = Color.FromArgb(31, 31, 31);
t1.Width = 332;
t1.BackColor = grey;
t1.BorderStyle = BorderStyle.None;
t1.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\text.txt");
t1.Text = lines[0];
}
catch { }
TextBox t2 = new TextBox();
t2.Name = "t2_" + (t2.Controls.Count + 1);
t2.Location = new Point(265, 39);
t2.Width = 332;
t2.Height = 155;
grey = Color.FromArgb(31,31,31);
t2.BackColor = grey;
t2.Multiline = true;
t2.BorderStyle = BorderStyle.None;
t2.ForeColor = Color.White;
try
{
using (var sr = new StreamReader(file + #"\text.txt"))
{
string line;
while ((line = sr.ReadLine()) != null)
{
t2.Text = line;
}
}
}
catch { }
TextBox t3 = new TextBox();
t3.Name = "t3_" + (t3.Controls.Count + 1);
t3.Location = new Point(265, 199);
grey = Color.FromArgb(31, 31, 31);
t3.Width = 332;
t3.BackColor = grey;
t3.BorderStyle = BorderStyle.None;
t3.ForeColor = Color.White;
try
{
string[] lines = File.ReadAllLines(file + #"\date.txt");
t3.Text = lines[0];
}
catch { }
Panel image = new Panel();
image.Name = "image" + (image.Controls.Count + 1);
image.Location = new Point(20, 20);
image.BackgroundImageLayout = ImageLayout.Zoom;
image.Width = 223;
image.Width = 192;
try
{
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg,*.wmf,*.ico,*.eps,*.tif,*.tiff";
foreach (string imageFile in Directory.GetFiles(file + #"\Files", "*.*", SearchOption.AllDirectories).Where(s => supportedExtensions.Contains(Path.GetExtension(s).ToLower())))
{
Console.WriteLine(imageFile);
image.BackgroundImage = Image.FromFile(imageFile);
}
}
catch { }
Panel p = new Panel();
p.Name = "panel" + (flowLayoutPanel1.Controls.Count + 1);
p.BackColor = Color.FromArgb(49,49,49);
p.Width = 628;
p.Height = 236;
p.Controls.Add(t1);
p.Controls.Add(t2);
p.Controls.Add(t3);
p.Controls.Add(image);
flowLayoutPanel1.Controls.Add(p);
}
I'm not quite sure I understand your requirement correctly, but I'll give it a try ...
The date is managed in a date.txt file. It contains the date in the format DD/MM/YYYY, correct?
DateTime timestamp = DateTime.Parse("ValueFromFile");
It is best to put the title, text and date in a class or struct. Maybe something like this:
public class Data
{
public string Title { get; set; }
public string Text { get; set; }
public DateTime Timestamp { get; set; }
}
You should put all the elements you have read into a list or a dictionary before displaying them on the UI and processing them further. Once all the data is in this list, you can easily sort it by date using LINQ.
List<Data> values = new List<Data>();
// TODO
// Add the items
foreach (Data item in values.OrderBy((item) => item.Timestamp))
{
}
// Or
foreach (Data item in values.OrderByDescending((item) => item.Timestamp))
{
}
I need to compare two lists of same type. Assume I have CurrentSC List(Current modified data by user) and PreviousSC List(Saved data from database) of below class.
public class SoftClose
{
private int AID = -1;
private bool _softCloseInd;
private bool _softCloseEditInd;
private string _softClosedBy;
private DateTime _softClosedDate;
private ReferenceEnums.ActionStatus _status = ReferenceEnums.ActionStatus.NO_CHANGE;
}
public static void TPostProcessAddRemoveSoftCloseStopPaymentPrefixes(IFPMServiceInternal fpmService, AgreementRevision revision)
{
List<SoftClose> psc = null;
List<SoftClose> csc = null;
string fanValue = revision.Agreement.FAN;
psc = fpmService.GetSoftCloseByFAN(fanValue);
if (psc != null)
{
//var currentprefixes = revision.Details.Where(x => x.Prefix != null).Select(y => y.Prefix).Distinct();
//Create current SoftClose object using revision object
foreach (var prefix in revision.Details.Where(x => x.Prefix != null).Select(y => y.Prefix).Distinct())
{
var newSF =
new SoftClose
{
Id = -1,
Status = ReferenceEnums.ActionStatus.NO_CHANGE,
AgreementRevId = revision.Id,
AgreementId = revision.Agreement.Id,
WorkflowStatus = revision.WorkflowStatus,
FAN = revision.Agreement.FAN,
PID = (int)revision.Agreement.PID,
Prefix = prefix
};
csc.Add(newSF);
}
//Now you have previous and current softcloses to compare prefixes...
psc.OrderBy(x => x.Prefix.Id);
csc.OrderBy(x => x.Prefix.Id);
for(int i = 0; i < csc.Count; i++)
{
}
}
}
Lets say I have changed D3 value in PreviousSC to D2 in CurrentSC. Now i need to delete D3 value from database(As D2 value already there in database i don't need to insert) and chnage _status to DELETE and I added D4 value in CurrentSC which is not there is PreviousSC. Now I need to add D4 value in database and assign _softCloseInd and _softCloseEditInd to Y and change _status to ADD.
How to achieve this in best way?
class Program
{
static void Main(string[] args)
{
List<SoftClose> psc = new List<SoftClose>(){
new SoftClose(){ID=1, Status = "NO_CHANGE",AID=19, Prefix = "D1"},
new SoftClose(){ID=2, Status = "NO_CHANGE",AID=20, Prefix = "D2"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID=21, Prefix = "D3"},
new SoftClose(){ID=3, Status = "NO_CHANGE",AID=22, Prefix = "D9"}
};
List<SoftClose> csc = new List<SoftClose>(){
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=19, Prefix = "D2"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=20, Prefix = "D2"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=21, Prefix = "D6"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=22, Prefix = "D4"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=23, Prefix = "D5"},
new SoftClose(){ID=-1, Status = "NO_CHANGE",AID=24, Prefix = "D3"}
};
List<SoftClose> esc = new List<SoftClose>();
Console.WriteLine("---------Previous List----------");
foreach (var item in psc)
{
Console.WriteLine($"Id:{item.ID}, Desc1:{item.Prefix}, Status:{item.Status}");
}
Console.WriteLine("--------------------------------------");
Console.WriteLine("---------Current List----------");
foreach (var item in csc)
{
Console.WriteLine($"Id:{item.ID}, Desc1:{item.Prefix}, Status:{item.Status}");
}
Console.WriteLine("--------------------------------------");
var addlist = csc.Where(c => psc.All(p => !p.Prefix.Equals(c.Prefix)));
foreach (var n in addlist)
{
var index = csc.FindIndex(p => p.Prefix.Equals(n.Prefix));
csc[index].Status = "ADD";
esc.Add(csc[index]);
}
var deletelist = psc.Where(p => p.Status.Equals("NO_CHANGE") && !csc.Exists(c => c.Prefix.Equals(p.Prefix)));
foreach (var n in deletelist)
{
var index = psc.FindIndex(c => c.Prefix.Equals(n.Prefix));
if (psc.FindIndex(c => c.Prefix.Equals(n.Prefix)) >= 0)
{
psc[index].Status = "REMOVE";
esc.Add(psc[index]);
}
}
Console.WriteLine("---------Effective List----------");
foreach (var item in esc)
{
Console.WriteLine($"Id:{item.ID}, Prefix:{item.Prefix}, Status:{item.Status}");
}
Console.ReadLine();
}
}
public class SoftClose
{
public int ID = -1;
public int AID = -1;
public int WFID = -1;
public string Prefix;
public DateTime SCDATE;
public string Status;
}
I'm reading a CSV file with MemoryStream to insert all it's data in the datatable.
Why inserted data in the database is disordered compare to my DataTable in code?
this is sample code:
using (Stream stream = new MemoryStream(bytes))
{
using (TextFieldParser reader2 = new TextFieldParser(stream, Encoding.GetEncoding(1256)))
{
string lineString = "";
var firstLine = reader2.ReadLine();
lineString = reader2.ReadToEnd();
var largeText = lineString.Split(this.RecordDelimiter);
foreach (var item in largeText)
{
if (!string.IsNullOrEmpty(item))
{
DataRow row = dt.NewRow();
row[0] = _databaseRepository.GetSequencerNextVal("cms_batchfile_records_seq");
row[1] = Convert.ToInt32(requestId);
row[2] = DateAndTime.GetServerDate();
row[3] = DateAndTime.GetServerTime();
row[4] = null;
row[5] = null;
row[6] = Convert.ToInt32(formatId);
row[7] = (int)BatchFileRecords_ProcessStatusEnum.NotProcess;
row[8] = null;
row[9] = item;
dt.Rows.Add(row);
_log.Info("Service"+item);
}
}
}
}
_batchFileRecordsRepository.InsertDatas(dt);
public void InsertDatas(DataTable dt)
{
try
{
BatchFileRecords item;
for (int i = 0; i < dt.Rows.Count; i++)
{
item = new BatchFileRecords()
{
Record_id = Convert.ToInt32(dt.Rows[i].ItemArray[0]),
Request_id = Convert.ToInt32(dt.Rows[i].ItemArray[1]),
Record_date = dt.Rows[i].ItemArray[2].ToString(),
Record_time = dt.Rows[i].ItemArray[3].ToString(),
Process_date = dt.Rows[i].ItemArray[4].ToString(),
Process_time = dt.Rows[i].ItemArray[5].ToString(),
Dataformat_id = Convert.ToInt32(dt.Rows[i].ItemArray[6]),
Processstatus = Convert.ToInt32(dt.Rows[i].ItemArray[7]),
Processresult = dt.Rows[i].ItemArray[8].ToString(),
Data = dt.Rows[i].ItemArray[9].ToString()
};
_unitOfWork.Session.Save(item);
}
_unitOfWork.Commit();
}
catch (Exception ex)
{
throw;
}
}
for example my file is :
2506737718,WFP,t,t,13830811,241641941709,9190517705,,F,,,14160
2506156741,WFP,t,t,13840915,409742096044,9195690240,,F,,,14160
2506158590,WFP,t,t,13840318,038664583449,9182550182,,F,,,14160
in db is:
2506737718,WFP,t,t,13830811,241641941709,9190517705,,F,,,14160
2506158590,WFP,t,t,13840318,038664583449,9182550182,,F,,,14160
2506156741,WFP,t,t,13840915,409742096044,9195690240,,F,,,14160
primary key in db is Record_id that are 2506737718, 2506158590,2506156741.
I am developing the my asp.net project, I'm try to make ASP.net text box for Auto Generate code, but its not working correctly, sample Auto Generate code = ID1.
I'm try to use this part,
string txt = txtBatchNo.Text;
txtBatchNo.Text = "C" + Convert.ToInt32(txt.Substring(1, txt.Length - 1)) + 1;
Code:
protected void btnAdd_Click(object sender, EventArgs e)
{
int newId = 1;
if (selectGRNDetailId == -1)
{
{
try
{
if (dtFabricItem.Rows.Count > 0)
{
newId = Convert.ToInt32(dtFabricItem.Rows[dtFabricItem.Rows.Count - 1]["GRNDetailsID"].ToString()) + 1;
}
}
catch (Exception)
{
newId = 1;
}
}
}
else
{
newId = selectGRNDetailId;
}
if (dtFabricItem == null)
{
CreateFabricDetails();
dtFabricItem = dt;
}
else
{
CreateFabricDetails();
}
DataRow dr2 = null;
dr2 = dt.NewRow();
dr2["GRNDetailsID"] = newId;
dr2["GRNDetailID"] = selectGRNId;
dr2["BatchNO"] = txtBatchNo.Text;
dr2["ItemId"] = Convert.ToInt32(ddlYarnName.SelectedValue);
dr2["ItemName"] = ddlYarnName.SelectedItem.Text;
dr2["LotId"] = Convert.ToInt32(ddlLotNo.SelectedValue);
dr2["LotName"] = ddlLotNo.SelectedItem.Text;
dr2["FibetLot"] = txtFiberLot.Text;
dr2["ContainsNo"] = txtContainsNO.Text;
dr2["Shade"] = txtShade.Text;
dr2["Quantity"] = Convert.ToDecimal(txtQty.Text).ToString();
dr2["YarnPrice"] = Convert.ToDecimal(txtYarnPrice.Text).ToString();
dr2["Cornweight"] = Convert.ToDecimal(txtCornWeight.Text).ToString();
dr2["BoxWeight"] = Convert.ToDecimal(txtBoxWeight.Text).ToString();
dr2["NumberofCones"] = Convert.ToDecimal(txtNumberofcones.Text).ToString();
dr2["Numberofboxes"] = Convert.ToDecimal(txtNumberofboxes.Text).ToString();
dt.Rows.Add(dr2);
//txtNumberofcones.Text = (Convert.ToDecimal(txtBoxWeight.Text) / Convert.ToDecimal(txtCornWeight.Text)).ToString();
if (dtFabricItem == null || dtFabricItem.Rows.Count == 0)
{
dtFabricItem = dt;
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
}
else
{
dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.Merge(dt);
}
//dtFabricItem.PrimaryKey = new DataColumn[] { dtFabricItem.Columns["GRNDetailsID"] };
dtFabricItem.AcceptChanges();
gvrItemDetails.DataSource = dtFabricItem;
gvrItemDetails.DataBind();
selectGRNDetailId = -1;
ClearDetails();
}
TextBox Id = `txtBatchNo`
I am newbee to .net code. I can understand the code but, feeling difficult to do changes. I am calling the method "threading" and passing a object parameter . I want to fill data in that object to fill in the data table. But, I am getting an error at that point. I am pasting all the code below and please do the needful help.
The below is the error message I am getting:
"Object is not an ADODB.RecordSet or an ADODB.Record.\r\nParameter name: adodb"
and error is at step oleDA1.Fill(dt1, don);
public class Report
{
public string ScheduleId;
public string reportName;
public string Frequency;
public string Customer;
public string Code;
public string ReportPath;
public string ReportId;
public string ReportFormat;
public string StartDate;
public string EndDate;
}
public List<Report> Populatereport(object SSISreport)
{
List<Report> list = new List<Report>();
Report al = null;
bool fireAgain = true;
using (OleDbDataAdapter oleDA = new OleDbDataAdapter())
using (DataTable dt = new DataTable())
{
oleDA.Fill(dt, SSISreport);
foreach (DataRow _row in dt.Rows)
{
al = new Report();
al.reportName = _row["ReportName"].ToString();
al.ScheduleId = _row["ScheduleId"].ToString();
al.Frequency = _row["Frequency"].ToString();
al.Customer = _row["Customer"].ToString();
al.Code = _row["code"].ToString();
al.ReportId = _row["ReportId"].ToString();
al.ReportFormat = _row["ReportFormat"].ToString();
al.ReportPath = _row["ReportPath"].ToString();
al.StartDate = _row["StartDate"].ToString();
al.EndDate = _row["EndDate"].ToString();
list.Add(al);
}
}
return list;
}
private object threading(object don)
{
Report aa = new Report();
DataRow row1;
ReportEnv env = null;
using (OleDbDataAdapter oleDA1 = new OleDbDataAdapter())
using (DataTable dt1 = new DataTable())
{
oleDA1.Fill(dt1, don);--err0r at this point
row1 = dt1.Rows[0];
aa.reportName = row1["ReportName"].ToString();
aa.ScheduleId = row1["ScheduleId"].ToString();
aa.Frequency = row1["Frequency"].ToString();
aa.Customer = row1["Customer"].ToString();
aa.ColcoCode = row1["code"].ToString();
aa.ReportId = row1["ReportId"].ToString();
aa.ReportFormat = row1["ReportFormat"].ToString();
aa.ReportPath = row1["ReportPath"].ToString();
aa.StartDate = row1["StartDate"].ToString();
aa.EndDate = row1["EndDate"].ToString();
}
ParameterValue[] paramval = new ParameterValue[5];
paramval[0] = new ParameterValue();
paramval[0].Name = "Startdate";
paramval[0].Value = aa.StartDate;
paramval[1] = new ParameterValue();
paramval[1].Name = "Enddate";
paramval[1].Value = aa.EndDate;
paramval[2] = new ParameterValue();
paramval[2].Name = "ReportID";
paramval[2].Value = aa.ReportId;
paramval[3] = new ParameterValue();
paramval[3].Name = "Code";
paramval[3].Value = aa.Code;
paramval[4] = new ParameterValue();
paramval[4].Name = "Frequency";
paramval[4].Value = aa.Frequency;
ReportExecutionService rs = new ReportExecutionService();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs.Url = "some url";
rs.LoadReport(aa.ReportPath, null);
rs.SetExecutionParameters(paramval, "en-GB");
String filename = env.Code + "_" + aa.reportName + DateTime.UtcNow.ToString("_dd-MM-yyyy_hh-mm-ss.fff") + "." + aa.ReportFormat;
//Render the report and generate pdf
Byte[] results;
string encoding = String.Empty;
string mimeType = String.Empty;
string extension = String.Empty;
Warning[] warnings = null;
string[] streamIDs = null;
string deviceInfo = null;
results = rs.Render(aa.ReportFormat, deviceInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
using (FileStream stream = File.OpenWrite(path+ filename))
{
stream.Write(results, 0, results.Length);
}
return null;
}
public void Main()
{
List<Report> aq = new List<Report>();
aq = Populatereport(Dts.Variables["vnSource_SQL_Result"].Value);
for (int i = 0; i < aq.Count; i++)
{
threading(aq[i]);
}
}
Check your Report class, I guess it should be casted to Recordset or Record according to msdn: https://msdn.microsoft.com/en-us/library/5s322715(v=vs.110).aspx