Showing posts with label working. Show all posts
Showing posts with label working. Show all posts

Wednesday, March 28, 2012

AJAX Calander Behind other Controls

Hi All,

I am using the Ajax Calander Control, I have it working in all and I have it writing to a textbox. I have this placed on a form where there are dropdown lists. It seems that the Cal. control always appears behind these dropdownlists instead of infront, therefore making it not visible.

Any work arounds?
Thanks in advance!!!
Tim

Hi tbraga,

I do not notice this behavior and I use VS.NET 2005 sp1 / Ajax Extentions 1 / AjaxControlToolkit 10920.

Can you post code that replicates this behavior?

Kind regards,
wim


Hi Tbraga,

As far as I know, this is a common issue. We suggest that you should upgrade your AJAX Control Toolkit to the latest version. If this doesn't work, you can set its zIndex properties. For example, $find("CalendarExtender's BehaviorID")._popupDiv.zIndex = large enough number.

function pageLoad(){
$find("CalendarExtender's BehaviorID").add_shown(resetZIndex);
}

function resetZIndex(){

$find("CalendarExtender's BehaviorID")._popupDiv.zIndex = value.

}

I hope this help.

Best regards,

Jonathan

Ajax Beta V.1: Strange behaviour with treeview inside the update panel (Again!)

I have a treevew control ( with dynamically created nodes) that was working great with July CTP. The control no longer works with beta any more:

1. Does not maintain the expanded state during ajax post back ( the nodes expand collapse unexpectly).

2. Strange behaviour if nodes are dynamically populated. This bug was present with the earlier atlas CTP's but was fixed with July CTP.

I have to use the same work around referenced in post:http://forums.asp.net/thread/1203662.aspx

------------------------

Similar issue, I didn’t want the tree to update always. The workaround that I am using is ,

Put tree in update panel (with conditional update).

- Add "TreeNodePopulate" event as a trigger in your update panel

- Turn off the client behaviour of tree expand ( putPopulateNodesFromClient = false ) and let atlas take care of it.

- Use Populate on demand = true.

-------------------------

Is any body else is having similar problem?

You might want to look at the CSS Adapters Beta 3 - they have what appears to be a 'ajaxified' treeview control that does not do full postbacks and retains viewstate on the client side... However, warning... if you do not need the other adaptewrs do not install them in your project as they override everything automatically and there is no method I know of to not allow the adapters controls it targets dynamically or explicitly...

The cool thing though is they provide all the source for it - so it may mean you can at least write an custom extender control for treeview that will integrate nicely with ajax...

Just a suggestion - and as usual unsure if I ever know what I am talking about...

Ajax beta 2 is not working with iis 6

i downloaded the ajax beta 2 from ajax.asp.net and install it in the production server which has iis 6, and i publish the site which is running well in the development server, ajax is not working any more, with any pages action they page refresh itself, i dont know what's is going on!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

OK!Have you deployment it?
Can you actually respond with actual errors it would help US help you..

Hi,

As my knowledge it wills works without any errors,

Please go through your code, you might be did mistakes in the code.

Or can you send the code then only forum can help you.

Maximum problem with your code only..

Pradeep Kumar Bura


the pages dosn't display any error message, the situation is that the page has update panel , so when user click on a search button it should display the result inside the update panel without refreshing the page, and thiss happen in the development server, but on the production page the same page server when user click on the search button, the pages is refreshed :(


Hi,

Have you checked event log for errors?

Pradeep Kumar Bura


Hi. I had a similar problem. After Installation on productive server, the sites were'nt executable because the webserver didn't found one the assemblies which will be installed while the extension installation (Microsoft.Web.Extension and Microsoft.Web.Extension.Design).

I installed and registered the assemblies whith gacutil and the aplication was running again.


I've deployed AJAX Beta 2 to four servers running IIS6. On two of the four I ran into the same issue that Michael63 describes. For me Microsoft.Web.Extension.Design was not added to the GAC. You can either register it in the GAC or you can copy it to your site's bin directory. I did the GAC way on one server and copied it into the bin folder on another - both work fine. The other thing you may want to check is that a new entry in the web.config is required. Check out the readme included with the installations for instructions.
Your site has to be running in full trust mode to be able to run the dlls in the bin folder.

i did that, and i checked that the assemply is added to the GAC , but still the site working very well in dvelopment server, but on production server, it's not the only differnce is that the development server has atlas component before but i uninstalled it before install ajax, but it was the only differnce


http://forums.asp.net/thread/1485037.aspx
follow this threadhttp://forums.asp.net/thread/1485037.aspx

AJAX Beta 2 and Toolkit 61102 released but missing CalendarExtender, TabPanel and TabConta

Any idea if these are likely to be put back in as I finally got them working?

Calendar and Tabs currently only exist in the Development branch as they are not yet stable for release. I believe that the beta2 changes in the Release branch will be merged back into the Development branch soon.

I have 55 pages using Tabs now and about 40 other pages that need the fixes in the Beta2 release.

This now makes it difficult to decide whether to temporarily code out all the Tab panels somehow and replace them with something else or wait until Tabs are back in the Toolkit.

Any idea when the Tabs will be back in? Guess?

Help...please...Crying


I'm looking at migrating Tabs right now, but keep in mind tabs is currently still in development and is not fully stable enough for the release branch. Its implementation may still change slightly before it hits the release.
Thanks. Much appreciated.

AJAX BETA 1: cascadong dropdwon list

my cascading drop down list is not working in the AJAX BETA 1 RELEASE,

if i have the cascading drop down list in side a form view then it is not working ,else it is working perfectly.

still not sure

oes any body has same problem????

Maybe:http://forums.asp.net/thread/1441672.aspx

