here's my current code that I am using
public string obfuscateNums(string src)
{
string returnSrc = src;
string[] numbers = Regex.Split(src, #"\D+");
foreach (string val in numbers)
{
if (!string.IsNullOrEmpty(val))
{
string newNum = obfuscateNumber(val);
Regex reg = new Regex(val);
returnSrc = reg.Replace(returnSrc, newNum);
}
}
return returnSrc;
}
public string obfuscateNumber(string origNumber)
{
Random random = new Random();
int orig = Convert.ToInt32(origNumber);
int add = random.Next(0, orig * 2);
int sub = add;
int mul = random.Next(0, orig * 2);
int div = mul;
return "((((" + orig + " + " + add + ")-" + sub + ")*" + mul + ")/" + div + ")";
}
Before it would only obfuscate the last number but now it's obfuscating numbers inside of the already obfuscated number. Anyone know how I would fix this?
Current Result:
local x = ((((27 + ((((5 + 9)-9)*0)/0)1)-((((5 + 9)-9)*0)/0)1)*((((3 + ((((5 + 9)-9)*0)/0))-((((5 + 9)-9)*0)/0))*0)/0))/((((3 + ((((5 + 9)-9)*0)/0))-((((5 + 9)-9)*0)/0))*0)/0)) + ((((29 + ((((5 + 9)-9)*0)/0)((((4 + 7)-7)*0)/0))-((((5 + 9)-9)*0)/0)((((4 + 7)-7)*0)/0))*((((4 + 7)-7)*0)/0))/((((4 + 7)-7)*0)/0)) + ((((28 + ((((5 + 9)-9)*0)/0)((((3 + ((((5 + 9)-9)*0)/0))-((((5 + 9)-9)*0)/0))*0)/0))-((((5 + 9)-9)*0)/0)((((3 + ((((5 + 9)-9)*0)/0))-((((5 + 9)-9)*0)/0))*0)/0))*((((3 + ((((5 + 9)-9)*0)/0))-((((5 + 9)-9)*0)/0))*0)/0))/((((3 + ((((5 + 9)-9)*0)/0))-((((5 + 9)-9)*0)/0))*0)/0)) + ((((26 + ((((4 + 7)-7)*0)/0)9)-((((4 + 7)-7)*0)/0)9)*((((3 + ((((5 + 9)-9)*0)/0))-((((5 + 9)-9)*0)/0))*0)/0))/((((3 + ((((5 + 9)-9)*0)/0))-((((5 + 9)-9)*0)/0))*0)/0)) + ((((3 + ((((5 + 9)-9)*0)/0))-((((5 + 9)-9)*0)/0))*0)/0) + ((((4 + 7)-7)*0)/0) + ((((5 + 9)-9)*0)/0)
You can use the overload of Regex.Replace(...) that takes a MatchEvaluator for this:
https://msdn.microsoft.com/en-us/library/cft8645c(v=vs.110).aspx
Like so:
public string obfuscateNums(string src)
{
string returnSrc = src;
var reg = new Regex(#"\d+");
return reg.Replace(src, (match) => obfuscateNumber(match.Value));
}
public string obfuscateNumber(string origNumber)
{
Random random = new Random();
int orig = Convert.ToInt32(origNumber);
int add = random.Next(0, orig * 2);
int sub = add;
int mul = random.Next(0, orig * 2);
int div = mul;
return "((((" + orig + " + " + add + ")-" + sub + ")*" + mul + ")/" + div + ")";
}
The MatchEvaluator method parameter is a method that processes each match and returns a replacement value.
Change obfuscateNums to:
var returnSrc = src;
var numbers = Regex.Split(src, #"\D+");
var lastIndex = 0;
foreach (var val in numbers)
if (!string.IsNullOrEmpty(val))
{
var newNum = ObfuscateNumber(val);
var startIndex = returnSrc.IndexOf(val, lastIndex);
if (startIndex == -1) continue;
returnSrc = returnSrc.Remove(startIndex, val.Length);
returnSrc = returnSrc.Insert(startIndex, newNum);
lastIndex = startIndex + newNum.Length;
}
return returnSrc;
Related
I was trying to show texts 50 times on the textbox, but it just show only once.
(which is the last time(50th) text)
enter image description here
'''
int x = 0;
int y = 0;
int counting = 0;
for(x = 0; x < 10; x++)
{
for(y = 0; y < 5; y++)
{
counting++;
richTextBox1.Text = "TEST" + " " + x.ToString() + " " + y.ToString() + "\r\n";
}
}
textBox1.Text = counting.ToString();
'''
The 'counting' works great, but "TEST" is just shows one time.
What should I have to do if I can make 50 texts?
Thank you.
You need to Change the line
richTextBox1.Text = "TEST" + " " + x.ToString() + " " + y.ToString() + "\r\n";
to 1 of 2 things:
richTextBox1.Text += "TEST" + " " + x.ToString() + " " + y.ToString() + "\r\n";
Or
richTextBox1.Text =richTextBox1.Text + "TEST" + " " + x.ToString() + " " + y.ToString() + "\r\n";
That Will append the new text to the existing.
You are setting a value to the text box 50 times, not building up the value as you set it. If you want to show all 50 values, you'll need to concatenate them:
int x = 0;
int y = 0;
int counting = 0;
# Start with an empty text box
richTextBox1.Text = "";
for(x = 0; x < 10; x++)
{
for(y = 0; y < 5; y++)
{
counting++;
richTextBox1.Text += "TEST" + " " + x.ToString() + " " + y.ToString() + "\r\n";
}
}
textBox1.Text = counting.ToString();```
I have a list of items that are determined by what a player enters into several input fields, but for the sake of this example, let's say that it contains "a", "b", "c", "d", and "e". These are then sorted into a dictionary with a list of numbers as the values (unimportant). I then randomize the dictionary with two different randomizer variables (i and j), for the sake of taking two objects from the dictionary and displaying them to the screen, so the player can press various associated buttons. This goes on until x amount of turns have passed. The main problem I'm having is the prevention of semi-duplicates, such as "a b" and "b a" from appearing.
I have tried entering inserting both the randomized pair and its semi-duplicate into another dictionary and then using while loop statements preventing any pairs from that dictionary from appearing. Unfortunately, this hasn't worked.
Below is my code.
public void Start() {
finalList = new Dictionary<string, int>();
for (index = 0; index < allNumbers; index++)
{
finalList.Add(itemList[index], valueList[index]);
Debug.Log(finalList[index.ToString()]);
}
}
public void Update() {
choose();
}
public void choose() {
duplicates = new Dictionary<string, string>();
duplicates.Clear();
while (rounds < insertNum) {
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
while (j == i || (duplicates.ContainsKey(key) || duplicates.ContainsKey(reverseKey))) {
i = UnityEngine.Random.Range(0, allNumbers - 1);
j = UnityEngine.Random.Range(0, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
Debug.Log("(new keys " + key + ", " + reverseKey + ")");
//break;
} while (j == i || (duplicates.ContainsKey(key) && duplicates.ContainsKey(reverseKey)))
{
i = UnityEngine.Random.Range(0, allNumbers - 1);
j = UnityEngine.Random.Range(0, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
Debug.Log("(new keys " + key + ", " + reverseKey + ")");
}while (j == i && (duplicates.ContainsKey(key) || dupes.ContainsKey(reverseKey))) {
i = UnityEngine.Random.Range(0, allNumbers - 1);
j = UnityEngine.Random.Range(0, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
Debug.Log("(new keys " + key + ", " + reverseKey + ")");
}
while (j == i && (duplicates.ContainsKey(key) && duplicates.ContainsKey(reverseKey))) {
i = UnityEngine.Random.Range(0, allNumbers - 1);
j = UnityEngine.Random.Range(0, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
reverseKey = "(" + itemList[j].ToString() + " " + itemList[i].ToString() + ")";
Debug.Log("(new keys " + key + ", " + reverseKey + ")");
}
duplicates.Add(key, "1"); // the one is just a filler variable
duplicates.Add(reverseKey, "1");
if (buttonOneBool) { //this is in another script, ignore
finalList[itemList[i].ToString()] = valueList[i] += 2;
finalList[itemList[j].ToString()] = valueList[j] -= 2;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonTwoBool) {
finalList[itemList[i].ToString()] = valueList[i] -= 2;
finalList[itemList[j].ToString()] = valueList[j] += 2;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonThreeBool) {
finalList[itemList[i].ToString()] = valueList[i] -= 1;
finalList[itemList[j].ToString()] = valueList[j] -= 1;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonFourBool) {
finalList[itemList[i].ToString()] = valueList[i] += 1;
finalList[itemList[j].ToString()] = valueList[j] += 1;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
}
break;
}
The simplest way to fix this is to guarantee i < j. When selecting a new i and j like this:
i = UnityEngine.Random.Range(min, max);
j = UnityEngine.Random.Range(min, max);
Instead do this:
i = UnityEngine.Random.Range(min, max - 1);
j = UnityEngine.Random.Range(i + 1, max);
Doing this rules out the possibility of selecting a "mirror image" of a previous case and also avoids the "i == j" case.
After these modifications your choose() function should look something like this:
public void choose()
{
duplicates = new HashSet<string>();
while (rounds < insertNum)
{
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
while (duplicates.Contains(key))
{
i = UnityEngine.Random.Range(0, allNumbers - 2);
j = UnityEngine.Random.Range(i + 1, allNumbers - 1);
key = "(" + itemList[i].ToString() + " " + itemList[j].ToString() + ")";
}
duplicates.Add(key); // the one is just a filler variable
if (buttonOneBool) { //bool definitions are in another script, ignore
finalList[itemList[i].ToString()] = valueList[i] += 2;
finalList[itemList[j].ToString()] = valueList[j] -= 2;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonTwoBool) {
finalList[itemList[i].ToString()] = valueList[i] -= 2;
finalList[itemList[j].ToString()] = valueList[j] += 2;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonThreeBool) {
finalList[itemList[i].ToString()] = valueList[i] -= 1;
finalList[itemList[j].ToString()] = valueList[j] -= 1;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
} else if (buttonFourBool) {
finalList[itemList[i].ToString()] = valueList[i] += 1;
finalList[itemList[j].ToString()] = valueList[j] += 1;
i = UnityEngine.Random.Range(0, n - 1);
j = UnityEngine.Random.Range(0, n - 1);
}
break;
}
}
You can get two random indexes to a list using code below. The code uses integer as the list type and will work with any type.
List<int> randomList = itemList.Select((x, i) => new { index = i, rand = rand.Next() }).OrderBy(x => x.rand).Select(x => x.index).ToList();
Then the two random indexes into the list are randomList[0] and randomList[1]. The code assigns a random number to each index i of the list. To get the two items from the list use itemList[randomList[0]] and itemList[randomList[1]]. The code assumes there are at least two items in the original list ItemList[].
If your original list has duplicates than you need to use Distinct() as shown in code below
List<int> distinctList = itemList.Distinct().ToList();
List<int> randomList = distinctList.Select((x, i) => new { index = i, rand = rand.Next() }).OrderBy(x => x.rand).Select(x => x.index).ToList();
I have 2 pictureboxes and a couple of labels and buttons in my form. The application reads variables from a PLC to draw a graph on pictureboxes and checks if any alarm has been occured by reading variables from PLC. I have 3 timers working at 0.5, 1 and 30 seconds interval for each one. After a while, pictureboxes go invalid. I mean red rectangle on white background by invalid. Buttons don't work. I run application from exe built by debug mode. No errors or exceptions have been occured. Should i refresh my form by my code? Should i enable double buffering property? Or what else should i do? Thanks for your time.
Best regards,
Bee-
Note: Before some changes the app worked around a week. And it was all ok. Changes are: 2 timers added(0.5 and 1 sec interval) and added a picturebox.
Edit: When i go debug mode, i figured out that picturebox.Invalidate() commands doesn't refresh picturebox. After invalidate command, debugger didn't hit paint event method. And also buttons creates form object but can't show it. I think there is something wrong with graphics/rendering. I'm just a beginner and thanks for your help. Codes below:
Reading values to create graph and invalidate pictureboxes:
private void timerCommunication_Tick(object sender, EventArgs e)
{
CurrentActiveShift();
if (Global_Variables.isShiftActiveNow)
{
if (adsClient.IsConnected == false)
adsClient.Connect(801);
string info = adsClient.ReadDeviceInfo().ToString();
float ActData = (float)adsClient.ReadAny(16416, 200, typeof(float));
textBox1.Text = Convert.ToString(ActData);
string[] vs = new string[9];
string[] vs1 = new string[6];
if (DateTime.Now.Hour < 10)
vs[0] = "0" + DateTime.Now.Hour.ToString() + ":";
else
vs[0] = DateTime.Now.Hour.ToString() + ":";
if (DateTime.Now.Minute < 10)
vs[0] += "0" + DateTime.Now.Minute.ToString();
else
vs[0] += DateTime.Now.Minute.ToString();
vs[1] = Convert.ToString(ActData);
vs1[0] = vs[0];
ActData = (float)adsClient.ReadAny(16416, 216, typeof(float));
vs1[1] = Convert.ToString(ActData);
float PrmUpperLimit = Global_Variables.PrmSetValue + Global_Variables.PrmAlarm + Global_Variables.PrmWarning + Global_Variables.PrmMaxMin;
float PrmLowerLimit = Global_Variables.PrmSetValue - Global_Variables.PrmAlarm - Global_Variables.PrmWarning - Global_Variables.PrmMaxMin;
float PrmSet = Global_Variables.PrmSetValue;
float PrmUpperWarning = Global_Variables.PrmSetValue + Global_Variables.PrmWarning;
float PrmLowerWarning = Global_Variables.PrmSetValue - Global_Variables.PrmWarning;
float PrmUpperAlarm = PrmUpperWarning + Global_Variables.PrmAlarm;
float PrmLowerAlarm = PrmLowerWarning - Global_Variables.PrmAlarm;
float OvlUpperLimit = Global_Variables.OvlSetValue + Global_Variables.OvlAlarm + Global_Variables.OvlWarning + Global_Variables.OvlMaxMin;
float OvlSet = Global_Variables.OvlSetValue;
float OvlUpperWarning = Global_Variables.OvlSetValue + Global_Variables.OvlWarning;
float OvlUpperAlarm = OvlUpperWarning + Global_Variables.OvlAlarm;
vs[2] = Convert.ToString(PrmUpperLimit);
vs1[2] = Convert.ToString(OvlUpperLimit);
vs[3] = Convert.ToString(PrmUpperAlarm);
vs1[3] = Convert.ToString(OvlUpperAlarm);
vs[4] = Convert.ToString(PrmUpperWarning);
vs1[4] = Convert.ToString(OvlUpperWarning);
vs[5] = Convert.ToString(PrmSet);
vs1[5] = Convert.ToString(OvlSet);
vs[6] = Convert.ToString(PrmLowerWarning);
vs[7] = Convert.ToString(PrmLowerAlarm);
vs[8] = Convert.ToString(PrmLowerLimit);
//string Header = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
string Header = DateTime.Now.ToString("yyyy.MM.dd") + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
//string Dir = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString();
string Dir = DateTime.Now.ToString("yyyy.MM.dd");
System.IO.Directory.CreateDirectory(Application.StartupPath + "\\Archive\\" + Dir);
MeasuringLog.WriteLog(Application.StartupPath + "\\Archive\\" + Dir + "\\" + Header + ".txt", vs);
MeasuringLog.WriteLog(Application.StartupPath + "\\Archive\\" + Dir + "\\" + Header + ".txt", vs1);
picboxPerimeter.Invalidate();
picboxOvality.Invalidate();
}
Picturebox Paint Event:
private void picboxPerimeter_Paint(object sender, PaintEventArgs e)
{
CurrentActiveShift();
if (Global_Variables.isShiftActiveNow)
{
string[] X = new string[2];
//string Header = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
string Header = DateTime.Now.ToString("yyyy.MM.dd") + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
//string Dir = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString();
string Dir = DateTime.Now.ToString("yyyy.MM.dd");
string path = Application.StartupPath + "\\Archive\\" + Dir + "\\" + Header + ".txt";
try
{
int index;
string[] ReadLog = System.IO.File.ReadAllLines(path);
float LargestSet = LargestLimit(ReadLog, 5, 0, out index);
float LargestTrend = LargestLimit(ReadLog, 2, 0, out index);
string[] FillLbL = ReadLog[index].Split('|');
string[] myL = ReadLog[index].Split('|');
FillLabelsPrm(FillLbL);
Trend.SetTrendLimits(LargestTrend, float.Parse(myL[8]));
listPerimeter.Clear();
X[0] = TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\:mm");
X[1] = TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\:mm");
Trend.Time = X;
string[] unravel = ReadLog[0].Split('|');
Trend.p1 = unravel;
for (int i = 2; i <= ReadLog.Length - 1; i += 2)
{
unravel = ReadLog[i].Split('|');
bool Check = Trend.DrawWholePicture(unravel, sender, e, listPerimeter);
}
}
catch
{
;
}
Point L_ptc = new Point();
L_ptc = picboxPerimeter.PointToClient(new Point(0, 0));
L_ptc = new Point(-L_ptc.X, -L_ptc.Y + picboxPerimeter.Size.Height);
Pen p = new Pen(Color.Black, 1.5f);
Label[] labels = new Label[17];
for (int i = 0; i <= 16; i++)
{
e.Graphics.DrawLine(p, i * picboxPerimeter.Width / 16, 0, i * picboxPerimeter.Width / 16, picboxPerimeter.Height);
labels[i] = new Label();
this.Controls.Add(labels[i]);
labels[i].Location = new Point(L_ptc.X - 15 + i * picboxPerimeter.Width / 16, L_ptc.Y - 15);
labels[i].BackColor = Color.Transparent;
labels[i].Size = new Size(35, 15);
labels[i].BringToFront();
try
{
double archive_sh = Convert.ToDouble(X[0].Substring(0, 2)) * 60 + Convert.ToDouble(X[0].Substring(3));
double archive_sh1 = Convert.ToDouble(X[1].Substring(0, 2)) * 60 + Convert.ToDouble(X[1].Substring(3));
if (archive_sh1 < archive_sh)
archive_sh1 += 24 * 60;
double a = archive_sh1 - archive_sh;
a /= 16.00;
double b = archive_sh;
TimeSpan span = TimeSpan.FromMinutes(b + i * a);
labels[i].Text = span.ToString(#"hh\:mm");
}
catch
{
;
}
}
}
}
The other picturebox' event is the same, the difference is: this one draw graph according to odd numbered lines of txt file and the other draws according to even numbered lines. Adding other timers' tick event methods below, don't know if necessary though.
Timer1; 1 sec interval, checks alarm values from PLC:
private void timer1_Tick(object sender, EventArgs e)
{
lblNotification.Text = "";
if (adsClient.IsConnected == false)
adsClient.Connect(801);
if((bool)adsClient.ReadAny(16417, 1, typeof(bool)))
{
adsClient.WriteAny(16417, 1, false);
}
if ((bool)adsClient.ReadAny(16417, 2, typeof(bool)))
{
adsClient.WriteAny(16417, 2, false);
}
bool alarm = (bool)adsClient.ReadAny(16416, 1, typeof(bool));
bool alarm1 = (bool)adsClient.ReadAny(16416, 2, typeof(bool));
bool[] myBool = (bool[])adsClient.ReadAny(16416, 400, typeof(bool[]), new int[] { 14 });
//string alarmDir = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString();
string alarmDir = DateTime.Now.ToString("yyyy.MM.dd");
System.IO.Directory.CreateDirectory(Application.StartupPath + "\\Alarm\\" + alarmDir);
//string alarmPath = DateTime.Now.Year.ToString() + "." + DateTime.Now.Month.ToString() + "." + DateTime.Now.Day.ToString() + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
string alarmPath = DateTime.Now.ToString("yyyy.MM.dd") + "," + TimeSpan.FromMinutes(Global_Variables.CurrentShiftStart).ToString(#"hh\.mm") + "-" + TimeSpan.FromMinutes(Global_Variables.CurrentShiftEnd).ToString(#"hh\.mm");
int alarmCount = 0;
for (int i=0; i <= myBool.Length - 1; i++)
{
alarmMessage[i] = AlarmLog.GetMessage(i);
if (!alarmisActive[i] && myBool[i])
{
alarmisActive[i] = true;
alarmActiveTime[i] = DateTime.Now.ToString("HH:mm");
alarmCount++;
if (!alarmisWritten[i])
{
lblNotification.Text = alarmMessage[i];
alarmisWritten[i] = true;
alarmFileData = alarmMessage[i] + "|" + alarmActiveTime[i] + "|" + alarmisActive[i].ToString() + "|" + alarmDeactiveTime[i] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
else if(alarmisActive[i] && !myBool[i])
{
if (alarmisWritten[i])
{
alarmisActive[i] = false;
alarmDeactiveTime[i] = DateTime.Now.ToString("HH:mm");
alarmisWritten[i] = false;
alarmFileData = alarmMessage[i] + "|" + alarmActiveTime[i] + "|" + alarmisActive[i].ToString() + "|" + alarmDeactiveTime[i] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
}
bool etherCatAlarm = (bool)adsClient.ReadAny(16417, 7, typeof(bool));
alarmMessage[14] = AlarmLog.GetMessage(14);
if (!alarmisActive[14] && etherCatAlarm)
{
alarmisActive[14] = true;
alarmActiveTime[14]= DateTime.Now.ToString("HH:mm");
alarmCount++;
if (!alarmisWritten[14])
{
alarmisWritten[14] = true;
alarmFileData = alarmMessage[14]+ "|" + alarmActiveTime[14] + "|" + alarmisActive[14].ToString() + "|" + alarmDeactiveTime[14] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
else if (alarmisActive[14] && !etherCatAlarm)
{
if (alarmisWritten[14])
{
alarmisActive[14] = false;
alarmDeactiveTime[14] = DateTime.Now.ToString("HH:mm");
alarmisWritten[14] = false;
alarmFileData = alarmMessage[14] + "|" + alarmActiveTime[14] + "|" + alarmisActive[14].ToString() + "|" + alarmDeactiveTime[14] + "\r\n";
System.IO.File.AppendAllText(Application.StartupPath + "\\Alarm\\" + alarmDir + "\\" + alarmPath + ".txt", alarmFileData);
}
}
if(alarmCount > 1)
{
lblNotification.Text = "Multiple alarms are active, check \"Active Alarm\" page...";
}
else if (alarmCount == 1)
{
for (int i = 0; i <= 13; i++)
{
lblNotification.Text = alarmMessage[i];
}
}
}
Timer2; 0.5 sec interval, reads values to show in labels:
private void timer2_Tick(object sender, EventArgs e)
{
if (adsClient.IsConnected == false)
adsClient.Connect(801);
float[] Actual = (float[])adsClient.ReadAny(16416, 200, typeof(float[]), new int[] { 8 });
lblPerimeterValue.Text = Actual[0].ToString();
lblPerimeterX.Text = Actual[1].ToString();
lblPerimeterY.Text = Actual[2].ToString();
lblOvalityValue.Text = Actual[4].ToString();
lblOvalityX.Text = Actual[5].ToString();
lblOvalityY.Text = Actual[6].ToString();
}
I need to color each line depends on the last char in each string form list. This is my code and it's always make the last line green. What's wrong with it?
List<string> plik = File.ReadAllLines(path).ToList();
string pom;
int size = plik.Count;
richTextBox1.Clear();
for (int i = 0; i < size; i++)
{
richTextBox1.Text += "[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine;
pom =plik[i];
richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), richTextBox1.Lines[i].Length);
// richTextBox1.Select(0, pom.Length);
if (pom.Substring(pom.Length - 1) == "n")
{
richTextBox1.SelectionBackColor = pom.Substring(pom.Length - 1) == "n" ? Color.Red :Color.Red;
}
if(pom.Substring(pom.Length - 1) != "n")
{
richTextBox1.SelectionBackColor = pom.Substring(pom.Length - 1) != "n"?Color.Green:Color.Green;
}
}
just replace
richTextBox1.Text += "[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine;
by
richTextBox1.AppendText("[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine);
Append the text instead of modifying it in whole. Using += will replace the entire string and hence you'll lose the set color each time. Use AppendText instead.
Also you can remove the unnecessary ifs in your code. This should work:
for (int i = 0; i < size; i++)
{
richTextBox1.AppendText("[" + i.ToString() + "]" + " " + plik[i] + Environment.NewLine);
richTextBox1.Select(richTextBox1.GetFirstCharIndexFromLine(i), richTextBox1.Lines[i].Length);
richTextBox1.SelectionBackColor = plik[i][plik[i].Length - 1] == 'n' ? Color.Red : Color.Green;
}
for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}
Shouldn't that be? Since you yourself adding rows to your gridview by calling Add() method as can be seen in your posted code
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(),
No idea since I don't know your requirement but to me it feels like you wanted to have the other part as else block.
for (int i = 0; i < metroGrid1.Rows.Count; i++)
{
if (metroGrid1.Rows[i].Cells[0].Value.ToString() == radGridView1.SelectedRows[0].Cells[0].Value.ToString())
{
counter = i;
metroGrid1.Rows[counter].Cells[2].Value = Convert.ToInt32(metroGrid1.Rows[counter].Cells[2].Value) + radSpinEditor1.Value;
MessageBox.Show("for loop");
}
else
{
metroGrid1.Rows.Add(radGridView1.SelectedRows[0].Cells[0].Value.ToString(), radGridView1.SelectedRows[0].Cells[1].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[2].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[3].Value.ToString() + " " + radGridView1.SelectedRows[0].Cells[4].Value.ToString(), radSpinEditor1.Value, decimal.Round(prodamt, 2), decimal.Round(prodtotamt, 2));
totamt += prodtotamt;
metroLabelTotalamt.Text = (string.Format("{0:#,###0.00}", totamt));
radSpinEditor1.Value = 1;
MessageBox.Show("else ");
}
}