Error in generate code and Update list - c#

i Try to make generate 16 bit code and when i add the record all number is same how can i fix it ?
in loop befor code[i] = Newcode; code is corect when code added in list changed last code to new so all code is same as last generate !!!!
public ActionResult Gen5Rm(GenerateCodeModel model){
Code Newcode = new Code();
int X = Convert.ToInt32(model.Quntity);
Code[] code = new Code[X];
for (int i = 0; i < X; i++)
{
string strDate = "";
string strmonth = "";
string strday = "";
string myday = "";
strmonth = DateTime.Now.ToString("MM");
myday = DateTime.Now.DayOfWeek.ToString();
if (myday == "Sunday")
{
strday = "SU";
}
if (myday == "Monday")
{
strday = "MO";
}
if (myday == "Tuesday")
{
strday = "TU";
}
if (myday == "Wednesday")
{
strday = "WE";
}
if (myday == "Thursday")
{
strday = "TU";
}
if (myday == "Friday")
{
strday = "FR";
}
if (myday == "Saturday")
{
strday = "ST";
}
strDate = generateBarcode();
Newcode.codebase = model.Agent + strmonth +
model.Type_Code + strDate + strday + "5" + model.Dealercode;
Newcode.price = 5;
Newcode.serial = "S" + DateTime.Now.ToString("mmssfff");
code[i] = Newcode;
}
return PartialView("_return5rm", code);
}
the export is like this

Newcode should be inside the for loop, otherwise all items in the array will point the same object (same memory address)
for (int i = 0; i < X; i++)
{
Code Newcode = new Code();
...
}

Related

Multiplication and Sum in GridView ASP.Net C#

