Get BIOS date in asp.net - c#

i check whether admin have licence or not so i check monthwise to login now i am using system date for check but admin change system date so i want date BIOS date
string crt_val = "",crt_mont = "",crt_year = "";
dt_v = objdata.select_upload();
if (dt_v.Rows.Count > 0)
{
crt_val = dt_v.Rows[0]["val"].ToString();
crt_mont = dt_v.Rows[0]["mon"].ToString();
crt_year = dt_v.Rows[0]["yer"].ToString();
//yy = Convert.ToInt32(crt_year);
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Window", "alert('Please Update your Licence Key');", true);
return;
}
if (Verification.Trim() != "")
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Window", "alert('Please Update your Licence Key');", true);
return;
}
string fin="";
string oyear = "";
oyear = DateTime.Now.Year.ToString();
int nyear = DateTime.Now.Year + 1;
int smonth = Convert.ToInt32(DateTime.Now.ToString("MM"));
fin = oyear + "-" + nyear.ToString();
int num;
switch (crt_mont)
{
case ("January"):
num = 1;
break;
case ("February"):
num = 2;
break;
case ("March"):
num = 3;
break;
case ("April"):
num = 4;
break;
case ("May"):
num = 5;
break;
case ("June"):
num = 6;
break;
case ("July"):
num = 7;
break;
case ("August"):
num = 8;
break;
case ("September"):
num = 9;
break;
case ("October"):
num = 10;
break;
case ("November"):
num = 11;
break;
default:
num = 12;
break;
}
if ((num < smonth) || (num == smonth))
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Window", "alert('Please Update your Licence Key');", true);
}
else
{
if (crt_val == "0")
{
Session["UserId"] = txtusername.Text.Trim();
objuser.UserCode = txtusername.Text.Trim();
objuser.Password = s_hex_md5(txtpassword.Text.Trim());
string pwd = s_hex_md5(txtpassword.Text);
objuser.Ccode = ddlCode.SelectedValue;
objuser.Lcode = ddlLocation.SelectedValue;
DataTable dt = new DataTable();
dt = objdata.UserLogin(objuser);
if (dt.Rows.Count > 0)
{
if ((dt.Rows[0]["UserCode"].ToString().Trim() == txtusername.Text.Trim()) && (dt.Rows[0]["Password"].ToString().Trim() == pwd) && (dt.Rows[0]["CompCode"].ToString().Trim() == ddlCode.SelectedValue) && (dt.Rows[0]["LocationCode"].ToString().Trim() == ddlLocation.SelectedValue))
{
Session["Isadmin"] = dt.Rows[0]["IsAdmin"].ToString().Trim();
Session["Usernmdisplay"] = txtusername.Text.Trim();
Session["Ccode"] = dt.Rows[0]["CompCode"].ToString().Trim();
Session["Lcode"] = dt.Rows[0]["LocationCode"].ToString().Trim();
if (Session["Isadmin"].ToString() == "1")
{
Session["RoleCode"] = "1";
}
else
{
Session["RoleCode"] = "2";
}
Response.Redirect("Dashboard.aspx");
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Window", "alert('User Name and Password Wrong');", true);
}
}
else
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Window", "alert('Please Update your Licence Key');", true);
}
}
else
{ }
}

Getting BIOS date won't change anything, because if someone changes the system date, the hardware real-time clock gets changed too.
Better option is to check date outside of client computer, so for example check some URL.

Related

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!

C# program with COM port going NOT RESPONDING

