AutoCompleteExtender strange problem - asp.net

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.

Related

error Incorrect syntax near ','

SqlConnection con = new SqlConnection(#"Data Source=shashi-PC\SQLEXPRESS;Initial Catalog=payroll;Integrated Security=True;Pooling=False");
SqlCommand com = new SqlCommand("insert into Leave_trans values(" + txtempid.Text + ",'" + ddlleavetype.SelectedValue + "'," + txtallowedays.Text + "," + txtpendingleave.Text + ",'" + txtleavefrom.Text + "','" + txtleaveto.Text + "'," + txttotalleaves.Text + ")");
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
Response.Write("<script>alert('Leave data saved successfully')</script>");
con.Close();
This doesn't directly answer your question, but you should never take user-input and use string concatenation to build an SQL query (please take some time to read about SQL injection e.g. here or here).
Instead of concatenating the full query, you should use SqlParameter instances as placeholders for your values, e.g:
var com = new SqlCommand(
"insert into Leave_trans values(#empId, #leaveType, #allowedDays, ...)");
com.Parameters.Add(new SqlParameter("#empId", txtempid.Text));
com.Parameters.Add(new SqlParameter("#leaveType", ddlleavetype.SelectedValue));
com.Parameters.Add(new SqlParameter("#allowedDays", txtalloweddays.Text));
...
BTW: the cause for your problem is that you are not correctly single-quoting your inputs inside the query (e.g. txtempid.Text is not in single quotes). Using SqlParameters will also solve that problem for you.
I think the problem is in your query. You didn't provide us the data type of your database columns. But assuming from your query you are inserting some text from TextBox and one DropDownList selected item. From your TextBox text you will always get a string type value and for inserting string into your columns you should use single quotation '' before and after on it. But on your query you didn't use any quotation for some of your value parameter. I made an assumption and made a query for you. try this updated one.
SqlConnection con = new SqlConnection(#"Data Source=shashi-PC\SQLEXPRESS;Initial Catalog=payroll;Integrated Security=True;Pooling=False");
SqlCommand com = new SqlCommand("insert into Leave_trans values(" + "'" + txtempid.Text + "'", "'" + ddlleavetype.SelectedValue + "'","'" + txtallowedays.Text + "'","'" + txtpendingleave.Text + "'", "'" + txtleavefrom.Text + "'","'" + txtleaveto.Text + "'", "'" + txttotalleaves.Text + "')");
com.Connection = con;
con.Open();
com.ExecuteNonQuery();
Response.Write("<script>alert('Leave data saved successfully')</script>");
But i have some suggestion for you that is- you shouldn't use string as your table's primary key data type, it should be int type and another one is you should take int id of your selected item from your DropDownList not the text.

ASPX Long Selectcommand

I know this has to be posted somewhere and I'm probably not searching by the correct wording, but how do you break up a long selectcommand statement so you can see it all? Mine are running off the page and they're hard to read. Thanks in advance!
If you're using c#, you can do this like so:
SqlCommand sqlcmd = new SqlCommand("SELECT TopicsTitle,TopicContents,UserName,Avatar,NumberOfPost,uPoints,uType " +
"FROM Topic, Registration " +
"WHERE Topic.Category ='" + ilblTopic.Text + "'" +
"AND LastPostDate ='" + DateTime.Parse("...") + "'");
Bonus: please use a parameterized query.
You can use string builder to create a long strings.
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("SELECT field1, field2, field3 as Field3_Something,");
sb.Append(field4, field5, field6, field7, field8, field9");
sb.Append(FROM table JOIN table2 AS TNS ON TNS.id = table.id");
sb.Append(" WHERE something = 1");
SqlCommand sqlcmd = new SqlCommand(sb.ToString());

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
....?

Gridview SQL LIKE from Dropdownlist

I have a textbox, dropdownlist and a SQL statement bound to a gridview.
How can I add the dropdownlist value to the SQL statement after the WHERE clause?
I've try the following but it's showing no data.
"SELECT FirstName, LastName FROM tblPerson WHERE '" & ddlSearch.SelectedValue & "' LIKE '%" & txtSearch.Text & "%' ORDER BY FirstName
You are missing your column name in your query so try this
string query = "SELECT FirstName, LastName FROM tblPerson
WHERE myDDLColumn like '% " + ddlSearch.SelectedValue + "'%'" + "and
myTextBoxColumn like '%" + txtSearch.Text + "'%'";
EDIT : If your dropdownlist contains the column names as value of item in dropdown then you can write it as :
string query = "SELECT FirstName, LastName FROM tblPerson WHERE "+
ddlSearch.SelectedValue+" like '%" + txtSearch.Text + "'%'";

How to search for same search string in multiple columns?

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)

Resources