I use PageMethods to return parameters from the client-side to the server-side. Something like this:
if (/*node has no kids*/) {
PageMethods.ApplicationInfo(node.data.key, node.data.title, onSuccess, onFailed);
<%=Page.ClientScript.GetPostBackEventReference(this, "MyCustomArgument") %>
}
else {
PageMethods.ApplicationInfo(0, "", onSuccess, onFailed);
}
My web method:
[WebMethod(EnableSession = true)]
public static void ApplicationInfo(int appId, string appDescr)
{
curAppId = appId;
curAppDescription = appDescr;
}
As you can see, I invoke a postback if the condition is true.
So, the problem is the web method runs smoothly and ends in onSuccess function in the 'else' condition, but gives me the 'server method failed' error otherwise.
What can cause it? Thanks a lot in advance!
EDIT
Ok problem changed.
I moved the postback to the onSuccess function, and stopped getting the mistake.
Locally, everything works fine, but the data which I pass to ApplicationInfo somehow are not passed, when I try to launch the site from the server.
What can be the problem?
Related
I have a updatepanel that is updated using timer every one second.
I also have async postback error handler set up in javascript as following:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onEndRequest);
function onEndRequest(sender, args) {
var error = args.get_error();
if (error != null) {
args.set_errorHandled(true);
alert(error.message);
}
}
when I refresh the page manually or click a hyperlink I get the following error in endRequest handler:
An unknown error occurred while processing the request on the server.
The status code returned from the server was: 0
How can i prevent this behavior?
Thanks
I figured it out.
For thoue who have the same problem, here is the code to determine if script manager async postback is currently running:
Sys.WebForms.PageRequestManager.getInstance().get_isInAsyncPostBack()
to cancel it call:
Sys.WebForms.PageRequestManager.getInstance().abortPostBack();
I just call the cancel method directly. It does not not anything when request is not running.
I am using signalr 0.4 on an aspx-Page,
var hub = $.connection.FooHub;
hub.disconnected(function () {
log("Server has disconnected");
});
hub.ShowInfo = function (Info) { .... }
$("#Button1").click(function () {
hub.FooFunction('foo');
});
$.connection.hub.start();
The Hub is defined as :
public class FooHub : Hub, IDisconnect
{
~FooHub()
{
log.Debug("FooHub Destroy");
}
public FooHub()
{
log.Debug("FooHub Startup");
}
public bool FooFunction(string stuff)
{
log.Debug("Hub FooFunction");
Clients.ShowInfo(someInfo);
return true;
}
public Task Disconnect()
{
// Query the database to find the user by it's client id etc. etc.
MyController.Disconnect(Context.ConnectionId);
log.Debug("Hub Disconnnect " + Context.ConnectionId);
return null;
}
......
}
When i open the page and immediately click on Button1
it calls the Hub which in turn calls the ShowInfo-function on the page.
With Firebug i can see that signalr is using long-polling for the communcation.
So everything works as expected.
But when i then wait a couple of minutes
i see that
FooHub is destroyed
Disconnect is called in the Hub,
however on the Page there is no new connection
Firebug shows the old one still being executed
and when i then click on the Button -
FooFunction is called (i see a new connection in firebug)
FooHub is created
FooFunction is executed in the Hub (there is a line in the Log)
but ShowInfo is not executed
Is this a bug in SignalR or do i have to do something else to get the ShowInfo-call?
Update (Possible answer):
It was using a Forever-Frame and not long-polling.
In addition, the problem seems to happen mostly when using mobile internet (usb-stick) and Firefox.
Changing the transport to long-Polling seems to fix this issue.
You mention switching to long polling instead of using a forever frame but didn't say how to do that. You can specify which transports to try when starting the connection.
connection.start({ transport: ['longPolling','webSockets'] });
See https://github.com/SignalR/SignalR/wiki/SignalR-JS-Client for more options.
Did u look at this https://github.com/SignalR/SignalR/wiki/Configuring-SignalR
Try this see. To me as per your code every thing seems to be OK. Also can you test the same in Chrome and see whats happening.
I'm just getting into QUnit testing, and have run into a problem on my first page :S
We use ASP.NET Service References to take advantage of async data loading on html pages, creating a reference to a web service in the same project. What ASP.NET does behind the scenes (ScriptManager control) is create a JS file representing the service methods and handling all the AJAX calling.
Using this, I have a page that calls one of these methods in the document.ready jQuery event. I'm now trying to test against this js file using QUnit, but avoid having the js file call the actual web service and use a mock service instead. Here's what I have for an attempt so far:
main.js (production code file)
var Service;
$(document).ready(function () {
//class definition created by asp.net behind the scenes
Service = MyProject.services.DataService;
//the method that calls the service
LoadData();
});
function LoadData() {
Service.GetData(OnGetDataSuccess, OnGetDataFailure);
}
main-test.js (test QUnit code, main.js is referenced in this page)
function SetupMockService(result) {
Service = { "GetData": function (OnSuccess, OnFailure) {
GetDataCalled = true;
OnSuccess(result);
//this is required in an asyncTest callback, I think?
start();
}, "GetDataCalled": false};
}
$(document).ready(function () {
module("LoadData");
asyncTest("LoadData should call GetData from service", function () {
SetupMockService(result);
LoadData();
equals(Service.GetDataCalled, true, "GetData has been called");
});
This test fails. The LoadData method is called as part of the original (main.js) document.ready event, so it still calls the production web service, and the tests fail because that GetDataCalled variable is never set (or defined in production). Am I doing the asyncTest wrong? (This is my first day with QUnit, so I could very well be)
The other way I can see this working is if I can override the main.js document.ready event, but I'm not quite sure on how to do that. I also don't want to add "testEnvironment == true" checks to my production main.js code.
Turns out I had things a bit backwards, as well as one obvious mistake. Here's the resulting code that works
main-tests.js
//the test itself isn't calling async methods, so it doesn't need to use asyncTest
test("LoadData should call GetData from service", function () {
SetupMockService();
LoadData();
equals(Service.GetDataCalled, true, "GetData has been called");
});
function SetupMockService() {
//redefining the Service variable specified in main.js with a mock object
Service = { "GetData": function (OnSuccess, OnFailure) {
//I forgot the "this" part... d'oh!
this.GetDataCalled = true;
}, "GetDataCalled": false
};
}
This still doesn't fix the issue with the original main.js's document.ready code being executed, but I'll figure that out.
I have been struggling to get my jquery call to a webmethod to work. I am being bounced by the server with a "401 Unauthorized" response. I must have an incorrect setting in the web.config or somewhere else that would be preventing a successful call.
Your insight is appreciated!
Call to js function the invokes the jquery call
button.OnClickAction = "PageMethod('TestWithParams', ['a', 'value', 'b', 2], 'AjaxSucceeded', 'AjaxFailed'); return false;";
JavaScript function that makes the jquery call
function PageMethod(fn, paramArray, successFn, errorFn) {
var pagePath = window.location.pathname;
var urlPath = pagePath + "/" + fn;
//Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
var paramList = '';
if (paramArray.length > 0) {
for (var i = 0; i < paramArray.length; i += 2) {
if (paramList.length > 0) paramList += ',';
paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
}
}
paramList = '{' + paramList + '}';
//Call the page method
$.ajax({
type: "POST",
url: pagePath + "/" + fn,
contentType: "application/json; charset=utf-8",
data: paramList,
timeout: 10000,
dataType: "json",
success: function(result) { alert('Overjoyed'); },
error: function(result) { alert('No joy'); }
});
}
Web method in page
public partial class WebLayout : System.Web.UI.Page
{
[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}
...
Response as seen in Firebug console
json: {"Message":"Authentication failed.","StackTrace":null,"ExceptionType":"System.InvalidOperationException"}
and
"NetworkError: 401 Unauthorized - http://localhost/Care-Provider-Home/Profile/Personal-Profile.aspx/TestWithParams" TestWithParams
I have looked at and read the usual sites on the subject (Encosia, et al), but to avail. Either I am missing a critical piece, or there are some subtleties in the security parameters of my environment that preventing a call.
Here are some other potentially useful tidbits that may impact your diagnosis:
Webmethods in codebehind
Using Sitecore CMS (Does not seem to intefere, never know)
IIS7
.NET 3.5
jQuery 1.3.2
I look forward to your insights and direction--thank you!
Yes, it did get working! Since Sitecore CMS does perform URL rewriting to generate friendly URLs (it assembles the pages in layers, dynamically, similar to Master Page concept), it occurred to me that it may be causing some problem the initially caused the 401 error. I verified this by creating a separate project with a single ASPX--and with some work I was able call the web methods and get values using the jquery. I then created nearly identical ASPX in my web root, but told Sitecore to ignore it when a request is made to it (IgnoreUrlPrefixes in the web.config), after some work I was able also get it to work successfully! Thanks for your help.
The json response from the Firebug Console provides the most telling clue IMO. The System.InvalidOperationException (which strangely rides on a 401 response) suggests something more is at work.
First, googling on "InvalidOperationException webmethod jquery" returns articles which suggest serialization problems can throw this exception. To rule this out, temporarily change "data: paramList" to "data: '{}'". In addition, attach a debugger and see if the exception happens before the method executes or after it completes and attempts to serialize the result.
If the steps above come up empty, you may want to try resetting to a clean web.config or read more of the results that come back from the "InvalidOperationException webmethod" search
What form of authentication are you using, if any? The first thing that comes to mind is to make sure that your webApp in IIS is set to allow anonymous users (if you indeed desire to make the call as an anonymous user). Also that your Authentication mode in web.config is not set to Windows by mistake. If you cannot allow anonymous users and are using forms authentication, then the user will have to be logged in before this call is made from your page.
If the above are properly set, then try making a regular call to the service from server side to make sure the problem is consistent regardless of the point of invocation of the service.
Post more settings if the problem is not resolved. Hope this helps.
Can anyone help? I have an issue with calling a asp.net webservice from jquery.. actually i think it maybe jquery ... as i have a break point and it doesn't arrive in the webservice..
Here is my jquery, the webservice method accepts 2 parameters...
So i setup a simple test to pass in 7 and 7 .. i tried replacing with the word "test" also and it doesn't work..
Basically lands in the error function which displays "sorry error happens" but the err is undefined.
jQuery.ajax({
type: 'POST'
, url: 'CallService.asmx/TempCanMakeCall'
, contentType: 'application/json; charset=utf-8'
, dataType: "json"
, data: "{'reservationNum':'7','completedReservationNum':'7'}"
, success: function(data, status) {
alert(data);
}
, error: function(xmlHttpRequest, status, err) {
alert('Sorry! Error happens.' + err);
}
}
);
Here is the asp.net webservice
[WebMethod()]
public bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}
xmlHttpRequest.responseText has always been my goto when dealing with jQuery AJAX errors.
Try making your ASP.NET function static:
[WebMethod()]
public static bool TempCanMakeCall(string reservationNum, string completedReservationNum )
{
return true;
}
Also note that the returned JSON value is encapsulated in an object named 'd' (ASP.NET specific.) To display your return value upon success, you would need to do this:
success: function(data, status) {
alert(data.d);
}
The jquery ajax call looks fine. I think you need to make sure that the path to "CallService.asmx" is correct. The way it is now, I will only work if the file making the jQuery call is in the same virtual directory as the ASMX.
In your error callback function, you could check 'xmlHttpRequest.status' to get the http code returned from the server. This may give you another clue. If ichiban above is correct, it should be a 404.
You can check the xmlHttpRequest.responseText property. The response text is very probably an html document returned by the server that contains the reason for the error.
If you are using Visual Studio, you can also enable script debugging in Internet Explorer and put the following keyword in your error function: debugger. The browser sees this as a breakpoint and will invoke a debugger (which should be Visual Studio). Now you can check the entire contents of the xmlHttpRequest instance.
For clarity, your error function will then look like this:
function(xmlHttpRequest, status, err)
{
debugger;
...rest of your function...
}