How to search for same search string in multiple columns? - asp.net

I am searching for string input from textbox control in EF data model. Could someone help me to construct the where clause in the code file to do this.
I tried the below piece of code in the code, even though it compiles throws an error when I enter the search string and submit the search.
Where("it.[CaseName] like '%'" + searchString +
"'%' or it.[CaseNumber] like '%'" + searchString +
"'%' or it.[AppRegNumber] like '%'" + searchString +
"'%' or it.[SSNo] like '%'" + searchString + "'%'")
When this same where clause was used in EntityDataSource control markup it accepts and search correctly.
I am in the process of changing my pages to use ObjectDataSource control to connect to a business logic layer class instead of directly to EDM data model.

If you want to use the Where Query Builder method of ObjectQuery (I think that's what you are using in your question), you need to remove the inner single quotes from the query expression:
Where("it.[CaseName] like '%" + searchString +
"%' or it.[CaseNumber] like '%" + searchString +
"%' or it.[AppRegNumber] like '%" + searchString +
"%' or it.[SSNo] like '%" + searchString + "%'")
Or as a parametrized query:
Where("it.[CaseName] like #search" +
" or it.[CaseNumber] like #search" +
" or it.[AppRegNumber] like #search" +
" or it.[SSNo] like #search",
new ObjectParameter("search", string.Concat("%", searchString, "%")))
Edit
Don't use the first version if searchString comes from user input on a web page as this version is vulnerable to SQL Injection (enter this term in search engine for explanation). Instead use the parametrized query in the second version.

Well, you can use the Linq extension methods:
.Where(r => r.CaseName.IndexOf(searchString) >= 0
|| r.CaseNumber.IndexOf(searchString) >= 0
|| r.AppRegNumber.IndexOf(searchString) >= 0
|| r.SSNo.IndexOf(searchString) >= 0)

Related

Move most matched result up in asp.net

I am developing an application where user searches for another user. The most matched results should come higher up.
string name = txtSearch.Text;
string space = " ";
if(name.Contains(space))
{
string[] FullName = txtSearch.Text.Split(' ');
using (SqlConnection conn = new SqlConnection(strcon))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select UserProfile.City, UserProfile.FirstName, UserProfile.LastName,UserProfile.Age where UserProfile.FirstName like '%" + FullName[0] + "%' or UserProfile.FirstName like '%" + FullName[1] + "%' or UserProfile.LastName like '%" + FullName[1] + "%'";
cmd.Connection = conn;
conn.Open();
dlContacts.DataSource = cmd.ExecuteReader();
dlContacts.DataBind();
conn.Close();
}
}
}
This is where I am handling search work. txrSearch is id of text box where user types username to search and finally data is bound to datalist. Now I want to move the matches record up. Like if user types "Tom John" then Tom John name should come on the top and then remaining records with lower frequency of those keywords should come down. How can I do it?
Thanks in advance
To avoid SQL injection attacks, always use parameterized queries.
cmd.Parameters.AddWithValue("#myFirstParam", FullName[0])
cmd.Parameters.AddWithValue("#mySecondParam", FullName[1])
your CommentText
(maby it is not ideal, but it works for you.)
SELECT
UserProfile.City,UserProfile.FirstName,UserProfile.LastName,UserProfile.Age
FROM
UserProfile
WHERE
UserProfile.FirstName LIKE '%' + #myFirstParam + '%' OR
UserProfile.FirstName LIKE '%' + #mySecondParam + '%' OR
UserProfile.LastName LIKE '%" + #mySecondParam + "%'
ORDER BY
CASE WHEN UserProfile.FirstName LIKE '%' + #myFirstParam + '%' THEN 1 ELSE 0 END +
CASE WHEN UserProfile.FirstName LIKE '%' + #mySecondParam + '%' THEN 1 ELSE 0 END +
CASE WHEN UserProfile.LastName LIKE '%' + #mySecondParam + '%' THEN 1 ELSE 0 END
DESC
what about
i have three names
i have three names
i use upper/lower case
i enter space and not type a second word
....?