AJAX Beta 1.0 - Odd Behaviour of AutoCompleteExtender

Moving to Beta 1.0 has not been a trivial task. I've been using AutoCompleteExtender for a while now and it was working quite well with the CTP. Upgrade to AJAX Beta 1.0 and everything stops working, and this is WITH the Value-Add CTP included as well.

Here is what I ran into:

My webservice method was never being called. I spent 3 hours on trying to figure out why my complex form wasn't calling the webservice when I'd put in a value. Turns out that with the CTP the parameter names on the web method didn't matter, but theyDO matter in beta 1.0.

Originally I had the following signature:

Public Function GetCustomers(ByVal prefixTextAs String,ByVal maxCountAs Integer)As String()
I then switched this this method signature and everything started working:
Public Function GetCustomers(ByVal prefixTextAs String,ByVal countAs Integer)As String()

I then went back and fixed all of my other autocompletes, but one still doesn't work. If you try and use the AutoComplete within a gridview control (I'm trying to let my user add rows by providing a row at the bottom with fields), the control never gets registered for autocomplete.

This used to work in the Atlas CTP. I've tried everything I can think of but no luck fixing this one.

Last thing, when a form has an AutoCompleteExtender and I click on a asp:hyperlink I get an exception thrown by WebResource.axd in the following code:

Sys.UI.DomElement.getVisible = function Sys$UI$DomElement$getVisible(element) {/// <param name="element" type="Sys.UI.DomElement"></param> /// <returns type="Boolean"></returns> var e = Function._validateParams(arguments, [ {name:"element", type: Sys.UI.DomElement} ]);if (e)throw e;return (element.style.visibility !=='hidden');}
The exception thrown is:
Microsoft JScript runtime error: Sys.ArgumentUndefinedException: Value cannot be undefined.Parameter name: element

All in all this has been a pretty frustrating upgrade. The CTP had been working so well for so long that I felt like moving to the Ajax Beta would be a safe proposition...
Charles

Another bugs:

I have AutoCompleteExtender in Wizard control on 3rd step. When I load a page, Javascript error occurs:
1if (!type.inheritsFrom(Sys.Component)) {
2 throw Error.argument('type', String.format(Sys.Res.createNotComponent, type.getName()));
3 }
4if (type.inheritsFrom(Sys.UI.Behavior) || type.inheritsFrom(Sys.UI.Control)) {
5 if (!element) throw Error.argument('element', Sys.Res.createNoDom);
6 }
on line 6 (i code it is line 1960):
Sys.ArgumentException: Value must not be null for Control and Behaviors.
Parameter name: element

I really don't know what to do with it


For us it has been the same. However, changing parameters names does not do the trick...

Can you please provide a short fragement of an ASP page with an AutoComplete that actually works with the new value added package?

Thanks,

J


I am also havin the same problem.I have uninstalled Atlas,installed the Asp.net Ajax and theJuly CTP .I recreated the project with Autocomplete extender but the webservice method is never being called and there are also no errors.

Guimauve, I would appreciate if u can post a sample code on how you made the extender call the webservice method?

Thanks,

PSK


The javascript errors are pretty annoying. Hopefully it wont be long for beta 2 (or beta 1.1?).:-) It is a shame that the CTP was going so well that it feels like a step backwards but they won't have made these changes for nothing and remember we are rather early adopters! If we shouldn't use beta's for production code then CTP is even more risky :-)

For the AutoCompleteExtender make sure your web service has the ScriptService tag as not having it fails silently. E.G:

