Showing posts with label method. Show all posts
Showing posts with label method. Show all posts

Wednesday, March 28, 2012

pageLoad javascript function not being called

for some reason the javascript pageLoad method is not being called

the javascript is in scirbble.js

the example i have followed informs me that the pageLoad method should be ran when the atlas script manager control has loaded.

Is this corret.

Could someone please point me in the right direction for getting the below code to work

Below is the javascript and aspx code

function pageLoad()
{
var surface = document.getElementById("drawingSurface");
image = surface.getElementsByTagName("IMG")[0];
originalSrc = image.src;

surface.attachEvent("onmousedown", startStroke);
surface.attachEvent("onmouseup", endStroke);
surface.attachEvent("onmouseout", endStroke);
surface.attachEvent("onmousemove", addPoints);
}

form id="form1" runat="server">
<Atlas:ScriptManager ID="AtlasScriptManager" runat="server" >
<Services>
<Atlas:ServiceReference Path="ScribbleService.asmx" />
</Services>
<Scripts>
<Atlas:ScriptReference Path="ScriptLibrary\Scribble.js" />
</Scripts>
</Atlas:ScriptManager>
<div id="drawingSurface"
style="border:solid 1px black;height:200px;width:200px">
<img alt="Scribble" src="http://pics.10026.com/?src=ScribbleImage.ashx"
style="height:200px;width:200px" />
</div>
</form>

i have the same problem since the last release. I had pageLoad() methods which were able to set elements on the initial loading which no longer fire automatically :?(

As a workaround, you can attach to thePageRequestManager events like so :

<script type="text/javascript"> Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoad);</script>

when i do the above mentioned work around i get an error

'Sys.WebForms.PageRequestManager' is null or not an object

i have tried adding the script above and below the sript manager html elements but it makes no diffrence.

below is the aspx page

any help would glady be appreciated.

<headrunat="server">

<title>Atlas Scribble Sample</title>

</

head><body><formid="form1"runat="server"><Atlas:ScriptManagerID="AtlasScriptManager"runat="server"EnablePartialRendering=true><Services><Atlas:ServiceReferencePath="ScribbleService.asmx"/></Services><Scripts><Atlas:ScriptReferencePath="ScriptLibrary\Scribble.js"/></Scripts></Atlas:ScriptManager><divid="drawingSurface"style="border:solid 1px black;height:200px;width:200px"><imgalt="Scribble"src="ScribbleImage.ashx"style="height:200px;width:200px"/></div><scripttype="text/javascript">

Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoad);

</script></form>

</

body>

</

html>
throw an alert into your pageLoad() function to see if it's getting called; my guess is that it is, at least nothing you've posted here would prevent it. The issue I see is that the element 'surface' isn't going to respond to the attachEvent function as you have it written, at least not in this framework. You could try to us $addHandler(surface,'onmousedown',startStroke); instead.

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 dont regenerate on file change?

If I define a new page method or change an existing page method I have to restart my dev asp.net server to see the change in the generated javascript (page prototype)? anyone else having this problem?

thanks

Hi,

Without any valuable information, it is hard to say where the problem lies on.

Please provide any more information,eg. any code of this.

Thanks!


Hi Craigw,

It seems like a cache issue rather than a IIS issue. So I suggest you to save your web.config file without any modifications and have a test. If it works, we can confirm it.

Also you can delete all the cache file or do the following steps. open the IE -->Tools-->Internet Options-->General Dialog-->Browswer History-->Settings-->select "Every time I visit the webpage".

I hope this help. If it doesn't work, please feel free to let me know with more information.

Best regards,

Jonathan


This problem has been quite annoying for some time. Can you please confirm if it has been identified and whether a fix will be available?

It happens on the server (Win 2003 R2) as well as on developer PCs (Cassini). Restarting the web server does the trick as well as re-saving web.config. It's quite easy to reproduce (and yes, I have enbaled PageMethods in the ScriptService tag...)

Monday, March 26, 2012

PageMethods is undefined

Hi there

