Searching for string in SQL table (Visual Studio C#) - sql

I am banging my head against the wall with this. I am trying to create a search function for a table in my database. I want to be able to search by ID and by first name + last name.
The search by ID function is working perfect:
if (is_id_search)
{
for (int i = 0; i < rowcount; i++)
{
if (table.Rows[i][0].ToString() == searched_id)
{
MessageBox.Show("Student With ID: " + searched_id + " Found", "", MessageBoxButtons.OK);
display_searched_info(table.Rows[i]);
break;
}
else
{
if (i == (rowcount - 1))
{
MessageBox.Show("SEARCH FAILED: Student ID Not Found!", "Search Failed!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
But when I try the same with searching by name it can't match the input string and the value in the table, I have even set a MessageBox to pop up on each iteration of the for loop displaying row[i][column].ToString() and it outputs the name I am searching but still says not found (code below):
else
{
for (int i = 0; i < rowcount; i++)
{
MessageBox.Show(table.Rows[i][1].ToString());
if (table.Rows[i][1].ToString() == searched_Fname)
{
MessageBox.Show("Student By Name Of: " + searched_Fname + " Found!", "Success!", MessageBoxButtons.OK);
break;
}
else
{
if (i == (rowcount - 1))
{
MessageBox.Show("Student By The Name Of: " + searched_Fname + " " + searched_Lname + " Not Found",
"Search Failed!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
}
Any help/advice is greatly appreciated (a couple of screenshots below)
output string from searched column
error message

Have you tried changing (table.Rows[i][0].ToString() == searched_Fname) for the String

Related

Check the null or empty record condition

I wanted to know if I did this code well, to check if the coding of a record is null or empty, getTraduction (), if I did something wrong, just let me know where I went wrong.
because I would like to have even null records printed
public void getTraduttoreIt_CLASS_HDR_NLS() throws Exception {
List<ClassHdrNls> db2 = getListCLASS_HDR_NLS();
List<DizioPt> sqlServer = getListDizioPt();
BufferedWriter scrivi = new BufferedWriter(
new FileWriter("C:/Users/francesco/Desktop/Table_ClassHdrNls_Sez3.txt"));
for (int i = 0; i < db2.size(); i++) {
for (int j = 0; j < sqlServer.size(); j++) {
if (db2.get(i).getNlsClassName().equals(sqlServer.get(j).getKeyword())) {
System.out.println("-------------------FILE N°3---------------------------");
System.out.println("-------------------ITALIANO---------------------------");
System.out.println("CLASS_NAME: " + db2.get(i).getClassName());
scrivi.newLine();
scrivi.write("CLASS_NAME: ");
scrivi.write(db2.get(i).getClassName());
scrivi.newLine();
System.out.println("NLS_CLASS_NAME: " + db2.get(i).getNlsClassName());
scrivi.write("NLS_CLASS_NAME: ");
scrivi.write(db2.get(i).getNlsClassName());
scrivi.newLine();
System.out.println("NLS_PL_CLASS_NAME: " + db2.get(i).getNlsPlClassName());
scrivi.write("NLS_PL_CLASS_NAME: ");
scrivi.write(db2.get(i).getNlsPlClassName());
scrivi.newLine();
System.out.println("KEYWORD: " + sqlServer.get(j).getKeyword());
scrivi.write("KEYWORD: ");
scrivi.write(sqlServer.get(j).getKeyword());
scrivi.newLine();
System.out.println("LINGUA ITALIANO: " + db2.get(i).getLanguage() + " ***");
scrivi.write("LINGUA ITALIANO: ");
scrivi.write(db2.get(i).getLanguage() + " ***");
scrivi.newLine();
// Faccio un controllo se il valore è diverso da null o il record è vuoto
if (sqlServer.get(j).getTraduzione() == null || sqlServer.get(j).getTraduzione().isEmpty()) {
System.out.println("TRADUZIONE: ***********");
scrivi.write("TRADUZIONE: ");
scrivi.write("*******************");
scrivi.newLine();
} else {
System.out.println("TRADUZIONE: " + sqlServer.get(j).getTraduzione());
scrivi.write("TRADUZIONE: ");
scrivi.write(sqlServer.get(j).getTraduzione());
scrivi.newLine();
}
System.out.println("-------------------------------------------------------");
scrivi.flush();
}
}
}
scrivi.close();
}
Output:
Print only non-null and non-empty records.
I also want to print null records
this line:
if (db2.get(i).getNlsClassName().equals(sqlServer.get(j).getKeyword()))
could be why you are not printing null values, since it forces printing only after there is a match.
You should inspect your data (print all of it) to see what you are getting.
If you are finding null values, then that means printing inside the if condition is what's stopping you from seeing the null values get printed.

SQL injection error in Dynamic SQL with prepared statement

I my application we are collection some user inputs from UI and based on those values we are generating dynamic SQLs with different 'Where' conditions to query data.
It is found that that piece of code has some SQL injection flaw.
public void filter(String strSerialNumberLogic, String strSerialNumber1,
String strSerialNumber2, String strCreationDateLogic,
long lngCreationDate1, long lngCreationDate2,
String strTypeNumbers, String strTitles, long lngLoc)
throws SQLException, ClassNotFoundException {
StringBuffer strWhere = new StringBuffer();
List paramList = new ArrayList();
String arrTypeNumbers[];
String arrTitles[];
int i;
boolean bolHit;
if (!strTypeNumbers.equals("") || !strTitles.equals("")) {
arrTypeNumbers = strTypeNumbers.split(",");
arrTitles = strTitles.split(",");
bolHit = false;
strWhere.append("(");
for (i = 0; i < arrTypeNumbers.length; i++) {
if (arrTypeNumbers[i].length() > 0) {
if (bolHit) {
strWhere.append(" OR ");
} else {
bolHit = true;
}
strWhere.append(" REPORT_NUMBER = ?");
paramList.add(arrTypeNumbers[i]);
}
}
for (i = 0; i < arrTitles.length; i++) {
if (arrTitles[i].length() > 0) {
if (bolHit) {
strWhere.append(" OR ");
} else {
bolHit = true;
}
strWhere.append(" REPORT_NAME = ?");
paramList.add(arrTitles[i]);
}
}
strWhere.append(") ");
}
if (!strSerialNumber1.equals("")) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_FILE_NO " + strSerialNumberLogic + " ? ");
paramList.add(strSerialNumber1);
if (strSerialNumberLogic.equals("between")) {
strWhere.append(" AND ? ");
paramList.add(strSerialNumber2);
}
}
if (lngCreationDate1 != 0) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_CREATION_DATE " + strCreationDateLogic + " ? ");
paramList.add(Long.toString(lngCreationDate1));
if (strCreationDateLogic.equals("between")) {
strWhere.append(" AND ? ");
paramList.add(Long.toString(lngCreationDate2));
}
}
if (lngLoc != 0) {
if (!strWhere.equals("")) {
strWhere.append(" AND ");
}
strWhere.append(" REPORT_FILE_LOCATION = ? ");
paramList.add(Long.toString(lngLoc));
}
String finalQuery = "";
if (!strWhere.equals("")) {
finalQuery = "WHERE " + strWhere.toString();
}
String strSQL = "SELECT * " + "FROM D990800 "
+ "LEFT JOIN D990400 ON REPORT_SYSTEM_ID ||" + " REPORT_NO = REPORT_NUMBER " + finalQuery
+ "ORDER BY REPORT_FILE_NO ASC";
System.out.println("strSQL:" + strSQL );
System.out.println("paramList:" + paramList );
Connection conn = ConnectionFactory.instance().getConnection();
PreparedStatement preparedStatement = null;
preparedStatement = conn.prepareStatement(strSQL);
for (int index = 0; index < paramList.size(); index++) {
String param = (String) paramList.get(index);
if (isParsableInt(param)) {
preparedStatement.setInt(index+1, Integer.parseInt(param));
} else {
preparedStatement.setString(index+1, param);
}
}
ResultSet rsReports = preparedStatement.executeQuery();
buildCollection(rsReports);
rsReports.close();
preparedStatement.close();
conn.close();
}
How did you come to the conclusion that you have SQL injection in this code? That would help clearing that up.
Anyway, looking at your code it seems that both strSerialNumberLogic and strCreationDateLogic are variables that comes from an external source, and are concatinated in a way that allows SQL to be injected. If this external source is the user, SQL injection can be executed. If not, than this is probably a false positive. I would improve the code anyway by chaning the logic variables turning them into Enums.

How to validate a link showing 500 error in Selenium?

I am trying to validate the links of a website using server response code and page title, the server response found through the code shown below is 200 and page title is also same for all the pages.
the code is as follows:
if(url == null || url.isEmpty())
{
System.out.println("URL is either not configured for anchor tag or it is
empty");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else if(!url.startsWith(homePage)){
System.out.println("URL belongs to another domain, skipping it.");
objExcelFile.writeExcel(filePath,"skipped_links",url);
}
else{
try {
huc = (HttpURLConnection)(new URL(url).openConnection());
huc.setRequestMethod("HEAD");
huc.connect();
respCode = huc.getResponseCode();
if(respCode != 200){
System.out.println(url+" is a broken link");
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"broken_links",url);
}
else{
String Actualtitle = driver.getTitle();
System.out.println(Actualtitle);
if (Actualtitle.contentEquals(unexpectedTitle)){
System.out.println(url+ " is a broken link");
objExcelFile.writeExcel(filePath,"broken_links",url);
} else {
System.out.println(url+ " is a valid link");
System.out.println(respCode);
objExcelFile.writeExcel(filePath,"valid_links",url);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
The header is intact but the link is showing 500 error below the header. The issue is that even though page is showing 500 error, I am getting the server response code as 200, hence I am not able to make out whether this link is broken or not
This is the screenshot of the issue for the page I am validating :
enter image description here
Once you induce connect() as in :
huc.connect();
You can write as many for() loops to check any condition of the Response Code invoking getResponseCode() method as below :
if (huc.getResponseCode() == 200)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 500)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 404)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == 402)
{
System.out.println(linkURL + " - " + httpUrlConnect.getResponseMessage());
}
if (huc.getResponseCode() == httpUrlConnect.HTTP_NOT_FOUND)
{
System.out.println(
linkURL + " - " + huc.getResponseMessage() + " - " + huc.HTTP_NOT_FOUND);
}
} catch (IOException e)
{
System.out.println(e.getMessage());
}

Coded UI c# - how to click a table htmlcell

I have tried numerous things to access a cell in a table. I have actually found the row that I need based on an innertext search, but then when I change the columnindex to the column for the found row, I cannot get mouse.click(cell); to do anything. Please see my code below. It has been modified many times! I have also used record to capture information about the cell.
The Method:
` public string SelectExistingCustomer(UITestControl parent, TestContext TestContext, string sLastName)
{
Controls control = new Controls(this.parent);
EditControl econtrol = new EditControl(this.parent);
HtmlTable tCustomerSearch = new HtmlTable(this.parent);
//HtmlTable tCustomerSearch1 = tCustomerSearch;
HtmlCell cell = new HtmlCell(tCustomerSearch);
//HtmlCell cell = GetCell;
string sFullName = "";
string sRowIndex = "";
if (sLastName != "")
{
try
{
// CodedUI scrolls items into view before it can click them
bool notfound = true;
int NumberOfpages = 0;
while (notfound)
{
tCustomerSearch.SearchProperties.Add(HtmlTable.PropertyNames.TagName, "TABLE");
Trace.WriteLine("####tCustomerSearch??? : " + tCustomerSearch + " : TABLE.");
tCustomerSearch.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
int rowcount = tCustomerSearch.RowCount;
Trace.WriteLine("Row###: " + rowcount + ".");
HtmlRow lastRow = (HtmlRow)tCustomerSearch.Rows[rowcount - 1];
//lastRow.EnsureClickable();
NumberOfpages++;
cell.SearchProperties.Add(HtmlCell.PropertyNames.InnerText, sLastName, PropertyExpressionOperator.Contains);
cell.SearchConfigurations.Add(SearchConfiguration.AlwaysSearch);
if (cell.TryFind())
{
notfound = false;
sFullName = cell.GetProperty(HtmlCell.PropertyNames.InnerText).ToString();
sRowIndex = cell.GetProperty(HtmlCell.PropertyNames.RowIndex).ToString();
Trace.WriteLine(string.Format("found name at page {0}", NumberOfpages));
Trace.WriteLine(string.Format("Table row nr: {0}", cell.RowIndex));
Trace.WriteLine("cell####: " + cell + ".");
}
else Trace.WriteLine("NOT FOUND: CELL###:" + cell + ". And sFullName: " + sFullName + ".");
}
Trace.WriteLine("CELL###:" + cell + ". And sFullName: " + sFullName + ". And sRowIndex: " + sRowIndex + ".");
cell.SearchProperties.Add(HtmlCell.PropertyNames.RowIndex, sRowIndex);
cell.SearchProperties.Add(HtmlCell.PropertyNames.ColumnIndex, "0");
cell.SearchProperties[HtmlCell.PropertyNames.InnerText] = "Get";
cell.SetFocus();
//HtmlInputButton stry = new HtmlInputButton(cell);
Mouse.Click(cell);
//Mouse.Click(stry);
Assert.IsTrue(!notfound);
}
catch (Exception ex)
{
Trace.WriteLine("Failed to Search and find. Exception: " + ex + ".");
return "Failed";
}
}
//else - For the Future
return sFullName;
}
Table and cell - I modified this from the recording, not really sure what this does but I did something similar when I was having difficulty selecting from a combox:
public class tCustomerSearch : HtmlTable
{
public tCustomerSearch(UITestControl searchLimitContainer) :
base(searchLimitContainer)
{
#region Search Criteria
this.FilterProperties[HtmlTable.PropertyNames.ControlDefinition] = "class=\"table table-striped\"";
this.FilterProperties[HtmlTable.PropertyNames.Class] = "table table-striped";
this.FilterProperties[HtmlTable.PropertyNames.TagInstance] = "1";
#endregion
}
#region Properties
public HtmlCell GetCell
{
get
{
if ((this.mGetCell == null))
{
this.mGetCell = new HtmlCell(this);
#region Search Criteria
this.mGetCell.SearchProperties[HtmlCell.PropertyNames.InnerText] = "Get";
//this.GetCell.SearchProperties[HtmlCell.PropertyNames.MaxDepth] = "3";
Trace.WriteLine("###sLastName: " + sLastName + ". And mGetCell: " + mGetCell + ".");
#endregion
}
return this.mGetCell;
}
}
#endregion
// public string ctrlPropertyValue { get; private set; }
public string sLastName { get; }
#region Fields
private HtmlCell mGetCell;
#endregion
}
`
So, I found my own answer - even though this is not the best - it works!
` Keyboard.SendKeys("{TAB}");
Keyboard.SendKeys("{ENTER}");
'
I use this in place of mouse.click(cell);
The TAB highlights the button in the cell, and Enter triggers the event.

Visual SourceSafe script starting out

I have never wrote a script before and I was asked today to make a Visual SourceSafe script that returns all of the labels that are stored.
I have 0 idea on how to start this as I have never wrote a script before. Can anybody point me in the right direction with this please?
Thanks!
You can use the History command of SourceSafe to get the history info of an item and extract the label info you need.
Here is a simple sample for you:
private void GetItem(VSSItem vssItem)
{
if (vssItem.Type == 0) //Type == 0 means it's a project
{
bool bIncludeDeleted = false;
IVSSItems vssItems = vssItem.get_Items(bIncludeDeleted);
foreach (VSSItem vssitem in vssItems)
{
GetItem(vssitem);
foreach (IVSSVersion vssVersion in vssitem.get_Versions(0))
{
string vssItemName = "";
if (vssVersion.VSSItem.Name == "")
vssItemName = vssitem.Spec;
else
vssItemName = vssVersion.VSSItem.Spec;
if (vssVersion.Action.IndexOf("Label") > -1 )
{
if (vssitem.Spec == vssVersion.VSSItem.Spec)
{
MessageBox.Show("Item " + vssItemName + " in " + "Version " + vssVersion.VersionNumber.ToString() + " With the lable: " + vssVersion.Label);
}
}
}
}
}