[Microsoft.Web.Script.Services.ScriptService]
[WebService(Namespace =http://tempuri.org/)]
[WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]


Hi, i have de same Exception (description = "Sys.ArgumentUndefinedException: Value cannot be undefined. Parameter name: element")in WebResource.axd (function Sys$UI$DomElement$getVisible(element)).But my Webservice (or ScriptService) is working fine. I fink the Control is working fine. Everything looks ok, but after Postback (some Applications still need it), pug!Dave
There is a a thread with a sample posted on issue regdin AutoCompleteextenderhttp://forums.asp.net/thread/1437583.aspxIts the same as thx 1137 pointed out

AJAX Baby Steps - removing an item

i am working on my first little ajax project.

Basically i have no idea how to start. I created a AJAX enabled website and i have a simple page on there that basically has a list of items taken from a Class thats stored in the session.

So I have

1 Gridview that bases its DataSource to a Dataset i create from a object (just a class that contains an array list)

2. I have methods in place to loop through the array list, create a datatable and bind it to the gridview

3. I have a method that also removes a selected item from a dataset and refreshes the gridview its a "remove" button.

I would like to have AJAX handle the removal of items (for now, eventually i want the whole thing ajax enabled) but just to start i want to just activate my Remove method from ajax.

But i dont know where to go from here.

So what do i have to do to call my method via AJAX ?

Any advice or help appreciated!

thanks

mcm

well i seem to have figured it out although i dont know what i did or how it works!

I added the ScriptManager tag to the page.

I added an UpdatePanel surrounding my Gridview,

and now my REMOVE buttons work without postbacks!

Holy Momma! How did it do it?!? I thought i'd have to be writing javascript and hooking into new events , etc.

is it REALLY all this easy?

mcm


Yep, it can really be that easy. caveat, though; the UpdatePanels can get pretty heavy in terms of resource requirements if you use them extensively, and there are also issues with certain combinations of controls (witness the volume on the forum of "Update panel and my..." posts. For simple things like you're describing, they work very well, though.

great! So now that i have seen how easy it "can be". I do have a couple more questions.

I created a sample AJAX enabled site to test this bin and it works GREAT im so impressed with myself.

But how complicated is it going to be to make this a component. My idea for the site is to use Master Pages (another first for me)

and down the left side this "component" will sit. I still dont know wether to make it a component or just a content page.

There will be a repeater or a formView on the right with products to add to the bin. I want those to be ajax enabled too. Is it hard to make different elements in different content pages "speak" to each other? Really all im doing (as stated in the first post) is adding items to a Collection stored in a Session Variable (using a facade pattern with a SessionManager class)

Also. I am using the new Web Application templates to build my stuff (from ScottGu's blogs) Can i switch this AJAX enabled site to be a WEb Application and keep the functionality?

thanks,

mcm

Monday, March 26, 2012

AJAX AutoPostBack not working...:(

Hi!

I've read a few posts about not working autocomplete, but I haven't found anything that would help me get my autocomplete in action. Here's my code and I hope someone can tell me what am I doing wrong...:

WebService:

<%

@dotnet.itags.org.WebServiceLanguage="C#"Class="WebService" %>

using

System;

using

System.Web;

using

System.Web.Services;

using

System.Web.Services.Protocols;

using

System.Web.Script.Services;

using

System.Web.Configuration;

using

System.Data.SqlClient;

using

System.Collections;

[

WebService(Namespace ="http://tempuri.org/")]

[

WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

public

classWebService : System.Web.Services.WebService {

[

WebMethod]

[

ScriptMethod]publicstring[] GetCompletionList(string prefixText,int count)

{

ArrayList list =newArrayList();

string connStringCompletionList =WebConfigurationManager.ConnectionStrings["NeolabConnectionString"].ConnectionString;SqlConnection connCompletionList =newSqlConnection(connStringCompletionList);

connCompletionList.Open();

SqlCommand cmdCompletionList =newSqlCommand("SELECT Seminar FROM Seminar ORDER BY Seminar;", connCompletionList);SqlDataReader rCompletionList = cmdCompletionList.ExecuteReader();while (rCompletionList.Read())

{

list.Add(rCompletionList.GetString(0));

}

string[] completionList = (string[])list.ToArray(typeof(string));return completionList;

}

}

(WebService looks to work just fine, it creates an XML filled with all items)

The page (actually it's a control)

<%

@dotnet.itags.org.ControlLanguage="C#"AutoEventWireup="true"CodeFile="SeminarjiFilter.ascx.cs"Inherits="UC_I_SeminarjiFilter" %>

<%

@dotnet.itags.org.RegisterAssembly="AjaxControlToolkit"Namespace="AjaxControlToolkit"TagPrefix="cc1" %>

<

asp:ScriptManagerID="ScriptManager1"runat="server"/>

<

h1>Filter</h1>

<

divclass="crta"></div><tablecellpadding="0"cellspacing="0"border="0"width="100%"runat="server">

<tr><td>

Seminar:

</td><td><cc1:AutoCompleteExtenderID="AutoCompleteExtender1"runat="server"TargetControlID="TextBox1"ServiceMethod="GetCompletionList"ServicePath="/WebService.asmx"MinimumPrefixLength="2"CompletionInterval="1000"EnableCaching="true"CompletionSetCount="12"></cc1:AutoCompleteExtender><asp:TextBoxID="TextBox1"runat="server"CssClass="input"AutoCompleteType="Disabled"/></td></tr>

Can anyone help me? I just can't find what am I doing wrong.

Thx!

p.s.: I'm using Visual Studio Web Developer 2005

Your webservice needs a ScriptService attribute. You do not need the ScriptMethod attribute on the method since this is not a page method.

Hi kirtid!

thx for your help, but it's still not working :(

I've added a ScripService attribute like you have suggested, so my WebService.asmx looks like that now:

<%

@.WebServiceLanguage="C#"Class="WebService" %>

using

System;

using

System.Web;

using

System.Web.Services;

using

System.Web.Services.Protocols;

using

System.Web.Script.Services;

using

System.Web.Configuration;

using

System.Data.SqlClient;

using

System.Collections;

[

ScriptService]

[

WebService(Namespace ="http://tempuri.org/")]

[

WebServiceBinding(ConformsTo =WsiProfiles.BasicProfile1_1)]

public

classWebService : System.Web.Services.WebService {

[

WebMethod]publicstring[] GetCompletionList(string prefixText,int count)

{

ArrayList list =newArrayList();

string connStringCompletionList =WebConfigurationManager.ConnectionStrings["NeolabConnectionString"].ConnectionString;SqlConnection connCompletionList =newSqlConnection(connStringCompletionList);

connCompletionList.Open();

SqlCommand cmdCompletionList =newSqlCommand("SELECT Seminar FROM Seminar ORDER BY Seminar;", connCompletionList);SqlDataReader rCompletionList = cmdCompletionList.ExecuteReader();while (rCompletionList.Read())

{

list.Add(rCompletionList.GetString(0));

}

string[] completionList = (string[])list.ToArray(typeof(string));return completionList;

}

}

I do get a JavaScript error in Firefox, which says:

Napaka: [Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.status]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame ::http://localhost:1952/CISEF/ScriptResource.axd?d=jhPPdebJMXZyNg9DlOLOhTS0Nid4TBhKPJdnm84vbDCB2-uUy_FSlPcxjsG2hmQvG2-MIlmaqMJ-KsoNz2f43LUv6JMplLSpW_hbE2koLH81&t=633108756900118528 :: Sys$Net$XMLHttpExecutor$get_statusCode :: line 4166" data: no]

Here's where it happens (file ScriptResource.axd):

function Sys$Net$XMLHttpExecutor$get_statusCode() { /// <value type="Number"></value> if (arguments.length !== 0) throw Error.parameterCount(); if (!this._responseAvailable) { throw Error.invalidOperation(String.format(Sys.Res.cannotCallBeforeResponse, 'get_statusCode')); } if (!this._xmlHttpRequest) { throw Error.invalidOperation(String.format(Sys.Res.cannotCallOutsideHandler, 'get_statusCode')); } return this._xmlHttpRequest.status; }
 
Any idea maybe?!?

Is the path to your webservice set in the ServicePath property correct? -> "/WebService.asmx".


Hi kirtid!

Sorry for late reply, I was on vacation :) Thanks for your help! It was a problem in a path like you assumed!

Later

AJAX AutoCompleteExtender

Hi there everyone.

I have a AutoCompleteExtender working on my site, very nice little feature... But i would liek some information to extend it some.

Now i have another webservice that provides me with a list of Cities in the world. on of these elements may look like this:

<CityList>
<City>
<CityCode>LAX</CityCode>
<CityName>LosAngeles</CityName>
<StateCode>CA</StateCode>
<TravelPort>LosAngelesIntlArpt</TravelPort>
<CountryCode>US</CountryCode>
<CountryName>UnitedStates</CountryName>
</City>
etc

Now currently i am pulling the <CityCode> element and generating a string[] that my web service then sends out to the AutoCompleteExtender.

Couple of things i would like to see happen here and would like some information on:

1) Say my user search for "Los" and LosAngeles shows up in the Entender. They click it. At this point i would like to add LAX as their selected value. Similar to how a DropDownMenu has a SelectedItem.Value and .Text... How do i get this done?

2) i would also like to see the reverse of that and have them still be able to searc h for LAX and LosAngele show up...

There has to be a way to do this right?

Nugs

Hi,

I think this link will help you out :

How to : Use a Key Value Pair in your AutoCompleteExtender ( updated again... )

Thanks

Ajax AutoComplete with database, not working

Hello,

I am interested in implementing a search box which gives suggestions as you type. So, I downloaded the AjaxControlToolKit source code, I compiled the solution in VS 2005, and it is OK.

Then I modified the [WebMethod] public string[] GetCompletionList(string prefixText, int count) in an attempt to get the string array from a User table in my database.

I don't quite understand this WebMethod. for example,what is prefixText? My modified code is as follows.

1 [WebMethod]2public string[] GetCompletionList(string prefixText,int count)3 {4if (count == 0)5 {6 count = 10;7 }89if (prefixText.Equals("xyz"))10 {11return new string[0];12 }1314string connectionString ="localhost;Initial Catalog=myDatabase; User Id=myUserID; Password=topSecrect";15 SqlConnection sqlConnection =new SqlConnection(connectionString);16 sqlConnection.Open();17 SqlCommand sqlCommand =new SqlCommand("SELECT LASTNAME + ', ' + FIRSTNAME FROM USER AS FULLNAME ORDER BY LASTNAME", sqlConnection);18 SqlDataReader sdr = sqlCommand.ExecuteReader();1920 ArrayList fullNames =new ArrayList(count);2122while (sdr.Read())23 {24if (!sdr.IsDBNull(0))25 {26char c1 = (char)sdr.GetString(0)[0];27char c2 = (char)sdr.GetString(0)[1];28char c3 = (char)sdr.GetString(0)[2];29 fullNames.Add(prefixText + c1 + c2 + c3);30 }3132 }33return (string[])fullNames.ToArray(typeof(string));34 }

Please note that I do not quite understand the part in the for loop as in the original source code shown in blue below. So I am only mimicking the code.

// ArrayList items = new ArrayList(count);
// Random random = new Random();
// for (int i = 0; i < count; i++)
// {
// char c1 = (char)random.Next(65, 90);
// char c2 = (char)random.Next(97, 122);
// char c3 = (char)random.Next(97, 122);

// items.Add(prefixText + c1 + c2 + c3);
// }

Also please note, that the compilation of the solution with the modified code passed, and I can check out http://localhost:7870/ToolkitTests/AutoComplete.aspx just fine, but when I type in the first textbox of this AutoComplete.aspx page, no suggestions show up. The second textbox still works as usual.

The Sql query and connection string are both fine. I ran it in some other applications, they work without a problem.

Any hint is highly appreciated. Thanks.

The prefixText field are the characters that have been typed and are being queried, the count is the max number of records to return then updated with the number of records returned.

The Random... etc code, was just a way for the demo application to generate random data without attaching a database.


jguadagno:

The prefixText field are the characters that have been typed and are being queried, the count is the max number of records to return then updated with the number of records returned.

The Random... etc code, was just a way for the demo application to generate random data without attaching a database.

OK, thanks. My guess about the prefText argument was right. But, what's wrong with my modified code, which attempts to get the suggestions from the database?


Is there a way to get the suggestion list from a database? No one knows?


You have the code in the GetCompletionList. Is it not working. Remember the prefixText are the letters that the text box control has so far. So if the is a Country drop down list as user type U, the prefixText should get a U and you have to return a list of your options that start with U.


OK, I found a sample code at

http://forums.asp.net/p/1126189/1772074.aspx#1772074

By J. Shen, In order to test the dynamic SQL, I created a regular web application (NOT web service!) I just copied the part of the aforementioned code which gets the suggestions from the DB and modified like so:

public string[] GetCompletionList(string prefixText, int count)
{
if (count == 0)
{
count = 10;
}

if (prefixText.Equals("xyz"))
{
return new string[0];
}

string connectionString = "Data Source=localhost;Initial Catalog=mydatabase; User Id=myUserID; Password=TopSecret";
SqlConnection sqlConnection = new SqlConnection(connectionString);

SqlCommand sqlCommand = new SqlCommand
("SELECT TOP @.nrows LASTNAME " +
"FROM v_USER " +
"WHERE LASTNAME LIKE @.term " +
"ORDER BY LASTNAME", sqlConnection);
sqlCommand.Parameters.AddWithValue("@.nrows", count);
sqlCommand.Parameters.AddWithValue("@.term", prefixText + "%");

List<string> suggestions = new List<string>();
sqlConnection.Open();

SqlDataReader sdr = sqlCommand.ExecuteReader(System.Data.CommandBehavior.CloseConnection);

while (sdr.Read())
{
suggestions.Add(sdr[0].ToString());
}

sqlConnection.Close();
sdr.Close();

return suggestions.ToArray();

}

As you see, except the SQL, it's the same as that of J. Shen's. I call this method in Page_Load like so:

protected void Page_Load(object sender, EventArgs e)
{

string[] s = GetCompletionList("Joh", 10);
Response.Write(s.Length);
}

When I run the Web application. I always get this error:

Exception Details:System.Data.SqlClient.SqlException: Line 1: Incorrect syntax near '@.nrows'.

I am using SQL Server 2000, and obviously, the SQL query syntax isn't accepted by Sql Server 2000. I cannot figure out what's wrong with it. I am new to dynamic sql.

Any hint? Thanks.


The problem is with TOP @.nrows ... You can not have a variable for that. You can build the string prior to

string sql ="SELECT TOP " + count.ToString() +"LASTNAME FROM v_USER ";string sql +=" WHERE LASTNAME LIKE @.term ORDER BY LASTNAME ";SqlCommand sqlCommand =new SqlCommand(sql, sqlConnection);


Thank you very much, Joseph. That was the problem. It's working now. The sample code given by J. Shen completely misled me. I did not cast any doubt on his code because I took it for granted that it was a working sample.


I am glad it worked. Please mark it as "Answered" so that others will know the solution.


Hi All,

I have been trying to replicate this post in VB.net and I "think" I am almost there. I am stuck on a couple of small pieces and I'm begging for help. I have been trying to get the AJAX autocomplete to work off of a SQL database for many hours before I ran into this post which seems promising. I feel I'm at my ends.

I'm having trouble with the following lines, I'm tried to figure out what the code was trying to do but this is what I could come up with and its not working:
----------------------------------
Dim suggestionsAs ListItemCollection =New ListItemCollection(OfString)

While (reader.Read())
suggestions.Add(reader[0].ToString())
EndWhile

Return suggestions.ToArray
----------------------------------

Thanks in advance, I truely appreciate it.
Tim

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Collections.Generic
Imports System.Data.Sql
Imports System.Data.SqlClient

<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
<System.Web.Script.Services.ScriptService()> _

PublicClass AutoComplete
Inherits System.Web.Services.WebService

<WebMethod()> _

PublicFunction GetCompletionList(ByVal prefixTextAsString,ByVal countAsInteger)AsString()

If (count = 0)Then
count = 10
EndIf

Dim connAs SqlConnection
Dim commAs SqlCommand
Dim readerAs SqlDataReader
Dim connectionstringAsString = ConfigurationManager.ConnectionStrings("Magic").ConnectionString
Dim sqlAsString ="SELECT TOP " + count.ToString() +"LASTNAME FROM v_USER "

sql +=" WHERE LASTNAME LIKE @.term ORDER BY LASTNAME "

conn =New SqlConnection(connectionstring)
comm =New SqlCommand(sql, conn)
comm.Parameters.AddWithValue("@.nrows", count)
comm.Parameters.AddWithValue("@.term", prefixText +"%")

Dim suggestionsAs ListItemCollection =New ListItemCollection(OfString)

conn.Open()
reader = comm.ExecuteReader(System.Data.CommandBehavior.CloseConnection

While (reader.Read())
suggestions.Add(reader[0].ToString())
EndWhile

conn.Close()
reader.Close()

Return suggestions.ToArray

EndFunction
EndClass


With comments

''' Creates a list array

Dim suggestionsAs ListItemCollection =New ListItemCollection(OfString)

''' Opens the connection

conn.Open()

''' Creates a data reader
reader = comm.ExecuteReader(System.Data.CommandBehavior.CloseConnection

''' Loops through the data reader

While (reader.Read())

''' Adds the first column to the suggestions array

''' note: in VB this should read
suggestions.Add(reader(0).ToString())
EndWhile

''' close the objects

conn.Close()
reader.Close()

''' return the suggestion

Return suggestions.ToArray


Almost there...

I have everything compiling correctly, Visual Studio 05 isn't giving me any error messages but when I type in the textbox nothing happens. It must be linked incorrectly. I know the SQL statement works correctly because I ran it in Query Analyzer, and I know the connection string works because I have other data pulling so I think the function GetCompletionList isn't being passed any parameters for it to return a result.

If someone could explain the mapping so I can go back and verify everything on my end that would be good. Currently I have the autocompleteextender controlID set to my textbox. Other than that, the AJAX website knows to use the AutoComplete.asmx which then points to the App_Code/Autocomplete.vb right? Or does this have to be set manually or something.

Idea's?
Thanks!
Tim


The autocompleteextender needs to be configured like this

<ajaxToolkit:AutoCompleteExtender runat="server" ID="autoComplete1" TargetControlID="myTextBox" ServiceMethod="GetCompletionList" ServicePath="AutoComplete.asmx" MinimumPrefixLength="2" CompletionInterval="1000" EnableCaching="true" CompletionSetCount="20" CompletionListCssClass="autocomplete_completionListElement" CompletionListItemCssClass="autocomplete_listItem" CompletionListHighlightedItemCssClass="autocomplete_highlightedListItem" DelimiterCharacters=";, :"> <Animations> <OnShow> ... </OnShow> <OnHide> ... </OnHide> </Animations></ajaxToolkit:AutoCompleteExtender>
Note, the ServiceMethod and ServicePath properties. They need to be pointed to whereever your AutoComplete is.

Ajax authentication, custom membership; cannot use Session object

I'm using ajax 1.0 authentication but based on a custom sql membership service which is working 100% except that in the membership code the Session object (HttpContext.Current.Session) cannot be accessed which though is crucial because I user Session["UsersID"] for login based functions. Any ideas how this can be fixed?

Hello,

Would you give me more details (when, where you can't access session object) ?

I don't have any problems with Session object even with Ajax async call back??

May be your situation is different from mine!


yes is in the authentication function in my custom membership provider code;

publicoverridebool ValidateUser(string username,string password)

{

SqlConnection conn =newSqlConnection(connectionString);SqlCommand cmd =newSqlCommand("ValidateUser", conn);

cmd.CommandType =

CommandType.StoredProcedure;

cmd.Parameters.Add(

"@.Username",SqlDbType.VarChar, 12).Value = username;

cmd.Parameters.Add(

"@.Password",SqlDbType.VarChar, 12).Value = password;

cmd.Parameters.Add(

"@.IPNumber",SqlDbType.VarChar, 16).Value =HttpContext.Current.Request.UserHostAddress;SqlDataReader reader =null;try

{

conn.Open();

reader = cmd.ExecuteReader(

CommandBehavior.SingleRow);if (reader.Read() ==false)

{

returnfalse;

}

int _usersID =Convert.ToInt32(reader["UsersID"]);

HttpContext.Current.Session["UsersID"] = _usersID;

}

...


Hi Dabbi2000,

That's indeed very tempting to do. However, this construct will never work. The deal is that your code is executed by an http module that runs before the AcquireRequestState event. In other words: there is no session yet.

The best way to achieve what you want is to store your user id in the items collection of the current context and than move it from context to session in the PostAcquireRequestState event. So replace the last line of your example with:

HttpContext.Current.Items["UsersID"] = _usersID;

and then after the session state has been loaded (for example in PostAcquireRequestState)

HttpContext.Current.Session["UsersID"] = HttpContext.Current.Items["" UsersID"];
HttpContext.Current.Items.Remove("UsersID");

HTH,

-- Henkk


Henk,

that is an excellent solution! Unfortunately the Items container doesn't contain the UsersID when accessing from PostAcquireRequestState event. Using VS Debugger and Fiddler it simply seems to be lost somewhere between the authentication code and the PostAcquireRequestState event (the requesting assembly is "~/Authentication_JSON_AppService.axd"). Still there are other system variables in the Item like Is there some obvious explanation for that??


hmm not entirely correct, it isn't lost but what happens is that json authentication causes PostAcquireRequestState event BEFORE the membership validateuser() function is called?!!


Hi Dabbi2000,

I wanted to see for myself and, yes, you're right. What's going on ? In a normal postback (including async ones) the pipeline follows the chain of events I described in a previous post.

The problem is: I thought you were using the normal forms based authentication stuff in combination with an Ajax enabled app. However, you appear to be using the Sys.Services.AuthenticationService. Unfortunately (my bad, sorry) this is not a normal postback. It's uses the same infrastructure (ScriptHandler) as script services (as far as I can see, it is a script service dressed up as a resource). This means that indeed by the time you reach the endpoint (the authentication service backend) the PostAcquireSessionState event is long gone.

Fortunately, there are other events to subscribe to. But, unfortunately, if the PostAcquireSessionState is done and there is no session state, they most have turned sessions off for this service (and indeed the Session property in the HttpContext returns null).

Meaning, there is no way for you to use the Session object.

However, if the only thing you want to do is get to the current user id, the FormsAuthenticationModule (like all other builtin authentication modules) makes sure the currently logged on user is reflected in the Page.User property (or HttpContext.User for which Page.User is just a wrapper).

If you need to store more, the profile should still work. BUT only after you made a roundtrip to the authentication service and you successfuly authenticated. The authentication service calls into the FormsAuthentication class to perform authentication and returns an authentication cookie like normal, but unfortunately it forgets to set HttpContext.User like the builtin authentication modules would do (feature request ...). This means the profile module has no info to fly on and will do an anonymous profile while in the call chain of the authentication service.

HTH,

-- Henkk


I wrote a blog post about the problem:http://www.jeffzon.net/Blog/post/Session-enabled-authentication-service.aspx

The only thing we should do is to use the following authentication service class instead of the default one:

using System;using System.Web;using System.Web.Services;using System.Web.Services.Protocols;using System.Reflection;using System.Web.Script.Services;using System.Web.UI;using System.Web.Security;[WebService(Namespace ="http://tempuri.org/")][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][ScriptService]public class SessionEnabledAuthService : System.Web.Services.WebService{private static MethodInfo checkEnabledMethodInfo;static SessionEnabledAuthService() { Type authServiceType =typeof(ScriptManager).Assembly.GetType("System.Web.Security.AuthenticationService"); checkEnabledMethodInfo = authServiceType.GetMethod("CheckAuthenticationServicesEnabled", BindingFlags.NonPublic | BindingFlags.Static); }private static void CheckAuthenticationServicesEnabled(bool enforceSSL) { checkEnabledMethodInfo.Invoke(null,new object[] { HttpContext.Current, enforceSSL }); } [WebMethod(EnableSession =true)] [ScriptMethod]public bool Login(string userName,string password,bool createPersistentCookie) { CheckAuthenticationServicesEnabled(true);if (Membership.Provider.ValidateUser(userName, password)) { FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);return true; }return false; } [WebMethod(EnableSession =true)] [ScriptMethod]public void Logout() { CheckAuthenticationServicesEnabled(false); FormsAuthentication.SignOut(); }}

Hi Jeff,

This of course would work, but a couple of remarks:

1) namespacehttp://tempuri.org/ is not very unique ;-) you'll want to change this into something that makes more sense

2) I wouldn't mark this service as basic profile compliant. In normal situations it doesn't even do SOAP (script services serialize JSON by default). And even when you call it using a normal proxy, it's main result is returned as a cookie (which is not basic profile compliant, although I don't think the builtin pipeline check catches that).

3) By using reflection to call into CheckAuthenticationServicesEnabled you now have to run full trust (you'll need SecurityPermissionFlags.UnmanagedCode). Which means you either have to run the webservice full trust, or you'll have to install an separate assembly in the GAC (or grant it full trust with a custom policy). You'd be better of implementing this yourself, because the only really interesting thing CheckAuthenticationServicesEnabled does for you is check if SSL is enabled, which you can easilty do yourself with HttpRequest.IsSecureConnection (the other part is checking if an enabled flag is set on AuthenticationService itself, but since you're implementing your own, you already know it's enabled ...)

4) just as a word of warning for those who want to use this construct in production: I rarely think it's a good idea to repeat builtin functionality (with a minor change). I guess the team had good reasons to disable sessions (they are chatty things anyway) and there's plenty of workarounds. I do think it is too bad they didn't setup HttpContext.User and Thread.CurrentPrincipal like the pipeline authentication modules do, but alas. Regardless, the problem of getting to the current user is solved in an entirely different way, so the original poster will not benefit from this service. He can simply look an Page.User and be done with it.

-- Henkk


hello,

your discussions are a little more advanced than my programming knowledge :) but I would like to comment on that solution of using Page.User. User.Identity stores the username which is very unpractical. Imagine all the tables where I have to refer rows to user e.g. forum posts. User names can be whole names, and in my web would contain icelandic letters and so I think they are very bad for primary keys. That is the reason for why I use Session["UsersID"] instead of the User object.


D'uh. Don't know what I was thinking, but you'll need reflectionPermissionFlags.MemberAccess. What I said about SecurityPermissionFlags.UnmanagedCode is complete and utter BS. The net result is the same though. You'll need full trust ...

-- Henkk


Great feedback, Henkk, I totoally agree with you.

Actually I just gave a prototoype of the solution - or more likely a work around. In this situation, if the poster really need to use session state in authentication, he can use the service class I wrote - remove the validation method will be enough.


Hi,

The mapping from identity.name to user id can be done in a variety of ways. There is a very elegant one that sticks out I think (this is my personal preference BTW), which has to do with the way membership providers work. The builtin membership providers can do a mapping of the current user onto a so called MembershipUser (just a class in the library). The membership user contains more info than your average principal (including password questions, email addresses, stuff like that). You can get to the membership user for the current user by calling Membership.GetUser().

Since you implement your own provider you get to fill this information yourself (in the GetUser(userName, userIsOnline) override on your custom membership provider). One of the bits of info in a membership user is a ProviderUserKey. This is an object that you can fill with whatever info you want. In your case, probably the user id. The standard SqlMembershipProvider stores a GUID in it, BTW.

Whenever you need to get to the current user id, just use Membership.GetUser().ProviderUserKey.

Be aware though that the mapping is not cached, so if it is expensive to get from current user name to current user id, you better cache the mapping (in the ASP.NET cache ...).

The beauty of the construct is that now all custom logic is in your membership provider ...

HTH,

-- Henkk


hope you guys are still watching this thread...

Henk's solution is tempting... it's a bit expensive for only retrieving an Int value but if it survives the AJAX authentication I'm ok with it! I'm no good at asp.net cache, how would I use that for this situation??


that is, how to make it specific to each user, I thought the cache object scope was application only?

Ajax application not working when deployed to web server

I installed the extender and then the toolkit and was able to create the sample application described here:http://ajax.asp.net/ajaxtoolkit/Walkthrough/UsingSampleExtender.aspx

However, when I deploy the webpage to my company's web server I get the following error when I try to run it:

Server Error in '/ajaxtest' Application.

Configuration Error

Description:An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.

Parser Error Message:Could not load file or assembly 'System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified. (E:\WebSites\ajaxtest\web.config line 41)

Source Error:

Line 39: </httpHandlers>Line 40: <httpModules>Line 41: <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>Line 42: </httpModules>Line 43: </system.web>


Source File:E:\WebSites\ajaxtest\web.config Line:41


The file it is referencing (E:\WebSites\ajaxtest\web.config) is there. Does anyone have any idea what's going on? I've Googled the problem and searched on here but nothing seems to work.

Thanks in advance!

Do you have System.Web.Extensions.dll in the bin directory in the server?

Do you mean the bin application of my AJAX enabled web app?

If so, that particular DLL is not in the bin folder, but it's not in the bin folder on my local machine either and it runs fine there. It just doesn't run on the web server.


If you don't have a bin of your application in the bin folder, maybe it's because you don't have a webApp project but a web site project. But, in both cases, you should have more dll's in the bin folder and that dll's should be copied to the bin folder on the server!

That's true. It is a web site project and not a web app project. However, I do have a bin folder for the application on my development machine and the server. When run on my development machine the application works, but when run on the server it doesn't. And neither bin folder has the dll you mentioned.

I'm sorry if I was confusing before.

Regardless, I will see about getting that dll into the proper folder and see what happens from there. Thanks again for your help and advice!


The dll you need should be here:

C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025\System.Web.Extensions.dll

Put it on bin folder on server and it should work, I hope. :P


SWEET! That did the trick!

Thanks a million, Agapito! I really appreciate it.


Gracias! Friend! it worked.

Yes

Saturday, March 24, 2012

AJAX and Vista -

I just upgraded to Vista from XP where I had IIS running very happily and AJAX installed and working great.

After upgrading to Vista I get this browser error on any AJAX website:

'Sys' is undefined

I remember seeing that error months ago back when it was called Atlas. But now that I'm running the latest OS, with a non-beta AJAX, why should I be getting this now? The upgrade to Vista has been painful all around, but I've managed to fix or find workarounds for most problems except this one.

It seems like the AJAX stuff isn't getting included into the webpage. I even tried creating a fresh project in VWD and specifying to use the VS template for "ASP.Net Ajax Enabled Website" and throwing together a simple page with an updatepanel and a command button. Same error.

I've run Windows Update and gotten all the updates, including the Visual Studio update that tells you to run VWD "as an administrator", which I'm doing.

The line in the generated page that it is complaining about is the first reference to Sys below.
Hopefully there is just some simple security setting in this locked down OS I don't know about to allow this to run? 
<script type="text/javascript">//<![CDATA[Sys.WebForms.PageRequestManager._initialize('ScriptManager1', document.getElementById('form1'));Sys.WebForms.PageRequestManager.getInstance()._updateControls(['tUpdatePanel1'], [], [], 90);//]]>
</script>

Do you have following entry in your web.confg file?

<add verb="GET" path="ScriptResource.axd" type="Microsoft.Web.Handlers.ScriptResourceHandler" validate="false"/>

Also, follow Readme notes on migration issues on ajax.asp.net .


Yes, I have that. This was a functioning ASP.Net 2.0/AJAX 1.0 application when I had XP, but now that I'm running windows Vista, it doesn't work.

I did have to manually edit applicationHost.config in C:\windows\system32\inetsrv\config to add entries for ASP.Net 2.0 (it only had enties for 1.1), so I'm wondering if something must be added there to support AJAX.

I tried downloading and re-installing AJAX, rebooting, all the obvious stuff with no luck. Upgrading to Windows has ALMOST completely shut me down from developing.

I did just discover that when I use the VWD built in web server, AJAX works fine. So AJAX is "installed" correctly on my PC. But as far as when I use the full-blown IIS web server, AJAX is dead.

I didn't see anything in the README relating to Vista migration, only migration from previous versions of Ajax/Atlas, which is not what I'm doing.


Here is what I ended up doing as I spent nearly two days trying to rebuild my Dev machine after purchasing a Vista capable laptop.

1. Mark your site in IIS7 as an Application (The choice is there if you right click on virtual IIS7 entry in the expanded list under websites...

2. Make sure that you have included all of the IIS7 web.config entries:

<

system.web.extensions>

<

scripting>

<

webServices>

<!--

Uncomment this line to customize maxJsonLength and add a custom converter-->

<!--

<jsonSerialization maxJsonLength="500">

<converters>

<add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>

</converters>

</jsonSerialization>

-->

<!--

Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate.-->

<

authenticationServiceenabled="true"requireSSL="false" />

<!--

Uncomment these lines to enable the profile service. To allow profile properties to be retrieved

and modified in Atlas applications, you need to add each property name to the setProperties and

getProperties attributes.

-->

<!--

<profileService enabled="true"

setProperties="propertyname1,propertyname2"

getProperties="propertyname1,propertyname2" />

-->

</

webServices>

</

scripting>

</

system.web.extensions>

<

system.webServer>

<

validationvalidateIntegratedModeConfiguration="false"/>

<

modules>

<

addname="ScriptModule"preCondition="integratedMode"type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</

modules>

<

handlers>

<

removename="WebServiceHandlerFactory-Integrated"/>

<

addname="ScriptHandlerFactory"verb="*"path="*.asmx"preCondition="integratedMode"type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<

addname="ScriptHandlerFactoryAppServices"verb="*"path="*_AppService.axd"preCondition="integratedMode"type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<

addname="ScriptResource"preCondition="integratedMode"verb="GET,HEAD"path="ScriptResource.axd"type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

</

handlers>

</

system.webServer>

Note that the PipeLine extension for the configured site can be set for Integrated (default) instead of the Classic Mode.

With those two steps I was able to get a XP configured site migrated over with Ajax...


My web site is set up as an application, and it uses an application pool set up for ASP.net 2.0.

When I set that application pool to use to use the Integrated mode, I can no longer even load my website (gives 404 error).

This is crazy, this was a perfectly functioning website under XP, and "upgrading" to vista has broken it.

Is there anything in the applicationHost.config file that needs to reference AJAX? I'm at the end of my rope here, I'm about to just install XP and loose ALL my programs and setting just to get back to a usable machine!

AJAX and IE7

I am using ASP.NET 2.0 AJAX and IE7.my application doesnot work.But if i run the same application in IE^ its working.

Why is it so.Is there any problem with IE7 and AJAX working.

Hi,

which problems are you experiencing? Which version of AJAX are you using (CTP, Atlas, Extensions 1.0, another AJAX framework)?

Could you also provide the least amount of relevant code to reproduce the problem? Without that it's going to be difficult to help you out.

Grz, Kris.

Wednesday, March 21, 2012

AJAX and Gzip

I would like to compress my .aspx pages.

When I tried using Gzip, the page size was greatly reduced, but the Ajax on the page stopped working.

Thank you for help.

Could you please be more specific on how you are currently using GZip? Are you using this in a HttpModule? Are you using it specific on pages only?

Did you ever find a solution to this? I am having the same problem while using an IHTTPMODULE. Very, Very, frustrating...


In the BeginRequest of your HttpModule you should check wheter there are ajax headers in the page:

for example:

check first if there are headers otherwise you could use compression:

string ajaxHeaders = app.Request.Headers.Get("X-MicrosoftAjax");if (String.IsNullOrEmpty(ajaxHeaders))

{

///compression...

}

Ajax should be working than and you can use compression on pages that dont use ajax.