I have C#/.NET program which uses a COM port and SQL CE Database with a WCF service. Sometimes the program becomes unresponsive (the window freezes) and even in debug mode I cannot the reason.
I can restart the program after restarting my PC or the COM port. The problem isn't with my COM port problem because I have tried it on many PCs and all have the same problem.
How could I resolve this?
private void timer_Tick(object sender, EventArgs e)
{
try
{
labeltimer.Text = DateTime.Now.ToString();
if (timerstarted == true)
{
return;
}
timerstarted = true;
_CARDCODE = 0;
string error = "";
bool hasbassed = false;
if (this._Close == true)
{
this.Close();
}
if (serialPort1.IsOpen)
{
if (i < 8)
{
i++;
}
else
{
i = 0;
}
to[0] = (byte)(128 + i);
try
{
serialPort1.Write(to, 0, 1);
}
catch (System.Exception ex)
{
ListViewItem Lvi = new ListViewItem((++rowcount).ToString());
Lvi.SubItems.Add("");
Lvi.SubItems.Add("");
Lvi.SubItems.Add("Disconnected");
Lvi.SubItems.Add("");
listView.Items.Add(Lvi);
StartPort();
}
if (progressBar.Value >= 1500)
progressBar.Value = 0;
else
progressBar.Value += 10;
if (serialPort1.BytesToRead != 0)
{
byte[] data = new byte[serialPort1.BytesToRead];
from = new byte[3];
try
{
serialPort1.Read(data, 0, data.Length);
}
catch (System.Exception ex)
{
ListViewItem LVi = new ListViewItem((++rowcount).ToString());
LVi.SubItems.Add("");
LVi.SubItems.Add("");
LVi.SubItems.Add("Disconnected");
LVi.SubItems.Add("");
listView.Items.Add(LVi);
StartPort();
}
// data.Length == 4 by Button or HassPassed
if (data.Length == 4)
{
if (data[1] > 2)
DBS.AddButtonPass(data[0], data[1] / 4);
else
{
DBS.EditPass((int)data[0]);
timerstarted = false;
return;
}
}
else if ((data[data.Length - 1] != 255) || (data.Length < 4))
{
from[0] = data[0];
from[1] = 0;
from[2] = 0;
serialPort1.Write(from, 0, 3);
timerstarted = false;
return;
}
//RegistoringSubscriber_ID Add Subscriber Card
else if ((RegistoringSubscriber_ID > 0) && (RegisterCheckpoint != 0) && (data[0] == RegisterCheckpoint))
{
Registoring = false;
if (RegistorNewCard(Convert.ToInt32(data[2].ToString() + data[3].ToString() + data[4].ToString())) > 0)
FormBringPC.AnswerType = 1;
else
FormBringPC.AnswerType = 2;
RegistoringSubscriber_ID = 0;
error = "register card";
}
// RegistoringSubscriber_ID < 0 Add Bonus Card
else if ((RegistoringSubscriber_ID < 0) && (RegisterCheckpoint != 0) && (data[0] == RegisterCheckpoint))
{
Registoring = false;
if (RegistorBonusCard(Convert.ToInt32(data[2].ToString() + data[3].ToString() + data[4].ToString())) > 0)
FormBringPC.AnswerType = 1;
else
FormBringPC.AnswerType = 2;
RegistoringSubscriber_ID = 0;
error = "register Bonus card";
}
else if ((List_Checkpoint_ID.Contains(data[0]) && ((data[1] == 130) || (data[1] == 129))))
{
// DBS.EditPass((int)data[0]);
}
else if ((List_Checkpoint_ID.Contains(data[0]) && (data.Length == 7)))
{
_CARDCODE = Convert.ToInt32(data[2].ToString() + data[3].ToString() + data[4].ToString());
GlobalTypes.InvalidPass pass = DBS.CheckPassStatus(_CARDCODE, (int)data[0], (int)data[1]);
if (pass == GlobalTypes.InvalidPass.Valid)
{
from[0] = data[0];
from[1] = 1;
from[2] = 1;
serialPort1.Write(from, 0, 3);
LBTitle.Text = DateTime.Now.ToLongTimeString();
hasbassed = true;
}
else
{
from[0] = data[0];
from[1] = 0;
from[2] = 0;
serialPort1.Write(from, 0, 3);
switch (pass)
{
case GlobalTypes.InvalidPass.InvalidCard:
{
error = "Չգրանցված քարտ";
break;
}
case GlobalTypes.InvalidPass.InvalidCount:
{
error = "Այց. քանակ";
break;
}
case GlobalTypes.InvalidPass.InvalidGraphic:
{
error = "Ժամանակ hh:mm:ss";
break;
}
case GlobalTypes.InvalidPass.InvalidPeriod:
{
error = "Ժամանակահատված xxxx.dd.yyy";
break;
}
case GlobalTypes.InvalidPass.InvalidStatus:
{
error = "Հառացված աբոնենտ";
break;
}
case GlobalTypes.InvalidPass.InvalidSuscribe:
{
error = "Անհայտ բաժանորդ";
break;
}
default:
{
error = "esim inch";
break;
}
}
}
}
else if ((List_Checkpoint_ID.Contains(data[0]) && (data.Length > 0)))
{
try
{
byte[] ticket = new byte[data.Length - 6];
for (int ii = 0; ii < data.Length - 6; ii++)
{
ticket[ii] = data[ii + 2];
}
_CARDCODE = Convert.ToInt32(Encoding.ASCII.GetString(ticket.ToArray()));
GlobalTypes.HasPass pass = DBS.CheckTicketPassStatus(_CARDCODE, (int)data[0], (int)data[1]);
if (pass == GlobalTypes.HasPass.TruePass)
{
from[0] = data[0];
from[1] = 1;
from[2] = 1;
serialPort1.Write(from, 0, 3);
LBTitle.Text = DateTime.Now.ToLongTimeString();
hasbassed = true;
}
else
{
from[0] = data[0];
from[1] = 0;
from[2] = 0;
serialPort1.Write(from, 0, 3);
switch (pass)
{
case GlobalTypes.HasPass.CardNotFound:
{
error = "Not registored ticket";
break;
}
case GlobalTypes.HasPass.CardRepeat:
{
error = "ReEntring";
break;
}
case GlobalTypes.HasPass.ValidationPeriodError:
{
error = "Ժամանակ hh:mm:ss";
break;
}
case GlobalTypes.HasPass.SeasonError:
{
error = "Ժամանակահատված xxxx.dd.yyy";
break;
}
case GlobalTypes.HasPass.WeekOfDayError:
{
error = "Day of Weak";
break;
}
default:
{
error = "esim inch";
break;
}
}
}
}
catch { timerstarted = false; return; }
}
if (rowcount >= 10)
{
rowcount = 0;
listView.Items.Clear();
}
ListViewItem lvi = new ListViewItem((++rowcount).ToString());
lvi.SubItems.Add(data[0].ToString());
if (data.Length == 4)
hasbassed = true;
if (((data[1] == 2) || (data[1] == 8)) && ((data.Length == 4) || (Dictionary_Chekpoint[data[0]].CheckPointType == 2)))
{
lvi.SubItems.Add("Ելք");
}
else
{
lvi.SubItems.Add("Մուտք");
}
if (data.Length != 4)
lvi.SubItems.Add(_CARDCODE.ToString());
else
lvi.SubItems.Add("Հերթապահ");
lvi.SubItems.Add(error);
if (hasbassed == true)
{
lvi.BackColor = Color.LightGreen;
}
else
{
lvi.BackColor = Color.LightPink;
}
listView.Items.Add(lvi);
}
}
else MessageBox.Show("Serial port is closed!", "RS232 tester", MessageBoxButtons.OK, MessageBoxIcon.Error);
timerstarted = false;
}
catch
{
timerstarted = false;
return;
}
}
C# programs show as NOT RESPONDING whenever there is processing happening in the main UI thread that is preventing UI processing. The general answer here is to push that work into a different thread, so that UI events can continue to process (see references below for more information). In the case of serial ports, the easiest thing to do is hook the SerialPort.DataReceived event instead of polling it: https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived%28v=vs.110%29.aspx
Ref:
GUI not responding while fetching data
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
https://msdn.microsoft.com/en-us/library/windows/desktop/dd744765%28v=vs.85%29.aspx
http://www.dreamincode.net/forums/topic/246911-c%23-multi-threading-in-a-gui-environment/

