Labeling checkTypes for biometric attendance - c#

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!

Related

validate data in a textbox in wpf from validation functions

well I have the following problem I try to validate the RUC of the provider of my country, the question is that I have implemented the validation functions which are the following:
ID validation function
public class Verifica_Identificacion
{
internal static bool VerificaIdentificacion(string identificacion)
{
bool estado = false;
char[] valced = new char[13];
int provincia;
if (identificacion.Length >= 10)
{
valced = identificacion.Trim().ToCharArray();
provincia = int.Parse((valced[0].ToString() + valced[1].ToString()));
if (provincia > 0 && provincia < 25)
{
if (int.Parse(valced[2].ToString()) < 6)
{
estado = VC.VerificaCedula(valced);
}
else if (int.Parse(valced[2].ToString()) == 6)
{
estado = VSP.VerificaSectorPublico(valced);
}
else if (int.Parse(valced[2].ToString()) == 9)
{
estado = VPJ.VerificaPersonaJuridica(valced);
}
}
}
return estado;
}
}
This function depends on other validations that are carried out independently because there are some types of RUC, below the other three functions are shown
ID verification
public class VC
{
public static bool VerificaCedula(char[] validarCedula)
{
int aux = 0, par = 0, impar = 0, verifi;
for (int i = 0; i < 9; i += 2)
{
aux = 2 * int.Parse(validarCedula[i].ToString());
if (aux > 9)
aux -= 9;
par += aux;
}
for (int i = 1; i < 9; i += 2)
{
impar += int.Parse(validarCedula[i].ToString());
}
aux = par + impar;
if (aux % 10 != 0)
{
verifi = 10 - (aux % 10);
}
else
verifi = 0;
if (verifi == int.Parse(validarCedula[9].ToString()))
return true;
else
return false;
}
}
public sector verification
public class VSP
{
public static bool VerificaSectorPublico(char[] validarCedula)
{
int aux = 0, prod, veri;
veri = int.Parse(validarCedula[9].ToString()) + int.Parse(validarCedula[10].ToString()) + int.Parse(validarCedula[11].ToString()) + int.Parse(validarCedula[12].ToString());
if (veri > 0)
{
int[] coeficiente = new int[8] { 3, 2, 7, 6, 5, 4, 3, 2 };
for (int i = 0; i < 8; i++)
{
prod = int.Parse(validarCedula[i].ToString()) * coeficiente[i];
aux += prod;
}
if (aux % 11 == 0)
{
veri = 0;
}
else if (aux % 11 == 1)
{
return false;
}
else
{
aux = aux % 11;
veri = 11 - aux;
}
if (veri == int.Parse(validarCedula[8].ToString()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
verification of legal person
public class VPJ
{
public static bool VerificaPersonaJuridica(char[] validarCedula)
{
int aux = 0, prod, veri;
veri = int.Parse(validarCedula[10].ToString()) + int.Parse(validarCedula[11].ToString()) + int.Parse(validarCedula[12].ToString());
if (veri > 0)
{
int[] coeficiente = new int[9] { 4, 3, 2, 7, 6, 5, 4, 3, 2 };
for (int i = 0; i < 9; i++)
{
prod = int.Parse(validarCedula[i].ToString()) * coeficiente[i];
aux += prod;
}
if (aux % 11 == 0)
{
veri = 0;
}
else if (aux % 11 == 1)
{
return false;
}
else
{
aux = aux % 11;
veri = 11 - aux;
}
if (veri == int.Parse(validarCedula[9].ToString()))
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
What I would like is to use the "ID validation function" in a textbox that accepts the RUC as input so far the data entry and that is stored in the database I did it as follows, however, as you can see I can only enter the string of the ruc without the respective validation. I would like a help to use my validation function at the time of entering the ruc and save it, if the entry was correct, the message "Provider stored correctly" appears and if it was not entered successfully, exit the message "Wrong RUC re-enter data"
data entry code from stored procedure (data layer)
public void Insertar(string NombreProveedor, string rucProveedor)
{
comando.Connection = con.AbrirConexion();
comando.CommandText = "IngresarProveedor";
comando.CommandType = CommandType.StoredProcedure;
comando.Parameters.AddWithValue("#NombreProveedor", NombreProveedor);
comando.Parameters.AddWithValue("#rucProveedor", rucProveedor);
comando.ExecuteNonQuery();
comando.Parameters.Clear();
con.CerrarConexion();
}
data entry code (business cape)
private CD_RUC proveedor_cd = new CD_RUC();
public void InsertarProv(string NombreProveedor, string rucProveedor)
{
proveedor_cd.Insertar(NombreProveedor, rucProveedor);
}
save button settings (presentation layer)
private void btn_Guardar_Click(object sender, RoutedEventArgs e)
{
proveedorcn NPro = new proveedorcn();
NPro.InsertarProv(TXT_Nombre_Proveedor_P.Text, TXT_RUC.Text);
MessageBox.Show("Proveedor Ingresado Correctamente");
}

How can I simplify code in the foreach loop indexOF?

I've a model with a lot of strings named "hours1, hours2, hours3... " which one is used to assign to the index of the foreach.
How can I simplify this code?
if (colNames.IndexOf(item2) == 0)
{
if (model.Hours == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours;
}
}
if (colNames.IndexOf(item2) == 1)
{
if (model.Hours1 == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours1;
}
}
if (colNames.IndexOf(item2) == 2)
{
if (model.Hours2 == null)
{
item.Hours = 0;
}
else
{
item.Hours = (decimal)model.Hours2;
}
}
This isn't very pretty, but perhaps:
decimal? hours = null;
switch(colNames.IndexOf(item2))
{
case 0: hours = model.Hours; break;
case 1: hours = model.Hours1; break;
case 2: hours = model.Hours2; break;
}
item.Hours = hours ?? 0M;

How to count the a specific value on a multidimensional array c#(Unity)

I'm having trouble on counting the number of my TIE value in my list
here is my code :
string[,] table = new string[104, 15];
int xIndex = 0;
int yIndex = 0;
for (int i = 0; i < list.Count; i++)
{
newString[0] += list[i].r;
newString[0] += ",";
}
string[] newChars = newString[0].Split(',');
string result = ""; // variable for the substring
string previousValue_ = ""; // store here the newprevious value without the T
int counterForTie = 0;
int counterForRow = 1;
int justMoveToY = 1;
foreach (string previousValue in newChars)
{
//check the length so that it wont throw an error
if (previousValue.Length > 1)
{
//get only the first letter of value P,B,T
result = previousValue.Substring(0, 1);
}
else
{
result = "";
}
if (table.GetLength(0) < xIndex)
{
break;
}
if (result.Equals(newPreviousValue) || result.Equals("T") && yIndex < table.GetLength(1))
{
if (counterForRow == 1)
{
yIndex = 0;
table[xIndex, yIndex] = result;
counterForRow++;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
else
{
yIndex += 1;
table[xIndex, yIndex] = result;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
}
else if (result.Equals(newPreviousValue) && previousValue.Equals("T") && yIndex < table.GetLength(1))
{
yIndex += 1;
table[xIndex, yIndex] = result;
if (firstDragonTail)
{
counterForTieSecondTime++;
}
else if (secondDragonTail)
{
counterForTieThirdTime++;
}
else
{
counterForTie++;
}
}
else
{
if (justMoveToY == 1 && counterForRow == 1)
{
xIndex = 0;
yIndex = 0;
table[xIndex, yIndex] = result;
justMoveToY++;
counterForRow++;
}
else if (justMoveToY == 1)
{
xIndex = 0;
yIndex += 1;
table[xIndex, yIndex] = result;
justMoveToY++;
}
else {
if (firstDragonTail)
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTieSecondTime = 0;
if (counterForTieSecondTime == 0)
{
secondDragonTail = true;
firstDragonTail = false;
}
else
{
secondDragonTail = false;
}
}
else if (secondDragonTail)
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTieThirdTime = 0;
if (counterForTieThirdTime == 0)
{
thirdDragonTail = true;
secondDragonTail = false;
}
else
{
thirdDragonTail = false;
}
}
else
{
xIndex += 1;
yIndex = 0;
table[xIndex, yIndex] = result;
counterForTie = 0;
}
}
}
previousValue_ = result;
if (!result.Equals("T"))
{
newPreviousValue = previousValue_;
}
}
My problem here is that i couldn't count separately all the TIE value . All i want just to count the TIE value on every column .
For example like this image
As you can see on the image above i want to know if the TIE value is on the PLAYER value(blue) / BANKER value(red) and count the TIE value if how many is it on the Player column and vice versa.
I tried this
//count tie in a row
if (result.Equals("T") && result.Equals("P"))
{
tieCounterPlayer++;
Debug.Log("TIE FOR PLAYER :" + tieCounterPlayer);
}
else if(result.Equals("T") && result.Equals("B"))
{
tieCounterBanker++;
Debug.Log("TIE FOR BANKER :" + tieCounterBanker);
}
But unfortunately it didn't work.
Sorry for asking
This is what i did.
if (newPreviousValue.Contains("B"))
{
if (result.Equals("T"))
{
tieCounterBanker++;
Debug.Log("TIE FOR BANKER : " + tieCounterBanker);
}
else
{
tieCounterBanker = 0;
}
}
else if(newPreviousValue.Contains("P"))
{
if (result.Equals("T"))
{
tieCounterPlayer++;
Debug.Log("TIE FOR PLAYER : " + tieCounterPlayer);
}
else
{
tieCounterPlayer = 0;
}
}

searching an array for specific criteria and displaying

Hi I am completely new to C# programming and I am getting stuck on my code. My program is to ask the user for a city or zip code, the amount of beds/baths they want, and their price range. I need to to search through my array and then display all the houses that meet their criteria (think Zillow, the website). My code currently displays random houses that do not meet any of the criteria I selected for the home. HELP!
for (int a = 0; a < HOUSES; ++a)
{
if (zipChecker == zip[a]) // check zip code
{
found = true;
foundPosition = a;
}
if (BtnBath1.Checked) // check baths
{
if (bath[a] > 0 && bath[a] <= 1)
{
found = true;
foundPosition = a;
}
}
else if (BtnBath2.Checked) // check baths
{
if (bath[a] > 1 && bath[a] <= 2)
{
found = true;
foundPosition = a;
}
}
else if (BtnBath3.Checked) // check baths
{
if (bath[a] > 2 && bath[a] <= 3)
{
found = true;
foundPosition = a;
}
}
else if (BtnBath4.Checked) // check baths
{
if (bath[a] > 3)
{
found = true;
foundPosition = a;
}
}
if (BtnBed1.Checked) // check bed
{
if (bed[a] > 0 && bed[a] <= 1)
{
found = true;
foundPosition = a;
}
}
else if (BtnBed2.Checked) //check bed
{
if (bed[a] > 1 && bed[a] <= 2)
{
found = true;
foundPosition = a;
}
}
else if (BtnBed3.Checked) //check bed
{
if (bed[a] > 2 || bed[a] <= 3)
{
found = true;
foundPosition = a;
}
}
else if (BtnBed4.Checked) //check bed
{
if (bed[a] > 3)
{
found = true;
foundPosition = a;
}
}
if (BoxPrice1.Checked) //check price
{
if (price[a] < 200000 && price[a] > 300000)
{
found = false;
foundPosition = a;
}
}
if (BoxPrice2.Checked) //check price
{
if (price[a] < 300000 && price[a] > 400000)
{
found = false;
foundPosition = a;
}
}
if (BoxPrice3.Checked) //check price
{
if (price[a] < 400000 && price[a] > 500000)
{
found = false;
foundPosition = a;
}
}
if (BoxPrice4.Checked) //check price
{
if (price[a] < 500000)
{
found = false;
foundPosition = a;
}
}
}
if (found)
{
label1.Text +=
string.Format("Bed: {0}, Bath:{1}, Asking Price:{2}, City:{3}, SQFT:{4}, " +
"Zip Code:{5}, Year:{6}", bed[foundPosition], bath[foundPosition],
price[foundPosition].ToString("c2"), city[foundPosition],
sqft[foundPosition].ToString("n0"), zip[foundPosition],
year[foundPosition]);
}
else
{
label1.Text = ("Sorry there were no houses that met your criteria");
}
int printcount = 0;
for (int a = 0; a < HOUSES; ++a) {
if (zipChecker == zip[a]) // check zip code
{
found = true;
foundPosition = a;
} else break;
if (BtnBath1.Checked) // check baths
{
if (bath[a] > 0 && bath[a] <= 1) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBath2.Checked) // check baths
{
if (bath[a] > 1 && bath[a] <= 2) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBath3.Checked) // check baths
{
if (bath[a] > 2 && bath[a] <= 3) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBath4.Checked) // check baths
{
if (bath[a] > 3) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed1.Checked) // check bed
{
if (bed[a] > 0 && bed[a] <= 1) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed2.Checked) //check bed
{
if (bed[a] > 1 && bed[a] <= 2) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed3.Checked) //check bed
{
if (bed[a] > 2 || bed[a] <= 3) {
found = true;
foundPosition = a;
} else break;
}
if (BtnBed4.Checked) //check bed
{
if (bed[a] > 3) {
found = true;
foundPosition = a;
} else break;
}
if (BoxPrice1.Checked) //check price
{
if (price[a] < 200000 && price[a] > 300000) {
found = false;
foundPosition = a;
} else break;
}
if (BoxPrice2.Checked) //check price
{
if (price[a] < 300000 && price[a] > 400000) {
found = false;
foundPosition = a;
} else break;
}
if (BoxPrice3.Checked) //check price
{
if (price[a] < 400000 && price[a] > 500000) {
found = false;
foundPosition = a;
} else break;
}
if (BoxPrice4.Checked) //check price
{
if (price[a] < 500000) {
found = false;
foundPosition = a;
} else break;
}
if (found) {
printcount++;
label1.Text += string.Format("Bed: {0}, Bath:{1}, Asking Price:{2}, City:{3},SQFT:{4}, Zip Code:{5}, Year:{6}", bed[foundPosition], bath[foundPosition], price[foundPosition].ToString("c2"), city[foundPosition], sqft[foundPosition].ToString("n0"), zip[foundPosition], year[foundPosition]);
}
}
if (printcount == 0) label1.Text = ("Sorry there were no houses that met your criteria");
just changed the code for your requirement but can't test it

C# datetimepicker clear specific items

I have a Java application I'm trying to convert to C#. I have solved a fair bit of the program, but I have this clear method that troubles me:
private void checkCourts()
{
if (splMonth.getSelectedValue() != null && splDate.getSelectedValue() != null)
{
courtModel.clear();
Calendar booking = new GregorianCalendar();
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = new Scanner(splMonth.getSelectedValue().toString()).nextInt() - 1;
int date = new Scanner(splDate.getSelectedValue().toString()).nextInt();
int time = Integer.parseInt(cmbxTime.getSelectedItem().toString());
int currentMonth = Calendar.getInstance().get(Calendar.MONTH);
int currentDate = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int currentTime = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
booking.set(year, month, date, time, 0, 0);
if (month > currentMonth || (month == currentMonth && date > currentDate) || (month == currentMonth && date == currentDate && time > currentTime))
{
try
{
ArrayList<Reservation> rs = BookingManager.getInstance().getReservations();
Reservation r = new Reservation(booking);
ArrayList<String> courtNames = BookingManager.getInstance().getCourtsName();
for (int i = 0; i < rs.size(); i++)
{
r.getReservationTime().clear(Calendar.MILLISECOND);
rs.get(i).getReservationTime().clear(Calendar.MILLISECOND);
}
if (!rs.contains(r))
{
for (String c : courtNames)
{
courtModel.addElement(c);
}
}
else
{
for (String c : courtNames)
{
courtModel.addElement(c);
}
for (int i = 0; i < rs.size(); i++)
{
if (r.getReservationTime().getTime().equals(rs.get(i).getReservationTime().getTime()))
{
String courtName = BookingManager.getInstance().getNameById(rs.get(i).getCourtId());
courtModel.removeElement(courtName);
}
}
}
splCourt.setModel(courtModel);
}
catch (Exception e)
{
System.out.println("ERROR - " + e.getMessage());
}
}
else
{
JOptionPane.showMessageDialog(null, "Den valgte dato er ikke tilgængelig for booking.", "Advarsel", JOptionPane.INFORMATION_MESSAGE);
}
}
}
Well, the top for loop is the real issue, I think. I would like to remove the reservation times that already have been booked.
This is my first for loop try-out:
private void checkCourts()
{
DateTime current = DateTime.Now;
int year = Int32.Parse(DateTimePicker.Value.ToString("yyyy"));
int currentYear = current.Year;
int month = Int32.Parse(DateTimePicker.Value.ToString("MM"));
int currentMonth = current.Month;
int day = Int32.Parse(DateTimePicker.Value.ToString("dd"));
int currentDay = current.Day;
int time = (int)cmbxTime.SelectedItem;
int currentTime = current.TimeOfDay.Hours;
string date1 = year.ToString() + "," + month.ToString() + "," + day.ToString();
DateTime thisdate = DateTime.Parse(date1);
thisdate = thisdate.AddHours(time);
List<Reservation> rs = BookingManager.getInstance().getReservations();
Reservation r = new Reservation(thisdate);
List<string> courtNames = BookingManager.getInstance().getCourtsName();
if (month > currentMonth || (month == currentMonth && day > currentDay) ||
(month == currentMonth && day == currentDay && time > currentTime) && year >= currentYear)
{
try
{
for (int i = 0; i < rs.Count; i++)
{
r.ReservationTime = r.ReservationTime.AddTicks(-r.ReservationTime.Ticks % 10000000);
rs[i].ReservationTime = rs[i].ReservationTime.AddTicks(-rs[i].ReservationTime.Ticks % 10000000);
}
if (!rs.Contains(r))
{
foreach (string c in courtNames)
{
lboxCourts.Items.Add(c);
}
}
else
{
foreach (string c in courtNames)
{
lboxCourts.Items.Add(c);
}
for (int i = 0; i < rs.Count; i++)
{
if (r.ReservationTime.Equals(rs[i].ReservationTime))
{
String courtName = BookingManager.getInstance().getNameById(rs[i].CourtId);
lboxCourts.Items.Remove(courtName);
MessageBox.Show("is equal");
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
MessageBox.Show("Den valgte dato er ikke gyldig! - vær opmærksom på at hvis du vælger dags dato, at tidspunktet ikke kan være tidligere end nuværende tidspunkt!");
}
}
Hope you can clear my sight.. I have simply lost focus. I know of what I have see online - that datetimepicker is not that easy to edit. But then I would just edit the already booked item - to something like "already booked".
According to the docs, your Java code .clear(Calendar.MILLISECOND) is simply removing any milliseconds from the value. It's not doing anything with your application logic to remove the actual reservation times. It doesn't appear to involve any kind of DateTimePicker either.
Assuming in c# that the ReservationTime is a DateTime property, and r.ReservationTime is a different property than rs[i].ReservationTime, then you would need to do the following:
for (int i = 0; i < rs.Count; i++)
{
r.ReservationTime = r.ReservationTime.AddTicks(-r.ReservationTime.Ticks % 10000000);
rs[i].ReservationTime = rs[i].ReservationTime.AddTicks(-rs[i].ReservationTime.Ticks % 10000000);
}
There are a couple of points to note:
Java's Calendar class has resolution to the millisecond, so removing milliseconds would be truncating the value to the second.
DateTime in .Net has resolution to the tick. I tick is 100 nanoseconds, so there are 10,000,000 ticks in a second.
Therefore, you can't just clear the milliseconds, you have to clear by computing the remainder of ticks smaller than one second. Those are then subtracted from the original value, getting you the same result.
DateTime in .Net is immutable, so you can't just change one property. You have to compute a new value, and then assign it back to the original variable.
It ended up like this:
for (int i = 0; i < rs.Count; i++)
{
r.ReservationTime = r.ReservationTime;
rs[i].ReservationTime = DateTime.Parse(rs[i].ReservationTime.ToString());
if (thisdate.CompareTo(rs[i].ReservationTime) != 0)
{
foreach (string c in courtNames)
{
lboxCourts.Items.Add(c);
}
}
else
{
lboxCourts.Items.Clear();
foreach (string c in courtNames)
{
lboxCourts.Items.Add(c);
}
for (int j = 0; j < rs.Count; j++)
{
if (r.ReservationTime.Equals(rs[j].ReservationTime))
{
string courtName = BookingManager.getInstance().getNameById(rs[j].CourtId);
lboxCourts.Items.Remove(courtName);
}
}
}
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
else
{
MessageBox.Show("Den valgte dato er ikke gyldig! - vær opmærksom på at hvis du vælger dags dato, at tidspunktet ikke kan være tidligere end nuværende tidspunkt!");
}
}
Thank you for your help... now my method is removing the already booked courts ;-)
Kindest regards
Rasmus

Categories