I am using the JSON object with jquery in asp.net application. The code is working with VS2008 but when i moved sam code in VS2003 then it is showing the JSON is undefined. Code is following
var mes = $('#filePath').val();
alert("File Path: " + mes);
var jsonText = JSON.stringify({ sFilePath: mes });
In third line it is giving the error :
Microsoft JScript runtime error: 'JSON' is undefined
Can any one help on this. Do i need to add any reference.
Thanks in Advance
Eshwer N
This does not smell like an ASP.NET issue. Rather try including the json2.js as part of your script tags -
http://www.json.org/
https://github.com/douglascrockford/JSON-js
http://www.json.org/js.html
<script src="http://wherever.com/json2.min.js" type="text/javascript"></script>
Related
I wanted to know if anyone has given this a go and got it working?
http://lightswitchhelpwebsite.com/Blog/tabid/61/EntryId/182/Connecting-To-SignalR-With-LightSwitch-HTML-Client.aspx
Basically my issue is i cant open the file to begin with, whether it be Visual Studio 2012, 2013 or 2015, so I have followed the guide and used the files from the downloaded project for this error message to occur:
which is caused by this line under the sendmessage_execute function:
chat.server.send(screen.displayname, screen.message);
im hoping someone has got this working and could point out anything different from the user guide, heres what I have used/done:
Under the PROJECT.Server I have:
created a folder called SignalR with the file ChatHub.cs in
added the json2.js (both) and signalR (both) files to the scripts
folder
Under the Project.HTMLClient
added the json2.js (both) and signalR (both) files to the scripts
folder
referenced the scripts including the localhost in the default.htm file
Created a screen. called ChatScreen and added all the referenced code here from the guide online (3 strings and 1 button)
i also installed the Nu-GET as instructed
More research for this was required, I found this post which explains how to do it a lot easier and in an application for both 2013/2015, works a treat and can easily be adapted for other screens
https://blogs.msdn.microsoft.com/rmattsampson/2013/03/14/asp-net-signalr-and-lightswitch-vs-2012-update-2-vs-2013-and-later/
I have also managed to edit there block of code to list all messages in a string, this is not stored and refresh's each time but its now possible to have a conversation while on the same screen
var string;
myapp.ChatScreen.created = function (screen) {
string = "";
$(function () {
chat = $.connection.chatHub;
chat.client.broadcastMessage = function (message) {
string = string + message + ";";
screen.updates = string.split(';').join("\r\n");
console.log(string.split(';').join("\r\n"))
};
$.connection.hub.start()
.done(function () {
})
.fail(function () {
alert("Could not Connect! - ensure EnableCrossDomain = true");
});
});
};
It would be better practice using an array and displaying it this way but the code above demonstrates it works
If I put the jquery code below within the script tag within a html page and drag the html page into a web browser the call to the API specified in the URL is made and I get back a response in JSON format. So this works good.
The reason I want to use .NET for calling the rest API that is made in node.js is because I want to use the unit test utility that exist in visual studio.
So when I start the unit test the call to the REST API made in node.js should be made and then I can check whatever I want in the returned json format by using the assert.AreEqual.
I have googled a lot and there is several example about
Unit Testing Controllers in ASP.NET Web API 2 but I don't want to unit test controller. I only want to call the REST API(made in node.js) when I start my unit test.
I assume to use .NET in the way I want is probably quite rare.
If it's not possible to use .NET and unit test in the way that I want here
I will use another test framework.
I hope to get some help from here.
Hope you understand what I mean.
$.ajax({
type: 'GET',
url: 'http://10.1.23.168:3000/api/v1/users/1',
dataType: 'json',
async: false,
headers: {
'Authorization': 'Basic ' + btoa('DEFAULT/user:password')
},
success: function(response) {
//your success code
console.log(response);
},
error: function (err) {
//your error code
console.log(err);
}
});
Many thanks
Basically what you need to do is to call node.js' API from your C# test code in a same way you call it using jQuery. There are several ways to do it:
Use HttpWebRequest class https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest%28v=vs.110%29.aspx
Use HttpClient class https://msdn.microsoft.com/en-us/library/system.net.http.httpclient%28v=vs.118%29.aspx It's more "RESTable" since it exposes methods to call HTTP methods like GET, PUT, POST and DELETE methods directly.
3rd party software http://restsharp.org/
Generally I recommend approach #2.
Here's the example source with all the rest of the code.
Another resource is the docs.
This code snippet should be enough to get you where you need.
using(var client = newHttpClient())
{
client.BaseAddress = newUri("http://localhost:55587/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(newMediaTypeWithQualityHeaderValue("application/json"));
//GET Method
HttpResponseMessage response = awaitclient.GetAsync("api/Department/1");
if (response.IsSuccessStatusCode)
{
Departmentdepartment = awaitresponse.Content.ReadAsAsync < Department > ();
Console.WriteLine("Id:{0}\tName:{1}", department.DepartmentId, department.DepartmentName);
Console.WriteLine("No of Employee in Department: {0}", department.Employees.Count);
}
else
{
Console.WriteLine("Internal server Error");
}
}
We are integrating with Linked IN to extract the users profile. Its working fine, but we notice in some Windows 7 / IE 9 machines, Linked IN pop up comes up and is blank. We see the below error in console.
Message: Object doesn't support property or method 'replace'
Line: 861
Char: 17
Code: 0
URI: http://platform.linkedin.com/js/framework?v=0.0.2000-RC1.21420-1403&lang=en_US
Code Snippet Below
<script type="text/javascript" src="https://platform.linkedin.com/in.js?async=false" >
api_key: tw6oqfav7ms1
authorize:false
</script>
//We have a custom image for linkedIN, onclick of the same below code is called.
$("#mylinkedin").click(function () {
IN.UI.Authorize().params({"scope":["r_fullprofile", "r_emailaddress","r_contactinfo"]}).place();
IN.Event.on(IN, "auth", onLinkedInAuth);
});
function onLinkedInAuth() {
IN.API.Profile("me").fields([ "id","firstName", "location","lastName","skills","positions","educations","languages","phone-numbers","certifications","emailAddress","mainAddress"]).result(displayProfiles);
IN.User.logout(); //After we take the data, we do a log out
$.get("https://api.linkedin.com/uas/oauth/invalidateToken");
}
function displayProfiles(profiles) {
//Access profile and process
member = profiles.values[0]
...........
}
Thanks for your response.I was able to figure the issue on my own. What we observed was in the Win7 machines with IE9, the Linked IN authorization Pop Up was blank. When I uncheck the "Enable Protected Mode" the pop up is coming up without any issues.
I haven't had a chance to test this, but to me it looks like you've introduced a race condition in your code, specifically, in onLinkedInAuth().
The call to IN.API.Profile() invokes an async call to LinkedIn that may not be complete by the time the JavaScript engine in the IN.User.logout() code.
I would change the code to the following to see if this resolves the issue:
IN.API.Profile("me")
.fields([ "id","firstName", "location","lastName","skills","positions","educations","languages","phone-numbers","certifications","emailAddress","mainAddress"])
.result(function(profile) {
displayProfiles(profile);
IN.User.logout(); //After we take the data, we do a log out
$.get("https://api.linkedin.com/uas/oauth/invalidateToken");
});
Please help me. Our aps.net web application is using SignalR as the notifier, it uses a hub and works well for one page but when I added these lines of code to MainSite.Master:
<script type="text/javascript">
jQuery(document).ready(function (jQuery) {
var notifyHub = jQuery.connection.notificationHub;
jQuery.connection.hub.start();
});
</script>
Visual Studio throw the error message:
Microsoft JScript runtime error: Unable to get value of the property 'transports': object is null or undefined
Thanks for any help.
I resolved my problem by replacing:
jQuery.connection.hub.start();
by
$.connection.hub.start({ transport: ['webSockets', 'serverSentEvents', 'longPolling'] });
I am attempting to write an ASP.net web service that will be utilized by a jQuery AJAX call.
I am absolutely at my wit's end trying to get this to work. I've seen a number of similar questions online but I haven't been able to find a solution that fits.
When I attempt to make the ajax call (via jquery) I get a successful response from the server but the request fails because of a parser error.
I've validated the json returned by the webservice and it is valid. The issue seems to stem from the fact that asp.net is returning the json object as xml.
I've specified the return type as json using
<Script.Services.ScriptMethod(responseFormat:=Script.Services.ResponseFormat.Json)> _
I've added the following http handler as it was mentioned as a potential fix
<httpHandlers>
<remove verb="*" path="*.asmx" />
<add verb="*" path="*.asmx" type="System.Web.Script.Services.ScriptHandlerFactory" validate="false" />
</httpHandlers>
The content Type is set to "application/json; charset=utf-8" and the dataType to "json" in my jquery ajax setup. The request type seems to be correct but the response is always xml.
I can make the request successfully by removing the dataType but i would very much like to avoid using an eval to deserialize the data.
If anyone has any suggestion i will be greatly appreciated. I've been pulling my hair out for a few days on this.
JAVASCRIPT
(function($) {
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
global: false,
dataType: "json"
});
function auto() {
console.log("test");
return;
};
$.fn.species = {
test: function() {
alert("test");
},
load: function() { //load and attach species list to element as dropdown
$.ajax({
url: "SpeciesService.asmx/List",
success: function(msg) {
console.log(msg);
},
error: function(xhr, desc, exceptionobj) {
console.log(xhr.responseText);
console.log(desc);
console.log(exceptionobj);
}
});
return this;
}
}; //Species Block
})(jQuery); //jQuery Alias Block
ASP.NET Webservice
<%# WebService Language="VB" Class="SpeciesService" %>
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports Species
Imports System.Runtime.Serialization
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' _
_
_
Public Class SpeciesService
Inherits System.Web.Services.WebService
<WebMethod()> _
<Script.Services.ScriptMethod(responseFormat:=Script.Services.ResponseFormat.Json)> _
Public Function Data(ByVal id As Integer) As String
Dim curSpecies As New Species(id)
Return curSpecies.serialize
End Function
<WebMethod()> _
<Script.Services.ScriptMethod(responseFormat:=Script.Services.ResponseFormat.Json)> _
Public Function List() As String
Return Species.list()
End Function
End Class
Try posting a dummy json data with JQuery like this :
$.ajaxSetup({
type: "POST",
data : "{'foo':'bar'}"
...
This is more hint than an answer - I've been using PageMethods rather than webservices and it works very well. I'd try that if it suffers with the same issue.
If you watch the headers is there a content-length being sent? IIS requires a content-length on a post, so even adding an empty body to the post might fix it.
And I think the reason it works with the datatype set to json is that jquery adds an empty post body for you in that case.
Alright - Thank you guys very much for your help.
The lack of dummy data was the core of the problem. When I tried to add it before it caused a server error and I moved on to something else.
I can't even figure out what fixed the server error portion of the problem. I just spent ten minutes absentmindedly messing with syntax (fixing indents, caps, comments) because i was getting too frustrated to focus on the problem at hand. I refreshed the page and suddenly it is working fine. So the answer was to post dummy data and fix random mystery syntax error.
Anyways I can not thank you enough for getting me back on the right track.