How do I open a popup message from C# in my javascriptAPP? - javascript

At the moment I am working on an APP. I am trying to find out why the methods from my webservices are not working but because I'm working with javascript in the app developer I am not able to debug my C# (Cordova and visual studio). Is there a way for me to write popups in the C# code so I can still see the values of my objects and properies?
So:
I want to be able to force a popup from C# while running the javascript APP because I can not debug my C# code since it's only a webservice.

Update:
This would be the normal way, C# is server-side and JavaScript is client-side. Inside of the web-method your C# should generate something like:
JavaScript serializer = new JavaScriptSerializer();
var response = serializer.Serialize(jsonObject);
Response.Write(response);
Response.End();
That would basically allow you to receive an object or collection back into the Ajax success or error for instance.
Since your utilizing a JavaScript Application, I'm under the notion that you're calling the service via Ajax. Your Ajax request will contain a success and error. These will allow you to return data from your Ajax.
// Sample:
$.ajax({
url: '...',
type: '...',
data: { Model : jsonObject },
success: function (response) {
// Response would be your C# Success.
},
error: function (response) {
// Response would be your C# Error.
}
});
The web-service should be serializing the response back for your web-service.
Our assistance will be minimal without seeing how you call the web-service, how the web-service responds, hopefully this helps you though.

Related

In javascript how do you open a file from the server?

