ASP.NET MVC : accesing object properties - c#

I'm converting my code for specific models to a generic (all models will be accepted) version so I'm converting my label border but I can't access data in model because of I was accessing them like this:
worksheet.Cells["A" + index].Value = temp[i - 2].CarID.ToString();
but now I converted this access to something like this:
worksheet.Cells[L + index].Value = temp[i - 2].names[j].ToString();
but it's not working. I understand first one accesses object values but second one tries to access different one so how can I access this object values? I'm past full code for this function can you give me some idea about this situation? Thanks for help
public void EEPCreateExcelGeneric(ReportRange reportRange)
{
using (ExcelPackage excel = new ExcelPackage())
{
// var temp = db.Database.SqlQuery<CarsTrxViewModel>(SqlCars.CarsTrxByID()).ToList();
var temp = db.Cars.ToList();
Cars cars = new Cars();
// var properties = temp.GetType().GetProperties();
var names = new List<string>();
var properties = cars.GetType().GetProperties();
foreach (var item in properties)
{
var attribute = (DisplayNameAttribute)item.GetCustomAttribute(typeof(DisplayNameAttribute), true);
if (attribute != null)
{
names.Add(attribute.DisplayName);
}
else
{
names.Add(item.Name);
}
}
// System.Diagnostics.Debug.WriteLine(properties);
DateTime startdate = reportRange.StartDate;// ?? new DateTime(2000, 10, 10, 1, 1, 1, 1);
DateTime enddate = reportRange.EndDate;// ?? DateTime.Now;
DateTime now = DateTime.Now;
string date = now.ToShortDateString();
string time = now.ToLongTimeString();
date = date + "-" + time;
// modeli çekerken db de temizlersek çok daha hızlı olur
foreach (var item in temp.ToList())
{
if (item.CreateDate < startdate || item.CreateDate > enddate)
{
temp.Remove(item);
}
}
int RowRange = temp.Count();
string name = "Report_";
date = date.Replace(" ", "_");
date = date.Replace(",", "_");
date = date.Replace(":", "-");
date = date.Replace("/", "_");
string sonu = ".xls";
date += sonu;
name += date;
ExcelRecords m = new ExcelRecords();
m.IsExist = false;
m.CreateDate = now;
m.EndDate = enddate;
m.StartDate = startdate;
m.GuidName = name;
db.ExcelRecords.Add(m);
db.SaveChanges();
excel.Workbook.Worksheets.Add("Worksheet1");
var worksheet = excel.Workbook.Worksheets["worksheet1"];
//worksheet.Cells["A1"].Value = "CarID";
//worksheet.Cells["B1"].Value = "CarBrand";
//worksheet.Cells["C1"].Value = "CarModel";
//worksheet.Cells["D1"].Value = "CreateDate";
//worksheet.Cells["A1"].Style.Font.Bold = true;
//worksheet.Cells["B1"].Style.Font.Bold = true;
//worksheet.Cells["C1"].Style.Font.Bold = true;
//worksheet.Cells["D1"].Style.Font.Bold = true;
for (int i = 0; i < names.Count(); i++)
{
string L = (Convert.ToChar(65+i)).ToString();
L += "1";
System.Diagnostics.Debug.WriteLine(L);
worksheet.Cells[L].Value = names[i];
worksheet.Cells[L].Style.Font.Bold = true;
}
for (int i = 2; i < (RowRange + 2); i++)
{
/*
string L = (Convert.ToChar(63 + i)).ToString();
string index = i.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CarID.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CarBrand.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CarModel.ToString();
worksheet.Cells[L + index].Value = temp[i - 2].CreateDate.ToString();
*/
string index = i.ToString();
for (int j = 0; j < names.Count; j++)
{
string L = (Convert.ToChar(65 + j)).ToString();
worksheet.Cells[L + index].Value = temp[i - 2].names[j].ToString();//<=
// its not working what is right way for doing this
}
worksheet.Cells["A" + index].Value = temp[i - 2].CarID.ToString();
worksheet.Cells["B" + index].Value = temp[i - 2].CarBrand.ToString();
worksheet.Cells["C" + index].Value = temp[i - 2].CarModel.ToString();
worksheet.Cells["D" + index].Value = temp[i - 2].CreateDate.ToString();
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
string path = Path.Combine(Server.MapPath("~/"), ("Reports\\" + name));
FileInfo excelFile = new FileInfo(path);
excel.SaveAs(excelFile);
var bull = db.ExcelRecords.SingleOrDefault(b => b.GuidName == name);
if (bull != null)
{
bull.IsExist = true;
db.SaveChanges();
}
}
}

Related

Chart not labeling entire X Axis (dynamic)

I am trying to display points from 7 files. Each file corresponds to a day, and I am trying to add a button where it takes the last 7 created files and displays them as x=dateTime and y= value. what this code currently does is that only displays the x axis on the left and right side.
private void button1_Click(object sender, EventArgs e)
{
chart1.Titles.Clear();
chart1.Series.Clear();
xAxis.Clear();
yAxis.Clear();
var Series1 = new Series
{
Name = comboBox2.Text,
Color = System.Drawing.Color.Green,
IsVisibleInLegend = false,
IsXValueIndexed = true,
ChartType = SeriesChartType.Area
};
this.chart1.Series.Add(Series1);
double measur = 0;
//clear graph
string Folder = #"\\Engineer\DI-808\outlooktest\";
var files = new DirectoryInfo(Folder).GetFiles("*_*");
string latestfile = "";
DateTime lastModified = DateTime.MinValue;
List<string> filesD = new List<string>();
DateTime endDate=DateTime.Now;
DateTime startDate= DateTime.Now.AddDays(-3);
DateTime dateToCheck;
Console.WriteLine(startDate + " " + endDate);
foreach (FileInfo file in files)
{
//Console.WriteLine(file.Name+"before");
string edited = file.Name.Remove(0, 6);
//Console.WriteLine(edited+"during");
char[] csv = { '.', 'c', 's', 'v'};
edited = edited.TrimEnd(csv);
//Console.WriteLine(edited + "after CSV");
edited = edited.Remove(10, 9);
// Console.WriteLine(edited+"after");
dateToCheck = Convert.ToDateTime(edited);
Console.WriteLine(dateToCheck+" date to check");
Console.WriteLine(startDate+" start");
Console.WriteLine(endDate+ " end" );
// if ( DateTime.Compare(dateToCheck,startDate)>=0dateToCheck >= startDate && dateToCheck <= endDate);
if (DateTime.Compare(dateToCheck, startDate)>=0 && DateTime.Compare(dateToCheck, endDate)<=0)
{
latestfile = file.Name;
filesD.Add(latestfile);
Console.WriteLine(latestfile+" dweeb");
}
}
Console.WriteLine(filesD.Count());
for (int i = 0; i < filesD.Count(); i++)
Console.WriteLine(files[i]);
string lineData;
try
{
for (int i=0;i<filesD.Count();i++) {
readData = new StreamReader(#"\\egvfps1.egv.mapes.local\Engineer\DI-808\outlooktest\" + filesD[i]);
for (int k = 0; k < 21; k++)
readData.ReadLine();
while ((lineData = readData.ReadLine()) != null)
{
if (Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) <= 0.001)
measur = 0;
else
{
measur = Convert.ToDouble(lineData.Split(',')[comboBox2.SelectedIndex + 2]) * 110;
xAxis.Add(Convert.ToDateTime(lineData.Split(',')[1]));
yAxis.Add(measur);
}
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
readData.Close();
this.chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
this.chart1.Titles.Add(comboBox2.Text + "(" + xAxis[0].ToString("MM/dd/yyyy") + ")");
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
for (int i = 0; i < xAxis.Count(); i++)
{
chart1.Series[comboBox2.Text].Points.AddXY(xAxis[i], yAxis[i]);
}
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.Interval = 1;
// chart1.ChartAreas[0].AxisX.MajorGrd.Enabled = false;
//chart1.ChartAreas[0].AxisY.MajorGrid.Enabled = false;
chart1.ChartAreas.FirstOrDefault().AxisX.Interval = 1;
// chart1.ChartAreas.FirstOrDefault().AxisY.Interval = 1;
chart1.ChartAreas[0].AxisX.Interval = 1;
chart1.ChartAreas[0].AxisX.IntervalType = DateTimeIntervalType.Hours;
chart1.ChartAreas[0].AxisX.IntervalOffset = 1;
chart1.Series[0].XValueType = ChartValueType.DateTime;
}
enter image description here
I know its somewhere in the Xaxis interval type part,but I don't know what values to put in.
Any suggestions helps!

Formula not identify cell values

I'm generating an excel using the following code in my ASP.Net MVC Application
var fileName = DateTime.Now.ToString("yyyy-MM-dd--hh-mm-ss") + ".xlsx";
var outputDir = ConfigurationManager.AppSettings["ExcelUploadPath"];
// var fileName = "ExcellData.xlsx";
var file = new FileInfo(outputDir + fileName);
var fDate = JsonConvert.DeserializeObject<DateTime>(fromDate);
var tDate = JsonConvert.DeserializeObject<DateTime>(toDate);
using (var package = new OfficeOpenXml.ExcelPackage(file))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Plan " + DateTime.Now.ToShortDateString());
// --------- Data and styling goes here -------------- //
DataTable dt = planService.GetFlow(fDate, tDate, customerId, ordertypeId, suppliers, items);
if (dt != null)
{
int iCol = 1;
// Add column headings...
for (int i = 9; i < dt.Columns.Count; i++)
{
dt.Columns[i].ColumnName = dt.Columns[i].ColumnName.MultiInsert("/", 1, 3);
}
foreach (DataColumn c in dt.Columns)
{
worksheet.Cells[1, iCol].Value = c.ColumnName;
worksheet.Cells[1, iCol].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[1, iCol].Style.Font.Bold = true;
worksheet.Cells[1, iCol].Style.Fill.BackgroundColor.SetColor(Color.LightGray);
iCol++;
}
for (int j = 0; j < dt.Rows.Count; j++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
worksheet.Cells[j + 2, k + 1].Value = dt.Rows[j].ItemArray[k].ToString();
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 6)
{
worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.Cyan);
}
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 7)
{
worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.Magenta);
//worksheet.Cells[j + 2, k + 1].Formula =
if((k+1) > 10){
var addressList = new List<string>();
for (int i = 11; i <= k+1; i++)
{
addressList.Add(worksheet.Cells[((j + 2) -1) , i].Address);
}
var lstAdress = String.Join(",", addressList);
worksheet.Cells[j + 2, k + 1].Formula = "SUM(" + lstAdress + ")";
}
}
if (int.Parse(dt.Rows[j].ItemArray[7].ToString()) == 8)
{
//worksheet.Cells[j + 2, k + 1].Style.Locked = false;
worksheet.Cells[j + 2, k + 1].Style.Fill.PatternType = ExcelFillStyle.Solid;
worksheet.Cells[j + 2, k + 1].Style.Fill.BackgroundColor.SetColor(Color.Gray);
}
}
var colCount = dt.Columns.Count;
// worksheet.Cells[j+2, 8, j+2, colCount- 1].Style.Numberformat.Format = "0.000";
var range = worksheet.Cells[j + 2, 9, j + 2, colCount - 1];
var r = range.ToString();
var decimalValidation = worksheet.DataValidations.AddDecimalValidation(range.ToString());
decimalValidation.ShowErrorMessage = true;
decimalValidation.ErrorStyle = ExcelDataValidationWarningStyle.stop;
decimalValidation.ErrorTitle = "The value you entered is not valid";
decimalValidation.Error = "This cell must be a valid positive number.";
decimalValidation.Operator = ExcelDataValidationOperator.greaterThanOrEqual;
decimalValidation.Formula.Value = 0D;
}
worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();
worksheet.Column(1).Hidden = true;
worksheet.Column(2).Hidden = true;
worksheet.Column(3).Hidden = true;
worksheet.Column(4).Hidden = true;
worksheet.Column(5).Hidden = true;
worksheet.Column(8).Hidden = true;
worksheet.Column(9).Hidden = true;
worksheet.Column(10).Hidden = true;
worksheet.Protection.IsProtected = true;
// save our new workbook and we are done!
worksheet.Calculate();
package.Save();
return Json(fileName, JsonRequestBehavior.AllowGet);
}
else
{
return Json("NoData", JsonRequestBehavior.AllowGet);
}
}
return Json("", JsonRequestBehavior.AllowGet);
Here I'm setting my formula with comma separated cell names eg:
SUM(A1,A2,A3.. etc)
The excel file is generating correctly. But the problem is the formula calculation is not happen when I open my excel file.
The formula works when I manually change a cell value in Column Type Agreed Flow.
And it can only identify values of manually edited cells.
How can I resolve this?
Formula recalculation is both an Excel and a workbook setting.
You could set it with at the workbook level with
workbook.CalcMode = ExcelCalcMode.Automatic;
If the user has set it to manual though, the formulas won't be recalculated.
If you want to ensure the saved values are correct you can force the calculation by calling
worksheet.Calculate();
You can also calculate the formulas at the workbook or range level, eg :
worksheet.Cells[j + 2, k + 1].Calculate();
or
package.Workbook.Calculate();
This is explained in the documentation. Keep in mind that EPPlus doesn't contain Excel's formula engine. It uses its own engine to parse and calculate formulas. Some things aren't supported
It worked when I change my formula as follows..
var addressList = new List<string>();
for (int i = 11; i <= k+1; i++)
{
addressList.Add(worksheet.Cells[((j + 2) -1) , i].Address);
}
var lstAdress = String.Join("+", addressList);
worksheet.Cells[j + 2, k + 1].Formula = "(" + lstAdress + ")";
I think there is an issue in my excel sheet when I use the SUM function So I write the formula without using it. Then it worked
(A1+B1+C1+D1+ ..... etc)