assistance with C# loop [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I just completed this code and would like to change the following code to a loop. Each department has a specific button that they are supose to click and should be visible only to those who are within either dept 1, 2, or 3.
Can someone give me some kind of guidence here.
pchk.Visible = true;
Int32 count = 0;
count = chk.GetCount(1);
// dept 1
if (count == -1)
{
btnDept1.Visible = false;
}
else
{
btnDept1.Text = "Next dep1[" + count.ToString() + "]";
if (count == 0)
btnDept1.Enabled = false;
}
// dept 2
count = chk.GetCount(2);
if (count == -1)
{
btnDept2.Visible = false;
}
else
{
btnDept2.Text = "Next dep2 [" + count.ToString() + "]";
if (count == 0)
btnDept02.Enabled = false;
}
// dept 3
count = chk.GetCount(3);
if (count == -1)
{
btnDept3.Visible = false;
}
else
{
btnDept3.Text = "Next dept3 [" + count.ToString() + "]";
if (count == 0)
btnDept3.Enabled = false;
}
}
The biggest challenge with converting this to a loop is getting the btnDept1 values based on a numeric value. One way would be to introduce a method which does this with a switch statement
Button GetButton(int id) {
switch (id) {
case 1: return btnDept1;
case 2: return btnDept2;
...
}
}
Or another approach would be to keep them in an array and use the index to access the array. Either way once you have that you can collapse to a loop in the following way
for (int i = 0; i < TheCount; i++) {
int id = i + 1;
Button button = GetButton(id);
int count = chk.GetCount(2);
if (count == -1) {
button.Visible = false;
} else {
button.Text = String.Format("Next dep{0} [{1}]", id, count);
if (count == 0) {
button.Enabled = false;
}
}
}
for (int i = 1; i <= 3; i++)
{
count = chk.GetCount(i);
if (count == -1)
{
switch (i)
{
case 1:
btnDept1.Visible = false;
break;
case 2:
btnDept2.Visible = false;
break;
case 3:
btnDept3.Visible = false;
break;
}
}
else
{
switch(i)
{
case 1:
btnDept1.Text = "Next dep1[" + count.ToString() + "]";
if (count == 0)
btnDept1.Enabled = false;
break;
case 2:
btnDept1.Text = "Next dep1[" + count.ToString() + "]";
if (count == 0)
btnDept1.Enabled = false;
break;
case 3:
btnDept1.Text = "Next dep1[" + count.ToString() + "]";
if (count == 0)
btnDept1.Enabled = false;
break;
}
}
}
Try something like this:
private void SetButton(int id, Button btn)
{
var count = chk.GetCount(id);
if (count == -1)
{
btn.Visible = false;
}
else
{
btn.Text = String.Format("Next dep{0}[{1}]", id.ToString(), count.ToString());
if (count == 0)
btn.Enabled = false;
}
}
Usage can be something like this:
SetButton(1, btnDept1);
SetButton(2, btnDept2);
SetButton(3, btnDept3);
Of course, if you use an array / list of buttons it can be even easier...
e.g.
Button[] buttons = new Button[] { btnDept1, btnDept2, btnDept3};
for (int i = 0; i < buttons.Length; i++)
SetButton(i, buttons[i]);
Here is an easier, way to get the button you want. Simply append the i value to "btnDept" in ActiveForm.Controls[...]. Check for null, and go to work...
for (int i = 0; i < deptCount; i++)
{
Button b = ActiveForm.Controls["btnDept" + i.ToString()] as Button;
if (b != null)
{
if (count == -1)
{
b.Visible = true;
}
else
{
// etc.
}
}
}

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)

