Click here to Skip to main content
Click here to Skip to main content

Remote Scripting

By , 25 Apr 2005
 

Contents

Introduction

How many times have you been on a web page and you selected a value in a drop down box, only to suddenly see the whole page refresh so that it can fetch values for another drop down box? I see it all the time in car web sites. You select the Make of the car and the whole page is reloaded to bring back all the corresponding Models. Then you select the Model and the whole page is reloaded again to bring back all the corresponding Trims. Annoying, isn't it?

Some sites avoid this problem by preloading all the possible alternatives in memory. This works, but there are times when the amount of data is just too overwhelming for all the possible combinations.

Remote Scripting offers a better alternative. Instead of the whole page refreshing, a hidden request is made to the server to execute a method which returns back just the data that needs to be changed on the page. The result is a smoother user experience. Indeed, Remote Scripting brings some of the benefits of a traditional fat-client application to a web application. It can be used to refresh individual controls, to validate controls, or even to process a form without having to post the whole page to the server. It's cool stuff and it works on all major browsers!

Over the years, I've seen two popular remote scripting implementations. Back in the days of Visual InterDev 6.0, Microsoft provided client and server-side include files inside its _ScriptLibrary directory. I used it in a few projects and it worked quite well. The only problem I found was that it used a Java applet to handle the communications, so it tended to be sluggish at times. Then I started doing JSP and I found a better alternative called JSRS. Depending on the browser, it created a hidden element on the page that submitted the request to the server which then responded back to it. It was more efficient, but it only allowed the remote calls to be asynchronous.

Now with ASP.NET, I've once again needed to use Remote Scripting. I initially wrote a small class library in C# that provided support for both Microsoft's and JSRS's clients. But then I decided to see if I could come up with a better client implementation, and I believe I did. I came up with a hybrid solution based on both of the existing implementations, which I believe looks and works better. This article presents my Remote Scripting client and server side implementation for ASP.NET. Enjoy!

Demo

The downloadables include a file called rsDemo.aspx which has a fully working example of this code. It also demonstrates how to populate the drop downs using data from an XML file (rsDemo.xml). The link below goes to the demo page. When you change the Type, the Amount is repopulated using Remote Scripting.

Usage

I've strived to make my Remote Scripting implementation as simple and easy to use as possible. There are just a few simple steps to take on the client and server side to get it working. Be sure to look at the rsDemo.aspx file to get the complete picture.

Client-side

  1. Include rs.js in your .aspx page, like this:
    <script language="'JavaScript'" src='/scripts/rs.js'></script>
  2. Use RS.Execute to invoke the remote method using JavaScript, like this:
    function dropdown_onchange()
    {
      RS.Execute("page.aspx", "RemoteMethod", 
                 "optionalParam1", "optionalParam2", ...., 
                 callback, optionalErrorCallback,
                 optionalCallbackParam2, optionalCallbackParam3, 
                 optionalCallbackParam4);
    }

    The page.aspx file is where the RemoteMethod will be executed. The RemoteMethod's parameters are optional, so don't pass anything if they're not needed. The callback function (which is not a string parameter) is also optional and if passed will be called when the server's response is received. Its first parameter will be the value returned by the RemoteMethod, converted to a string. If there's a chance for error, you can also pass a second callback method that will receive the error description. If it's not passed, an alert box will be shown in case of error. If you pass optionalCallbackParam2, optionalCallbackParam3, or optionalCallbackParam4, they will also be passed to the callbacks. Keep in mind that RS.Execute is asynchronous, so the callbacks are the only way to know when and what was returned from the server.

  3. If you care about the RemoteMethod's result, add a callback method to get it, and optionally do the same for error messages:
    function callback(result)
    {
      alert("The remote method returned this: " + result);
    }
    
    function errorCallback(result)
    {
      alert("An error occurred while invoking the remote method: " + result);
    }

