I have an ASP.Net application with a button containing the following Javascript to be invoked when it is clicked:-
function calculate() {
sectionIndex = getSelectedRadioIndex("section");
compositionIndex = getSelectedRadioIndex("composition");
CallBackOU.callback( "calculate" , sectionIndex, compositionIndex );
}
I can verify that control reaches the last line of this function by setting a breakpoint on it. But instead of invoking the method in the code-behind file...
protected void CallBackOU_Callback (object sender, ComponentArt.Web.UI.CallBackEventArgs e)
{
//blah blah
}
I get a dialogue reporting
Callback Error: Invalid response from server.
This dialogue appears three times, after which the page sits there doing nothing (forever, so far as I can make out).
I can't find any information about this. Can anyone give me any clues or pointers about how to go about diagnosing the problem?
Without seeing the signature of the calculate callback method this is only a shot in the dark but some issues i have encounter when invoking web methods from javascript are make sure the method is properly decorated [WebMethod], make sure the method is static, make sure the parameters are of the correct type and named properly (they are infact case sensitive when deserializing JSON iirc). A little more information regarding how the call is made (JSON/XML) and the signature might help. Also, you can try using fiddler to see if you get any more information regarding the error.
Related
I've been struggling for hours on this one. I keep getting "Value does not fall within the expected range" when I call one of my web service functions. I'm using a POST method to which I'm passing a json object and expecting some json data to be returned.
It doesn't make sense as I've got other web service functions working perfectly well and most annoyingly, it works a perfectly when called from Fiddler 2.
I'm calling the following code in a try/catch
string jsonResponse = await wc.UploadStringTaskAsync(new Uri(App.WebServiceUri + "/json/getdocumentbydocid"), jsonRequest);
I've put break points in my code and when called from fiddler, it goes into the specific function but when called through code, it generates the exception "Value does not fall within the expected range" but it isn't caught in the try/catch
It bombs out straight to
private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs
e)
Maybe it's not being caught by the try/catch because I'm calling this from an async function:
public static Task<string> UploadStringTaskAsync(this WebClient wc, Uri url, string data)
{
var tcs = new TaskCompletionSource<string>();
wc.UploadStringCompleted += (s, e) =>
{
if (e.Error != null)
tcs.TrySetException(e.Error);
else if (e.Cancelled)
tcs.TrySetCanceled();
else
tcs.TrySetResult(e.Result);
};
wc.UploadStringAsync(url, "POST", data);
return tcs.Task;
}
but it still doesn't explain my error. I'm not dealing with any list or similar, so again I have to assume that it's something related to the uri, but that's not it either!
After I the error is caught in Application_UnhandledException, and continue running the app, it actually calls my code and returns the appropriate data but my app has bombed out.
It just doesn't make sense! The json object pass is a simple poco object which contains a string (table name), a long (docid) and a int (page no) and it returns a poco object, again none containing list or similar, so I don't understand what this error mean and why does it work perfectly for every other functions defined in my web service.
Any ideas?
Thanks.
UPDATE:
This is the second time I'm changing this answer!! I deleted my original one and I thought I had it fixed and provided the details but it wasn't the correct reason.
I'm so fed up getting this wrong but at least I'm learning something in the process but the error still doesn't make sense, well at least not to me!
I thought it was related to dodgy xaml, or not having a lazy load when calling my async function from the constructor, but that's not the case.
While I had dodgy code, I'm pretty sure now that I've cleared it up and all is set up as expected but I'm still getting the error.
I have a third-party control that needs to be on a UserControl. My UserControl has a single property i.e. SourceFile of type string
public string SourceFile
{
get
{
return _sourceFile;
}
set
{
_sourceFile = value;
}
}
This property is binded to a property from my viewModel i.e. DocumentUri
public string DocumentUri
{
get { return this._documentUri; }
set
{
if (this._documentUri != value)
{
this.SetProperty(ref this._documentUri, value);
}
}
}
The SetProperty takes care of the INotifyPropertyChanged and my event handler is definitely being set.
Now here is my xaml code:
<Grid Grid.Row="1">
<StackPanel Orientation="Vertical">
<cc:Viewer SourceFile="{Binding DocumentUri}" />
</StackPanel>
</Grid>
Where cc:Viewer is my UserControl.
When set as the above, I get the following error: "Value does not fall within the expected range."
If I remove the SourceFile="{Binding DocumentUri}", the error disappears but that's pointless as I need this property to display my document when it is downloaded. It just confirms that it is in fact linked to this property.
Any ideas?
Thanks.
Thierry
I deleted my original answer as I just spotted what was causing the problem and this time I'm 100% sure of it.
While I thought it was maybe related to dodgy xaml, or not having a lazy load when calling my async function from the constructor, it was a combination of things.
The error thrown is totally misleading!! It was due to a combination of things:
Calling an async from the constructor without using the Asynchronous Initialization Pattern.
Not checking if values were blank in my constructor and properties
Creating a property in my UserControl which wasn't binded. I just created a regular property when I should have in fact have created a property using DepencyProperty to make it bindable.
Once all of the above were correct, my problem got sorted.
I have made a web service and clients will call its methods. Suppose one method takes four parameters and I want to check that if any one of these is empty I want to send a response back to the client and I want to send it like an alert so client knows what argument is empty. I can not force client to give all parameters accurate. Is this possible?
[WebMethod]
Public void Method1(string str1,string str2,string str3,string str4)
{
if((str1=="") || (str2==""))
{
//send response back to client in form of an alert
}
}
As far as I know, you can send some agreed-upon object back to the sender, which the sender should be prepared to receive. It could be as simple as a string that contains "OK" or "ERROR", or it could be complex and have an error code, description, severity level, etc. What the sender does with it when they consume it is completely up to them though.
You could, for instance, make one of the fields in your response a severity level (maybe using something like Microsoft's Severity enum), which the sender could then use to determine whether they display an alert to their users or simply log the error somewhere on their system.
Don't reinvent the wheel with custom objects. Look at this MSDN article.
The easiest thing is just to throw an exception (sounds like an ArgumentException is appropriate in your case) and the client will receive a SoapException.
Or throw a SoapException yourself if you want more control, such as the ability to set a fault code.
You said you can't control the person calling the web method. As the method is of type void, the user will only know if something drastic happens. How about throwing an exception, and the error will propagate, to what detail it depends on the settings of the web server hosting the web service and the web server hosting the client (if the client is a web page).
throw new Exception("str1 or str2 in Method1 is empty");
In the "best" case, the user will see the error message "str1 or str2 in Method1 is empty. In the "worst" case, the user will get the standard IIS/ASP.NET error page. Like you said you have no control over the caller, it depends on how the caller codes the client and how he deploys the application. But whatever the case, it gets his attention!
I put best and worst in quotes because best and worst mean different things to different people. For people who want maximum security, best is when the error page says nothing about the error. For people who want user friendliness and fast troubleshooting, best is when the error message has a lot of details and what to do next.
This is rather weird issue that I am facing with by WCF/Silverlight application. I am using a WCF to get data from a database for my Silverlight application and the completed event is not triggering for method in WCF on some systems. I have checked the called method executes properly has returns the values. I have checked via Fiddler and it clearly shows that response has the returned values as well. However the completed event is not getting triggered. Moreover in few of the systems, everything is fine and I am able to process the returned value in the completed method.
Any thoughts or suggestions would be greatly appreciated. I have tried searching around the web but without any luck :(
Following is the code.. Calling the method..
void RFCDeploy_Loaded(object sender, RoutedEventArgs e)
{
btnSelectFile.IsEnabled = true;
btnUploadFile.IsEnabled = false;
btnSelectFile.Click += new RoutedEventHandler(btnSelectFile_Click);
btnUploadFile.Click += new RoutedEventHandler(btnUploadFile_Click);
RFCChangeDataGrid.KeyDown += new KeyEventHandler(RFCChangeDataGrid_KeyDown);
btnAddRFCManually.Click += new RoutedEventHandler(btnAddRFCManually_Click);
ServiceReference1.DataService1Client ws = new BEVDashBoard.ServiceReference1.DataService1Client();
ws.GetRFCChangeCompleted += new EventHandler<BEVDashBoard.ServiceReference1.GetRFCChangeCompletedEventArgs>(ws_GetRFCChangeCompleted);
ws.GetRFCChangeAsync();
this.BusyIndicator1.IsBusy = true;
}
Completed Event....
void ws_GetRFCChangeCompleted(object sender, BEVDashBoard.ServiceReference1.GetRFCChangeCompletedEventArgs e)
{
PagedCollectionView view = new PagedCollectionView(e.Result);
view.GroupDescriptions.Add(new PropertyGroupDescription("RFC"));
RFCChangeDataGrid.ItemsSource = view;
foreach (CollectionViewGroup group in view.Groups)
{
RFCChangeDataGrid.CollapseRowGroup(group, true);
}
this.BusyIndicator1.IsBusy = false;
}
Please note that this WCF has lots of other method as well and all of them are working fine.... I have problem with only this method...
Thanks...
As others have noted, a look at some of your code would help. But some things to check:
(1) Turn off "Enable Just My Code" under Debug/Options/Debugging/General, and set some breakpoints in the Reference.cs file, to see whether any of the low-level callback methods there are getting hit.
(2) Confirm that you're setting the completed event handlers, and on the right instance of the proxy client. If you're setting the event handlers on one instance, and making the call on another, that could result in the behavior you're describing.
(3) Poke around with MS Service Trace Viewer, as described here, and see if there are any obvious errors (usually helpfully highlighted in red).
Likely there are other things you could check, but this will keep you busy for a day or so :-).
(Edits made after code posted)
(4) You might want to try defining your ws variable at the class level rather than the function. In theory, having an event-handler defined on it means that it won't get garbage collected, but it's still a little odd, in that once you're out of the function, you don't have a handle to it anymore, and hence can't do important things like, say, closing it.
(5) If you haven't already, try rebuilding your proxy class through the Add Service Reference dialog box in Visual Studio. I've seen the occasional odd problem pop up when the web service has changed subtly and the client wasn't updated to reflect the changes: some methods will get called successfully, others won't.
(6) If you're likely to have multiple instances of a proxy client open at the same time, consider merging them into one instance (and use the optional "object userState" parameter of the method call to pass the callback, so you don't run into the nasty possibility of multiple event handlers getting assigned). I've run into nasty problems in the past when multiple instances were stepping on each other, and my current best practice is to structure my code in such a way that there's only ever one client instance open at a time. I know that's not necessarily what MS says, but it's been my experience.
This issue is because of special characters in one of the fields returned from DB which browser was not able to render. After considerable debug n search over the web, was able to find this out. Used Regular expressions to remove these special characters in WCF, the new returned values from the method was successfully rendered in various browsers on different system. :)
Make sure you have checked 'Generate asynchronous operations' in your service reference. Right-click on the service reference and check the box. This solved it for me.
I am in a bit tricky situation. I am using JavaScript's PageMethod functionality where I am invoking a PageMethod which works like a gem. However I am having an issue in accessing the HttpContext's state which returns me a value "SYSTEM" for
HttpContext.Current.User.Identity.Name
which is not the actual current User Name.
I know there are couple options like storing HttpContext.Current in a Session or saving Context's state in some other custom container but given a web farm environment I am assuming that this will not work as expected.
Here is the code I am working on with
function MyFunction(){
PageMethod.MyPageMethod();
}
here is the signature of the server method
[System.Web.Services.WebMethod()]
public static void MyPageMethod()
{
// gives me "SYSTEM"
var user = HttpContext.Current.User.Identity.Name;
}
Also if I use the above code to access user name in OnLoad event of the page then it works fine and returns me the CurrentUserName.
I am trying to get the above code to work in an ASP.NET Webform... :)
So I am wondering if there is a way to access the current actual user in page methods without making use of sessions.
Any help will be deeply appreciated.
NiK...
After quite some reading I think I was trying to do something which is not correct as to how page methods work. It gets quite tricky when your application's authentication system is windows based and these page methods when you invoke from JavaScript will not cause a postback and do not invoke the HttpModules. Instead it just calls that page method.
FYI, we had our own custom HTTPModule to handle security.This is even before any other HttpModule occurs and this was not being invoked while calling the page method as we are not doing a postback or even a partial postback (so the whole "niche" of a HTTPPost was missing). Moreover this led to a conclusion that we were making service calls without any authentication and was potentially a big security issue for us.
The bottom line is it was a bad design, well having said that I would like to mention about the solution/workaround we came up with and here is what we did. So, the only option we had is to do a postback keeping the UI alive and we wanted to update a label's message asynchronously and we achieved it by doing a hack using Sys.Application.add_init.
<script language="javascript" type="text/javascript" >
Sys.Application.add_init(function() {
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(endRequest);
});
function beginProcess() {
processCurrentItem();
}
var currentItem = 0;
function processCurrentItem() {
if (currentItem < 5) {
currentItem = currentItem + 1;
__doPostBack('updatePanel', currentItem);
}
}
function endRequest() {
processCurrentItem();
}
</script>
The markup we had in place was pretty simple with a label in the update panel and a button that invokes the "beginProcess()" function. Finally in the OnLoad we had the following code in place
protected override void OnLoad(EventArgs e)
{
if (this.IsPostBack)
{
this.lblLabel.Text = "text you may wanna update with";
// Call the Method you may wanna call
// also you may use Request["__EVENTARGUMENT"] to know who caused the
// postback and Request["__EVENTTARGET"] to access the argument you may
// have passed in.
}
}
And this solution is no longer using the JavaScript Page methods. And based on this solution if anyone thinks I am missing something here or think there is any other other way of doing this then do update this post with your suggestions.
NiK
I have a javascript call to a C# WebMethod. The same page has another call and it is working. I debugged the javascript code, this is called:
function userUpdReq_onOk()
{
...
var clientValidationPassed =Page_ClientValidate();
if( clientValidationPassed )
{
PageMethods.RequestUserUpdate(username, email, sex, zipCode, state, city, neighborhood, address, addressNumber, addressComplement, phone, promotionalInfo, connectionType, connectionSpeed, userUpdReq_OnComplete, userUpdReq_OnError);
}
...
}
The debugger passes by this line, but the next method it enters is userUpdReq_OnError( ). Why does it happen?
What is the message in error argument passed to userUpdReq_OnError()?
The OnError method is called when an error occurs inside of your page method. Sometimes this will be a casting issue, or a server error for some other reason. The error message passed to your OnError method should be able to guide you to the reason for the failure.
To get the error message, you can define the error handler as follows:
function userUpdReq_OnError(error){}
The error parameter will have a message indicating the reason for the failure.
Here is another issue "innocent" I think but it givme a lot troubbles, however, for some unknown reason, in some place aspx lost some reference to ScriptManager, so, what we must do to fix it is remove ScriptManager from aspx, add it again and set EnablePageMethods located in properties window to true.
Regards.