I have a simple page that calls a server side page method via the scriptmanager / page methods detailed on this site. This has worked fine recently when until I updated our dev team to use the new asp.net ajax 1.0.

Once I'd updated my web.config as per the doco all works fine on my pc but on all others when I call the server side method I get the client script error " PageMethods Is 'Undefined' ". I am sure this is an environmental issue but I would appreciate any tips on how to figure out what is going on!

To update one of the boxes (eg our test server) I did the following steps.

    Uninstall previous ASP.net Ajax (RC1)Install new versionUpdate web.config as per instructions in the doco

Here is my source code

<%@dotnet.itags.org. Page Language="C#" AutoEventWireup="true" CodeFile="AddNote.aspx.cs" Inherits="controls_AddNote" EnableViewState="true" %><%@dotnet.itags.org. Import Namespace="System.Web.Services" %><!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 id="Head1" runat="server"> <title>Add a note to this cell</title> <link rel="stylesheet" type="text/css" href="../css/calumo default.css" /> </head> <body leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0"> <script type="text/javascript" language="javascript"> function PageMethodCall() { var TicketId=parseInt($get("inpTicketId").value); var DataSource=$get("inpDataSrc").value; var Catalog=$get("inpCatalog").value; var Cube=$get("inpCube").value; var DataPointMdx=$get("inpMdx").value; var NoteValue=$get("taNote").value; if(NoteValue.length>0) PageMethods.SendNote(TicketId,DataSource,Catalog,Cube,DataPointMdx,NoteValue,OnSucceeded); } // This is the callback function // that process the page method call // return value. function OnSucceeded(result) { // Display the result. if(result==1) window.close(); else alert("Calumo Server Exception:-" + result); } function Validate() { if($get("taNote").innerText.length>0) $get("btnSend").value="Send"; else $get("btnSend").value="Close"; } </script> <form id="frmAddNote" runat="server" target="_self"><asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager> <input runat="server" type="hidden" id="inpTicketId" value="" /> <input runat="server" type="hidden" id="inpDataSrc" value="" /> <input runat="server" type="hidden" id="inpCatalog" value="" /> <input runat="server" type="hidden" id="inpCube" value="" /> <input runat="server" type="hidden" id="inpMdx" value="" /> <table id="Table1" runat="server" height="100%" width="95%" cellpadding="0" cellspacing="0"> <tr id="trHeader" > <td><img alt="" src="../images/Calumo/top_bar.jpg"/></td> </tr> <tr><td> </td></tr> <tr id="trBody"> <td id="tdNoteArea" align="center">  <textarea cols="10" runat="server" style="height:100%;width:650px;" id="taNote" rows="10" ></textarea> </td> </tr> <tr><td> </td></tr> <tr id="trFooter"> <td style="padding-right:20px;width:100%" id="tdClose" align="right"> <input id="btnSend" type="button" value="Send" onclick="javascript:PageMethodCall();" /> </td> </tr> </table> </form> </body></html>

