Showing posts with label defined. Show all posts
Showing posts with label defined. Show all posts

Wednesday, March 28, 2012

PageError event of scriptmanager not firing

I have a content page that has a master page. I have an updatepanel and a scriptmanger in my content page. I defined a handler for OnPageError for the scriptmanager and defined a error template for the scriptmanager but when I set the e.errormessage in the OnPageError event, but if I set a break point in the event, the break point is never reached and the error message in the template still displays 'unknown error' Any ideas?

if I put a button on the page and in the click event of the button i manually throw and error.

thrownewException("error button clicked");

the event fires and works fine.

but if I put some invalid characters like '<img src' inside a textbox and then click the button (removing the throw) then the OnPageError isn't fired

PageMethods is not defined - Modal Popup

Just upgraded from RC1 to the RTM copy of AJAX and found everything is working for me (with the normal changes to the AutoCompleteExtender) except for my modal popups.

When I attempt to use the client side java script, I get a javascript error:

"PageMethods is not defined."

Here is my JavaScript code:

function myModalPop(regID){ $get("hidRegID").value = regID; PageMethods.popModal(regID, Add_Complete, Add_Timeout, Add_Error);}

and the code behind is:

[System.Web.Services.WebMethod]public static string[] popModal(string regID) { gcmControl DSsend =new gcmControl(); DataSet dsMet =new DataSet(); dsMet = DSsend.gcmDS(dsMet,"SQL","dbAll","SELECT * FROM dbo.tblFinRegister WHERE regID = '" + regID +"' AND clubID = '" + clubID +"'","tblFinRegister"); DataTable tblFinRegister = dsMet.Tables["tblFinRegister"]; DateTime dtRegDate = Convert.ToDateTime(tblFinRegister.Rows[0]["regDate"]);string regDate = dtRegDate.ToString("d");string payeeID = lookupPayee(Convert.ToInt32(tblFinRegister.Rows[0]["payeeID"]));string chartID = tblFinRegister.Rows[0]["chartID"].ToString();string regNumber = tblFinRegister.Rows[0]["regNumber"].ToString();string regPayment;if (tblFinRegister.Rows[0]["regPayment"].ToString() =="0.00") { regPayment =""; }else { regPayment = tblFinRegister.Rows[0]["regPayment"].ToString(); }string regDeposit;if (tblFinRegister.Rows[0]["regDeposit"].ToString() =="0.00") { regDeposit =""; }else { regDeposit = tblFinRegister.Rows[0]["regDeposit"].ToString(); }string regRecon = tblFinRegister.Rows[0]["regRecon"].ToString();string regMemo = tblFinRegister.Rows[0]["regMemo"].ToString();return new string[] { regDate, payeeID, chartID, regNumber, regPayment, regDeposit, regRecon, regMemo }; }
Any suggestions would be fantastic.The way the Toolkit calls page methods is such that no changes are necessary from ASP.NET AJAX RC to 1.0. However, if you're using the ASP.NET AJAX PageMethods wrappers, they made a breaking change such that you now need to set EnablePageMethods=true on your ScriptManager in order to call PageMethods like it seems you're doing above.

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)

Monday, March 26, 2012

PageMethods is undefined

When using the July CTP, I was able to use the PageMethods defined in my web page with no problems.

After loading the beta 1.0 release, I get the error "PageMethods is undefined" when attempting to use WebMethods from my page.

The "Change from the CTP" docs mention that this has been changed to use static page methods and that it's supposed to be easier now. It would be very helpful to see a working sample using PageMethods in the most recent beta release.

Anyone have a working sample?

Ken

hello.

here's a quick test i've written