How to make value of a column name appear with single apostrophe in sql statement of sql helper inside asp. net

SQLHelper sqhlpr = new SQLHelper();
sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class=" + NurseryButton.Text;
DataTable dt = sqhlpr.getDataTable(false);
This is my code.Now the result of sqhlpr.sqlText is
select StudentName from tblStudentInfo where class= **Nursery**
(i.e.NurseryButton.Text=Nursery) but the result that i want is select StudentName from tblStudentInfo where class= 'Nursery'.How can this be done??? This looks simple but I can't just figure it out...
"Select StudentName from tblStudentInfo where class='" + NurseryButton.Text + "'";
But you definitively should not use it that way! (SQL Injection)
Here is a good answer: Sql inline query with parameters. Parameter is not read when the query is executed
Your query is a string. You do:
result = "somestring" + someVariable;
Now you want to enclose someVariable in sinlge quotes, which is done like this:
result = "somestring" + "'" + someVariable + "'";
Or shorter:
result = "somestring'" + someVariable + "'";
However is is worth noting that manually building queries is quite "not done". You should look at tools like parameterized queries or even O/R mappers like Entity Framework.
The following code will do what you want:
SQLHelper sqhlpr = new SQLHelper();
sqhlpr.SqlText = "Select StudentName from tblStudentInfo where class = '" + NurseryButton.Text + "'";
DataTable dt = sqhlpr.getDataTable(false);
You need to think about two more things though:
What happens if someone puts an apostrophe in the NurseryButton.Text somehow
Will SQLHelper protect you from this sort of thing, or do you need to do it yourself
You should consider parametrized querying or stored procedures in some way to make sure that your input to the database is done safely.

asp.net GridView and Checkboxes Dynamic Bind

I am having a little issue that I don't seem to understand the best way to approach.
I have a GridView that get automatic column generations based on the query I run. The GridView will contain (Name) (Description) (Edit) (Delete) (View) (Admin).
Now because the Edit, Delete, View... are bit's in the database when the query returns the results and binds the data with the GridView I get these grayed out Checkboxes with checked if True or Unchecked if False.
Now because I didn't create those disabled checkboxes are they really a checkbox or are the something that's just display like that... If they are really a checkboxes how do I access them and enable or disable them? I tried looping through each cell in grid but when I say cell.text it gives me empty string back... What would be the best way to approach this or am I misunderstanding the DataBind of a bit fields?
Thanks all for your help.
UPDATED
string sSQLAccess = "SELECT ap.n_Name 'App', a.b_Edit 'Edit', a.b_Delete 'Delete', a.b_View 'View' " + Environment.NewLine
+ "FROM tbl_Actions a " + Environment.NewLine
+ "JOIN tbl_Applications ap ON ap.u_ID = a.u_ApplicationID" + Environment.NewLine
+ "JOIN tbl_Roles r ON r.u_ID = a.u_RoleID" + Environment.NewLine
+ "WHERE a.b_Deleted = 0" + Environment.NewLine
+ "AND ap.b_Deleted = 0 " + Environment.NewLine
+ "AND r.b_Deleted = 0 " + Environment.NewLine
+ "AND a.u_RoleID = '" + Request.QueryString["ID"] + "'" + Environment.NewLine;
grdAccess.DataSource = vwAccess;
grdAccess.DataBind();
The checkbox will not be enabled unless the gridview is in edit mode - you would need to define an edit template for the gridview.

Insert the date into table

