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");
}
Related
I'm a math student with little to no experience programming, but I wrote this to act like a brute force algorithm. It seems to run fine except that it runs all the password combinations out to 3 characters for passwords as short as 2. Also I'm sure there's a way to refactor the for and if statements as well. Any help would be appreciated, thanks.
I've already been testing to see if some of the if statements aren't executing, and it looks like the statements with "console.writeln(Is this executing)" aren't executing but I'm not really sure.
public Form1()
{
InitializeComponent();
}
static char[] Match ={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f','g','h','i','j' ,'k','l','m','n','o','p',
'q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','C','L','M','N','O','P',
'Q','R','S','T','U','V','X','Y','Z','!','?',' ','*','-','+'};
private string[] tempPass;
private void button1_Click(object sender, EventArgs e)
{
string tempPass1 = "lm";
string result = String.Empty;
int passLength = 1;
int maxLength = 17;
tempPass = new string[passLength];
for (int i = 0; i < Match.Length; i++)
{
if (tempPass1 != result)
{
tempPass[0] = Match[i].ToString();
result = String.Concat(tempPass);
if (passLength > 1)
{
for (int j = 0; j < Match.Length; j++)
{
if (tempPass1 != result)
{
tempPass[1] = Match[j].ToString();
result = String.Concat(tempPass);
if (passLength > 2)
{
for (int k = 0; k < Match.Length; k++)
{
if (tempPass1 != result)
{
tempPass[2] = Match[k].ToString();
result = String.Concat(tempPass);
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass[2] == "+" && tempPass1 != result)
{
Console.WriteLine("This will execute?");
passLength++;
tempPass = new string[passLength];
k = 0;
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is big gay: " + result);
break;
}
}
}
}
if (tempPass[0] == "+" && tempPass[1] == "+" && tempPass1 != result)
{
Console.WriteLine("Did this execute?");
passLength++;
tempPass = new string[passLength];
j = 0;
i = 0;
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is bigger gay: " + result);
break;
}
}
}
}
//tempPass[1] = "World!";
//Console.WriteLine(result);
if (tempPass[tempPass.Length - 1] == "+" && tempPass1 != result)
{
passLength++;
tempPass = new string[passLength];
Console.WriteLine(tempPass.Length + " " + result + " " + "Success");
Console.WriteLine(i);
i = 0; /**update
j = 0;
k = 0;
l = 0;
m = 0;*/
}
else if (result == tempPass1)
{
Console.WriteLine("Broken");
Console.WriteLine("This is biggest gay: " + result);
}
}
}
}
Play with this; modified from my answer here. It'll show you all the 2 and 3 length combinations. Clicking the button will start/stop the generation process. You need a button, label, and a timer:
public partial class Form1 : Form
{
private Revision rev;
public Form1()
{
InitializeComponent();
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = !timer1.Enabled;
}
private void timer1_Tick(object sender, EventArgs e)
{
rev.NextRevision();
if (rev.CurrentRevision.Length == 4)
{
timer1.Stop();
MessageBox.Show("Sequence Complete");
// make it start back at the beginning?
rev = new Revision("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!? *-+", "00");
label1.Text = rev.CurrentRevision;
}
else
{
label1.Text = rev.CurrentRevision;
}
}
}
public class Revision
{
private string chars;
private char[] values;
private System.Text.StringBuilder curRevision;
public Revision()
{
this.DefaultRevision();
}
public Revision(string validChars)
{
if (validChars.Length > 0)
{
chars = validChars;
values = validChars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
else
{
this.DefaultRevision();
}
}
public Revision(string validChars, string startingRevision)
: this(validChars)
{
curRevision = new System.Text.StringBuilder(startingRevision.ToUpper());
int i = 0;
for (i = 0; i <= curRevision.Length - 1; i++)
{
if (Array.IndexOf(values, curRevision[i]) == -1)
{
curRevision = new System.Text.StringBuilder(values[0]);
break;
}
}
}
private void DefaultRevision()
{
chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
values = chars.ToCharArray();
curRevision = new System.Text.StringBuilder(values[0]);
}
public string ValidChars
{
get { return chars; }
}
public string CurrentRevision
{
get { return curRevision.ToString(); }
}
public string NextRevision(int numRevisions = 1)
{
bool forward = (numRevisions > 0);
numRevisions = Math.Abs(numRevisions);
int i = 0;
for (i = 1; i <= numRevisions; i++)
{
if (forward)
{
this.Increment();
}
else
{
this.Decrement();
}
}
return this.CurrentRevision;
}
private void Increment()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index < (chars.Length - 1))
{
index = index + 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[0];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index < (values.Length - 1))
{
index = index + 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[0];
}
}
curRevision.Insert(0, values[0]);
}
}
private void Decrement()
{
char curChar = curRevision[curRevision.Length - 1];
int index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[curRevision.Length - 1] = values[index];
}
else
{
curRevision[curRevision.Length - 1] = values[values.Length - 1];
int i = 0;
int startPosition = curRevision.Length - 2;
for (i = startPosition; i >= 0; i += -1)
{
curChar = curRevision[i];
index = Array.IndexOf(values, curChar);
if (index > 0)
{
index = index - 1;
curRevision[i] = values[index];
return;
}
else
{
curRevision[i] = values[values.Length - 1];
}
}
curRevision.Remove(0, 1);
if (curRevision.Length == 0)
{
curRevision.Insert(0, values[0]);
}
}
}
}
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;
}
}
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!
So I have the arrays set up and they are assigned to a value in the design Main Window view. It's set up like a quiz and each question (if statement) is a question with different point values. I just can't figure out how to add all the points for each question up at the end.
namespace ParallelArrRbnQuiz
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
string[] arrUserAnswer = new string[10];
int[] arrPoints = new int[10];
string[] arrCorrectAnswer = new string[10];
int intScore = 0;
public MainWindow()
{
InitializeComponent();
arrCorrectAnswer[0] = "Loop";
arrCorrectAnswer[1] = "Conditional";
arrCorrectAnswer[2] = "Variable";
arrCorrectAnswer[3] = "Java";
arrCorrectAnswer[4] = "Decision";
arrCorrectAnswer[5] = "XAML";
arrCorrectAnswer[6] = "Compiler";
arrCorrectAnswer[7] = "Array";
arrCorrectAnswer[8] = "Syntax Error";
arrCorrectAnswer[9] = "Camel Casing";
arrPoints[0] = 5;
arrPoints[1] = 10;
arrPoints[2] = 15;
arrPoints[3] = 5;
arrPoints[4] = 10;
arrPoints[5] = 20;
arrPoints[6] = 5;
arrPoints[7] = 5;
arrPoints[8] = 5;
arrPoints[9] = 20;
arrUserAnswer[0] = "Loop";
arrUserAnswer[1] = "Conditional";
arrUserAnswer[2] = "Variable";
arrUserAnswer[3] = "Java";
arrUserAnswer[4] = "Decision";
arrUserAnswer[5] = "XAML";
arrUserAnswer[6] = "Compiler";
arrUserAnswer[7] = "Array";
arrUserAnswer[8] = "Syntax Error";
arrUserAnswer[9] = "Camel Casing";
}
private void Submit_Answers(object sender, RoutedEventArgs e)
{
if(arrCorrectAnswer[0] == arrUserAnswer[0])
{
intScore += arrPoints[0];
}
if(arrCorrectAnswer[1] == arrUserAnswer[1])
{
intScore += arrPoints[1];
}
if(arrCorrectAnswer[2] == arrUserAnswer[2])
{
intScore += arrPoints[2];
}
if(arrCorrectAnswer[3] == arrUserAnswer[3])
{
intScore += arrPoints[3];
}
if(arrCorrectAnswer[4] == arrUserAnswer[4])
{
intScore += arrPoints[4];
}
if(arrCorrectAnswer[5] == arrUserAnswer[5])
{
intScore += arrPoints[5];
}
if(arrCorrectAnswer[6] == arrUserAnswer[6])
{
intScore += arrPoints[6];
}
if(arrCorrectAnswer[7] == arrUserAnswer[7])
{
intScore += arrPoints[7];
}
if(arrCorrectAnswer[8] == arrUserAnswer[8])
{
intScore += arrPoints[8];
if(arrCorrectAnswer[9] == arrUserAnswer[9])
{
intScore += arrPoints[9];
}
txtScore.Text = intScore.ToString();
}
}
}
}
This is what I understand from your code
for(int i=0;i<10;i++)
{
if(arrCorrectAnswer[i] == arrUserAnswer[i])
{
arrPoints[i] += arrPoints[i];
}
}
and then
int TotalPoints = 0;
for(int i=0;i<10;i++)
{
TotalPoints += arrPoints[i];
}
But I believe it should be
int TotalPoints = 0;
for(int i=0;i<10;i++)
{
if(arrCorrectAnswer[i] == arrUserAnswer[i])
{
TotalPoints += arrPoints[i];
}
}
After that you can show TotalPoints
Use a counter to go through each element in the array. You could create a method that does something like this:
var counter = 0;
while (counter <= arrPoints.Length(){
counter += arrPoints[counter]
}
return counter;
You can use the Sum Linq Extension method to get the total of your array.
(note: FrameWork 3.5 and greater)
static void Main(string[] args)
{
int[] arrPoints = new int[] { 5, 10, 15, 5, 10, 20, 5, 5, 5, 20 } ;
int value = arrPoints.Sum();
Console.WriteLine(value);
Console.ReadLine();
}
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/