<%@. Page Language="C#" %>
<%@. Import namespace="LivroAtlas"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
[System.Web.Services.WebMethod]
public static Aluno[] ObtemAlunos()
{
Aluno[] alunos = new Aluno[]{
new Aluno( "João", 15 ),
new Aluno( "Rita", 16 ),
};

return alunos;
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="manager" />
<input type="button" value="invocar método da página" onclick="handle()" />
</form>
<script type="text/javascript">
function handle()
{
PageMethods.ObtemAlunos( handleCallback);
}
function handleCallback( res )
{
for( var i = 0; i < res.length; i++ )
{
alert( res[i].Nome + "-" + res[i].Idade );
}
}
</script>
</body>
</html>


Thanks very much, Luis.

I had missed that page methods are now required to be static.

Ken


Could someone please bring back the old PageMethods, when it could access the page control's value, that was great.

hello.

use updatepanels for that and set the childrenastrigger to false so that you don't send back html to the client. there's no need to have pagemethods without them being static.can anyone provide a good scenario where non-static page methods are really the only way to go?


I'm actually using the PageMethod object so that when a user presses an image button, it calls a server side method that pulls values out of session state as well as control values and then makes a call to a back end software that does some processing for our application and returns an object that we then load into a treeview. However, you are not able to reference Session variables from static methods neither are you able to reference controls. This is my example...do you think i'm doing it wrong or do I have a valid scenario?

hello.

how about using an updatepanel or a web method? you do say that you need to refresh the UI...btw, i do think that you can access session state from a static method:

<%@. Page Language="C#" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server">
[System.Web.Services.WebMethod]
public static int O()
{
HttpContext ctx = HttpContext.Current;
ctx.Session["i"] = Convert.ToInt32(ctx.Session["i"]) + 1;
return Convert.ToInt32( ctx.Session["i"] );
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);

if (!this.IsPostBack)
{
HttpContext ctx = HttpContext.Current;
ctx.Session["i"] = 0;
}
}
</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="manager" />
<div>
<input type="button" runat="server" id="bt" onclick="handleClick()" />
</div>
</form>
<script type="text/javascript">
function handleClick()
{
PageMethods.O(function(res){ alert( res ); });
}

</script>
</body>
</html>

that sample simple returns an int. maybe you can adapt it so that it returns what you need.


This is odd, but I can't seem to get PageMethods to call when the WebMethod is in a codefile. I didn't have a problem with that before. Any thoughts? The exact same code works fine if the WebMethod is part of C# embedded on the page in script tags as Luis has done. I really prefer it the way I had it before, as I prefer using codefiles.

"C#"-->"-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><script runat="server"> [System.Web.Services.WebMethod] public static string Test() { return "Success"; }</script><html xmlns="http://www.w3.org/1999/xhtml" >"Head1" runat="server"> "form1" runat="server"> "server" ID="manager"> "button"value="invocar método da página" onclick="handle()"> "text/javascript"> function handle() { PageMethods.Test(handleCallback); } function handleCallback( res ) { alert( res ); }

On the other hand, it doesn't work like this:

"C#" AutoEventWireup='false' CodeFile="Default.aspx.cs" Inherits="_Default"-->"-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >"Head1" runat="server"> "form1" runat="server"> "server" ID="manager"> "button"value="invocar método da página" onclick="handle()"> "text/javascript"> function handle() { PageMethods.Test(handleCallback); } function handleCallback( res ) { alert( res ); }using System;using System.Data;using System.Configuration;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;public partialclass _Default : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e) { } [System.Web.Services.WebMethod]public static string Test() {return"Success"; }} 

There is a bug in the beta build that prevents codebehind page methods from working, just incase requiring static methods weren't already going to make them useless enough..Wink... you have to include them in the aspx file if you want to use them...

See this post for more detailhttp://forums.asp.net/thread/1435443.aspx


hello.

jkolbo is right ony about one thing: there's a bug in the beta build and you can't put them in the code beahind file.

regarding the second part, i will not repeat myself and try to explain (once more) why the old instance page methods sucks...this time, i'll just say why the new static methods are good for. in previous releases, if you didn't want to use page methods due to the performance penalties associated with them, you'd have to use web services. static page methods lets you get the some thing without having to develop webservices


Hi,

Just because someone doesn't want to develop webservices is not a compelling reason to take away the functionalities of the old PageMethods. Performance was still better than a complete postback(which is what most of the internet is using). There should atleast be an alternative. Now we got 2 very similiar methods that do the same thing as oppose to 2 distinct methods that do different things.


Hello.

mnn888:

Performance was still better than a complete postback(which is what most of the internet is using). There should atleast be an alternative. Now we got 2 very similiar methods that do the same thing as oppose to 2 distinct methods that do different things.