I have a datatable which is bound to GridView datasource as follows.
Overall i want to Multiply 'Quantity' column value with 'Part1 qty' column value until 'column5' cell value is repeating and so on
the result of operation should appear underneath the value as highlighted in red for understanding
My GridView data currently
I want the following output
Required Output
My GridMarkup
My GridMarkup
What I have done so far is
protected void GridView1_DataBound(object sender, EventArgs e)
{
int gridViewCellCount = GridView1.Rows[0].Cells.Count;
string[] columnNames = new string[gridViewCellCount];
for (int k = 0; k < gridViewCellCount; k++)
{
columnNames[k] = ((System.Web.UI.WebControls.DataControlFieldCell)(GridView1.Rows[0].Cells[k])).ContainingField.HeaderText;
}
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
var result = Array.FindIndex(columnNames, element => element.EndsWith("QTY"));
var Arraymax=columnNames.Max();
int maxIndex = columnNames.ToList().IndexOf(Arraymax);
decimal MultiplicationResult=0;
int counter = 0;
for (int j = 8; j < row.Cells.Count; j++)
{
if (row.Cells[j].Text == previousRow.Cells[j].Text)
{
counter++;
if (row.Cells[j].Text != " " && result < maxIndex)
{
var Quantity = GridView1.Rows[i].Cells[1].Text;
var GLQuantity = GridView1.Rows[i].Cells[result].Text;
var PreviousQuantity= GridView1.Rows[i-1].Cells[1].Text;
var PreviousGLQuantity= GridView1.Rows[i-1].Cells[result].Text;
//var Quantity = dt.Rows[i].ItemArray[1];
//var GLQuantity = dt.Rows[i].ItemArray[Convert.ToInt64(result)].ToString();
var GLQ = GLQuantity.TrimEnd(new Char[] { '0' });
var PGLQ = PreviousGLQuantity.TrimEnd(new char[] { '0' });
if (GLQ == "")
{
GLQ = 0.ToString();
}
if (PGLQ == "")
{
PGLQ = 0.ToString();
}
MultiplicationResult = Convert.ToDecimal(Quantity) * Convert.ToDecimal(GLQ) + Convert.ToDecimal(PreviousQuantity) * Convert.ToDecimal(PGLQ);
object o = dt.Rows[i].ItemArray[j] + " " + MultiplicationResult.ToString();
GridView1.Rows[i].Cells[j].Text = o.ToString();
GridView1.Rows[i].Cells[j].Text.Replace("\n", "<br/>");
result++;
}
else
result++;
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
else
result++;
}
}
}
Thanks in advance.
We can use below Answer
protected void GridView1_DataBound(object sender, EventArgs e)
{
int gridViewCellCount = GridView1.Rows[0].Cells.Count;
string[] columnNames = new string[gridViewCellCount];
for (int k = 0; k < gridViewCellCount; k++)
{
columnNames[k] = ((System.Web.UI.WebControls.DataControlFieldCell)(GridView1.Rows[0].Cells[k])).ContainingField.HeaderText;
}
for (int i = GridView1.Rows.Count - 1; i > 0; i--)
{
GridViewRow row = GridView1.Rows[i];
GridViewRow previousRow = GridView1.Rows[i - 1];
var result = Array.FindIndex(columnNames, element => element.EndsWith("QTY"));
var Arraymax = columnNames.Max();
int maxIndex = columnNames.ToList().IndexOf(Arraymax);
decimal MultiplicationResult = 0;
decimal currentCellResult = 0;
for (int j = 8; j < row.Cells.Count; j++)
{
var defaultvalue = row.Cells[j].Text.ToString();
var defaultvalueArray = defaultvalue.Split(' ');
var originalMultiplicationResult = defaultvalueArray.Count() == 2 ? defaultvalueArray.Last() : "0";
var originalCellValue = defaultvalueArray.Count() == 2 ? defaultvalueArray.First() : row.Cells[j].Text.ToString();
if (originalCellValue == previousRow.Cells[j].Text)
{
if (row.Cells[j].Text != " " && result < maxIndex)
{
var Quantity = GridView1.Rows[i].Cells[1].Text;
var GLQuantity = GridView1.Rows[i].Cells[result].Text;
var PreviousQuantity = GridView1.Rows[i - 1].Cells[1].Text;
var PreviousGLQuantity = GridView1.Rows[i - 1].Cells[result].Text;
var GLQ = GLQuantity.TrimEnd(new Char[] { '0' });
var PGLQ = PreviousGLQuantity.TrimEnd(new char[] { '0' });
if (GLQ == "")
{
GLQ = 0.ToString();
}
if (PGLQ == "")
{
PGLQ = 0.ToString();
}
currentCellResult = Convert.ToDecimal(Quantity) * Convert.ToDecimal(GLQ);
MultiplicationResult = currentCellResult + Convert.ToDecimal(PreviousQuantity) * Convert.ToDecimal(PGLQ);
if (row.Cells[j].RowSpan == 0)
{
//DataTable dt = (DataTable)ViewState["dt"];
object o = dt.Rows[i].ItemArray[j] + " " + MultiplicationResult.ToString();
previousRow.Cells[j].Text = o.ToString();
//previousRow.Cells[j].Text = previousRow.Cells[j].Text.Split("");
}
else
{
//DataTable dt = (DataTable)ViewState["dt"];
var t = Convert.ToDecimal(originalMultiplicationResult) - Convert.ToDecimal(currentCellResult) + MultiplicationResult;
object o = dt.Rows[i].ItemArray[j] + " " + t.ToString();
previousRow.Cells[j].Text = o.ToString();
//previousRow.Cells[j].Text.Replace("\n", "<br>");
}
result++;
}
else
result++;
if (previousRow.Cells[j].RowSpan == 0)
{
if (row.Cells[j].RowSpan == 0)
{
previousRow.Cells[j].RowSpan += 2;
}
else
{
previousRow.Cells[j].RowSpan = row.Cells[j].RowSpan + 1;
}
row.Cells[j].Visible = false;
}
}
else
result++;
}
}
}

Custom pattern matching in C#

