Consume WCF Rest Service in ASP.net using jquery - asp.net-mvc

I am trying to consume a wcf rest api in a asp.net project using jquery. for doing so i have done:
Created a WCF Rest service source code can be downloaded from here.
Created a ASP.Net project to consume that restAPI using jquery. source code here.
In ASP .Net project on the click of button I am trying to call a REST service. But every time I gets two issues:
calling var jsondata = JSON.stringify(request); in TestHTML5.js throws an error saying "Microsoft JScript runtime error: 'JSON' is undefined"
When I press ignore it continues towards WCF Rest API call but it always returns error (Not Found) function. Rest API never gets called.
Thanks for every one's help in advance.
ANSWER:
Solution and source link can be found on this link.

I have looked at the sample code you provided and the problem is that you are violating the same origin policy restriction. You cannot perform cross domain AJAX calls. In your example the service is hosted on http://localhost:35798 and the web application calling it on http://localhost:23590 which is not possible. You will have to host both the service and the calling application in the same ASP.NET project. You seem to have attempted to enable CORS on the client side using ($.support.cors = true;) but on your service doesn't support CORS.
Another issue saw with your calling page (TestHTML5.htm) is the fact that you have included jquery twice (once the minified and once the standard version) and you have included your script (TestHTML5.js) after jquery. You should fix your script references. And yet another issue is the following line <script type="text/javascript"/> which is invalid.
So start by fixing your markup (I have removed all the CSS noise you had in your markup in order to focus on the important parts):
<!DOCTYPE html>
<html dir="ltr" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>SignUp Form</title>
<script type="text/javascript" src="../Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../Scripts/TestHTML5.js"></script>
</head>
<body>
<button id="Send" onclick="testHTML5OnClick();">
Send Me ID!
</button>
</body>
</html>
and then in your TestHTML5.js you could also clean a little bit. For example your service is listening for the following url pattern json/{id} and accepting only GET verbs and you are attempting to use POST which is not possible. In addition to that you are attempting to use the JSON.stringify method which doesn't make any sense with the GET verb. You should simply send the id as part of the url portion as you defined in your service.
function testHTML5OnClick() {
var id = 5;
var url = "../RestServiceImpl.svc/json/" + id;
var type = 'GET';
callLoginService(url);
}
function callLoginService(url, type) {
$.ajax({
type: type,
url: url,
success: serviceSucceeded,
error: serviceFailed
});
}
function serviceSucceeded(result) {
alert(JSON.stringify(result));
}
function serviceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
}

Did u add this reference?
script type="text/javascript" src="../../json.js"></script>
I have same problem and search i get this and this result

Related

YouTube API Academy

I just completed the YouTube API tutorials on Codecademy and successfully managed to display results relating to a given 'q' value in the console window provided using the following code:
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See http://goo.gl/PdPA1 to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: "Hello",
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
and:
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
The problem I am having now is that I have taken this code and put it into my own local files with the intention of furthering my understanding and manipulating it work in a way which suits me, however it just returns a blank page. I assume that it works on Codecademy because they use a particular environment and the code used perhaps only works within that environment, I am surprised they wouldn't provide information on what changes would be required to use this outside of their given environment and was hoping someone could shed some light on this? Perhaps I am altogether wrong, if so, any insight would be appreciated.
Browser Console Output:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
I also had the same problem but it was resolved when I used Xampp. What you have to do is install xampp on your machine and then locate its directory. After You will find a folder named "htdocs". Just move your folder containing both js and HTML file into this folder. Now you have to open Xampp Control Panel and click on start button for both - Apache and SQL server. Now open your browser and type in the URL:
http://localhost/"(Your htdocs directory name containing both of your pages)"
After this, click on .html file and you are done.

Cannot login to yammer using yam.connect.logonButton in IE11

Trying to login using yam.connect.loginButton, works fine on firefox and chrome but not on IE (I am using IE11). The response has an auth but no user object. Or sometimes the popup window doesn't close and the callback is never called. Code I used is below:
<html>
<head>
<script id="yammer-js-include" data-app-id="APP-CLIENT-ID-GOES-HERE" src="https://assets.yammer.com/assets/platform_js_sdk.js"></script>
</head>
<body>
<span id="yammer-login"></span>
<script>
yam.connect.loginButton('#yammer-login',
function (response) {
console.dir(response);
document.getElementById('yammer-login').innerHTML = 'user ' + (typeof response.user !== 'undefined' ? 'exists in response' : 'is missing!');
}
);
</script>
</body>
</html>
You mention that was the code you used, but did you replace the data-app-id with the one provided from your app on https://yammer.com/client_applications ?
Assuming yes, a lot of people run in to problems with IE and not having Yammer urls added to Trusted Sites in IE. If you can add more logs from your console output that it would help.
You can read more about what to include in your Trusted Sites here:
http://developer.yammer.com/connect/#IETrustedSites
When I add the host of where my app was running also in the Trusted Sites, it worked.
http://kendomen.wordpress.com/2014/11/06/yammer-authentication-with-javascript-and-yammer-sdk/

Google Chrome Extension with OAuth