I am trying to get From date and To date in two text boxes using the calender control and then trying to insert this value in a table. How can I proceed with this??
Please help..
string comstr = "insert into ATM_DETAILS_TB values(" + txtpin.Text + ",'" + Convert.ToDateTime(txtvldfrm.Text) + "','" + Convert.ToDateTime(txtvldto.Text) + "'," + Convert.ToInt32(ddlaccno.SelectedValue) + ",'" + Session["strUid"].ToString() + "')";
while using this code it shows error like "String was not recognized as a valid DateTime"
what should I do??
Use Validation controls to validate that the values in textbox values are valid dates.
Your code us contencating strings directly from user input. This opens you up to all sorts of nasty attacks, the primary being SQL Injection. Use parameterized queries instead.
Always use DateTime.TryParse or TryParseExact method to parse the date.
DateTime vldDate;
bool isValid=false;
if(DateTime.TryParse(txtvldfrm.Text,out vldDate))
{
isValid=true;
}
....
if(isValid)
{
command.Parametter.Add("#vldto",SqlDbType.DateTime).Value=vldDate;
command.Parametter.Add("#strUid",SqlDbType.VarChar,30).Value=Session["strUid"];
.....
}
You Use from parameterized queries like this:
string comstr = "insert into ATM_DETAILS_TB values(#pin,#vldfrm,#vldto,#ddlaccno,#strUid)";
YourCommand.Parametter.AddWithValue("#vldto",Convert.ToDateTime(txtvldto.Text));
YourCommand.Parametter.AddWithValue("#strUid",Session["strUid"].ToString());
....Define the Other Paraametter
Edit----
check this question String was not rec...

AutoCompleteExtender strange problem

I've faced with a strange problem in ASP.net/SQL Server and really can not find out what is the problem. I have a AutoCompleteExtender that finds out the predicted results from a web service. All the times it was working great with both english and non-english characters until I became forced to change the collation of the SQL Server 2008 database that was feeding the webservice.
Nothing changed but the collation of this database and column type which was changed from Nvarchar to Varchar. SQL server shows results correct while executing the query but:
The problem is that when typing in english in autocompleteextender textbox it responds immediately but when I enter a non-english word there, i should PRESS the BACKSPACE key to delete the last character so that it respond. My database collation is SQL_Latin1_General_CP1256_CI_AS.
I can't realize why this strange behaviour is exposed while entering non-english characters.
Here is the Web service code attached to my ajax autocompleteextender:
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod]
public string[] GetCompletionListByVT(string prefixText, int count)
{
List<string> returnData = new List<string>();
try
{
string connStr = ConfigurationManager.ConnectionStrings["CS"].ConnectionString;
SqlConnection objconnection = new SqlConnection(#connStr);
string strsql = "SELECT TOP 10 CompanyName FROM ViewAutoCompleteWSFeed WHERE (CompanyName LIKE '%" + prefixText+"" + "%');";
objconnection.Open();
// strsql = "SELECT TOP 10 CompanyName FROM ViewAutoCompleteWSFeed WHERE (CompanyName LIKE '%" + prefixText + "%' OR Business_Landline_Phone_1 LIKE '%" + prefixText + "%' OR Business_Landline_Phone_2 LIKE '%" + prefixText + "%' OR MobileNumb1 LIKE '%" + prefixText + "%' OR MobileNumb2 LIKE '%" + prefixText + "%' OR EmailAddress LIKE '%" + prefixText + "%' OR Business_Address LIKE '%" + prefixText + "%' OR htCompanySN LIKE '%" + prefixText + "%' OR htCompanyNo LIKE '%" + prefixText + "%' OR Notes LIKE '%" + prefixText + "%');";
SqlCommand objcommand = new SqlCommand(strsql, objconnection);
SqlDataReader dr = objcommand.ExecuteReader();
while (dr.Read())
{
returnData.Add(dr["CompanyName"].ToString());
}
objconnection.Close();
return returnData.ToArray();
}
catch (Exception ex)
{
returnData.Add(prefixText);
}
return returnData.ToArray();
}
The solution is that you delete the temporary folder for your website under the .net framework folder on your windows folder.
The next time you compile and build your website the problem disappears.

Resources