Autocomplet extender control in ajax (asp.net)? - asp.net

I am using autocomplete extender in my application but it is not working. This is my code:
<form id="form1" runat="server">
<asp:scriptmanager ID="Scriptmanager1" runat="server"></asp:scriptmanager>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<div>
<cc1:AutoCompleteExtender TargetControlID="TextBox1" MinimumPrefixLength="1"
ServiceMethod="GetVideoTitles" CompletionSetCount="10" ServicePath="Myservices.asmx" ID="AutoCompleteExtender1" runat="server">
</cc1:AutoCompleteExtender>
</div>
</form>
This is the webservice method:
public string[] GetVideoTitles(string prefixText)
{
SqlConnection con = new SqlConnection(#"Data Source=SERVER5\SQLserver2005;Initial Catalog=tpvnew;User ID=xx;Password=525");
con.Open();
SqlCommand cmd = new SqlCommand("video_videotitles", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#prefixText", SqlDbType.VarChar, 50);
cmd.Parameters["#prefixText"].Value = prefixText;
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
string[] items = new string[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["videotitle"].ToString(), i);
i++;
}
return items;
}

Have you tried setting a breakpoint in your GetVideoTitles method, and verified that it returns any items?

Try this trick
public string[] GetVideoTitles(string prefixText) {
try
{
...Your code...
foreach (DataRow dr in dt.Rows)
{
items.SetValue(dr["videotitle"].ToString(), i);
Debug.Write(dr["videotitle"].ToString());
i++;
}
...Your code...
}
catch(Exception)
{
Debug.Assert(false);
}
}
This way you first locate if somthing stop running on webservice method.
Also use the DebugView from sysinternals to check live the data you get from Debug.write()
Debug View
Hope this 2 thinks help you locate the bug.
-- Found this on asp.net forums--
http://forums.asp.net/t/1123944.aspx
In most cases where the WebService method does not get calls becasue the WebMethod Signature does not match with the AutoComplete Extender signature. The Method signature needs to be:
string[] WSMethodName(string prefixText, int count)
You can have different method name but the parameter names and return type needs to be exact match even in case.
Reading this page
http://www.vishwamohan.com/post/2007/05/07/AJAX-Error-Sys-is-undefined.aspx
and this page
http://blogs.imeta.co.uk/TAxworthy/archive/2009/01/15/569.aspx
Found that the sys problem can solve that way....
The most important line was:
allowDefinition="MachineToApplication"
<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication" />
When compared to the application’s web.config, the last section was missing. When this line was amended, the javascript error was fixed, and the AJAX controls worked correctly again.

Try to see if your web method GetVideoTitles() works or not.
if it works, then check if you have set your .asmx web service path in the scriptmanager.
<asp:ScriptManager ID="smMain" runat="server">
<Services>
<asp:ServiceReference Path="~/WebServices/AutoComplete.asmx"/>
</Services>
</asp:ScriptManager>

you miss this
da.SelectCommand.Parameters.Add("#prefixText", SqlDbType.VarChar, 50).Value = **prefixText + "%"**;
and in your query must use
like #prefixText

Related

Autocomplete extender not working and not firing page method instead it shows junk page markup in response

I am trying to put Ajax Autocomplete extender method in my child page using page method.Somehow page method is not firing up and instead page holds for a second saying long script is executing and shows some random page mark up in targeted textbox.
I tried setting context key parameter but it didn't work. I even set my code behind file path in sevicepath attribute of extender but that too didn't work
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
CodeBehind="FleetBooking.aspx.cs" Inherits="TMSAdmin.FleetBooking" %>
<%# Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit"
TagPrefix="CC1" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<head runat="server"></head>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" >
</asp:ScriptManager>
<section class="content-header">
<h1>Fleet booking
<small>Preview page</small>
</h1>
</section>
<div class="row">
<div class="col-md-2">
<h4>Route Name:</h4>
</div>
<div class="col-md-2">
<asp:TextBox ID="txtRoutes" runat="server" CssClass="form-control" />
<CC1:AutoCompleteExtender ServiceMethod="GetRoutes" MinimumPrefixLength="1"
CompletionInterval="100"
EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtRoutes"
ID="AutoCompleteExtender2"
runat="server" FirstRowSelected="false"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem">
</CC1:AutoCompleteExtender>
</div>
</asp:Content>
Code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static List<string> GetRoutes(string prefixText, int count)
{
using (SqlConnection con = new SqlConnection())
{
//con.ConnectionString = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
con.ConnectionString = ClsCon.myconn;
using (SqlCommand com = new SqlCommand())
{
com.CommandText = "select Route_Name from tbl_RouteMaster where "
+ "Route_Name like ' #Search + '%'";
com.Parameters.AddWithValue("#Search", prefixText);
com.Connection = con;
con.Open();
List<string> routeNames = new List<string>();
using (SqlDataReader sdr = com.ExecuteReader())
{
while (sdr.Read())
{
routeNames.Add(sdr["Route_Name"].ToString());
}
}
con.Close();
return routeNames;
}
}
}
I expect it should fire my page method so that i can debug and solve issues if any.
A similar issue is discussed here but I couldn't make the proposed solution to work.
I was able to implement with an alternative approach using a web service. Add the following code in WebService1.asmx.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace WebFormsProject
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetRoutes(string prefixText)
{
var list = new List<string>();
list.Add("Item 1");
list.Add("Item 2");
return list;
}
}
}
Update the AutoCompleteExtender as follows:
<CC1:AutoCompleteExtender
ServiceMethod="GetRoutes" ServicePath="~/WebService1.asmx"
MinimumPrefixLength="1"
CompletionInterval="100"
EnableCaching="false" CompletionSetCount="10"
TargetControlID="txtRoutes"
ID="AutoCompleteExtender2"
runat="server" FirstRowSelected="false"
CompletionListCssClass="autocomplete_completionListElement"
CompletionListItemCssClass="autocomplete_listItem"
CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem">
</CC1:AutoCompleteExtender>
With the above code I was able to have results in the textbox.
Hope this helps.
I think there's a mistake in the SQL:
+ "Route_Name like ' #Search + '%'"; // missing double-quote.
should be
+ "Route_Name like '" + #Search + "%'";
or
+ "Route_Name like '%" + #Search + "%'";