Display Null Value or Zero-Valued Data from Textfile in C# ASP.Net

This code functions by reading textfile content, manipulate the data in it and display the output in a textbox.
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
string filenameDate = FileUpload1.FileName.Substring(15, 2);
Dictionary<string, int> dMyobject = new Dictionary<string, int>();
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
//int readedLineTime = Convert.ToInt32(readedLine.Substring(09, 02));
string sDate = readedLine.Substring(0, 11);
MatchCollection collection = Regex.Matches(readedLine, #"D;");
countedChars = collection.Count;
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, collection.Count);
}
else
{
dMyobject[sDate] = dMyobject[sDate] + collection.Count;
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
txtContent.Text = textfileContent;
lblLineCount.Text = i.ToString();
//Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
lblFileDate.Text = filenameDate;
foreach (var item in dMyobject)
{
textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine;
// textfileOutput += (item.Value) + Environment.NewLine;
}
txtOutput.Text = textfileOutput;
}
each line in the textfile contains a date and series of pattern. this code read each lines separated by dates and count the total occurrence of a pattern, in this example, counting the pattern "D;" and summarize its total per Date (lines with same date should be summed-up). For example
running the code will give this current output
2016-12-01 - 7
2016-12-02 - 9
2016-12-03 - 5
2016-12-05 - 1
My Objective and desired output should include in the output the date with NULL VALUE. In my example, there was no 2016-12-04 record, **expected output should have displayed the date still and display 0 or blank such as:**
2016-12-01 - 7
2016-12-02 - 9
2016-12-03 - 5
2016-12-04 - 0
2016-12-05 - 1
This will do it.
using (StreamReader stRead = new StreamReader(#"c:\test.txt"))
{
string filenameDate = "test";
string textfileContent = string.Empty;
int i = 0;
string textfileOutput = string.Empty;
Dictionary<string, int> dMyobject = new Dictionary<string, int>();
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
string sDate = readedLine.Substring(0, 11).Trim();
MatchCollection collection = Regex.Matches(readedLine, #"D;");
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, collection.Count);
}
else
{
dMyobject[sDate] = dMyobject[sDate] + collection.Count;
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
var date = DateTime.Parse(dMyobject.First().Key);
var beginOfMonth = new DateTime(date.Year, date.Month, 1);
var days = new Dictionary<string, int>();
for (var x = 0; x < DateTime.DaysInMonth(date.Year, date.Month); x++)
{
days.Add(beginOfMonth.AddDays(x).ToString("yyyy-MM-dd"), 0);
}
foreach (var item in days)
{
textfileOutput += (dMyobject.ContainsKey(item.Key) ? (item.Key + " " + dMyobject[item.Key]) : (item.Key + " 0")) + Environment.NewLine;
}
}
So the the last bit of code first creates the date ranges that are needed by picking a date from your Dictionary and iterating to the last day of that month. It then checks your matches and counts against the date ranges and if there is a match, use the updated count instead of 0.
In your upload file, there have 2016-12-04 line, you just edit you Regex for got all char and count the total score.
fix 1:Check whether the continuous time.
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
string filenameDate = FileUpload1.FileName.Substring(15, 2);
SortedDictionary<string, int> dMyobject = new SortedDictionary<string, int>(); //this is a dictionary sorted by key
DateTime? startDatetime = null, endDatetime = null;//got mininum and maxinum dates, at late will be check the continuous time
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
string sDate = readedLine.Substring(0, 11).Trim();
DateTime date;
if (DateTime.TryParse(sDate, out date))
{
if (startDatetime.HasValue == false)
startDatetime = date;
endDatetime = date;
//got start date and end date
//if date does not from big to small
//here need compare bwteen date and endDatetime
}
MatchCollection collection = Regex.Matches(readedLine, "(?<c>[A-Z]+);");
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, GetTotal(collection));
}
else
{
dMyobject[sDate] = dMyobject[sDate] + GetTotal(collection);
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
//here is check the continuous time
if (startDatetime.HasValue && endDatetime.HasValue)
{
for (var dt = startDatetime; dt.Value.CompareTo(endDatetime) <= 0; dt = dt.Value.AddDays(1))
{
string key = dt.Value.ToString("yyyy-MM-dd");
if (!dMyobject.Keys.Contains(key))
{
dMyobject[key] = 0;
}
}
}
txtContent.Text = textfileContent;
lblLineCount.Text = i.ToString();
//Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
lblFileDate.Text = filenameDate;
foreach (var item in dMyobject)
{
textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine;
// textfileOutput += (item.Value) + Environment.NewLine;
}
txtOutput.Text = textfileOutput;
}
//this method is a new method, it got total score, and if you rule chanage you can set `D` +1, `A` +2 etc.
private int GetTotal(MatchCollection collection)
{
Dictionary<string, int> point = new Dictionary<string, int>();
point["D"] = 1;
point["A"] = 0;
int total = 0;
foreach (Match m in collection)
{
string str = m.Groups["c"].Value;
if (point.ContainsKey(str))
total += point[str];
}
return total;
}
Adding comments JohanP Answer, code is working fine expect date sub-string is wrong in original code and there are no issue with Dictionary 0 Value
JohanP's answer is a big help, but there are limitations because it also needs to write the first dates when it is null. So based from his answer, I have come up with this codes.
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
Dictionary<string, int> dMyobject = new Dictionary<string, int>();
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
//int readedLineTime = Convert.ToInt32(readedLine.Substring(11, 02));
string sDate = readedLine.Substring(11, 2);
MatchCollection collection = Regex.Matches(readedLine, #"D;");
countedChars = collection.Count;
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, collection.Count);
}
else
{
dMyobject[sDate] = dMyobject[sDate] + collection.Count;
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
txtContent.Text = textfileContent;
lblLineCount.Text = i.ToString();
var prevDate = string.Empty;
int tester = 01;
foreach (var item in dMyobject)
{
int testCorrectStart = Convert.ToInt32(item.Key) - tester;
if (testCorrectStart == 0)
{
if (!string.IsNullOrEmpty(prevDate))
{
var cur = Int32.Parse(item.Key); // convert current key into int
var prev = Int32.Parse(prevDate);
int dayDiff = cur - prev;
for (var x = 0; x < dayDiff - 1; x++) // run through day difference, add it to the last date that was added
{
textfileOutput += ((prev + (x + 1)).ToString() + " 0" + Environment.NewLine);
}
}
textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine;
prevDate = item.Key;
tester++;
}
else
{
if (!string.IsNullOrEmpty(tester.ToString()))
{
var cur = Int32.Parse(item.Key); // convert current key into int
var prev = Int32.Parse(tester.ToString());
int dayDiff = cur - prev;
for (var x = 0; x < dayDiff ; x++) // run through day difference, add it to the last date that was added
{
textfileOutput += ("0" +(prev + x).ToString() + " 0" + Environment.NewLine);
}
}
textfileOutput += (item.Key + " " + item.Value) + Environment.NewLine;
prevDate = item.Key;
tester = Convert.ToInt32(prevDate) + 1;
}
}
txtOutput.Text = textfileOutput;
}
you can test its correcteness

