Showing posts with label call. Show all posts
Showing posts with label call. Show all posts

Wednesday, March 28, 2012

PageMethod called within User Control (ascx)

Hi all,

I am trying to call a PageMethod on an AutoComplete extender within an ascx (user control). I am able to do so when the extender sits directly on an ASPX (web form) but would like to reuse the component.

I know to decorate the method with [WebMethod] and [ScriptMethod] attributes and also to make the method static. I know, too, that the parameter names must match the expected signature.

Is it possible to place Page Methods within User Controls or do they have to sit on ASPX pages?

Thanks in advance,

MIKE

I have seen a couple of blog posts saying no and I was trying to do something similar last night and couldn't make it work. I would really perfer the AutoComplete extender and the NumericUpDown extender to have the option to fire events or at least non static methods but I don't think that will be possible under the current Ajax setup.

pagemethod call code sample

Can anyont point me to a code sample where a call is made to a server page method from the client script code?

thanks!

Pratibha

Hi,

please checkthis post from my blog.

PageMethod in the codebehind

I have a method in my codebehind that I would like to call from javascript. My script manager tag has EnablePageMethods="true" and the method in my codebehind is tagged with [WebMethod] and [ScriptMethod]. When I trigger the javascript, I get errors. I've found some things that say that if you want to call a server side method (not in a web service) from your javascript with the PageMethods collection, you have to have that in a script block in your aspx. I've created a script block with a method in my aspx that just calls the function in my codebehind, but I think that's kind of ugly. Is there something I might have just missed that would allow me to just call my codebehind?

Thanks

Here's a code example: http://encosia.com/index.php/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/


Your pagemethod has to be public and static. If that doesn't help, try posting some sample code for us to help debug.