ReportViewer errors in ASP.net

I have been trying to get report viewer to work for several days now with no luck. I have followed several different tutorials but still no dice.
What I am trying to do is create a webform to allow the user to view a remote SRSS report with parameters. utilizing the following code:
protected void ddlTask_OnSelectedIndexChanged(object sender, EventArgs e)
{
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = ReportViewer1.ServerReport;
serverReport.ReportServerUrl = new Uri("http://Server/reportserver");
serverReport.ReportPath = "/QAQC_Reports/" + sqlCommands.GetSpecificFormReportName(ddlType.SelectedValue);
ReportParameter BU = new ReportParameter("#BU", ddlBusinessUnit.SelectedValue);
ReportParameter TID = new ReportParameter("#TID", ddlTask.SelectedValue);
ReportViewer1.ServerReport.SetParameters(new[] { BU, TID });
}
on my aspx page I have the following:
<%# Register Assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" Namespace="Microsoft.Reporting.WebForms" TagPrefix="rsweb" %>
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" ProcessingMode="Remote"></rsweb:ReportViewer>
I think I am almost there but I am getting the following error:
The permissions granted to user 'domain\computername$' are insufficient for performing this operation. (rsAccessDenied)

Why can't I see ajax slide show images when I run?

I'd like to have an ajax slideshow on my web site. I get image urls from a database.
I think the code is right,but when I debug it my database photos are not shown.
I'm sure that my photos load completely.
<ajax:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
</ajax:ToolkitScriptManager>
<div align="center">
<asp:Image ID="imgslides" runat="server" Height="400px"
ImageUrl="Gallery images/72007_205.jpg" BorderColor="Black"
BorderStyle="Solid" BorderWidth="5 px" />
<asp:Button ID="btnPrevious" runat="server" Text="Prev" />
<asp:Button ID="btnPlay" runat="server" Text="Play" />
<asp:Button ID="btnNext" runat="server" Text="Next" />
<ajax:SlideShowExtender ID="SlideShowExtender1"
runat="server" AutoPlay="true" Loop="true"
NextButtonID="btnNext"
PreviousButtonID="btnPrevious"
PlayButtonID="btnPlay"
PlayButtonText="Play"
StopButtonText="Stop"
TargetControlID="imgslides"
SlideShowServiceMethod="GetSlides"
SlideShowServicePath = "Slideshow.asmx">
</ajax:SlideShowExtender>
and this is my web service code Slideshow.asmx
public AjaxControlToolkit.Slide[] GetSlides()
{
SqlConnection myconn = new SqlConnection();
myconn.ConnectionString = "Data Source=PARISA-PC;Initial Catalog=Images;Integrated Security=True";
myconn.Open();
string selectCmd = "select * from images";
string countCmd = "select count(*) from images";
SqlCommand myCmd = new SqlCommand(selectCmd,myconn);
SqlCommand myCmd2 = new SqlCommand(countCmd,myconn);
int i = 0;
SqlDataReader dr = myCmd.ExecuteReader();
ArrayList ar = new ArrayList();
try
{
while (dr.Read())
{
ar.Add(dr.GetString(2));
}
}
catch (Exception)
{
throw;
}
myconn.Close();
AjaxControlToolkit.Slide[] Photos = new AjaxControlToolkit.Slide[ar.Count];
for(i=0 ; i< ar.Count ; i++){
Photos[i] = new AjaxControlToolkit.Slide(ar[i].ToString(),"image"+i.ToString(),"Booth's images");
}
return Photos;
}
[1]: http://i.stack.imgur.com/eMw4S.jpg
You have to use http handler or an aspx page (which showing images from database). Then you can send the Query String to that handler or aspx for a particular image from ajax slide web service. You can get enough examples in google about it.

AJAX cascading dropdownlist not populating