this is the kind of thing to which i completely disagree! page methods had to send everything back to the server (ie, all the form's firlds, including hidden ones) and they only returned a value from the server. you don't need a postback to do this! if you need to send some values back to the server why not use javascript + web service method call or static page method call? they're a lot better that instance page methods!

if page methods updated the viwestate+control state, i'd be quite and i would be the 1st to say: bring them back. however, that didn't happened...so i'm not sure on where's the performance gain in using old page methods...can you see it?


One other thing to add. AutoEventWireup for the Page must be set to "true" or else the JS proxy is never generated.


hello.

as you can see by my previous sample, there's no need to have autoeventwireup set to true for gettig the proxy inserted on the client side. why?do?you?say?that?

Luis Abreu:

hello.

how about using an updatepanel or a web method? you do say that you need to refresh the UI...btw, i do think that you can access session state from a static method:

<%@. Page Language="C#" %
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"
<script runat="server">
[System.Web.Services.WebMethod]
public static int O()
{
HttpContext ctx = HttpContext.Current;
ctx.Session["i"] = Convert.ToInt32(ctx.Session["i"]) + 1;
return Convert.ToInt32( ctx.Session["i"] );
}

protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);

if (!this.IsPostBack)
{
HttpContext ctx = HttpContext.Current;
ctx.Session["i"] = 0;
}
}
</script
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager runat="server" ID="manager" />
<div>
<input type="button" runat="server" id="bt" onclick="handleClick()" />
</div>
</form>
<script type="text/javascript">
function handleClick()
{
PageMethods.O(function(res){ alert( res ); });
}

</script>
</body>
</html>

that sample simple returns an int. maybe you can adapt it so that it returns what you need.

I'm a relative novice to ASP.Net AJAX, so please forgive me if i'm doing something blaringly obviously wrong here, but i copied and pasted the code shown above exactly, and when i press the button on the form, instead of the number "0" being displayed in the alert box, it is in actual fact displaying the entire html source of the page.

Any idea why this is happening?

PageMethods static, ASMX and security

Hi,

I just tried out the PageMethods approach and at first, i got this weird "PageMethods not defined", then I found out that's because my codebhind method needs to be static. Why is that? Should I use asmx instead cuz i just feel weird to declare static methods everywhere in my codebehind.