Thanks. That's what I was trying and it didn't work for me. I found some posts around that said that if you wanted to do this, the server side method you were calling had to be in the ASPX. Seemed to fit because of the errors I was getting and the fact that putting a wrapper function in my ASPX for the actual method I wanted to call worked. However, I gave it one more shot this morning (same exact code that didn't work before, I swear) and it's gold.

PageMethod Timeout

Hi

I call a web method exposed in an aspx page as follows:

PageMethods.MyWS("hello world",
OnCallbackComplete,
OnCallbackTimeout,
OnCallbackError,
null,
10); // timeoutInterval

To simulate the timeout I add some sleep time to the thread in the web method, lets say 10000 (10 seconds). Problem is the timeout callback method on the client doesn't get invoked.

Any ideas?

CraigThere was a bug where we weren't respecting the timeoutInterval set onthe request if the default timeout interval is set. Can you checkif you have set the WebRequestManager's timeout interval? Trysetting the WebRequestManager's timeout interval and see if thattriggers the timeout callback...

Hope that helps,
-Hao

Thanks for the reply.

I tried the following which didn't trigger the timeout as expected:

Sys.Net._WebRequestManager._timeoutInterval = 10;

Sys.Net._WebRequestManager.timeoutInterval = 10;

Sys.Net._WebRequestManager.set_timeoutInterval(10); // threw an exception

PageMethods.MyWS("hello world",
OnCallbackComplete,
OnCallbackTimeout,
OnCallbackError);
So that's not quite right, the instance you want to use is the static Sys.Net.WebRequestManager, rather than the _ one.

So you can do Sys.Net.WebRequestManager.set_timeoutInterval(10), or in the xml markup, you can do something like

<script type="text/xml-script">
<page xmlns:script="http://schemas.microsoft.com/xml-script/2005">
<components>
<webRequestManager timeoutInterval="3000"/>
</components>
</page>
</script
Hope that helps,
-Hao

that did the trickBig Smile [:D]

thanks

PageMethods call from user controls (ascx)

Hello,

i am looking for a way to call webmethods defined in an (ascx) user control (not a web form page aspx) using PageMethods.{MethodName}. For now, i only get a javascript error saying that PageMethods is not defined. Is there a different syntax to acces thos methods or is it just not possible ?

Thank you for your help

thomas

Any answer would be appreciated.

Thank you

thomas


hello.

currently, you can only call web service methods or page methods (and in this case, the methods must be static)

PageMethods call - Authentication Failed.

Hello,
I am working with RC1 and am having problems calling a pagemethod. It keeps telling me Authentication failed. 
My page is using a master page where the Scriptmanager is declared. As you can see I am using a ScriptmanagerProxy on my main page.
The code works fine when forms authentication is not on and everything else on the site works fine when Authentication is on except Ajax pagemethod calls.
Authentication is occurring on my login in page and all of the Athentication is builtinto the codebehinds. My Question. Do I have to implement
Sys.Services.AuthenticationService to be allowed to call an Ajax web service call or pageMethod call when usingFormsAuthenication?
 Here is an incomplete example of what I am trying to do. Missing the login page
// java script file test.jsfunction pageLoad(sender, eventArgs){ PageMethods.TestThis("bar",onTestComplete, OnTestFail);} 
function onTestComplete(result){ alert(result);} function OnTestFail(error){ alert(error._message)}
// code behind[WebMethod]public static string TestThis(string name){return"foo " + name;}
 
<!-- web config --><system.web><authentication mode="Forms"><forms name="test" loginUrl="Login.aspx" protection="All" timeout="60" path="/" requireSSL="false" slidingExpiration="true" defaultUrl="Default.aspx" cookieless="UseDeviceProfile" enableCrossAppRedirects="true"/></authentication><authorization><deny users="?"></deny><allow users="*"/></authorization></system.web><!-- html page --><asp:ScriptManagerProxy id="ScriptManagerProxy1" runat="server"> <SCRIPTS> <asp:ScriptReference Name="PreviewScript.js" Assembly="Microsoft.Web.Preview> <asp:ScriptReference Path="Scripts/test.js" ScriptMode="Debug"'> </SCRIPTS> <SERVICES> </SERVICES></asp:ScriptManagerProxy>
"Debug"'>Can someone please help me??
"Debug"'>Thanks in advance. 
"Debug"'> 

Ok, Im gonna guess that its probably becasue the pageMethod has to be defined as static, if so is there a workaround?

Or are pageMethods totally useless in site with forms authentication?


Try changing your pagemethod's WebMethod attribute to be: [WebMethod(Session=true)]. That should help w/ the authentication issue.

PageMethods and xml-script?

So, I've only seen a couple posts that touch on this, and none had a direct answer. What I'm looking to do is to call one of my pages' WebMethods using the declarative syntax. I'm not sure exactly how to do that.

Using javascript it works fine, so I know that I have the rest of the thing set up right, but for whatever reason using all the components and bindings and all that just.

Conversely, I tried doing it with just a regular web service and binding,a nd that works fine too. Anyone successfully use declarative markup with WebMethods that are served from the aspx page?

hello.

currently, you can only do that if you call web service methods, you can, however, develop your own class which could be used from xml-script (you can adapt the ServiceMethodRequest to do that).


I'm not sure, I guess, what differentiates a webmethod called from the codefile from a webmethod called from a web service, in the eyes of xml-script. What is the body of code that influences the xml-script schema? I assume it's one of the classes in atlas.js, but I'm not sure which one. I'm interested in hearing how you'd do it if it were your task, though.

thanks,

Paul


hello.

take a look at the servicemethodrequest class. you just have to build a similar class but instead of using the servicemethod class internally, you should use teh pagemethod class.


Oh, I see. yeah, I spent the last half hour or so just reading (again) the atlas.js source. I'm not as sharp in javascript as I am in server-side stuff, but I'm starting to get the flow. thanks for the tip, if I end up implementing this I'll post the results.

Wow, ok, that was a LOT easier than I thought it would be. Thanks for the tip. Code follows. I went ahead and put it in my namespace b/c I didn't want to pollute teh Sys.Net namespace, but feel free to take, modify, whatever at liberty. As you suggested, the main thing to do here was to take the existing ServiceMethodRequest class and swap out the ServiceMethod references for PageMethod ones. I also pulled otu some of the member variables that I knew I wouldn't need (e.g. url-related ones) to tidy it up. This is a first draft, so I might find more that I want to do now that I have my teeth in it.

Thanks again!!

Paul

/*

Title: PageMethodExtender.js

Author: Paul Vencill

Summary: Add-on class to Atlas that will allow web methods exposed in the page's codefile to be called from the page's xml-script.

*/

Type.registerNamespace(

'Com');

Type.registerNamespace(

'Com.VelocityDataSolutions');

Com.VelocityDataSolutions.PageMethodRequest =

function() {

Com.VelocityDataSolutions.PageMethodRequest.initializeBase(

this);var _methodName =null;var _parameters =null;var _response =null;var _userContext =null;var _result =null;var _request =null;var _timeoutInterval = 0;var _priority = Sys.Net.WebRequestPriority.Normal;this.get_url =function() {return _url;

}

this.set_url =function(value) {

_url = value;

}

this.get_appUrl =function() {return _appUrl;

}

this.set_appUrl =function(value) {

_appUrl = value;

}

this.get_methodName =function() {return _methodName;

}

this.set_methodName =function(value) {

_methodName = value;

}

this.get_parameters =function() {if (_parameters ==null) {

_parameters = { };

}

return _parameters;

}

this.get_response =function() {return _response;

}

this.get_result =function() {return _result;

}

this.get_timeoutInterval =function() {return _timeoutInterval;

}

this.set_timeoutInterval =function(value) {

_timeoutInterval = value;

}

this.get_priority =function() {return _priority;

}

this.set_priority =function(value) {

_priority = value;

}

this.completed =this.createEvent();this.timeout =this.createEvent();this.error =this.createEvent();this.aborted =this.createEvent();this.invoke =function(userContext) {if (_request !=null) {returnfalse;

}

var _pageMethod =new Sys.Net.PageMethod(_methodName);

_request = _pageMethod.invoke(_parameters, onMethodComplete, onMethodTimeout,

onMethodError, onMethodAborted,

this ,

_timeoutInterval, _priority);

function onMethodComplete(result, response, target ) {

_request =

null;

_userContext = userContext;

_response = response;

_result = result;

target.completed.invoke(target, Sys.EventArgs.Empty);

}

function onMethodError(result, response, target ) {

_request =

null;

_userContext = userContext;

_response = response;

_result = result;

target.error.invoke(target, Sys.EventArgs.Empty);

}

function onMethodTimeout(request, target ) {

_request =

null;

_userContext = userContext;

target.timeout.invoke(request, Sys.EventArgs.Empty);

}

function onMethodAborted(request, target ) {

_request =

null;

_userContext = userContext;

target.aborted.invoke(request, Sys.EventArgs.Empty);

}

returntrue;

}

this.abort =function() {if (_request) {

_request.abort();

}

}

this.getDescriptor =function() {var td = Com.VelocityDataSolutions.PageMethodRequest.callBaseMethod(this,'getDescriptor');

td.addProperty(

'methodName', String);

td.addProperty(

'parameters', Object,true);

td.addProperty(

'response', Sys.Net.WebRequestExecutor,true);

td.addProperty(

'result', Object,true);

td.addProperty(

'timeoutInterval', Number);

td.addProperty(

'priority', Number);

td.addMethod(

'invoke');

td.addMethod(

'abort');

td.addEvent(

'completed',true);

td.addEvent(

'timeout',true);

td.addEvent(

'error',true);

td.addEvent(

'aborted',true);return td;

}

Com.VelocityDataSolutions.PageMethodRequest.registerBaseMethod(

this,'getDescriptor');

}

Com.VelocityDataSolutions.PageMethodRequest.registerClass(

' Com.VelocityDataSolutions.PageMethodRequest', Sys.Component);

Sys.TypeDescriptor.addType(

'script','pageMethod', Com.VelocityDataSolutions.PageMethodRequest);

cool!

that's the spirit :)


Hi,

thanks for posting the code, Paul.

Glad to, I'm very excited about this. I also went ahead and built a Page subclass that inserts a ScriptManager control if there isn't one and pulls in the xml-script from an external file (by default located in the same folder and with the same name as the parent document but with a .ascr extension.). Here's teh code for that subclass as well. It works, but I'm still polishing it to make it a little more robust, add comments, etc etc. I just wanted to see if i could hack my way through it.

using

System;

using

System.Web.UI;

//using System.Xml;

using

System.Xml.XPath;

///

<summary>

///

Summary description for AtlasPage

///

</summary>

public

classAtlasPage : System.Web.UI.Page

{

privatestring _xmlScript;privatebool _hasScriptManager;protectedoverridevoid OnInit(EventArgs e)

{

addScriptManager();

addAtlasScript();

base.OnInit(e);

}

protectedstring _scriptFile;publicstring ScriptFile

{

get {return _scriptFile; }set { _scriptFile =value; }

}

privatevoid getXmlScript()

{

if(String.IsNullOrEmpty(_scriptFile))

{

string url = Request.Url.ToString();

url = url.Replace(

".aspx",".ascr");

_scriptFile = url;

}

try

{

XPathDocument xdoc =newXPathDocument(_scriptFile);XPathNavigator xNav = xdoc.CreateNavigator();

xNav.Select(

"script");

_xmlScript =

String.Format("\n{0}\n",xNav.OuterXml.ToString());

}

catch

{

_xmlScript =

String.Format(@."<!-- File not found: {0} -->","xml-script");

}

}

privatevoid addAtlasScript()

{

getXmlScript();

LiteralControl lit =newLiteralControl(_xmlScript);this.Controls.AddAt(this.Controls.Count - 1, lit);

}

privatevoid addScriptManager()

{

_hasScriptManager =

false;

iterateCollection(Controls);

if (!_hasScriptManager)

{

Microsoft.Web.UI.

ScriptManager scm =new Microsoft.Web.UI.ScriptManager();this.Header.Controls.Add(scm);

}

}

privatevoid iterateCollection(ControlCollection ctrls)

{

foreach (Control ctrlin ctrls)

{

if (ctrl.HasControls())

{

iterateCollection(ctrl.Controls);

}

if (ctrl.ToString().Contains("ScriptManager"))

{ _hasScriptManager =

true; }

}

}

}

Paul Vencill

Velocity Data Solutions. LLC

www.velocitydatasolutions.com

Monday, March 26, 2012

PageMethods is undefined when calling webservice from usercontrol

I have the following code to call a webservice in an aspx file. But the same code does not work in a usercontrol that I have created. I always get the message that 'PageMethods is undefined'. On the aspx page it generates the following:

<script type="text/javascript">
<!--
var PageMethods = { HelloWorld:function(s,onMethodComplete, onMethodTimeout, onMethodError) {return Web.Net.PageMethodRequest.callMethod("HelloWorld",{s:s}, onMethodComplete, onMethodTimeout, onMethodError); }
}
// -->
</script>

but in the usercontrol this variable is not generated. The following is the code in the aspx page which is very similar to the code in the user control. Please help!

<atlas:ScriptID="Script1"runat="server"Path="~/ScriptLibrary/AtlasCompat.js"Browser="Mozilla"/>

<atlas:ScriptID="Script2"runat="server"Path="~/ScriptLibrary/AtlasCompat.js"Browser="Firefox"/>

<atlas:ScriptID="Script3"runat="server"Path="~/ScriptLibrary/Atlas.js"/>

<scripttype="text/C#"runat="server">

[WebMethod]

publicstring HelloWorld(string s)

{

return"Hello '" + s +"'";

}

</script>

</head>

<body>

<formid="Form1"runat="server">

Enter your name:

<asp:TextBoxid="nameTextBox"runat="server"></asp:TextBox>

<buttonid="buttonGo"onclick="return OnbuttonGo_click()">GO</button>

</form>

<scripttype="text/javascript"language="JavaScript">

function OnbuttonGo_click()

{

//textbox string value passed as a param to the server method

PageMethods.HelloWorld(document.getElementById("nameTextBox").value, OnWebRequestComplete1);

returnfalse;

}

PageMethods are currently not supported inside user controls. I've open a bug to track that issue. Thanks.


If I put the WebMethod in the calling page I can call it from the usercontrol, which allows for the functionality that I desire. This is not as clean as I hoped for but it will work.

Thanks


Has this been fixed in the December release? It appears not, unless I am doing something incorrect. I am getting the js error 'Web' is undefined. Even my work around for this problem apears to be broken.

PageRequestManagerParseErrorException

Hello. I'm have the problem with UpdatePanel. When the user does click on de button I call a method

Button1_Click

This method call other page in modo modal where the user type a password. If this password is ok I'll try to use

UpdatePanell2.Update() but I can′t call the page2 in modo modal because appear this error.

Read this to avoid this issue:

http://weblogs.asp.net/leftslipper/archive/2007/02/26/sys-webforms-pagerequestmanagerparsererrorexception-what-it-is-and-how-to-avoid-it.aspx

Wednesday, March 21, 2012

partial postback and FireFox

in FireFox, using javascript to call parent.__doPostback('mycontrol') seems to initiate the partial postback on the parent window, and you can see the UpdateProgress rotating Image, but it does not go away and the page never refreshes.

This works fine on IE and Opera - is this a known FireFox issue that the atlas team is working on?

Thanks in advance

hello.

any chance on providing a demo page that reproduces this problem?


Thanks for the reply Luis... unfortunately I don't have a demo page at hand, but will try to put one together if no-one else is already familiar with this particular issue.


hello.

well, you could also use fiddler to see what's getting passed from client to server and vice-versa...


FYI, this seems to have resolved itself with Beta 2

Correction, this still is not resolved - I was under the impression that it was fixed because calling __doPostBack with an eventtarget parameter that does not exist is causing a regular postback (a change from CTP)... you still cannot call __doPostBack() in hopes for a partial postback in FireFox.


I am having a similar problem as well. However i am initiating the partial page postback through a pop-up window. The pop-up window calls window.opener.__doPostBack(target, argument). The postback actually gets executed on the server, but the UpdatePanel on the underlying page does not get updated on FireFox. This works fine on IE.

Here is the source of a very simple page.

ASPX Page

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="sm1" runat="server" />
<asp:UpdatePanel id="updater" runat="server">
<ContentTemplate>
<asp:Label ID="serverTime" runat="server" /><br />
<asp:Button ID="getTime" Text="Get Server Time" runat="server" UseSubmitBehavior="false" OnClick="getTime_Click" /><br />
<a href="#" onclick="window.open('popupAjax.html','Popup','width=200,height=200');">Open Popup</a>
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

Code Behind

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;

public partialclass UpdatePanel : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
serverTime.Text = DateTime.Now.ToLongTimeString();
}
protected void getTime_Click(object sender, EventArgs e)
{
Thread.Sleep(1000); // Used just to similate processing of something.
serverTime.Text = DateTime.Now.ToLongTimeString();
}
}