ask for confirmation when checking a box

i currently have a form that has several check boxes, once all the boxes are checked or left empty, it sends it to the database the state of the check boxes
i want to add, if a box is not checked, when you check it, it should ask for confirmation window "you sure you wanna check this"
any help please?
this is the current code
public IMeditor(IMui IMui, IMuser U, string User)
{
InitializeComponent();
this.IMui = IMui;
imu = U;
if (imu.UID == 0)
{
Add.Text = "Add";
imu.name = user;
}
else
Add.Text = "Update";
AuthChat.Checked = imu.AuthChat == 1;
AuthTac1.Checked = imu.AuthTac1 == 1;
AuthTac2.Checked = imu.AuthTac2 == 1;
AuthTac3.Checked = imu.AuthTac3 == 1;
AuthTac4.Checked = imu.AuthTac4 == 1;
AuthTac5.Checked = imu.AuthTac5 == 1;
AuthTac6.Checked = imu.AuthTac6 == 1;
AuthTac7.Checked = imu.AuthTac7 == 1;
AuthTac8.Checked = imu.AuthTac8 == 1;
AuthTac9.Checked = imu.AuthTac9 == 1;
AuthTac10.Checked = imu.AuthTac10 == 1;
switch (imu.Transport.ToLower()) {
case "aim": Transport.SelectedIndex = 0; break;
case "gtalk": Transport.SelectedIndex = 1; break;
case "msn": Transport.SelectedIndex = 2; break;
case "yahoo": Transport.SelectedIndex = 3; break;
}
}
I agree with Izzy. Add something like
private void PrivateInitialize()
{
CheckBox chkBox = new CheckBox();
chkBox.Text = "Click me";
chkBox.CheckedChanged += new EventHandler(chkBox_CheckedChanged);
}
private void chkBox_CheckedChanged(object sender, EventArgs e)
{
MessageBox.Show("Nag, nag, nag! You take out the trash yet?");
}
You need to handle the event CheckedChangedEvent for the checkbox. You can find the sample code on MSDN. Also
this link for the complete understanding of checkbox.
Or else you can derive your own class from CheckBox control of windows forms then override the required function and implement your own logic and create all the checkboxes in your application from this derived class
public IMeditor(IMui IMui, IMuser U, string User)
{
InitializeComponent();
this.IMui = IMui;
imu = U;
if (imu.UID == 0)
{
Add.Text = "Add";
imu.name = user;
}
else
Add.Text = "Update";
AuthChat.Checked = imu.AuthChat == 1;
AuthTac1.Checked = imu.AuthTac1 == 1;
AuthTac2.Checked = imu.AuthTac2 == 1;
AuthTac3.Checked = imu.AuthTac3 == 1;
AuthTac4.Checked = imu.AuthTac4 == 1;
AuthTac5.Checked = imu.AuthTac5 == 1;
AuthTac6.Checked = imu.AuthTac6 == 1;
AuthTac7.Checked = imu.AuthTac7 == 1;
AuthTac8.Checked = imu.AuthTac8 == 1;
AuthTac9.Checked = imu.AuthTac9 == 1;
AuthTac10.Checked = imu.AuthTac10 == 1;
switch (imu.Transport.ToLower()) {
case "aim": Transport.SelectedIndex = 0; break;
case "gtalk": Transport.SelectedIndex = 1; break;
case "msn": Transport.SelectedIndex = 2; break;
case "yahoo": Transport.SelectedIndex = 3; break;
}
AuthChat.Click += new EventHandler(ClickHandler);
}
void ClickHandler(Object obj, EventArgs args)
{
if (obj == AuthChat && AuthChat.CheckState == CheckState.Checked)
{
DialogResult result = MessageBox.Show("Do you want to change?", "are you sure?", MessageBoxButtons.YesNo);
if (result == DialogResult.No)
{
AuthChat.Checked = false;
}
}
}
public IMeditor(IMui IMui, IMuser U, string User)
{
InitializeComponent();
this.IMui = IMui;
imu = U;
if (imu.UID == 0)
{
Add.Text = "Add";
imu.name = user;
}
else
Add.Text = "Update";
AuthChat.Checked = imu.AuthChat == 1;
AuthTac1.Checked = imu.AuthTac1 == 1;
AuthTac2.Checked = imu.AuthTac2 == 1;
AuthTac3.Checked = imu.AuthTac3 == 1;
AuthTac4.Checked = imu.AuthTac4 == 1;
AuthTac5.Checked = imu.AuthTac5 == 1;
AuthTac6.Checked = imu.AuthTac6 == 1;
AuthTac7.Checked = imu.AuthTac7 == 1;
AuthTac8.Checked = imu.AuthTac8 == 1;
AuthTac9.Checked = imu.AuthTac9 == 1;
AuthTac10.Checked = imu.AuthTac10 == 1;
switch (imu.Transport.ToLower()) {
case "aim": Transport.SelectedIndex = 0; break;
case "gtalk": Transport.SelectedIndex = 1; break;
case "msn": Transport.SelectedIndex = 2; break;
case "yahoo": Transport.SelectedIndex = 3; break;
}
AuthChat.CheckedChanged += new EventHandler(CheckChangedHandler);
AuthChat1.CheckedChanged += new EventHandler(CheckChangedHandler);
}
void CheckChangedHandler(Object obj, EventArgs args)
{
if (obj == AuthChat)
{
MessageBox.Show("Checked changed for AuthChat");
}
else if (obj == AuthChat1)
{
MessageBox.Show("Checked changed for AuthChat1");
}
}
do it with javascript? add OnClientClick="return confirmCheck(this);"
<script language="javascript">
function confirmCheck(e){
return confirm("are you sure?");
// do other stuff
}
</script>
this should be better than redirecting people

Categories