Count Pattern / String Occurrence Per Group using C# in ASP.Net

This is the sample textfile
Line is categorized by date, per line date can be repeated like for example, December 1 and 2 have two entries. Expected Output should be counting the pattern "D;" for example per date
2016-12-01 - 7
2016-12-02 - 9
2016-12-03 - 5
This is what I currently have
using (StreamReader stRead = new StreamReader(FileUpload1.PostedFile.InputStream))
{
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
for (int j = 01; j <= 31; j++)
{
int readedLineTime = Convert.ToInt32(readedLine.Substring(09, 02));
if (readedLineTime == j)
{
MatchCollection collection = Regex.Matches(readedLine, #"D;");
countedChars = collection.Count;
textfileOutput += readedLine.Substring(0, 11) + " - " + countedChars + Environment.NewLine;
}
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
TextBox1.Text = textfileOutput;
TextBox2.Text = textfileContent;
Label1.Text = i.ToString();
//Label1.Text = this.TextBox1.Text.Split(new Char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries).Length.ToString();
// Label2.Text = filename;
}
and this is its current output that is being displayed in multiple line textbox
2016-12-01 - 4
2016-12-01 - 3
2016-12-02 - 4
2016-12-02 - 5
2016-12-03 - 5
Let me know if this works.
Dictionary<string, int> dMyobject = new Dictionary<string, int>();
while (!stRead.EndOfStream)
{
var readedLine = stRead.ReadLine();
if (!string.IsNullOrWhiteSpace(readedLine))
{
int readedLineTime = Convert.ToInt32(readedLine.Substring(09, 02));
string sDate = readedLine.Substring(0, 11);
MatchCollection collection = Regex.Matches(readedLine, #"D;");
countedChars = collection.Count;
if (!dMyobject.Keys.Contains(sDate))
{
dMyobject.Add(sDate, collection.Count);
}
else
{
dMyobject[sDate] = dMyobject[sDate] + collection.Count;
}
}
textfileContent += readedLine + Environment.NewLine;
i++;
}
You will need to push these values in some collection. So that you can check it.
Later, for using these values for printing or anything, use following
foreach (var item in dMyobject)
{
Console.WriteLine(item.Key + " " + item.Value);
}
string line = "";
Dictionary<string, int> list = new Dictionary<string, int>();
int count;
if (File.Exists(fileName) == true)
{
StreamReader objReader;
objReader = new StreamReader(fileName);
StreamWriter file = new StreamWriter(OutputfileName");
do
{
line = objReader.ReadLine();
string temp = line.Substring(0, 10);
if (!list.ContainsKey(temp))
{
MatchCollection collection = Regex.Matches(line, #"D;");
count = collection.Count;
list.Add(temp, count);
}
else
{
MatchCollection collection = Regex.Matches(line, #"D;");
count = collection.Count;
var val = list[temp];
list[temp] = count + val;
}
} while (objReader.Peek() != -1);
foreach (var j in list)
{
file.WriteLine(j.Key + " - " + j.Value+"\n");
}
file.Close();
}

How to parse JSON foreach object in array?

I'm currently looping through a JSON array and generating an object for each item in the array.
I wondering how I can parse data from the current object.
int i = 0, count = 0, yMP, yGP, yGT, favscountB8 = 0;
string gamertag;
JObject o1 = JObject.Parse(File.ReadAllText(#"gamerprofile.json"));
string jsonGamerprofile = JsonConvert.SerializeObject(o1);
var resultObjects = AllChildren(JObject.Parse(jsonGamerprofile))
.First(c => c.Type == JTokenType.Array && c.Path.Contains("favorites"))
.Children<JObject>();
foreach (JObject result in resultObjects)
{
// Here I wish to make the string gamertag = the value of (FavsGTS_gpF) which is inside the current object.
favscountB8 = favscountB8 + 1;
count = count + 1;
yMP = 6 + (62 * (count - 1));
yGP = 7 + (62 * (count - 1));
yGT = 11 + (62 * (count - 1));
Panel mainpanel1 = new Panel();
PictureBox gamerpic1 = new PictureBox();
Label gamertag1 = new Label();
mainpanel1.BackColor = Color.Red;
mainpanel1.Location = new Point(6, yMP);
mainpanel1.Size = new Size(957, 60);
mainpanel1.Name = "mainpanel" + i.ToString();
gamerpic1.BackColor = Color.Azure;
gamerpic1.Location = new Point(7, yGP);
gamerpic1.Size = new Size(54, 54);
gamerpic1.Name = "gamerpic" + i.ToString();
gamerpic1.BringToFront();
gamertag1.ForeColor = Color.FromArgb(110, 120, 127);
gamertag1.BackColor = Color.White;
gamertag1.Text = "Gamertag " + count.ToString();
gamertag1.Font = new Font("Arial Narrow", 14, FontStyle.Bold);
gamertag1.Location = new Point(76, yGT);
gamertag1.Size = new Size(145, 23);
gamertag1.Name = "Gamertag " + count.ToString();
gamertag1.BringToFront();
i = i + 1;
panel4.Controls.Add(gamertag1);
panel4.Controls.Add(gamerpic1);
panel4.Controls.Add(mainpanel1);
}
Inside the foreach statement I wish to make the "gamertag" string equal to the value of "FavsGTS_gpF" which is in each object in the array.

Categories

Resources