Simple Popup Page

<!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>
<title>Untitled Page</title>
</head>
<body>
<a href="#" onclick="window.opener.__doPostBack('getTime','');window.close();">Update And Close Window</a>
</body>
</html>


In the example above I was using the latest ASP.NET AJAX Beta 2 build.

It seems you are having the same issue as I... the work-around we used for FireFox is to simply do a full postback - as follows:

if (opener.document.getElementById("__EVENTTARGET") !=null)

opener.document.getElementById("__EVENTTARGET").value ="XXXXXXXX";

if (opener.document.getElementById("__EVENTARGUMENT") !=null)

opener.document.getElementById("__EVENTARGUMENT").value ="";

opener.document.forms[0].submit();


hstechl:

It seems you are having the same issue as I... the work-around we used for FireFox is to simply do a full postback - as follows:

if (opener.document.getElementById("__EVENTTARGET") !=null)

opener.document.getElementById("__EVENTTARGET").value ="XXXXXXXX";

if (opener.document.getElementById("__EVENTARGUMENT") !=null)

opener.document.getElementById("__EVENTARGUMENT").value ="";

opener.document.forms[0].submit();

Where do you put this script ? In a client script block or ?


I would try the followings:

- I have problems in firefox 2.0 and ajax ctp/beta 1/beta 2 (rc1 not tested yet) when opening popups via javascript (strange javascipt errors, i have athread about it, but no response yet)

so instead of

<a href="#" onclick="window.open('popupAjax.html','Popup','width=200,height=200');">Open Popup</a>

try

<a target="_blank" href="popupAjax.html">Open Popup</a>

(I think this is better for the "modern" browsers, because you not force your user for a defined window size and the user could decide where to place our popups: in a new window?, in a new tab? However there is one drawback: you cannot close the popup by javascript without a security warningSmile )

- Maybe thedummy button trick is works for you (I am using it for ajax popups and parent update panels always). Not elegant but works.