Currently I am making a AI based on text.
I have a database with a pattern for each answer
A pattern looks like [Who is the] Winner of the World Cup 2018
[] = Optional words
<> = Needed words
When I enter the sentence Who is the Winner of the World Cup 2018 my method should return the indentifier of the answer.
My database has 2 rows called "AnswerIndentifier" and "Pattern"
I did it myself and programmed this algoryhm:
private static bool MatchesPattern(string text, string pattern)
{
List<string> patternTokens = new List<string>();
string tok = "";
pattern = pattern.ToLower() + "[";
int state = 0;
for(int i = 0; i < pattern.ToCharArray().Length; i++)
{
char token = pattern[i];
if(token == '[')
{
if(tok != "")
{
patternTokens.Add("NEC" + char.MaxValue + tok);
tok = "";
}
state = 1;
continue;
}
if(token == ']' && state == 1)
{
i++;
state = 0;
patternTokens.Add("OPT" + char.MaxValue + tok);
tok = "";
continue;
}
if(token == ' ' && i + 1 < text.ToCharArray().Length && text[i + 1] == '[')
continue;
tok += token;
}
string[] patternTokensCopy = new string[patternTokens.Count];
for(int i = 0; i < patternTokens.Count; i++)
patternTokensCopy[i] = patternTokens[i];
int max = (int) Math.Pow(2, patternTokens.Where(x => x.StartsWith("OPT")).ToList().Count);
for(int i = 0; i < max; i++)
{
string binary = Convert.ToString(i, 2).PadLeft(patternTokensCopy.Where(x => x.StartsWith("OPT")).ToList().Count, '0');
for(int x = 0; x < patternTokensCopy.Where(t => t.StartsWith("OPT")).ToList().Count; x++)
if(binary[x] == '0')
{
List<string> optionalTokens = new List<string>();
foreach(string curpattern in patternTokensCopy)
if(curpattern.StartsWith("OPT"))
optionalTokens.Add(curpattern);
patternTokens.Remove(optionalTokens[x]);
}
string patternAsSentence = "";
foreach(string patternToken in patternTokens)
patternAsSentence += patternToken.Split(char.MaxValue)[1] + " ";
while(patternAsSentence[patternAsSentence.Length - 1] == ' ')
patternAsSentence = patternAsSentence.Substring(0, patternAsSentence.Length - 1);
patternAsSentence = patternAsSentence.Replace("\r", "").Replace(" ", " ");
int similarity = StringSimilarity.GetStringSimilarity(patternAsSentence, text);
if(text.Length < 6)
{
if(text == patternAsSentence)
return true;
}
else
{
if(similarity <= 6)
return true;
}
patternTokens = new List<string>();
patternTokensCopy.ToList().ForEach(x => patternTokens.Add(x));
}
return false;
}
The only changes are that the needed text must not marked with <> and the similarity check(see C# - Compare String Similarity)

Labeling checkTypes for biometric attendance

I have a table named Attendancelogs where I am saving the records that I fetch from a biometric device, the table structure is;
LogType defines the type of log i.e. Biometric/Manual
CheckType defines the type of entry i.e. I or O
VerifyMode defines the type of punch i.e. Fingerprint/Password
isIgnore is used to exclude an entry from the logs.
Now, what I am trying to do is to write a function called sortFunc(); that will process on the already stored records in the Attendancelogs table. what this is suppose to do is;
Mark the checkType of each employee as I for the first entry, then O for their second entry of the date and so on.
If an employee has a last I at the end of the day, meaning no check out, then the next day's first punch of that employee (with in 12 AM - 7 AM) is considered check out for the previous day (marking as a nighter case for that employee) the rest entries are considered as sequential I and O.
any multiple entries within 10 seconds (or defined time) is ignored and marked CheckType as "Auto Ignored for x seconds"
If an employee is not allowed to use Card/Password then his CheckTypes are marked as Card not allowed or Password not allowed
Here is the function that I wrote;
public static bool inn = true;
public void sortLogs(int machineNum)
{
DateTime prevDate = DateTime.MinValue;
DateTime currentDate = DateTime.MinValue;
DateTime prevDateTime = DateTime.MinValue;
DateTime currentDateTime = DateTime.MinValue;
TimeSpan lowerBound = TimeSpan.Zero;
TimeSpan upperBound = TimeSpan.Zero;
var time = DateTime.ParseExact("00:00:00", "HH:mm:ss", null).ToString("hh:mm:ss tt", CultureInfo.GetCultureInfo("en-US"));
lowerBound = Convert.ToDateTime(time).TimeOfDay;
var time2 = DateTime.ParseExact("07:00:00", "HH:mm:ss", null).ToString("hh:mm:ss tt", CultureInfo.GetCultureInfo("en-US"));
upperBound = Convert.ToDateTime(time2).TimeOfDay;
upperBound = new TimeSpan(7, 0, 0);
var CheckType = "N/S";
bool isNighter = false;
List<AttendanceLog> firstDates = new List<AttendanceLog>();
AttendanceLog lastEmp = new AttendanceLog();
var empList = db.AttendanceLogs.OrderBy(x => x.EmpID).ThenBy(x => x.DateTime).ToList();
var countEmps = empList.DistinctBy(p => p.EmpID).Count();
string[,] array = new string[countEmps, 2];
var checkDevice = db.DeviceInformations.Where(xy => xy.DeviceID == machineNum && xy.IsActive == 1.ToString()).ToList();
AttendanceLog firstObj = new AttendanceLog();
int counter = 0;
int tempEmp = -1;
foreach (var emp in empList)
{
if (emp.EmpID == 0)
continue;
var cardAcceptance = db.Roles.Where(x => x.EmpID == emp.EmpID && x.Card_Acceptance == true).ToList();
var passwordAcceptance = db.Roles.Where(x => x.EmpID == emp.EmpID && x.Password_Acceptance == true).ToList();
currentDate = emp.Date;
currentDateTime = emp.DateTime;
if (emp.EmpID != tempEmp)
{
inn = true;
}
if (prevDateTime != DateTime.MinValue)
{
var seconds = (emp.DateTime - prevDateTime).TotalSeconds;
var settings = db.settings.Where(xy => xy.Constant_Name == "Entry Delay").FirstOrDefault();
if (settings.Constant_Value <= 0)
settings.Constant_Value = 10;
else
if (seconds > 0 && seconds < settings.Constant_Value)
{
//store prevDateTime in deleted table
emp.CheckType = "Auto Ignored: " + seconds + " seconds interval.";
// prevDateTime = emp.DateTime;
continue;
}
}
if (passwordAcceptance.Count <= 0)
{
if (emp.VerifyMode == "3")
{
try
{
emp.CheckType = "Password not allowed";
//db.SaveChanges();
continue;
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
foreach (var ve in eve.ValidationErrors)
{
}
}
throw;
}
}
}
if (cardAcceptance.Count <= 0)
{
if (emp.VerifyMode == "4")
{
try
{
emp.CheckType = "Card not allowed";
// db.SaveChanges();
continue;
}
catch (DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
foreach (var ve in eve.ValidationErrors)
{
}
}
throw;
}
}
}
if (counter != countEmps)
{
if (emp.EmpID != firstObj.EmpID)
{
array[counter, 0] = emp.EmpID.ToString();
firstObj.EmpID = emp.EmpID;
firstObj.Date = emp.Date;
counter++;
}
}
if (currentDate == firstObj.Date)
{
//check for entry delay
//get emp datetime here
//comapre with the slots
//if the datetime exsits in between
//otherwise store it with boolean flag for the first entry only, the rest should not be flagged
if (emp.DateTime.TimeOfDay > lowerBound && emp.DateTime.TimeOfDay < upperBound)
{
//consider the first check as nighter and then ignore the rest
}
else {
//checks after the upperBound means, no nighter
}
if (inn)
{
inn = false;
emp.CheckType = "I";
}
else
{
inn = true;
emp.CheckType = "O";
}
for (int i = 0; i < array.Length / 2; i++)
{
if (array[i, 0] == emp.EmpID.ToString())
{
array[i, 1] = emp.CheckType;
break;
}
}
//CheckType = emp.CheckType;
prevDate = currentDate;
prevDateTime = currentDateTime;
}
else
{
if (prevDate != currentDate)
{
if (emp.DateTime.TimeOfDay > lowerBound && emp.DateTime.TimeOfDay < upperBound)
{
//consider the first check as nighter and then ignore the rest
if (inn)
{
inn = false;
emp.CheckType = "I";
}
else
{
inn = true;
emp.CheckType = "O";
}
for (int i = 0; i < array.Length / 2; i++)
{
if (array[i, 0] == emp.EmpID.ToString())
{
array[i, 1] = emp.CheckType;
break;
}
}
//CheckType = emp.CheckType;
prevDate = currentDate;
prevDateTime = currentDateTime;
}
else
{
//checks after the upperBound means, no nighter
}
for (int i = 0; i < array.Length / 2; i++)
{
if (array[i, 0] == emp.EmpID.ToString())
{
if (array[i, 1] == "I")
{
emp.CheckType = "O";
inn = true;
}
else
{
emp.CheckType = "I";
inn = false;
}
}
}
}
else
{
if (inn)
{
inn = false;
emp.CheckType = "I";
}
else
{
inn = true;
emp.CheckType = "O";
}
for (int i = 0; i < array.Length / 2; i++)
{
if (array[i, 0] == emp.EmpID.ToString())
{
array[i, 1] = emp.CheckType;
}
}
}
prevDate = currentDate;
}
tempEmp = emp.EmpID.Value;
}
db.SaveChanges();
}
This did run but it messes up the "12 AM to 7 AM" checks and the password checks, i.e. not the accurate results.
As one of the example seen ^ consecutive O should not be there. I have been going crazy over this!