I'm following the tutorial here to try to implement cascading drop down lists using the AJAX toolkit in VS2012, however, I am using MySQL as my database instead. I created a webservice (as the tutorial describes - seen below),
<WebMethod()>
Public Function GetComplex(ByVal knownCategoryValues As String, ByVal category As String) As CascadingDropDownNameValue()
Dim conn As New MySqlConnection("Server=localhost; database=lockout; User ID=root; Pwd=123let?")
conn.Open()
Dim comm As New MySqlCommand("SELECT complex_id, complex_name FROM complex ORDER BY complex_name", conn)
Dim dr As MySqlDataReader = comm.ExecuteReader()
Dim l As New List(Of CascadingDropDownNameValue)
While (dr.Read())
l.Add(New CascadingDropDownNameValue(dr("complex_name").ToString(), dr("complex_id").ToString()))
End While
conn.Close()
Return l.ToArray()
End Function
and I am able to connect to my database and invoke my function. Invoking the function returns the following in my web browser:
<ArrayOfCascadingDropDownNameValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<CascadingDropDownNameValue>
<name>14 Line</name>
<value>1</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
<CascadingDropDownNameValue>
<name>16 Line</name>
<value>2</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
<CascadingDropDownNameValue>
<name>Converting</name>
<value>3</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
<CascadingDropDownNameValue>
<name>F&E</name>
<value>4</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
<CascadingDropDownNameValue>
<name>Water Quality</name>
<value>5</value>
<isDefaultValue>false</isDefaultValue>
</CascadingDropDownNameValue>
</ArrayOfCascadingDropDownNameValue>
I can see that I am generating the necessary array, but for some reason, the array does not appear in my drop down list and I'm not sure why. It looks as though I have covered everything in the tutorial, but I just can't seem to get it to work. Shown below is my .aspx file.
<%# Page Title="LockoutNew" Language="VB" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="LockoutNew.aspx.vb" Inherits="Lockout.LockoutNew" %>
<%# Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="ajaxToolkit" %>
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<div>
Complex: <asp:DropDownList ID="ComplexList" runat="server" /><br />
<!-- Machine: <asp:DropDownList ID="MachineList" runat="server" /><br /> -->
</div>
<ajaxToolkit:CascadingDropDown ID="ccd1" runat="server"
ServicePath="lockoutService.asmx" ServiceMethod="GetComplex"
TargetControlID="ComplexList" Category="Complex"
PromptText="Select Complex" />
<!-- <ajaxToolkit:CascadingDropDown ID="ccd2" runat="server"
ServicePath="lockoutService.asmx.vb" ServiceMethod="GetMachine"
TargetControlID="MachineList" ParentControlID="ComplexList"
Category="Machine"
PromptText="Select Machine" /> -->
</asp:Content>
Any help is greatly appreciated...
I had the same exact issue.
The thing is that when building cascading logic u need to know that the first element is different from the rest.
The first in the chain element does not have any parameters to pass to the method !
Thus your method for the first drop down list must contain no parameters :
Public Function GetComplex() As CascadingDropDownNameValue()
Dim conn As New MySqlConnection("Server=localhost; database=lockout; User ID=root; Pwd=123let?")
conn.Open()
Dim comm As New MySqlCommand("SELECT complex_id, complex_name FROM complex ORDER BY complex_name", conn)
Dim dr As MySqlDataReader = comm.ExecuteReader()
Dim l As New List(Of CascadingDropDownNameValue)
While (dr.Read())
l.Add(New CascadingDropDownNameValue(dr("complex_name").ToString(), dr("complex_id").ToString()))
End While
conn.Close()
Return l.ToArray()
End Function

How to save text of FCKEditor on database?

I am using FCKEditor on my page.
and i want to save its content on database..but on doing this error A potentially dangerous Request.Form value was detected from the client (LongDescriptionVal="<p>hello..</p>"). occur on my page..
what i am doing is here:-
aspx.cs:-
protected void btnadd_Click(object sender, EventArgs e)
{
string _detail = Request["LongDescriptionVal"].ToString();
string query = "insert into Description(description) values('" + _detail.Trim() + "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
and aspx:-
<strong>Full Description :</strong>
<br />
<!--Editor Code comes here -->
<script type="text/javascript">
<!--
var oFCKeditor = new FCKeditor( 'LongDescriptionVal') ;
oFCKeditor.BasePath = 'fckeditor/';
oFCKeditor.Height = 300;
oFCKeditor.Value = '<%=FullDescription%>';
oFCKeditor.Create() ;
//-->
</script>
<br />
<asp:Button ID="btnadd" runat="server" Text="Add" OnClick="btnadd_Click" />
anyone can tell me that how can i save data on database...
Thanks in advance..
add validateRequest="false" into your page;
Sample;
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" ValidateRequest="false" Inherits="MyApp.Default" %>
Have a look at this question:
A potentially dangerous Request.Form value was detected from the client
The gist of the answer is that you can suppress the warning by setting validateRequest="false" in the <#Page directive of your aspx file.
There is a reason for that warning however, by doing so you could in your case open yourself up to all sorts of attacks. Given the nature of your database access code can I suggest that you read up on using Parameterized Queries
in aspx page, set the property ValidateRequest="False", but don't forget to encode input before saving in database.

Resources