If i use asmx for my ajax methods.. what if people start to hit my asmx directly outside of my website? I want to prevent ppl from directly accessing my webmethods. (I'm not that good with webservcies, but my understanding it of it is any .asmx page is accessible to the public?)

Please give me some of your insight into this matter. Thanks a lot.

Hi,

I'm not sure about what I'm going to say but it seems you can use Sessions to verify that a user is authenticated on your web site. By adding the EnableSession attribute to a WebMethod, you can access all the session data like in a normal aspx page. I tried that with an AutoCompleteExtender and a WebMethod, and the WebMethod doesn't return anything if the user isn't authenticated.

Hope this helps.

Laurent


Hi Laurent,

That's some good information. Do you know how can I enable the default membership authentication with it? like some types of attribute [authenticated=true] type of things?
Thanks a lot. That clears up some of my confusion.

There's no attribute for that that I'm aware of, but doing something like:

[WebMethod(EnableSession=true)]
public string HandsOffMyStuff()
{
if(!User.IsAuthenticated)
throw new Exception("hands off, jerky!");

/// Do cool stuff
}

will solve your issue for you.


Ah, coolbeans. thanks a lot. Strange that this wasn't documented anywhere, i'd imagine by NOT doing this, most of the ajax implementation are exposing themselves unnecessarily. Security aside, your bandwidth is exposed for usage. hm..

I just read by decorating <scriptservice> attribute will solve security issue, but I wasn't sure what they are talking about exactly. I'll have to test it out quickly.

Here is a blog talking about it.

http://portal.spidynamics.com/blogs/developersecurity/archive/2006/10/31/Web-service-security-improvement-in-ASP.NET-AJAX-beta-1.aspx

not much explaination.

Thanks though, I'll go with User.IsAuthenticated and EnableSession check


I don't believe you need "the EnableSession=true".

This is just regular ASP.NET authentication. .asmx files, just like .aspx files or .html files, are public to the world by default unless you restrict access via authentication. That's probably why you didn't find any ASP.NET AJAX-specific documentation about this.

The blog post you pointed to was just saying that in early prerelease versions of "Atlas", all the web services in your project became accessible to script, but now you need to put a [ScriptService] attribute on the ones you want to call from script, and the rest are only callable via SOAP. This is basically an attack surface reduction.


That depends on how you're doing authentication, though. If you're doing Forms authentication, for example, you don't want to put your web services in a restricted folder, b/c the redirect to login page is not desireable behavior w/ a web service. So instead what you can do is leave it in an 'open' folder but then check authentication on the Session object as described above.


okay. just to clarify, what happens if it's a public site which allows anonymous access, and all i want to do is grant access to the asmx services from javscript calls WITHIN my own website (by decorating it with <scriptservices> attribute right? Because I don't want anybody excpet me to use my backend service.

Deos this prevents other people from referencing my web services?, u know, visual studio->add web reference? (again, I've only done limited amount of work on webservices, such asking these questions...) I'll have to do some tests to clarify all these.

Fundamentally, if you allow unauthenticated users to access your web services from the browser, you can't prevent them from doing so from some other application. Even if you disable the SOAP protocols on your web service, someone could still write their own code to use JSON to talk to your service, or even simpler, they could do a File/Save As... in the browser to download a copy of your web page and just load it in the browser (possibly changing it to call your web service 30 times a second).


hm..ic and that's what i'm worried about... espeically some of my asmx services accepts input data (write to database) like membership regirstration...(good thing that I used an email confirmation mechnism and password is generated randomly on the backend) this way, i can prevent myself from spammers.

Okay... I'll have to research some more on this before I launch my public ajax enabled website, i just need to make myself comfortable first..

Thanks a lot guys.

Okay, just to follow up on my own thread... i did a few tests.

1. calling local ajax webservices from javascript within my own website.

With [ScriptServices] attribute, my javascript is able to call the webmethods of the .asmx file. [Success]
Without [ScriptServices], it fails. [Failed]

Remote Ajax .asmx services WITHOUT forms authentication
-----------------------------
2. calling a remote ajax .asmx services from my javascript (without forms authentication) [To Test]

3. calling a remote ajax .asmx services from my codebehind (without forms authentication) [Success]

Remote Ajax .asmx services WITH forms authentication
---------------------------
4. calling a remote ajax .asmx services from my javascript (with forms authentication) [To Test]

5. calling a remote ajax .asmx services from my codebehind (with forms authentication) [Failed]

So it confirms what everyone said above. By looking at #5 and #3), my conclusion this far is, if we have forms authentication enabled, my webservices is safe. But if my site allows anonymous access, such as a public site, we need to be careful.

For example, my public site's member registration page use an ajax method to register a new member of my website. By having this ajax method available, I'm able to call the method from another site, and automatically register new members. It's dangerous because if I loop 1000 times, I'm able to create 1000 members. This is an invite for spammers. If you go through my web page, at least I can prevent spammers by using CAPCHA image or whatever, through webservices, there is no protection from direct access.

Again, it's a good thing that I created users based on email confirmation.. but still, remote direct access will leave a lot of temporary data in my database.

So now, I will remove all "Write" ajax methods from my public website, at least I can prevent useless data. But my "read" .asmx servcies methods of the public site are still all open to everyone, everybody can call my webservices whenever they want from within their own application. I can see it'll cause unnecessary bandwidth.... then again, spammer could simply hit my webpages and it'll eat up my monthly bandwidth as well. Just feel like I opened up another door for them that's all.

*headache*


Oh yeah, another way is to use PageMethods.. this looks safe from remote access, but the question remains... if i have 100 ajax methods, they are all static, twhat's the "cost" on my webserver? 100 static methods for ajax??

Hi!

I think you are a bit pessimistic on this matter. Even on a public website, you have access to a user context, which includes a session. This way, there's always a workaround, like initiating a session object in your MasterPage and looking for this object in all your webmethods. I think that would prevent from most of the possible attacks, because a malicious user would have to create a much more complex program than including a web reference.

Anyway, this same malicious user would always be able to call your web service, even if the call fail. It's like downloading an image, by default it's always possible if you know the address. If your webmethods send data which cost a lot of bandwidth, you can create a monitoring system, which will verify that a same user doesn't call your webservice more than x times a second/minute, but that would be quite heavy...

Hope this helps,

Laurent