Im working in an application that uses java + spring on the server side aswell as extdirectspring. On the client side it uses extjs/javascript.
I want to poke a method on the serverside and retrieve a file from the database. If the file doesn't exist then I'd like to display an error in some way.
The attempt to retrieve the file and the check it exists need to happen in the same call - the file could be deleted in between calls.
The way I can see people have done it in the current application is using spring controllers + request mappings and a window.open("someUrl/filename.blah"); with the server returning the file from the mapped method.
This doesnt seem to let you handle the case where the file doesn't exist though.
Ideally I'd just like to send some json back from the server which has the file data (possibly null) and sucess/failure. When I get the response I can then either show some information about the failure or open the file. Unfortunately I can't observe the current failure mode because something somewhere is caching the files - if I delete them from the database then they appear to still exist and you can still download them!
By 'open' I mean show the standard 'what do you want to do with this file open/save' dialog. I'm not trying to parse the file or do anything with it - I just want to serve it up to the browser/user.
Is there a way to do that without using a url and window.open? Eg some method that takes a blob of data and a file name or similar?
Update
The transfer of the data/json isn't the problem I'm trying to solve.
As I'm using extdirect I'll probably just do it like this:
public class SomeClass
{
#ExtDirectMethod
public AFile getFile(Long id) throws Exception
{
//do stuff
}
}
Then on the clientside you just do:
someClass.getFile(id, function(file){
if(file.found){
SomeHowGiveThisToTheUser(file.name,file.data); ????
return;
}
ReportCouldntFind(file.name);
});
The bit I dont know how to do is the give the file to the user.
Further update
I dont think it's possible to do this without blob urls or data uri's. Both of these are mentioned in this post. I haven't tried them out as we are having to support a browser that is too old for both techniques.
You are wanting to do some standard Ajax (Assuming you have jQuery available).
Something like:
$.getJSON( url, function( data ) {
if (data.success){
} else {
}
});
And on the server side, add code to return the expected JSON.
In extJS:
Ext.Ajax.request({
url : url,
method: 'GET',
headers: { 'Content-Type': 'application/json' },
params : params,
success: function (response) {
var jsonResp = Ext.util.JSON.decode(response.responseText);
if (response.success){
// do success stuff, like using response.fileData
} else {
// do fail stuff
}
failure: function (response) {
var jsonResp = Ext.util.JSON.decode(response.responseText);
// etc.
});
On the server in a Java servlet you could something like this (assumes apache commons file util):
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
InputStream in = new URL( "http://remote.file.url" ).openStream();
IOUtils.copy(in, response.getOutputStream());
}
Probably a more spring specific way to do it, but that gives you an idea.
For your case, you want to wrap the file contents in a JSON object that includes the success proeprty. For that, use the Java JSON jar: http://json.org/java/
Update: Finally understand what you are asking.
It finally occurred to me that you are asking how to handle the actual download.
There's a couple ways these days.
Take a look at this SO answer, this is using an iFrame: Download File Using Javascript/jQuery
There are also several fancy downloader components, including several for jQuery.
So you would do a two part process: check for the file availability using a standard ajax call, and then if response.success, use the downloader to serve the file to the user.

Feeding webpage data via remote Web API

I'm trying to operate two servers.
MVC Web API service.
MVC Web application.
The idea is that the web application renders a page filled with javascript requests, which populate the actual data from the remote API service. The web application will never itself touch the database, or the API service (besides setting up authorisation tokens initially).
What is the best way to achieve this?
So far I've been using JQuery AJAX requests, attempting to use JSONP. However I always get "x was not called" exceptions.
$.ajax({
url: '#(ViewBag.API)api/customer',
type: 'get',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: function (data) {
debugger;
// code to load to ko
},
error: function (xhr, status, error) {
alert(error.message);
}
});
Also the jsonpCallback function is called before the request is sent, so I assume its actually trying to call a function to generate a string? If I reform this request:
window.success = function (data) {
debugger;
// code to load to ko
};
... with jsonpCallback being "success", I still get the same error (but the success method is never called.
Any ideas? Thanks.
Edit: I've gotten started on the right course from this:
http://www.codeproject.com/Tips/631685/JSONP-in-ASP-NET-Web-API-Quick-Get-Started
Added the formatter, and replaced jsonCallback with success, like a normal ajax. However this only seems to work for get. I cannot delete or update. :(
Can you get it to work using the $.getJSON method?
$.getJSON( "ajax/test.json", function( data ) {
//handle response
});
Have you fired up developer tools in IE and watched the network traffic to see precisely what is being sent and returned?

How I get respone text in application and bind to the label in cross ajax call

I am calling the web service from other domain using Ajax call and I want to get returned response from server in my application by using following code I get response text in firebug but not in my JavaScript code. Control are not showing success and error response it goes out directly.
I want response in my success or error section but both not handling in this.
I am trying lot but not finding any solution please any one help me.
I am in a trouble. I hope somebody can help me for calling cross domain web service by using Ajax call. I am trying from 1 week but didn't find any solution till. I am getting response on browser but not getting it on my actual code.
My JavaScript code.
crossdomain.async_load_javascript(jquery_path, function () {
$(function () {
crossdomain.ajax({
type: "GET",
url: "http://192.168.15.188/Service/Service.svc/GetMachineInfo?serialNumber="+123,
success: function (txt) {
$('#responseget').html(txt);
alert("hii get");
}
});
crossdomain.ajax({
type: "POST",
url: "http://192.168.15.188/Server/Service.svc/GetEvents/",
// data: "origin=" + escape(origin),
success: function (txt) {
$('#responsepost').html(txt);
alert("hii post");
}
});
});
});
</script>
You can't simply ignore the Same Origin Policy.
There are only three solutions to fetch an answer from a web-service coming from another domain :
do it server-side (on your server)
let the browser think it comes from the same domain by using a proxy on your server
change the web service server, by making it JSONP or (much cleaner today) by adding CORS headers

How to consume WCF service in Windows8 HTML5/JS app?

I'm developing a win8 app, that should consume a WCF service hosted on IIS, but it wont...
NOTE: The Web service works just fine. I've tested it with the WCF Test Client in VS2012
Here's my code:
IService.cs:
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
[ServiceContract]
public interface IService
{
[OperationContract]
string SitePredmeti();
[OperationContract]
[WebInvoke(Method = "POST", BodyStyle = WebMessageBodyStyle.Wrapped, ResponseFormat = WebMessageFormat.Xml)]
List<Profesor> SiteProfesori();
}
i made two methods: one returns xml one returns json just so i can test which one works. it doesn't matter whether the WS returns json or xml, i can work with either in the app.
i use the default SPLIT APP TEMPLATE for a html5/JS app in win8 WITHOUT ANY CHANGES. for now i just need to consume the wcf service, i'll deal with the data templates later.
the url to my iis hosted wcf:
http://localhost/InformatorWS/Service.svc
here's what i've tried so far:
var baseURl = "http://localhost/InformatorWS/Service.svc/SitePredmeti/";
var url = baseURl+Number1.value+"/"+Number2.value;
WinJS.xhr({ url: url }).then(function (r) {
var result = JSON.parse(r.responseText);
ResultSpan.innerHTML = result; });
the error i get here is:
{"exception":null,"error":{},"promise":{"_oncancel":null,"_nextState":null,"_state":>{"name":"error","done":null,"then":null},"_listeners":null,"_value":{},"_isException":false,"_errorId":2},"id":2}
next i tried calling it via jquery ajax:
$(document).ready(function () {
jQuery.support.cors = true;
//Calling WCF Service using jQuery ajax method
$.ajax({
type: "GET",
async: "false",
url: "http://localhost/InformatorWS/Service.svc/SitePredmeti",
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (result) {
//AjaxSucceeded(result);
alert('ok')
},
error: alert('ne ok')
});
});
and when i link jquery
<script type="text/javascript" src="js/jquery-ui-1.8.9.custom.min.js"></script>
<script type="text/javascript" src="js/jquery-1.4.3.js"></script>
i get three exceptions:
Unhandled exception at line 10, column 2 in
ms-appx://66b782f9-8814-4b8e-a2e3-d6e73893690a/js/jquery-ui-1.8.9.custom.min.js
0x800a1391 - JavaScript runtime error: 'jQuery' is undefined
(and two of these - for the two alert in success and error)
Unhandled exception at line 8, column 9 in
ms-appx://66b782f9-8814-4b8e-a2e3-d6e73893690a/js/default.js
0x800a1391 - JavaScript runtime error: 'alert' is undefined
anyone have any idea what i am doing wrong? or just anyone know any way of consuming a WCF service hosted on IIS?
Thank you very much in advance.
There may be a couple of issues at play here. You need different endpoints to be consumed by the WCFTestClient and JavaScript. For the first, you need a SOAP endpoint, but for the second you need a non-SOAP (a.k.a. REST) endpoint. Since you didn't mention in your question, I'm assuming you only have one endpoint, and since the WCFTestClient works, it's a SOAP endpoint, which doesn't work for JavaScript 1. If this is the case, add a new Web endpoint to your service (or replace the one you have with that)2. You can read more about web endpoints in the WCF Web HTTP Programming Model doc at MSDN.
1 In theory, it's possible to call SOAP endpoints with JavaScript (especially if the endpoint is using some simple binding like BasicHttpBinding). But you'll need to create the XML payload to send to it, and format it according to the SOAP specification - not the JSON payload which you're sending and expecting as a result.
2 And if you do that - have only one, non-SOAP, endpoint, WCF Test Client will not work with it anymore, but that's expected, since it tries to consume the service WSDL to talk to it.

AD FS 2.0 Authentication and AJAX

I have a web site that is trying to call an MVC controller action on another web site. These sites are both setup as relying party trusts in AD FS 2.0. Everything authenticates and works fine when opening pages in the browser window between the two sites. However, when trying to call a controller action from JavaScript using the jQuery AJAX method it always fails. Here is a code snippet of what I'm trying to do...
$.ajax({
url: "relyingPartySite/Controller/Action",
data: { foobar },
dataType: "json",
type: "POST",
async: false,
cache: false,
success: function (data) {
// do something here
},
error: function (data, status) {
alert(status);
}
});
The issue is that AD FS uses JavaScript to post a hidden html form to the relying party.
When tracing with Fiddler I can see it get to the AD FS site and return this html form which should post and redirect to the controller action authenticated. The problem is this form is coming back as the result of the ajax request and obviously going to fail with a parser error since the ajax request expects json from the controller action. It seems like this would be a common scenario, so what is the proper way to communicate with AD FS from AJAX and handle this redirection?
You have two options.
More info here.
The first is to share a session cookie between an entry application (one that is HTML based) and your API solutions. You configure both applications to use the same WIF cookie. This only works if both applications are on the same root domain.
See the above post or this stackoverflow question.
The other option is to disable the passiveRedirect for AJAX requests (as Gutek's answer). This will return a http status code of 401 which you can handle in Javascript.
When you detect the 401, you load a dummy page (or a "Authenticating" dialog which could double as a login dialog if credentials need to be given again) in an iFrame. When the iFrame has completed you then attempt the call again. This time the session cookie will be present on the call and it should succeed.
//Requires Jquery 1.9+
var webAPIHtmlPage = "http://webapi.somedomain/preauth.html"
function authenticate() {
return $.Deferred(function (d) {
//Potentially could make this into a little popup layer
//that shows we are authenticating, and allows for re-authentication if needed
var iFrame = $("<iframe></iframe>");
iFrame.hide();
iFrame.appendTo("body");
iFrame.attr('src', webAPIHtmlPage);
iFrame.load(function () {
iFrame.remove();
d.resolve();
});
});
};
function makeCall() {
return $.getJSON(uri)
.then(function(data) {
return $.Deferred(function(d) { d.resolve(data); });
},
function(error) {
if (error.status == 401) {
//Authenticating,
//TODO:should add a check to prevnet infinite loop
return authenticate().then(function() {
//Making the call again
return makeCall();
});
} else {
return $.Deferred(function(d) {
d.reject(error);
});
}
});
}
If you do not want to receive HTML with the link you can handle AuthorizationFailed on WSFederationAuthenticationModule and set RedirectToIdentityProvider to false on Ajax calls only.
for example:
FederatedAuthentication.WSFederationAuthenticationModule.AuthorizationFailed += (sender, e) =>
{
if (Context.Request.RequestContext.HttpContext.Request.IsAjaxRequest())
{
e.RedirectToIdentityProvider = false;
}
};
This with Authorize attribute will return you status code 401 and if you want to have something different, then you can implement own Authorize attribute and write special code on Ajax Request.
In the project which I currently work with, we had the same issue with SAML token expiration on the clientside and causing issues with ajax calls. In our particular case we needed all requests to be enqueud after the first 401 is encountered and after successful authentication all of them could be resent. The authentication uses the iframe solution suggested by Adam Mills, but also goes a little further in case user credentials need to be entered, which is done by displaying a dialog informing the user to login on an external view (since ADFS does not allow displaying login page in an iframe atleast not default configuration) during which waiting request are waiting to be finished but the user needs to login on from an external page. The waiting requests can also be rejected if user chooses to Cancel and in those cases jquery error will be called for each request.
Here's a link to a gist with the example code:
https://gist.github.com/kavhad/bb0d8e4a446496a6c05a
Note my code is based on usage of jquery for handling all ajax request. If your ajax request are being handled by vanilla javascript, other libraries or frameworks then you can perhaps find some inspiration in this example. The usage of jquery ui is only because of the dialog and stands for a small portion of the code which could easly be swapped out.
Update
Sorry I changed my github account name and that's why link did not work. It should work now.
First of all you say you are trying to make an ajax call to another website, does your call conforms to same origin policy of web browsers? If it does then you are expecting html as a response from your server, changedatatype of the ajax call to dataType: "html", then insert the form into your DOM.
Perhaps the 2 first posts of this serie will help you. They consider ADFS and AJAX requests
What I think I would try to do is to see why the authentication cookies are not transmitted through ajax, and find a mean to send them with my request. Or wrap the ajax call in a function that pre authenticate by retrieving the html form, appending it hidden to the DOM, submitting it (it will hopefully set the good cookies) then send the appropriate request you wanted to send originally
You can do only this type of datatype
"xml": Treat the response as an XML document that can be processed via jQuery.
"html": Treat the response as HTML (plain text); included script tags are evaluated.
"script": Evaluates the response as JavaScript and evaluates it.
"json": Evaluates the response as JSON and sends a JavaScript Object to the success callback.
If you can see in your fiddler that is returning only html then change your data type to html or if that only a script code then you can use script.
You should create a file anyname like json.php and then put the connection to the relayparty website this should works
$.ajax({
url: "json.php",
data: { foobar },
dataType: "json",
type: "POST",
async: false,
cache: false,
success: function (data) {
// do something here
},
error: function (data, status) {
alert(status);
}
});

Categories

Resources