How to get output to be a continuous string rather than it being stacked on top of each letter - c#

public class LetterArray
{
internal static string[] Alphabet()
{
var letterValues = new string[26];
letterValues[0] = "A";
letterValues[1] = "B";
letterValues[2] = "C";
letterValues[3] = "D";
letterValues[4] = "E";
letterValues[5] = "F";
letterValues[6] = "G";
letterValues[7] = "H";
letterValues[8] = "I";
letterValues[9] = "J";
letterValues[10] = "K";
letterValues[11] = "L";
letterValues[12] = "M";
letterValues[13] = "N";
letterValues[14] = "O";
letterValues[15] = "P";
letterValues[16] = "Q";
letterValues[17] = "R";
letterValues[18] = "S";
letterValues[19] = "T";
letterValues[20] = "U";
letterValues[21] = "V";
letterValues[22] = "W";
letterValues[23] = "X";
letterValues[24] = "Y";
letterValues[25] = "Z";
return letterValues;
}
}
public class decrypt
{
public static void Main() //Main method
{
int res = 34;
string[] letterValues = LetterArray.Alphabet();
//Create for loop that runs through every possible shift value
for (int shift = 0; shift <= 25; shift++)
{
Console.WriteLine("\nShift Value = " + shift + ": ");
// For each character in the text file
foreach (var ch in ReadText.cipherTxt()) {
if (ch == ' ')
{ }
else
{
for (int i = 0; i <= 25; i++)
{
if ((ch.ToString().ToUpper()) == letterValues[i])
{
res = i;
}
}
if (shift > res)
{
Console.WriteLine(letterValues[26 - (shift - res)][0]);
}
else
{
Console.WriteLine(letterValues[res - shift][0]);
}
}
}
}
}
}
Not sure how to output the following so be a continuous string instead of each letter being stacked on top of each other. I have tried to change the Console.WriteLine values but it seems to mess the program up and throw an error instead.
Use Console.Write if you don't want each value in a new line.
Console.Write(letterValues[res - shift]);
You can also use a StringBuilder and Append characters to it. Then print it once after the loop.