I am trying to integrate OAuth with my chrome extension. I am following the tutorial by google: https://developer.chrome.com/extensions/tut_oauth.html
I create ExOauth from the background.js (defined by me and it is loaded by background.html).
var oauth = ChromeExOAuth.initBackgroundPage({
'request_url': 'https://www.google.com/accounts/OAuthGetRequestToken',
'authorize_url': 'https://www.google.com/accounts/OAuthAuthorizeToken',
'access_url': 'https://www.google.com/accounts/OAuthGetAccessToken',
'consumer_key': 'anonymous',
'consumer_secret': 'anonymous',
'scope': 'https://docs.google.com/feeds/',
'app_name': Test app'
});
oauth.authorize(onAuthorized);
Here is the OnAuthorized method:
onAuthorized = function () {
// Start my application logic.
};
Am I missing something here? When I load the extension, it opens up several "Redirecting...." tabs.
The tutorial seems to be missing one file. If you open chrome_ex_oauth.html, you'll see that it tries to load 3 js files:
<script type="text/javascript" src="chrome_ex_oauthsimple.js"></script>
<script type="text/javascript" src="chrome_ex_oauth.js"></script>
<script type="text/javascript" src="onload.js"></script>
The onload.js file is not provided. The OAuth contacts example provides such a file, with the following content:
window.onload = function() {
ChromeExOAuth.initCallbackPage();
}
After adding this file, it seems to work just fine.
I know the Question is a bit older but i had the same Problem.
I made the mistake that i want to authenticate two oauth endpoint and call both times the ChromeExOAuth.initBackgroundPage({})
Obviously that's wrong cause i dont want to init my background page twice.
Maybe using the ..._oauthsimple.js will fix that

Embedding NPAPI plugin in background using just Firefox Addon SDK

I have recently developed a NPAPI plugin (using FireBreath) in combination with a Google Chrome Extension. I am embedding the plugin using the background.html page and access it from multiple extension pages. Thus, the plugin remains loaded in the background page (until the extension is unloaded or the browser is closed).
I am now searching for the easiest way to port this extension to Firefox. Using the Addon SDK and it's API, i can reproduce the communication between the addon code and HTML user interface.
As there is no such global background DOM as in the Chrome Extension, how would I load the NPAPI plugin just once, without inserting it in every page of the app UI?
I've seen that using a XUL overlay would allow that - is there a way using just the addon sdk?
Edit: I've created an answer to this question with a minimal solution to this problem using page-workers.
You'll want to look at the page-worker module:
https://addons.mozilla.org/en-US/developers/docs/sdk/1.8/packages/addon-kit/page-worker.html
The caveat I would give is that the NPAPI plugin might have made assumptions about visibility or other details of the environment it is running in that simply don't apply in the page-worker environment. If you run into errors, I'd be interested to hear them!
The following code provides a minimal working solution to the problem using the page-workers as as canuckistani suggested.
Note: This solution requires the addon-sdk's unsafeWindow to access the plugin member methods. If there's a better solution that does not depend on that, feel free to send a me a note/comment.
data/background.html
<html>
<head>
<script type="text/javascript" charset="utf-8">
function pluginLoaded() {
// Create an event once plugin is loaded
// This allows the contentscript to detect plugin state
var evt = document.createEvent("CustomEvent");
evt.initCustomEvent("pluginLoaded", true, false, null);
window.dispatchEvent(evt);
}
</script>
</head>
<body>
<object id="myplugin" type="application/x-myplugin" width="0" height="0">
<param name="onload" value="pluginLoaded" />
</object>
</body>
</html>
data/background.js
var module = null;
window.addEventListener("pluginLoaded", function( event ) {
// set the module through unsafeWindow
module = unsafeWindow.document.getElementById("myplugin");
module = XPCNativeWrapper.unwrap(module);
self.port.emit("pluginLoaded");
});
// Handle incoming requests to the plugin
self.port.on("pluginCall", function(msg) {
var response;
if (module) {
// Call NPAPI-plugin member method
response = module[msg.method].apply(this, msg.args);
} else {
response = {error: true, error_msg: "Module not loaded!"};
}
self.port.emit("pluginResponse", {data: response});
});
main.js
// Create background page that loads NPAPI plugin
var plugin = require("page-worker").Page({
contentURL: data.url("background.html"),
contentScriptFile: data.url("background.js"),
contentScriptWhen: "ready"
});
// Send request to plugin
plugin.port.emit("pluginCall", message);

Error "Origin null is not allowed by Access-Control-Allow-Origin" in jsOAuth

I'm trying to use the twitter API with library jsOAuth.
Full html
<div id="message">Loading..</div>
<script src="jsOAuth-1.3.3.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script>
<script type="text/javascript">
var oauth = OAuth({
consumerKey: "-MY-KEY-",
consumerSecret: "MY-SECRET"
});
Updated
oauth.get("http://api.twitter.com/1/statuses/home_timeline.json?callback=?", success, failure);
function success(data){
$("#message").html("Sucess: " + data.text);
var timeline = jQuery.parseJSON(data.text);
console.log(timeline);
$.each(timeline, function (element){
console.log(element.text);
});
}
function failure(data) {
console.log("Throw rotten fruit, something failed");
$("#message").html("Error" );
}
</script>
Result
Full image
Questions
What am I doing wrong?
How can I use the twitter API in my PC.
If you can send me I would appreciate any examples.
Thank you all.
What am I doing wrong?
You are trying to make an AJAX request to Twitter. You are violating cross domain access policies - you cannot access data on the Twitter domain.
How can I use the Twitter API on my PC?
Pick one :
Use JSONP
Use a server-side proxy
Store your code on a file:// path, which removes the cross domain restrictions
Change your browser's security settings to allow this kind of access.
I have styled the unlikely ones in italic.
Also, as an experienced Twitter developer, I have one important note to make about your code: you're using Javascript to access the API. While using JS to do that isn't disallowed, using OAuth in javascript is very unsafe and your application will be blocked from the Twitter API if you used this code on a website.

Resources