How to re enter a string in text box if string doesn't match?
code I'm trying is but it stucks in loop and does not allow me to enter string again in textbox.
Can anybody guide me how to do this
the code is:
public void userpass()
{
int us = 0; //for user pass
string readText2 = File.ReadAllText(pathuser);
using (StreamReader sr2 = new StreamReader(pathuser))
{
string usernam = username.Text;
string line;
string[] lines = new String[500];
while ((line = sr2.ReadLine()) != null )
{
lines[us] = line;
if (lines[us] == usernam && usernam != "")
{
check = 1;
MessageBox.Show(usernam);
Form2 f2 = new Form2();
this.Hide();
break;
}
us++;
}
if (lines[us-1] != usernam && usernam != null)
{
this.DialogResult = DialogResult.None;
DialogResult result = new DialogResult();
result = MessageBox.Show("Invalid Username or Password?", "Retry", MessageBoxButtons.OK);
if (result == DialogResult.OK)
{
username.Clear();
}
}
}
Okay so i think your problem is mostly checking if the value exist in the file. You can use this function to check if it exist or not and then you can do what you need :
public bool findValueInFile(string filePath, string value)
{
//Get all lines from the txt file
string[] lines = File.ReadAllLines(filePath);
//Go thru all the lines
foreach(string line in lines)
{
//If we find the line we're looking for
if (line.Equals(value))
{
return true;
}
}
//If we haven't found anything return false
return false;
}
After calling this function depending on the return you can show a messagebox or do something else :
if(findValueInFile(yourPath, yourValue))
{
// We found the value
}
else
{
// We didn't find the value
}
Related
I have a way here how I check multiple variables for null, and fill them with the correct data according to the nullness. However, this way is very messy and I am now wondering if there is a better way to do this.
`
try
{
user = new ADUser();
nextEntry = ldapSearch.Next();
var attName = nextEntry.getAttribute("name");
var attMail = nextEntry.getAttribute("mail");
var attTelephone = nextEntry.getAttribute("telephoneNumber");
if(attName == null || attMail == null || attTelephone == null)
{
if( attName == null)
{
user.name = "";
}
else
{
user.name = attName.StringValue;
}
if(attMail == null)
{
user.mail = "";
}
else
{
user.mail = attMail.StringValue;
}
if(attTelephone == null)
{
user.telephone = "";
}
else
{
user.telephone = attTelephone.StringValue;
}
}
else
{
user.name = attName.StringValue;
user.mail = attMail.StringValue;
user.telephone = attTelephone.StringValue;
}
model.ADUserList.Add(user);
}
catch
{
continue;
}
`
I have tried it my way, but I think it can be done cleaner.
yes, you can achive the same result without any 'if-else':
user.name = attName?.StringValue ?? "";
user.mail = attMail?.StringValue ?? "";
user.telephone = attTelephone?.StringValue ?? "";
you can also write an extension method to return the empty string:
public static class StringExtensions
{
public static string EmptyIfNull(this string str)
{
return str ?? String.Empty;
}
}
and then use it like this:
user.name = attName?.StringValue.EmptyIfNull();
user.mail = attMail?.StringValue.EmptyIfNull();
user.telephone = attTelephone?.StringValue.EmptyIfNull();
I'm trying to filter trough by gridview using a textbox when I need to use commas to search for specific items in that grid view
This is my gridview:
As you can see the column Ingredientes contains items separated by commas. What I'm trying to do is if I write in the Ingredientes textbox "repolho,salsa" for example the row appears.
At the moment I can search if the Ingredientes column has just a single item like that one with the "ing"
This is my code
// Procura pelos ingredientes
else if (txtTitulo.Text == "" && txtIngredientes.Text != "")
{
dataGridReceitas.Rows.Clear();
if (File.Exists(receitas))
{
sr = File.OpenText(receitas);
string linha = "";
int x = 0;
while((linha = sr.ReadLine()) != null)
{
string[] campos = linha.Split(';');
if(txtIngredientes.Text == campos[3])
{
dataGridReceitas.Rows.Add(1);
dataGridReceitas[0, x].Value = campos[0];
dataGridReceitas[1, x].Value = campos[1];
dataGridReceitas[2, x].Value = campos[2];
dataGridReceitas[3, x].Value = campos[3];
x++;
}
}
sr.Close();
}
}
You can simply do this :
else if (txtTitulo.Text == "" && txtIngredientes.Text != "")
{
string searchValue = txtIngredientes.Text;
dataGridReceitas.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
try
{
bool valueResult = false;
foreach (DataGridViewRow row in dataGridReceitas.Rows)
{
if (row.Cells[3].Value != null && row.Cells[3].Value.ToString().Equals(searchValue))
{
int rowIndex = row.Index;
dataGridView1.Rows[rowIndex].Selected = true;
valueResult = true;
break;
}
}
if (!valueResult)
{
MessageBox.Show("Unable to find " + searchtextBox.Text, "Not Found");
return;
}
}
catch (Exception exc)
{
MessageBox.Show(exc.Message);
}
}
While submitting a form, in one of the fields i am inserting vulnerable characters like =cmd|'/C calc'!A0. So in security terms it is termed as CSV-injection in export functionality
I have written code like this for above error. but its not working
[WebMethod]
public static string SaveRecord(RRSOCSaving RRSOCSaving, string Indication)
{
string strReturnId = "";
string strAppURL = ConfigurationManager.AppSettings["AppUrl"].ToString();
string strmail_Content = "";
CommonDB commonObj = new CommonDB();
try
{
// Cross site scripting issue code tag..!!
if (commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_CODE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.CITY)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_1)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_SITENAME_LANDL_2)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_ASST_MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.STORE_MANAGER_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.MANAGER_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.EMP_NEAREST_STORE_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SUPERVISOR_MOBNO)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_NAME_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.SECURITY_SUP_MOBNO_STORE)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_NAME)
|| commonObj.HackerTextExistOrNot(RRSOCSaving.ALPM_ALPO_MOBNO))
{
strReturnId = "Something went wrong due to malicious script attack..!!!";
}
else
{
if (RRSOCSaving.ROLE_ASSIGNED == "SLP State Head")
{
bool blnState1 = Array.Exists(RRSOCSaving.ASSIGNED_STATE.ToString().ToUpper().Split(','), element => element == (RRSOCSaving.STATE).ToString().ToUpper());
if (blnState1)
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
}
else
{
strReturnId = "User can add data for " + RRSOCSaving.ASSIGNED_STATE + " only";
}
}
else if (RRSOCSaving.ROLE_ASSIGNED == "NHQ Admin")
{
strmail_Content = Get_Email_Content(RRSOCSaving.STORE_CODE, RRSOCSaving.UserName, Indication, RRSOCSaving.STATE, RRSOCSaving.SITE_STORE_FORMAT, RRSOCSaving.STORE_SITENAME);
// SendEmail(RRSOCSaving.UserName, RRSOCSaving.STORE_CODE, RRSOCSaving.SLP_EMAILID, ConfigurationManager.AppSettings["NHQEmail"].ToString(), strmail_Content, Indication);
strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving, Indication);
//strReturnId = "Record Saved Succesfully";
}
}
// strReturnId = CommonDB.INSERT_INTO_RRSOC_INFO(RRSOCSaving);
}
catch (Exception)
{
throw;
}
return strReturnId;
}
public bool HackerTextExistOrNot(string Text)
{
bool flgValid = false;
Regex htmltags = new Regex(#"<.*?>");
Match chkMatch = htmltags.Match(Text);
if (chkMatch.Success)
{
flgValid = true;
}
return flgValid;
}
Please suggest how to stop this error.
Your HackerTextExistOrNot method is checking for the existance of html tags.
You should however check if the text is starting with one of the formular triggering characters.
To protect yourself against the injection attack ensure that none of the given text begins with any of the following characters:
Equals to ("=")
Plus ("+")
Minus ("-")
At ("#")
So you can check like this:
var attackChars = new char[]{'=','+','-','#'};
if(attackChars.Contains(text[0])
{
}
Tell me please, how can I do so that would only give the last meaning of this search.
At the moment, about 15 MessageBox.Show is opened.
How to make it so that only the latter would show?
For the fifth hour I am suffering with different variations. Nothing happens.
TextReader tr = null;
try
{
File.Copy(SteamLogFilePath, tmpFile, true);
}
catch { }
try
{
tr = new StreamReader(tmpFile);
try
{
string line = null;
while (true)
{
line = tr.ReadLine();
if (line.Contains("RecvMsgClientLogOnResponse") && line.Contains("OK"))
{
tmpSplit1 = line.Split(')');
string SteamIdbrut = tmpSplit1[1];
tmpSplit1 = SteamIdbrut.Split(']');
string SteamIdnet = tmpSplit1[0].Replace(" : [", "");
long steam32 = Convert.ToInt64((GetFriendID(SteamIdnet)));
MessageBox.Show((FromSteam32ToSteam64(steam32)).ToString());
}
}
}
catch { }
}
catch { }
if (tr != null)
tr.Close();
You could use this instead:
string lastLine = File.ReadLines(tmpFile)
.Where(line => line.Contains("RecvMsgClientLogOnResponse") && line.Contains("OK"))
.LastOrDefault();
// rest of code to create the MessageBox
This code replaces all of your code from 2nd try to tr.Close();.
I will be straight forward and say that I found this code online and therefore is not my own. It works perfectly if I type in the name of the program as shown in Programs and Features but for instance, I want to type Mozilla Firefox and have it find the installed Mozilla Firefox 26.0 (x86 en-US). I tried many times to use .substring and .contains in the line that checks the two strings but each time leads the program to just lock up. Any help is appreciated.
Just for side notes:
I am using a list of programs in a txt file that are read in to check against the installed apps.
I ran a messagebox right after it sets the display name and several of the message boxes show up blank. I tried to limit it with string.length not being 0 and length being equal or greater than the string from the txt file but all still locks up the program.
Code:
private static bool IsAppInstalled(string p_machineName, string p_name)
{
string keyName;
// search in: CurrentUser
keyName = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.CurrentUser, keyName, "DisplayName", p_name) == true)
{
return true;
}
// search in: LocalMachine_32
keyName = #"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.LocalMachine, keyName, "DisplayName", p_name) == true)
{
return true;
}
// search in: LocalMachine_64
keyName = #"SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall";
if (ExistsInRemoteSubKey(p_machineName, RegistryHive.LocalMachine, keyName, "DisplayName", p_name) == true)
{
return true;
}
return false;
}
private static bool ExistsInRemoteSubKey(string p_machineName, RegistryHive p_hive, string p_subKeyName, string p_attributeName, string p_name)
{
RegistryKey subkey;
string displayName;
using (RegistryKey regHive = RegistryKey.OpenRemoteBaseKey(p_hive, p_machineName))
{
using (RegistryKey regKey = regHive.OpenSubKey(p_subKeyName))
{
if (regKey != null)
{
foreach (string kn in regKey.GetSubKeyNames())
{
using (subkey = regKey.OpenSubKey(kn))
{
displayName = subkey.GetValue(p_attributeName) as string;
MessageBox.Show(displayName);
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true) // key found!
{
return true;
}
}
}
}
}
}
return false;
}
I have tried too many different things to list (or remember)... If it helps this is the majority of the rest of the code calling it:
private void Button_Click(object sender, EventArgs e)
{
string[] lines = new string[250];
string msg = "";
string path = System.Windows.Forms.Application.StartupPath;
if (blah.Checked)
{
try
{
StreamReader filePick = new StreamReader(#path + "\\blah.txt");
int counter = 0;
while ((lines[counter] = filePick.ReadLine()) != null)
{
counter++;
}
filePick.Close();
}
catch (Exception ex)
{
msg += ex.Message;
}
}
else if (blah2.Checked)
{
try
{
StreamReader filePick = new StreamReader(#path + "\\blah2.txt");
int counter = 0;
while ((lines[counter] = filePick.ReadLine()) != null)
{
counter++;
}
filePick.Close();
}
catch (Exception ex)
{
msg += ex.Message;
}
}
string MACHINE_NAME = System.Environment.MachineName;
int counter2 = 0;
string APPLICATION_NAME = "";
string filename = "";
while (lines[counter2] != null)
{
APPLICATION_NAME = lines[counter2];
try
{
bool isAppInstalled = IsAppInstalled(MACHINE_NAME, APPLICATION_NAME);
if (isAppInstalled == true)
{
appsNeedAttention = true;
msg += APPLICATION_NAME + " is still installed.";
}
counter2++;
}
catch (Exception ex)
{
msg += ex.Message;
}
}
if (blah.Checked == true)
{
filename = "blah.txt";
}
else if (blah2.Checked == true)
{
filename = "blah2.txt";
}
if (counter2 == 0 && File.Exists(filename) == true)
{
msg = "There are no programs listed in the file.";
}
if (msg != "")
{
MessageBox.Show(msg, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
Try to change this part :
if (p_name.Equals(displayName, StringComparison.OrdinalIgnoreCase) == true)
{
return true;
}
To this :
//check null to avoid error
if (!string.IsNullOrEmpty(displayName))
{
//convert both string to lower case to ignore case difference
//and use contains to match partially
if (displayName.ToLower().Contains(p_name.ToLower()))
{
return true;
}
}