Parallel.For error

Im trying to pare a DateTime in a Parallel.For:
part of the code:
public void LoadLogFile(String fileName) {
//Thread.CurrentThread.Priority = ThreadPriority.Lowest;
String currentFile = "";
if (fileName.Contains("Compass")) {
currentFile = "Compass";
CompassLogLoadCompleted = false;
compassLogCollection.Clear();
compassLogCollection.AsParallel();
} else if (fileName.Contains("")) {
currentFile = "CoreService";
CoreServiceLogLoadCompleted = false;
coreServiceLogCollection.Clear();
;
compassLogCollection.AsParallel();
} else {
Console.Out.WriteLine("Wrong File");
}
if (fileName.Contains("CoreService") ||
fileName.Contains("Compass")) {
int numberOfSingleLineLog = 0;
int numberOfmultipleLineLog = 0;
String[] lines = new string[] {};
String temp = "";
string[] parts;
DateTime dateTime = new DateTime();
LoggingLvl loggingLvl = new LoggingLvl();
LoggingLvl.ELoggingLvl eLoggingLvl = new LoggingLvl.ELoggingLvl();
int id = 0;
char[] delimiters = new[] {' '};
string threadId = "";
string loggingMessage;
string loggingMessage2 = "";
//string dateAndTimestamp = "";
int ff = 0;
// Read the File and add it to lines string
try {
swCompass.Start();
lines = File.ReadAllLines(fileName);
swCompass.Stop();
} catch (Exception e) {
CompassLogLoadCompleted = true;
CoreServiceLogLoadCompleted = true;
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
swCompass.Reset();
swCompass.Start();
// Adding the objects to the collections
//compassLogCollection.EnableNotify = false;
Parallel.For(0, lines.Count(), j => {
//for (int i = 0; i < lines.Count(); i++) {
string dateAndTimestamp = "";
if (!CompassLogLoadCompleted || !CoreServiceLogLoadCompleted) {
try {
if (SingleLined(ref lines, j)) {
parts = lines[j].Split(delimiters,
StringSplitOptions.
RemoveEmptyEntries);
numberOfSingleLineLog++;
foreach (string t in parts) {
switch (ff) {
case 0:
dateAndTimestamp = t;
break;
case 1:
dateAndTimestamp += " " + t.Replace(",", ".");
dateTime = DateTime.Parse(dateAndTimestamp);
//dateTime = new DateTime();
dateAndTimestamp = "";
break;
case 2:
eLoggingLvl = loggingLvl.ParseLoggingLvl(t);
break;
case 3:
threadId = t;
break;
default:
temp += t;
break;
}
ff++;
}
loggingMessage = temp;
temp = "";
ff = 0;
id++;
loggingLvl = new LoggingLvl(eLoggingLvl);
if (fileName.Contains("Compass")) {
//CompassLogLoadPercent = ((double) numberOfSingleLineLog/lines.Count())*100;
CompassLogData cLD =
new CompassLogData(
(numberOfSingleLineLog +
numberOfmultipleLineLog),
dateTime,
loggingLvl, threadId,
loggingMessage);
//await addRoCompassLogCollectionAsync(cLD);
compassLogCollection.Add(cLD);
} else if (fileName.Contains("CoreService")) {
CoreServiceLogData cSLD =
new CoreServiceLogData(
(numberOfSingleLineLog +
numberOfmultipleLineLog),
dateTime,
loggingLvl,
threadId,
loggingMessage);
//await addRoCoreServiceCollectionAsync(cSLD);
coreServiceLogCollection.Add(cSLD);
} else {
Console.Out.WriteLine("File Not recognizable ");
}
//Console.Out.WriteLine(loggingMessage);
//loggingMessage = "";
} else {
loggingMessage2 += lines[j];
loggingMessage2 += "\n";
//parts[i] += lines[i];
//parts[i] += "\n";
if (NextLineIsANumber(ref lines, j)) {
numberOfmultipleLineLog++;
//Console.Out.WriteLine(loggingMessage2);
parts = loggingMessage2.Split(delimiters,
StringSplitOptions.
RemoveEmptyEntries);
foreach (string t in parts) {
switch (ff) {
case 0:
dateAndTimestamp = t;
break;
case 1:
dateAndTimestamp += " " +
t.Replace(",", ".");
//dateTime = DateTime.Parse(dateAndTimestamp);
dateTime = new DateTime();
dateAndTimestamp = "";
break;
case 2:
eLoggingLvl =
loggingLvl.ParseLoggingLvl(t);
break;
case 3:
threadId = t;
break;
default:
temp += t;
break;
}
ff++;
}
loggingMessage = temp;
temp = "";
ff = 0;
id++;
loggingLvl = new LoggingLvl(eLoggingLvl);
if (fileName.Contains("Compass")) {
CompassLogData cLD =
new CompassLogData(
(numberOfSingleLineLog +
numberOfmultipleLineLog),
dateTime,
loggingLvl, threadId,
loggingMessage);
//await addRoCompassLogCollectionAsync(cLD);
compassLogCollection.Add(cLD);
} else if (fileName.Contains("CoreService")) {
CoreServiceLogData cSLD =
new CoreServiceLogData(
(numberOfSingleLineLog +
numberOfmultipleLineLog),
dateTime,
loggingLvl,
threadId,
loggingMessage);
//await addRoCoreServiceCollectionAsync(cSLD);
coreServiceLogCollection.Add(cSLD);
} else {
Console.Out.WriteLine("File Not recognizable ");
}
loggingMessage2 = "";
}
}
} catch (Exception e) {
Console.Out.WriteLine("Shit Happens");
Console.Out.WriteLine(e.StackTrace);
}
if (currentFile == "Compass") {
//CompassLogLoadPercent =
// ((double)
// i
// /lines.Count())*100;
CompassLogLoadPercent = ((double)
j
/lines.Count())*100;
} else if (currentFile == "CoreService") {
CoreServiceLogLoadPercent =
((double)
j
/lines.Count())*100;
}
}
});
//}
//compassLogCollection.EnableNotify = true;
//compassLogCollection.notifyAll();
if (currentFile == "Compass") {
Console.Out.WriteLine("Compass TIME: " + swCompass.Elapsed);
} else {
Console.Out.WriteLine("CoreSevice TIME: " + swCompass.Elapsed);
}
if (currentFile == "Compass") {
CompassLogLoadCompleted = true;
Console.Out.WriteLine("Compass LOADING DONE");
} else if (currentFile == "CoreService") {
CoreServiceLogLoadCompleted = true;
Console.Out.WriteLine("CoreService LOADING DONE");
}
//CoreServiceLogLoadCompleted = true;
Console.Out.WriteLine("numberOfSingleLineLog: " +
numberOfSingleLineLog);
Console.Out.WriteLine("numberOfmultipleLineLog: " +
numberOfmultipleLineLog);
Console.Out.WriteLine("numberOfLogs: " +
(numberOfSingleLineLog +
numberOfmultipleLineLog));
Console.Out.WriteLine("");
//}
}
}
but i get the following Exception:
at System.DateTimeParse.Parse(String s, DateTimeFormatInfo dtfi, DateTimeStyles styles)
at System.DateTime.Parse(String s)
at LogViewerV1.LogSession.<>c__DisplayClass3.<LoadLogFile>b__0(Int32 i) in c:\Users\Reza\Documents\Visual Studio 2012\Projects\Pallas informatik\LogViewerV1\LogViewerV1\src\LogSession.cs:line 169
A first chance exception of type 'System.FormatException' occurred in mscorlib.d
If I run this in a ordinary for loop i dont get any exception and everything works fine.
any Idea how to fix This?
FormatException would indicate that the input DateTime is not in the expected format. You should be using the overloads of DateTime.Parse which allow you to specify the DateTypeStyle.
See http://msdn.microsoft.com/en-us/library/system.datetime.parse.aspx#Parse1_Example
I think the problem is that you somehow set the culture of the main thread. But culture is not copied to any other thread, so the background threads that run (parts of) the Parallel.For() loop have different culture.
What you should do is to explicitly specify the culture to use:
DateTime.Parse(dateAndTimestamp, theCorrectCulture)

Categories