and here is the server code

 [WebMethod()]public static string SendNote(int TicketId,string DataSource,string Catalog,string Cube,string DataPointMdx,string NoteValue) {try {// Add a note to the server code and return a sample msgreturn"It Works"; }catch(Exception ex) {return ex.Message; } }

Any hints on troubleshooting would be greatly appreciated

Thanks in advance

Graham

Try settingEnablePageMethods="true"

<

asp:ScriptManagerID="ScriptManager1"runat="server"EnablePageMethods="true">

Yep thats it! Would probably be a good idea to add to the update doco

thanks


Was that missing in the documentation somewhere? We'll happily fix it... just point me to where it's missing.


There should probably be a section on Page Methods...in the docs that is accessible by the left hand side index..

Also, for whatever reason - the UpdatePanels UpdateMode is set by default to "Always" a special highlight in the docs should indicate this is the default and to change it to conditional for partial rendering / asynchronous updates. I was kinda surprised when investigating some of the post and issues on always full postbacks - that when I just dragged and dropped an updatepanel in designer - it defaulted to "Always"... kinda missing the purpose I think as if you are releasing this - then the default should err on side of the Ajax technology it is supposed to provide and this is a change I think from the RCs but not positive as I always declare everything anyways... but alot of folks just drag and drop and assume they are getting the settings for exploiting the Ajax enviroment...


I followed this docohttp://ajax.asp.net/documentation/Migration_Guide_RC_to_RTM.aspx

and unless I skipped over it I didn't find any reference to the EnablePageMethods

thanks again


I agree! Where can you find reference and documentation to PageMethods ? I use the block of code on this post as my reference right now ..


http://ajax.asp.net/docs/tutorials/ExposingWebServicesToAJAXTutorial.aspx

I agree this would be nice to see in the "differences" docs. I'll see if it can be added.


Just wanted to say thanks, all.

I was trying to get a method to run from a page (both in the .aspx file and in the code behind) and kept getting the js error of "PageMethods" not found. Adding that attribute to the ScriptManager cured the problem.

Pete.

PageMethods quirk

So here's what I found while using PageMethods in Beta 2

    A server side method needs the attribute [System.Web.Services.WebMethod]A server side method should be static or else you'll get a PageMethods is undefined errorA server side method should NOT be defined in code behind but should be in the ASPX page in <script runat="server"> tag.Here's the quirk. A server side method CANNOT have two parameters with names that differ only in the case of their letters. eg. someParam and SomeParam, even if they are of different types, e.g. string and int This will result in a Sys.ArgumentTypeException with the message Object of type Number cannot be converted to type Function. Parameter name OnSuccess.
    <script runat="server"> [System.Web.Services.WebMethod] public static string SomeMethod(string someParam, int SomeParam) { return "Hello " + someParam + " you are " + SomeParam.ToString() + " years old"; } </script>
    <script type="text/javascript" language="javascript"> function CallMethod() { var age = 28; PageMethods.SomeMethod('MyName',age, OnCallResponse); } function OnCallResponse(arg) { alert(arg); } </script>
    Change the SomeParam to age and it will work.

So my question is : Is this a bug, quirk or by design? If a bug or quirk will it be fixed? Sure one NEVER names two parameters the same with just a change in the case but then again, NEVER say NEVER.

Thanks

I SO MUCH SUPPORT your finding #3. It's so stupid that the server side code won't work in code-behind but inline code would work. What the heck?

To any MSFT moderator:

Is there any workaround for #3? This is driving me crazy.


Weird, but I just tried to create a page just like yours and it works even if the static method is in the code behind...

This is the class:

public partialclass _Default : System.Web.UI.Page { [WebMethod]public static string GetServerDate() {return DateTime.Now.ToString(); }}


And this is the ASPX:

<%@. Page Language="C#" AutoEventWireup="true" CodeFile="~/Default.aspx.cs" Inherits="_Default" %><%@. Importnamespace="System.Web.Services"%>"-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml">Untitled Page"server"> "form1" runat="server" method="post"> "ScriptManager1" runat="server" />

"button"value="get date" onclick="GetDate();" id="Button1" />

"date" />

"text/javascript">function GetDate(){ var div = document.getElementById("date"); PageMethods.GetServerDate(function (result) { div.innerText = result; });}

Sorry about my last post which is unreadable...Angel

Reposted:

Weird, but I just tried to create a page just like yours and it works even if the static method is in the code behind...

This is the class:

public partialclass _Default : System.Web.UI.Page
{
[WebMethod]
public static string GetServerDate()
{
return DateTime.Now.ToString();
}
}


And this is the ASPX:

<%@. Page Language="C#" AutoEventWireup="true" CodeFile="~/Default.aspx.cs" Inherits="_Default" %><%@. Import namespace="System.Web.Services"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"> <title>Untitled Page</title></head><body> <form id="form1" runat="server" method="post"> <asp:ScriptManager ID="ScriptManager1" runat="server" /> <div> <input type="button" value="get date" onclick="GetDate();" id="Button1" /> <div id="date" /> </div> </form> </body></html><script type="text/javascript">function GetDate(){ var div = document.getElementById("date"); PageMethods.GetServerDate(function (result) { div.innerText = result; });}</script>

This looks a bug, thanks for reporting this issue, and it will be fixed in a future build.
-Hao


Hi,

that is not a bug. Remember that vbscript is case unsensitive.


Hi,

I tried the approach of using static methods for PageMethods in AJAX v1.0 Beta 2, but it is not working. The only change that happened is that the error message has changed from "PageMethods is undefined" to "PageMethods is null or not a object.

PLEASE HELP !!!!


Advance,

Where the heck is "vbscript" in whole picture? We are trying to access a WebMethod from Javascript using MS Ajax Beta 2 in the code-behind file.


I was hoping this would have been corrected in Beta 2. I guess I'll keep using the ATLAS CTP until this is resolved. Oh well, maybe in build 3??


hello.,

this is correct. the problem is related with the EnsureParameters of the WebServiceMethodData class. I don't know why, but it's "eating parameters" when they have the same name and differ only in case. here's the "bad" code:

privatevoidEnsureParameters()
{
if (this._parameterData ==null)
{
lock (this)
{
Dictionary<string,WebServiceParameterData>dictionary1 =newDictionary<string,WebServiceParameterData>(StringComparer.OrdinalIgnoreCase);
intnum1 =0;
foreach (ParameterInfoinfo1inthis._methodInfo.GetParameters())
{
dictionary1[info1.Name] =newWebServiceParameterData(info1,num1);
num1++;
}
this._parameterData =dictionary1;
}
}
}
 
I've tried reproducing this with a simple method and i get the 2 parameters and if i add them to a dictionary, i get 2 entries. this is not happening here (yes, i've used reeflection to reproduce what's going on and i can say that the dic only has one parameter.
if anyone have an idea on why is that, please,share with us!
thanks. 


hi.

dom't you hate it when you spend 1 hour looking at code and writing reflection just to see that the damn thing is right in front of you?:

newDictionary<string,WebServiceParameterData>(StringComparer.OrdinalIgnoreCase);
thanks Garbin!
 
 

Yeah, there are two places in the code that are using OrdinalIgnoreCase comparers which is what's causing the problem, removing the IgnoreCase for both dictionaries fixes the problem.

Hope that helps,
-Hao


hello.

does that mena that it'll be removed in the next release?


Yes I've already fixed it in the codebase.

Hope that helps,
-Hao

PageMethods or WebServices ..

I need to recover some server-info from JavaScript (ansynchroniously) so I need any exposed method on the server that could be called from the client. I've seen that there are 2 ways to do this (without using, the easy-fashion UpdatePanel):

WebService

PageMethods

I just don't know what to choose. Most solutions I've seen around the .net community are based upon the use of WebServices but I think that exposing a WebService may cause a lack of security (anyway, I dont know if it's possible to forbid access to the .amsnx file directly from the browser).

Thankyou!

nach_:

I dont know if it's possible to forbid access to the .amsnx file directly from the browser.

It isn't. When using webservices it is the browser which is accessing the the webservice, so forbidding it would prevent the method from working. You could make the webservice call inject a special header in the HTTP request, and check for its existence on the server, but that's about it (well, you could create a more advanced security system, but that also means more overhead).

Webservices are (a lot) less resource hungry than PageMethods, since PageMethods bring along the viewstate and basically instantiate everything on the page as if there was a regular postback in action. PageMethods should only be used if the state of the page is relevant in the call.


Thankyou for your answer gunteman!

The first thing is clear, if you forbid access to .amsnx then nothing will work, great.

What I don't understand is why WebServices are less resource hungry than PageMethods. Far as I know, PageMethods only allow static methods to be exposed so I don't understand why the state of the page may be relevant in that cases (hope I've explained).

Thankyou again!


Whoa! It seems PageMethods have changed since I abandoned them (they used to be non-static and heavy as hell).

Well, then it seems the most logical argument for using webservices is re-use, if the method is to be used from several pages.


That's what I thought but if not reuse is needed then maybe the good option is to use PageMethods (at least are less accessible for possible leechers than webservices, or not)?

Thankyou again!


You could definitely use PageMethods, but bear in mind that they are just as leechable as webservices. The calling mechanism is (now) basically the same as when using webservices. However, if you use some kind of login on your website, the PageMethods will be protected from non-authenticated users (or however you define your security). The same is true for webservices if so defined.

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

PageRequestManager blocks any other instance of XMLHttpRequest?

I'm trying to implement a progress bar that reports on the contents of session variables during the course of a slow method on one of my pages. The slow method in question populates/updates a datagrid inside an update panel.

I'm aware that it's only possible to have one request at a time using PageRequestManager, so i thought i would use some of my old own ajax libraries, and make a manual call to a webservice which would return the contents of the relevant session variables. However, even using this approach, the call to the webservice does not go through until the slow method has finished, which is obviously not ideal. Does PageRequestManager block any other instances of XmlHttpRequest on the page?

I read an article that suggested what i was attempting to do was possible using PageMethods, but since the latest release, where pagemethods have to not only reside in the aspx file but also have to be static, this is just not feasible.

I'd be grateful if anyone could shed some light on this, cheers

I'm not sure if something is awry with my installation, but now i am unable to request any other page from within the current application whilst the ajax request is in process - it just hangs, and then processes when the current ajax operation is complete. For slow methods that retrieve a lot of data, i'm sure you can see why this is almost ludicrous behaviour. Surely this isn't intended?

hello.

in previous releases, you could only make a partial refresh at a time (ie, you could only start a partial refresh after a previous one ended). in the last version, i think this has been changed and now what happens is that the last request overrides the previous one. this only happens when you're using UpdatePanels (ie, the behavior i've described only happens when you use updatepanels). you can still use xmlhttprequest as you see fit in your pages and you should be able to make several calls.


Thanks for the reply.

Are you aware of any other scenario in which setting a long running method running on one page would block any other requests to other pages within the same application until it is complete? I'm not accessing or modifying session data in either page.

Cheers


hello.

well, even though you're not using session data, it all depends on the way your final page is rendered. for instance, i think that if you don't set the enableSessionstate attribute on the page directive, the page will still use read/write session state. do you think that this might be the problem you're having?


I was unaware i had to specifically set the enableSessionState directive to "false" - even "readonly" still made the page block.

Thanks a lot for the help, appreciated.

Saturday, March 24, 2012

Paging Problem in Dynamically added GridView

Hi

I am developing a composite control which includes a GridView. GridView is created and bound in CreateChildControls() method. Normally the control works greate. But if I set AllowPaging=True, it gives an "Object null reference exception". Following is the code. Please give me a solution. [N:B: I have added the PageIndexChages Event also].

protected override void CreateChildControls(){_lsAjaxGridView =new GridView();_lsAjaxGridView.ID ="Leadsoft_AjaxGrid";_lsAjaxGridView.AutoGenerateColumns =this.AutoGenerateColumns;foreach (DataControlField dataControlFieldin Columns) _lsAjaxGridView.Columns.Add(dataControlField);if (this.AllowPaging){if (this.PageSize > 0) _lsAjaxGridView.PageSize =this.PageSize; _lsAjaxGridView.AllowPaging =this.AllowPaging; _lsAjaxGridView.PageIndexChanging +=new GridViewPageEventHandler(Leadsoft_AjaxGrid_PageIndexChanged);}_lsAjaxGridView.DataSource = LSDataSourceView;_lsAjaxGridView.DataBind();}
The exception occurs in "_lsAjaxGridView.DataBind();" only when AllowPaging is True.
Exception Message:"Object reference not set to an instance of an object."

Hi this problem is solved. thing is any DataBinding should be done after the control is added to the form.

lsAjaxGridView.DataSource = LSDataSourceView;

Controls.Add(lsAjaxGridView);
_lsAjaxGridView.DataBind();