Server-side

  1. Make sure AMS.Web.RemoteScripting.dll file is deployed to your site's bin directory.
  2. At the top of the Page_Load method, add these two lines:
    if (AMS.Web.RemoteScripting.InvokeMethod(Page))
      return;

    This accomplishes several things. First, it checks if the client is making a remote request on the page. If not, this method returns false (and Page_Load proceeds). If there is a client request, the remote method is invoked, its return value is written to the response, and it is then sent back to the client immediately.

    If your page does not have a Page_Load method (and you don't want to add one), you can just place those two lines at the top of your page inside <% %> tags.

  3. Add the remote method as a public instance or static member of your Page class:
    public string RemoteMethod(string param1, string param2, ... )
    {
      return "This is what the client sent me: \n" + param1 
             + "\n" + param2 + ... ;
    }

    If you just need to read a field's value, you can use a property instead of a method:

    public string RemoteProperty
    { 
      get { return m_someField; };
    }

    The return type does not need to be a string but it will be converted to a string before going back to the client. The parameters must all be of type string, and the method (or property) must be public or you'll receive a System.MissingMethodException error.

    As an alternative to remotely executing a public method or property of the Page, you may also directly execute a public method or property of a control on the page. For example, if you want to retrieve the Text property of a TextBox control called "txtAmount", you can pass "txtAmount.Text" as the name of the remote method in RS.Execute.

Notes

I added a method called ReplaceOptions inside rs.js. It makes it convenient to repopulate a drop down box with the results of a remote method. It expects the result string to be formatted like this:

"<option value='0'>Text 0</option><option selected value='1'>Text 1</option>..."

You can use it like this inside the callback:

function callback(result)
{
  RS.ReplaceOptions(document.form.theDropDown, result);
}

An even better alternative is RS.ReplaceOptions2, which may be passed directly to RS.Execute as the callback function:

function dropdown_onchange()
{
  RS.Execute("page.aspx", "RemoteMethod", 
             "optionalParam1", "optionalParam2", ...., 
             RS.ReplaceOptions2, document.form.theDropDown);
}

RS.ReplaceOptions2 takes the same parameters as RS.ReplaceOptions but in the opposite order so that it can be used as a callback. This allows you to do everything in one call!

The RS object also has a member called debug that you can set to true (RS.debug = true;) to show the hidden elements used for communicating with the server.

On the server side, you'll see that the RemoteScripting class is designed to handle any of three possible clients: Mine (RS), JSRS, and Microsoft's (MSRS). The type of client is determined based on the parameters passed into the request. If you have your own client implementation, my architecture makes it easy to add an implementation for it by deriving from the RemoteScriptingClient class.

Microsoft is the only remote client implementation that supports synchronous calls to the server, so if you absolutely need that, you can use it. All you need on the client is the rs.htm and RSProxy.class files from the _ScriptLibrary directory. I personally don't recommend it since it ties up the browser until the response is sent back and it requires the browser to support Java. Nevertheless, I added support for it inside the RemoteScriptingClient class.

Something else to point out: for drop downs that are populated and repopulated based on remote scripting calls, I recommend you remove them from the ViewState (EnableViewState=false), since you'll need to populate them on every trip back to the server. In other words, regardless of whether IsPostBack is true or not, you'll need to populate these drop downs, so it will be a waste to save them to the ViewState.

History

  • Version 1.0 - Mar 12, 2004.
    • Initial release.
  • Version 2.0 - Sept 3, 2004.
    • Enhanced RS.Execute to allow passing of up to three additional parameters to the callbacks (aside from the result of the remote method).
    • Enhanced RemoteScriptingClient.InvokeMethod to allow execution of a method or property of a control of the page. Thanks to Jonathan Marbutt for the idea and his implementation.
    • Fixed bug that didn't allow remote scripting to work with the Opera browser. Thanks to Christoph Weber for reporting it.
    • Fixed bug that prevented remote scripting from working in SSL sites. Thanks to Peter for reporting it and providing the solution.
    • Fixed bug that was filling the call pool when remote methods were executed over 100 times. Thanks to emadns and Anonymous for reporting it.
    • Fixed bug that was taking the result string and replacing any slashes (/) with \/.
  • Version 2.1 - Feb 7, 2005.
    • Fixed small problem in RemoteScriptingCall.setResult of rs.js when simultaneous calls were made to RS.Execute. Thanks to Eddy A for reporting it and providing the solution.
    • Fixed bug with RS.ReplaceOptions of rs.js which wasn't properly handling values containing angle brackets. Thanks to pussicatt0102 for reporting it.
    • Updated the rsDemo.aspx page to demonstrate how to make it work with a Submit button.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Alvaro Mendez
Web Developer
United States United States
Member
I've done extensive work with C++, MFC, COM, and ATL on the Windows side. On the Web side, I've worked with VB, ASP, JavaScript, and COM+. I've also been involved with server-side Java, which includes JSP, Servlets, and EJB, and more recently with ASP.NET/C#.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
QuestionQuestion about licensing?groupGwyn Murray7 Oct '09 - 13:54 
Hi:
 
I am trying to figure out which license applies to CXEdit. Can you please help me with this?
 
Thanks,
 
Gwyn
QuestionRemoteScripting errormemberdgcrouse8 Jun '09 - 11:37 
<script type="text/jscript" language="javascript" src="rs.js"></script>
 
    <script type="text/jscript" language="javascript">
        var interval = "";
        function OnPageLoad() {
            interval = window.setInterval("Update()", 50000);
        }
        function Update() {
            RS.Execute("Chat.aspx", "redraw");
            RS.PopupDebugInfo();
        }
    </script>
 
 public void redraw()
    {
        int[] exp = new int[l.Count];
        List<Message> updList = new List<Message>();
        ChatBox.Text += "r";
        for (int i = 0; i < l.Count; i++)
        {
            Message m = l[i];
            if (!m.isExpired())
            {
                updList.Add(m);
            }
            ChatBox.Text = m.getMsg() + "\n" + ChatBox.Text;
        } 
        l = updList;
 
        onlineBox.Text = "Online";
        foreach(String s in users)
        {
            onlineBox.Text += "\n" + s;
        }
    }
 
Won't work. The method returns "Busy" on debug popup. Any help?
GeneralCharacter [’] (without the brackets) causes an errormemberMP7113 Jul '08 - 23:03 
Hi, on all of my systems (vista, xz, 2k3 either in english or in italian) this character [’] (without the brackets) causes an error.
I'm using the code changes suggested here
http://www.codeproject.com/KB/aspnet/AlvaroRemoteScripting.aspx?msg=1343968[^] but no luck.
 
The error is:
System.FormatException occurred
Message="Could not find any recognizable digits."
Source="mscorlib"
StackTrace:
at System.ParseNumbers.StringToInt(String s, Int32 radix, Int32 flags, Int32* currPos)
at System.Convert.ToInt16(String value, Int32 fromBase)
at AMS.Web.RemoteScriptingClient.JS.DecodeUrl(String url) in D:\Progetti\PMC\INVCIW\v.1.0.0\branches\1.10.0.0b\src\RemoteScripting.cs:line 416
 

Any help would be greatly appreciated.
 
Regards,
Massimiliano
QuestionCan I use include file in remote scripting server side? -Urgent!!!memberAndraw11128 Apr '08 - 3:34 
Hi, All,
I have seperated the reDemo.aspx to two files.
in reDemo.aspx:
RS.Execute("reDemoServer.aspx","UpdateAmounts", .............."
 
Inside reDemoServer.aspx file, declare the function UpdateAmounts(), I change the server side code from C# to VB.Net, everything works fine.
 
But if I include a file that create DB connection, when I return the connection string, it's empty.
 
Can anybody tell me what's wrong.
 
The codes in reDemoServer.aspx are as the following:
 
<![CDATA[<%@ Page Language="VB" %>]]>
 
<!-- #INCLUDE FILE="../../include/dbConnection.aspx" -->
 
<script language="VB" runat="server">
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If AMS.Web.RemoteScripting.InvokeMethod(Page) Then
Return
End If
End Sub
 
Public Function UpdateAmounts(ByVal argu1 as string) As String
Return "Return String From Remote Scripting." 'Works fine
'Return myConn 'myConn is defined in above include file, it's a
'string , but when I return it, it's an empty.
End Function
</script>
 
I need to solve this soon, otherwise I cannot do the furthere work.
 
Please help, thanks!
 
Andraw
QuestionRemote Scripting Doesn't Work for me, Did my precedure wrong?memberAndraw11124 Apr '08 - 5:39 
I use VB instead of C#.
 
Nothing wrong, but callBack() function is not trigered.
 
In client-side in file1.aspx:
<script language='JavaScript' src='/script/rs.js'></script>
<script language='JavaScript' >
 
function xxxx(){
   RS.Execute("anotherFile.aspx", "CreateHolder1", callBack);
}
 
function callBack(result){
   alert(result);
}
<script>
 
'''''''''''''''''''''
In server-side in anotherFile.aspx:
<@ Page Language="VB" >
 
<%if AMS.Web.RemoteScripting.InvokeMethod(Page) then
      response.end
   end if
 
   Function CreateHolder1() As String
      CreateHolder1= "OK"
   exit Function
%>
 
Can anybody tell me what's wrong?
 
Thanks!
Andraw
AnswerRe: Remote Scripting Doesn't Work for me, Did my precedure wrong?memberAndraw11124 Apr '08 - 5:55 
Sorry mistyping, exit Function should be end function. but still doesn't work.
AnswerRe: Remote Scripting Doesn't Work for me, Did my precedure wrong?memberAndraw11124 Apr '08 - 9:32 
Hi,
 
I have question, I seperate the rsDemo.aspx to two files, put the remote call function to another file(called rsDemoServe.aspx), inside this file:rsDemoServe.aspx are:
 
<!-- Remote Scripting Demo -->
 

<script language="C#" runat="server">

void Page_Load(object sender, EventArgs e)
{
if (AMS.Web.RemoteScripting.InvokeMethod(Page))
return;
}


public string UpdateAmounts(string type)
{
return "OK|Hello|Lucy"; //result.ToString();
}
 
</script>
 
But when I modify the code as VB formate, it don't work. Do I must use C#?
 
Andraw
QuestionGerman characters "umlaut" disappearsmemberveronika_kj14 Jun '07 - 0:27 
Hi Alvaro,
I'm using your code in an ASP.net 2.0 application and it is really useful.
Recently I have following problem:
When I'm calling a server-side method from my javascript and pass a string as parameter which contains an "umlaut" like the word "eisbär", during the transfer it transforms to "eisbr". In the server-side method which is called only the wrong parameter arrives.
Is there a possibility to change the charset or text encoding (I'm not sure) so that I can use UTF-8 characters?
 
I would be thankful for any information or ideas.
Veronika
AnswerRe: German characters &quot;umlaut&quot; disappearsmemberveronika_kj21 Jun '07 - 22:49 
Hello,
I found an answer on another post "foreign language" (http://www.codeproject.com/aspnet/AlvaroRemoteScripting.asp?msg=1343968#xx1343968xx) and tried your suggestion. It worked fine. Thanks.
 
Regards, Veronika
GeneralDoes this work with .Net Framework 2.0 [modified]memberTimothy Le13 Jun '07 - 12:26 
I have problem getting this to work with .Net 2.0. Does anyone has this work w/ 2.0?
 
Error msg:
---------------------------
Microsoft Internet Explorer
---------------------------
System.MissingMethodException: Method 'ASP.default_aspx.Method1' not found.
 
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
 
at System.Type.InvokeMember(String name, BindingFlags invokeAttr, Binder binder, Object target, Object[] args)
 
at AMS.Web.RemoteScriptingClient.InvokeMethod() in RemoteScripting.cs:line 265
---------------------------
OK
---------------------------
 
To repro, here is the code:
Code:
 
My aspx page:
--------------------------------------------------
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" src="Scripts/rs.js"></script>
</head>
<body>
 
<script language="javascript" type="text/javascript">
 
function Method1CallBack(results)
{
alert('Method1CallBack returned results: ' + results);
}
 
function ExecMethod1()
{
alert('in ExecMethod1');
RS.Execute('Default.aspx', 'Method1',
'value1', 'Method1CallBack');
}
 
</script>
 
<form id="form1" runat="server">
<asp:Button ID="SubmitButton" runat="server" OnClientClick="ExecMethod1(); return false;" Text="Submit" />
</form>
</body>
</html>
--------------------------------------------------
 

My aspx.cs code:
--------------------------------------------------
using System;
 
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (AMS.Web.RemoteScripting.InvokeMethod(Page))
return;
}
 
public string Method1(string value)
{
return "true,";
}
}
--------------------------------------------------
 
-TL
 

-- modified at 18:32 Wednesday 13th June, 2007
GeneralRe: Does this work with .Net Framework 2.0memberveronika_kj14 Jun '07 - 1:17 
Hi Timothy,
On first sight I would say don't use quotes in this place:
instead of
RS.Execute('Default.aspx', 'Method1', 'value1', 'Method1CallBack');
use
RS.Execute('Default.aspx', 'Method1', value1, Method1CallBack);
 
Only an idea, thats the way I use it.
Veronika
GeneralRe: Does this work with .Net Framework 2.0memberTimothy Le14 Jun '07 - 9:19 
Thanks Veronika, that was it. I put the call back function in quote. The correct call should be:
 
RS.Execute('Default.aspx', 'Method1', 'value1', Method1CallBack);
 
This still works beautifully in VS 2005.
 
-TL

GeneralProblem with Checkboxmemberjaja20075 Jun '07 - 6:59 

Hi, i download your example app in C# , and i add new lines :
 
i am created a checkbox type ASP ------> <asp:CheckBox ID="CheckBox1" runat="server" Checked="false" /> , your status cehcked is false
 
And in the method public string UpdateAmounts(string type) , i add a new line -
----->CheckBox1.Checked = true;
 
but when executed this program, the checkbox don't changed??? please tell me , what do wrong?
 

thansk for you answer
QuestionCan I use your code?memberMyDays5 Mar '07 - 4:47 
Hi Alvaro.
 
You look like the one who gave the direction to Microsoft on how to make Callback in their 2005 .NET version.
I am a beginner programmer, and I want to know if I can use your code for one of my projects at work.
 
Thanks,
Sookhee
AnswerRe: Can I use your code?memberAlvaro Mendez16 May '07 - 10:29 
MyDays wrote:
I am a beginner programmer, and I want to know if I can use your code for one of my projects at work.

 
Of course, help yourself.
 
Regards,
Alvaro
 

Eat right.
Exercise.
Die anyway.

GeneralA query from a poor niave student, that really wants to use your stuff, but cant figure something outmemberSacha Barber1 Dec '06 - 6:43 
I recently (today) came across this article and thought that is exactly what I need to do as part of my Msc project.
 
So I downloaded you code, it worked fine.
 
I then created my own page, like yours, but I dont want a callback to the client, I simply want to call a server side method, and thats it. Which seems to be ok, with what you have implemented, as you state that the callback is optional.
 
OK, so what I need to do is, call the method from the client, then in the method at server side, I want to change some properties of another (more in the real project) of another server side web control, you know with the runat="server" attribute. The samll page I am trying it on has a TextBox, and I am trying to change the Text property in the remote method call, Like shown below
 

THE MARKUP: Tets.aspx
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
 
<body>
<%@ Page language="c#" Codebehind="Tets.aspx.cs" AutoEventWireup="false" 
Inherits="ASP_pics.Tets" %><br>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" ><br>
<HTML><br>
<HEAD><br>
<title>Tets</title><br>
<meta name="GENERATOR" Content="Microsoft Visual Studio .NET 
7.1"><br>
<meta name="CODE_LANGUAGE" Content="C#"><br>
<meta name="vs_defaultClientScript" content="JavaScript"><br>
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5"><br>
<script language="'javascript'" src='scripts/rs.js'></script><br>
<script language="'javascript'"><br>
// This triggers the call to the remote method to reload the amounts<br>
function testServerScript()<br>
{ <br>
window.status = "A Small maybe niave test...";<br>
RS.Execute("Tets.aspx", "PopulateText", "some text for 
TextBox1");<br>
alert("testServerScript was called");<br>
}<br>
</script>
<p> </HEAD><br>
  <body MS_POSITIONING="GridLayout" onload="testServerScript();"><br>
  <form id="Form1" method="post" runat="server"><br>
  <asp:Button id="Button1" Runat="server" Text="Button"></asp:Button><br>
  <asp:TextBox id="TextBox1" runat="server" Width="216px"></asp:TextBox><br>
  </form><br>
  </body><br>
  </HTML><br>
</p>
</body>
</html>
 
THE CODE BEHIND: Tets.aspx.cs
 
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
 
namespace ASP_pics
{
	/// <summary>
	/// Summary description for Tets.
	/// </summary>
	public class Tets : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.TextBox TextBox1;
		protected System.Web.UI.WebControls.Button Button1;
	
		private void Page_Load(object sender, System.EventArgs e)
		{
			// If it was called, invoke the remote method and get back to the client
			if (AMS.Web.RemoteScripting.InvokeMethod(Page))
				return;
 
		}
 
		
		// This is the remote method; the chosen type is passed as its parameter.
		public void PopulateText(string txt)
		{
			TextBox1.Text= txt;
		}	
 

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
			this.Load += new System.EventHandler(this.Page_Load);
 
		}
		#endregion
	}
}
 

So thats what I am tring to do, but am totally not getting, if what you have done, even allows for this. It should, shouldnt it, or have I got it completely wrong.
 
I am new to the whole Ajax style of thing, I get the concept, I know this is not Ajax, but to me it is exactly what I wanted, An Ajax type of arrangement, where I could call a server method, without a callback, this is what I want to do.
 
PLEASE PLEASE PLEASE could you have a look at this simply example I am doing, and see what I am doing wrong.
 
I would be happy to email source if you like, my email, is sachabarber@hotmail.com
 

MANY THANKS
 
sacha barber

GeneralRe: A query from a poor niave student, that really wants to use your stuff, but cant figure something outmemberAlvaro Mendez16 May '07 - 11:55 
If you haven't already, I recommend you use an Ajax implementation, like Anthem.NET which will do what you want. However, to answer your particular question, you really didn't need Remote Scripting to change a textbox on the form. You could have done it with some simple Javascript on the client:
 
document.getElementById("TextBox1").value = "some text for TextBox1";
 
Regards,
Alvaro
 

Eat right.
Exercise.
Die anyway.

GeneralRe: A query from a poor niave student, that really wants to use your stuff, but cant figure something outmemberSacha Barber16 May '07 - 20:26 
Yeah its has been working with Ajax library for .NET for ages, its all cool
 
Sacha Barber
A Modern Geek - I cook, I clean, I drink, I Program. Modern or what?
 
My Blog : sachabarber.net

GeneralCalling to InClass functionmemberronziv30 Aug '06 - 17:39 
Hi Alvaro,
 
Thank you very much for this implementation. I am using it and it's working great.
 
I am new to ASP.NET so I hope my question won't be too silly.
 
I have a "xxx.aspx" file and "xxx.aspx.cs" file which implement an inherit class that holds all the events for the xxx.aspx controls.
 
Is it passable when calling rs.Execute( " xxx.aspx.cs", "To put here a member function of the class",………)???
Or you have an idea how to work this around???
 
Thanks again Ziv

GeneralRe: Calling to InClass functionmemberronziv30 Aug '06 - 22:35 
it Me again sorry for the silly question Alvaro, i found out the answer.
 
RS.Execute( "xxx.aspx",.....)
instead of RS.Execute( "xxx.aspx.cs",...)
 
Ziv
GeneralCombining Source CodememberDeveloper @ RGG Network15 Jul '06 - 10:36 
I have taken the RS source code and packed it into another assembly. I have also combined the client-side javascript into this assembly.
 
When the if(AMS.Web.RemoteScripting.InvokeMethod(Page))return; is called it writes the clientside javascript nicely into the head of the calling document. (this is so you do not have to worry about where the client side script resides etc.)
 
I have also written a new function / method that is a one-stop-shop remote scripting call: (see below). It allows you to define all the information and class in one easy-to-use function:
 
Please it inside the client side javascript file...
 
============================================================
============================================================
 
function handleRemoteScripting()
{
rs="";
rs+="RS.Execute(\""+arguments[0]+"\",";
for(o=1;o<=arguments.length;o++)
{
switch(o)
{
case 1:{
rs+="\""+arguments[1]+"\",";
break;
}
case arguments.length:{
rs+="eval("+arguments[1]+")";
break;
}
default:{
rs+="\""+arguments[o]+"\",";
break;
}
}
}
rs+=")";
eval(rs);
}
===============================================================
===============================================================
 

usage:
 
handleRemoteScripting("Default.aspx","aFunctionOrMethod","Param1","Param2");
 
give the Callback the same name as the server-side method name:
 
Client-Side:
 
function aFunctionOrMethod(){alert(arguments[0]);}
 
Server-Side:
 
public string aFunctionOrMethod(String Param1, String Param2)
{return Param1+Param2; // or do something else}
 
on the client side call / usage: (arguments are as follows)
 
arguments 0 = the calling document (i.e. "Default.Aspx")
arguments 1 = the client-side function / server-side method-name
(i.e. "aFunctionOrMethod")
 
arguments 2 and greater are all parameters passed to the server-side public method. (i.e. "Param1", "Param2")
 
note:
 
return multiple results in a comma delimited string and split the results into and array within the callback function (client-side)
 
**
 
The new RS DLL will be available shortly (with permission from AM of course)
GeneralUnreliabe IE Progress barmemberA. Santamaria8 Jun '06 - 11:00 
Howdy Alvaro,
 
Well, not sure how to convey so many thanks for your library. Maybe a big THANKS... but well, still not big enough. I'd even bring some flowers Rose | [Rose] but hmmm maybe better not Smile | :) . Anyway, thanks for such a great library; and your writing style is excellent.
 
You reported on an earlier comment[^] that you preferred not to use POST since there were some reports that the IE progress bar was unreliable. I ran into the same, and after making sure I was using GET and still experiencing the same issue (more or less randomly), I digged a little longer and deeper.
 
I found a report from MS which put me on the right track, as it explains that when a behavior is dynamically attached to a page, the progress bar, well, basically just loses it. I traced the execution and found that if I insert a "windows.status='Done';" at the end of the setResult call (just below this.busy=false;), the problem would be gone, and the progress bar come back to its senses; for the time being, at least.
 
Note that if you use "window.status='';" ", as I wanted to, the problem remains; you have to use an actual string... sucks for other language browsers, but well, what the heck.
 
The MS article is: http://support.microsoft.com/kb/320731/en-us[^]
 
Again, thanks for the library, and everyone have a good one!
 

Andrés
GeneralRe: Unreliabe IE Progress barmemberAlvaro Mendez16 May '07 - 11:38 
Andrés
 
Thanks for your great comments and fix for that pesky progress bar issue.
 
I imagine by now you've switched over to some Ajax implementation. I've been using Anthem.NET with great satisfaction.
 
Regards,
Alvaro
 

Eat right.
Exercise.
Die anyway.

Questionwhat is the advantage compare wtih ajax?memberSpiritExplorer24 May '06 - 22:33 
what is the advantage compare wtih ajax? ajax can do the same kind of work too.Smile | :)
 
Code killer Smile | :)
AnswerRe: what is the advantage compare wtih ajax?memberAlvaro Mendez25 May '06 - 4:58 
SpiritExplorer wrote:
what is the advantage compare wtih ajax? ajax can do the same kind of work too

 
Honestly, I don't see any advantage. This just came out first, and it works across most platforms and browsers since it doesn't rely on the XMLHttpRequest component.
 
Use Ajax.
 
Regards,
Alvaro

 

The bible was written when people were even more stupid than they are today. Can you imagine that? - David Cross
Questionpossible bug?memberAndreiVM19 Apr '06 - 12:26 
Alvaro,
First of all, thank you for the code - it worked very smoothly for quite some time now.
I think there is a little bug: A remote method in the Page won't return "</textarea>" string back to the client. Try returning "</textarea> and then view result on the client: alert(result); - it will display an empty box.
Please confirm.
AnswerRe: possible bug?memberAlvaro Mendez25 May '06 - 5:01 
AndreiVM wrote:
Try returning "</textarea> and then view result on the client: alert(result); - it will display an empty box.

 
Yep, that's because the result from the server is placed inside a textarea element.
 
Regards,
Alvaro
 

The bible was written when people were even more stupid than they are today. Can you imagine that? - David Cross
QuestionHow can I refresh an asp.net table??memberezztek18 Apr '06 - 7:01 
I am using your remote script and cannot refresh an asp.net table.. How can I do that??
AnswerRe: How can I refresh an asp.net table??memberAlvaro Mendez25 May '06 - 5:04 
ezztek wrote:
I am using your remote script and cannot refresh an asp.net table.. How can I do that??

 
You'd have to do it programmatically with Javascript. I recommend you look at the Ajax implementations to see if they offer an easier solution.
 
Alvaro

 

The bible was written when people were even more stupid than they are today. Can you imagine that? - David Cross
General'RS' is undefined errormemberTheEagle3 Apr '06 - 23:21 
Hi..
When i change the index of a dropdown List in my application that uses your Remote Scripting method i got the Error:
 
'RS' is undefined.
 
i have added the Lines of code:
<HTML>
     <HEAD>
          <title>WebForm1</title>
          <script language="javascript" src="/scripts/rs.js">
          </script>
          <script language="javascript">
     function dropdown_onchange()
     {
     RS.Execute("default.aspx","RemoteMethod","optionalparam1","optionalparam2",callback);
     }
     function callback(result)
     {
     return "The remote method returned:"+result;
     }
          </script>...
 
So what could cause this error?
GeneralRe: 'RS' is undefined errormemberAlvaro Mendez25 May '06 - 5:05 
TheEagle wrote:
So what could cause this error?

 
rs.js is not being loaded. Are you sure it's in the /scripts/ directory?
 
Regards,
Alvaro
 

The bible was written when people were even more stupid than they are today. Can you imagine that? - David Cross
Generalarray or string limitmemberSebasg783 Apr '06 - 0:49 
Hi Alvaro
 
I'm coding a simple chat and i though i could your your fantastic rs Big Grin | :-D ..
My question: is there any way to retrieve an array? or splitting a string is the only solution? in this case, what's the string limit? the 250 chars from the browser's address bar?
 
Saludos y gracias de antemano
Sebastian
GeneralRe: array or string limitmemberAlvaro Mendez25 May '06 - 5:10 
Sebasg78 wrote:
I'm coding a simple chat and i though i could your your fantastic rs

 
Thanks Sebastian.
 
These days Ajax is a better alternative. If you haven't already, I recommend you look at the available implementations. Anthem seems to be pretty good.
 
Sebasg78 wrote:
My question: is there any way to retrieve an array? or splitting a string is the only solution? in this case, what's the string limit? the 250 chars from the browser's address bar?

 
Everything comes back as one string, so yes, you'd have to parse it. It's coming back from the server, so there's no size limit.
 
Saludos,
Alvaro
 

The bible was written when people were even more stupid than they are today. Can you imagine that? - David Cross
GeneralRe: array or string limitmemberSameer Alibhai5 Jun '07 - 8:27 
YOu might wanna reconsider
 
"Servers should be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations may not properly support these lengths."
 
http://classicasp.aspfaq.com/forms/what-is-the-limit-on-querystring/get/url-parameters.html[^]
 
Author, SharpDeveloper.NET
 

GeneralProblem with a second selectmemberlisandroc30 Mar '06 - 21:52 
when i try to read the selected option of a drplist bounded with this tool the selected value is empty.

 
Gallina
GeneralRe: Problem with a second selectmemberAlvaro Mendez25 May '06 - 5:12 
lisandroc wrote:
when i try to read the selected option of a drplist bounded with this tool the selected value is empty.

 
Read it from where, the client or server?
 
lisandroc wrote:
Gallina

 
No seas. Smile | :)
 
Alvaro
 

The bible was written when people were even more stupid than they are today. Can you imagine that? - David Cross
GeneralsessonIDs and authentication cookiesmemberJTW210 Mar '06 - 2:15 
Hi,
This is a terrific tool and we use it throughout our site. Recently a question came up that I could not answer: how does the remote scripting call to the server pass the sessionID and forms-authentication cookie so that when the call reaches the server it attaches to the correct session, etc? Does this question make sense? Is this something the browser handles before calling the page_load event (and the AMS.Web.RemoteScripting.InvokeMethod(Page) call)? Or are you doing it in your dll?
 
thanks -- john
GeneralRe: sessonIDs and authentication cookiesmemberAlvaro Mendez23 Mar '06 - 9:37 
JTW2 wrote:
are you doing it in your dll?

 
I'm not doing a thing. Smile | :)
 
Whenever the remote method is called, the browser (via a hidden frame) accesses a page on your site and sends down all the cookies (where the Session ID is kept).
 
Regards,
Alvaro
 

... since we've descended to name calling, I'm thinking you're about twenty pounds of troll droppings in a ten pound bag. - Vincent Reynolds
GeneralSafarimemberGlenSpam15 Feb '06 - 3:30 
Hi Alvaro,
 
I'm just wondering if this works with Safari?
 
Thanks!
GeneralRe: SafarimemberAlvaro Mendez16 Feb '06 - 4:58 
GlenSpam wrote:
I'm just wondering if this works with Safari?

 
I haven't tried it, have you? Point your Safari browser here[^] and let me know.
 
Regards,
Alvaro

 

... now you see that evil will always triumph because good is dumb. - Dark Helmet
GeneralRe: SafarimemberGlenSpam16 Feb '06 - 5:21 
Hi Alvaro,
 
Thank you for your response. I tried the link and it does not work with Safari. You can change the drop down but the salary does not load up - only when you click on the button and the page refreshes do the values become available. I think it might be when rs.js is initiated it 'sniffs' the browser type and does some settings for that browser. Javascript seems to think Safari is MOZ! Not sure what to do (apart from not use Safari!)?
 
Cheers,
Glen.

GeneralRe: SafarimemberJames Perrins28 Mar '06 - 3:14 
I've used it in Safari - I don't remember needing to make any changes to rs bits - though some other cross browser components weren't quite as cross browser as they might have been
 
HTH
James
GeneralHELPmemberktorres31 Jan '06 - 8:19 
Hi, I saw and donwload the sample and i like to know how to get the value of a function's dll, i'm working in VB .NET and ASP .NET, i never used the JScript or C# plz hlp me Smile | :)
GeneralRe: HELPmemberAlvaro Mendez1 Feb '06 - 18:02 
Add a public method to your page that calls your DLL's method. This will be your remote method which you can then call from JavaScript, like in the sample.
 
Regards,
Alvaro
 


GeneralForeign Languagesmemberemadns8 Jan '06 - 0:20 
Hi,
 
I am trying to pass a french string to the remote scripting method. On the client side, the string is stored correctly, but when it arrives at the server side, the characters with accent are distorted. Is there a fix for this? Does it work with Unicode characters.
 
Thanks

GeneralRe: Foreign LanguagesmemberAlvaro Mendez22 Jan '06 - 18:42 
Hi,
 
I was able to reproduce the problem. It's unfortunate that when the QueryString does not get properly decoded on the server, as it should be. To make it work, I had to actually parse the RawURL!
 
To make the fix, go to line 357 of RemoteScripting.cs, where the Arguments property is, and replace it with the following code:
 
			public override string[] Arguments
			{ 
				get
				{
					// Count the parameters				
					int paramCount = 0;
					while (m_page.Request["P" + paramCount] != null)
						paramCount++;				
				 
					// Check if we're getting the parameters directly from the URL or from the form.
					string[] args = new string[paramCount];
					string url = m_page.Request.RawUrl;
					if (url.IndexOf("P0=[") < 0)
						url = null;
 
					for (int i = 0, start = 0; i < paramCount; i++)
					{
						if (url == null)
						{
							args[i] = m_page.Request["P" + i];
							args[i] = args[i].Substring(1, args[i].Length - 2);
							continue;
						}
 
						// Since we're using the URL, we need to parse and decode the RawURL 
						// in case special characters were passed in.
						start = url.IndexOf("P" + i + "=[", start + 1);
						if (start < 0)
						{
							args[i] = null;
							continue;
						}
 
						start = url.IndexOf("[", start) + 1;
						int end = url.IndexOf("]", start);
						if (end < 0)
							end = url.Length;
 
						args[i] = DecodeUrl(url.Substring(start, end - start));						
					}	
 
					return args;
				}			
			}										 
  
			private static string DecodeUrl(string url)
			{
				StringBuilder result = new StringBuilder();
 
				for (int i = 0; i < url.Length; i++)				
				{
					char c = url[i];
					if (c == '%')
					{
						c = Convert.ToChar(Convert.ToInt16(url.Substring(i + 1, 2), 16));
						i += 2;
					}
 
					result.Append(c);
				}
				return result.ToString();
			}	
That fixes the problem. (I couldn't even use HttpServerUtility.DecodeUrl to parse the arguments; I had to write my own.)
 
I'll include this in a future update.
 
Thanks,
Alvaro
 


GeneralRe: Foreign Languagesmemberemadns23 Jan '06 - 2:05 
Thank you very much. I appreciate it. I also managed to fix the problem by changing the posting mode to POST instead of GET.
 
My best regards

GeneralRe: Foreign LanguagesmemberAlvaro Mendez23 Jan '06 - 5:27 
emadns wrote:
I also managed to fix the problem by changing the posting mode to POST instead of GET.

 
Yes, I noticed that too.
 
Unfortunately using POST sometimes causes the IE browser to not remove the progress bar from the status bar, as if the page is still loading. And using GET avoids that issue.
 
Regards,
Alvaro
 


GeneralPermission DeniedmemberSanin3 Jan '06 - 11:45 
I get Permission Denied when trying to execute a script that is on a server different than the original page. I believe the issue has to do with cross-site scripting permissions, but I still have to make this work somehow. I tried setting document.domain property in various places, but could not make it to work. Any suggestions?
 
Sanin
 
-- modified at 17:45 Tuesday 3rd January, 2006
GeneralRe: Permission DeniedmemberAlvaro Mendez22 Jan '06 - 18:44 
I don't know what the problem could be, but someone may have run into it in the past. Have you looked at the comments on this forum?
 
Regards,
Alvaro
 


General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 25 Apr 2005
Article Copyright 2004 by Alvaro Mendez
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid