I have a single Visual Studio project that has the aspx default page, some jquery scripts and the .svc WCF service file. It works fine if I connect with a browser (non debug) but when I debug in VS and hit a button that calls a web method to display the server time, it works fine the first and second times but then shows the first time again and cycles through both times. If I put a breakpoint on the web method it doesn't break after the first few times.
Is this to do with the fact that they are in the same project?
Sorry, here's the JQuery function:
function controlOutput(outputNumber, state) {
var webMethod = "ControlOutput?DeviceIPAddress=" + adamsIPAddress + "&OutputNumber=" + outputNumber + "&State=" + state + "&vSessionID=" + sessionID;
var fullCommandURL = webServiceUrl + webMethod;
jQuery.support.cors = true;
$.ajax({
type: "GET", //GET or POST or PUT or DELETE verb
url: fullCommandURL, // Location of the service
contentType: 'application/json; charset=utf-8', // content type sent to server
dataType: "json", //Expected data format from server
success: function (result) {//On Successfull service call
connectionInfo = result;
$(h2Test).text(result);
//alert(result);
},
error: function (result) {// When Service call fails
alert(result.statusText);
}
});
}
And the WCF Service code:
public string ControlOutput(string DeviceIPAddress, int OuputNumber, int State, Guid SessionID)
{
try
{
string ret = DateTime.Now.ToString("HH:mm:ss.fff");
AdamSocket adamSocket = new AdamSocket();
adamSocket.SetTimeout(1000, 1000, 1000);
bool con = adamSocket.Connect(DeviceIPAddress, ProtocolType.Tcp, 502);
bool res = adamSocket.Modbus().ForceSingleCoil(17, State);
adamSocket.Disconnect();
return ret;
}
catch (Exception ex)
{
LogEvent(null, "Application Exception", ex.Message, SessionID);
return "Failed";
}
}
It turns out the GET command was caching and so only executing a couple of times. Using POST fixed this. ;)
Related
asp.net .net 4.7 web API
I am accessing a ASP.NET web API via jQuery.
JQuery collects a number of ids and sends one ajax request per id.
If there is 1 id the query is processed in 6-10ms
If there is more than 1 it can take 500-1000 ms as seen in browser web dev timing or in IIS log access log files. A stopwatch in controller is consistent for all queries below 10ms.
Same issue on both IIS prod server and local Dev machine.
function dashboardLoader() {
var tcs = $(".dashboardtc");
for (var i = 0; i < tcs.length; i++) {
var fid = $(tcs[i]).attr("data-fid");
$.ajax({
url: '/ctl/dashboardfeature/' + fid,
type: 'GET',
cache: false,
contentType: "application/json",
success: function (d1) {
adjustDashBoardCell(d1);
},
error: function (result) {
console.log(result.Message);
}
});
}
}
API:
[Authorize]
[Route("ctl/dashboardfeature/{fid}")]
[HttpGet]
public async Task<dashboardFeaturePayload> GetDashboardFeature(string fid)
{
try
{
var timer = new Stopwatch();
timer.Start();
if (!User.Identity.IsAuthenticated) return null;
string un = User.Identity.Name;
int fID = fid.val();
string rtn = await Task.FromResult<string>(DashboardCode.GetDashboardFeatureAPI(fID, true));
timer.Stop();
TimeSpan timeTaken = timer.Elapsed;
System.Diagnostics.Debug.WriteLine(timer.Elapsed.TotalMilliseconds.ToString());
return new dashboardFeaturePayload(fID, rtn);
}
catch (Exception ex)
{
AdminTask.ExceptionLoging(ex);
return new dashboardFeaturePayload(fid.val(), "ERROR");
}
}
Would appear to be link to the ability of IIS to process multiple requests arriving in the same time.
Web Dev Timing:
VS Output stopwatch:
I'm posting to my Web API on Azure from a remote webpage. I use the following:
$.ajax({
type: "POST",
url: BaseHref + "/api/PIRknownPersons/",
data: data,
contentType: "application/json; charset=UTF-8",
success: function (response) {
//alert('Saved known ');
},
error: function (e) {
//alert('Unable to save Known ' );
}
});
I could be wrong but it looks like remote posting is blocked on Azure as the code works fine when I do it locally. Is this the case? Is there a setting on Azure that I can turn off?
PIRknownPersons -
namespace TripWeb.Controllers
{
public class PIRknownPersonsController : ApiController
{
private TripDB3Entities db = new TripDB3Entities();
// POST: api/PIRknownPersons
[ResponseType(typeof(bool))]
public HttpResponseMessage Post([FromBody]ApiPIRknownPerson APIPIRknownPerson)
{
var inst = db.Institutions.Where(x => x.RemoteID == APIPIRknownPerson.RemoteID).FirstOrDefault();
if (inst == null)
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Action Not Authorized");
}
var newPIRknownPerson = ObjectMapper.GetEfApiPIRknownPerson(APIPIRknownPerson);
try
{
db.PIRknownPersons.Add(newPIRknownPerson);
db.SaveChanges();
return Request.CreateResponse<bool>(HttpStatusCode.OK, true);
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex.Message);
}
}
}
}
I found the problem - or at least I got it working. I did two things:
Enabled CORS on Azure through the control panel
Appended [System.Web.Http.AcceptVerbs("GET", "POST")] to the top of my controller files.
Don't know if both are needed but it works now anyway.
I have a method on an API Controller where I've set the route in an attribute, but I don't seem to be able to pass a string into this. When I try to hit this with an Ajax Request from the browser the console shows the following error:
BAD REQUEST - The request could not be processed by the server due to
invalid syntax.
The string I'm passing over is huge, but unfortunately is the only way I can import the data into the legacy application I'm working with. The test URL I'm using is (brace yourselves):
http://localhost:50915/api/job/import/ALMIG³123456³2%20DAY%20ECONOMY³20170720³20170721³0³³³³22³Lara%20Croft%20Way³Derby³³³DE23%206GB³Stuff³10³1³0³25³0³³1%7CI%20Great%20Danger³0³0³0³³³0³true³0³³³³³³³1³0³0³16³Baden%20Road³Stoke-on-Trent³³³ST6%201SA³³0³0³0³³³³0³0³0³0³³0³1³0³³³³³³³³³³³Liane³07730044916³Lara³07730044916³0³d2f0acf7-50e1-4a53-96ce-4fffd00b1a96³0
And the method is defined as below, the code inside is irrelevant as I put a break point on the start of the method which is never hit:
[System.Web.Http.HttpPost]
[System.Web.Http.Route("api/job/import")]
public int TmsImport([FromBody]string import)
{
// do something...
}
Edit: Added Ajax Request
job.confirmBookings = function () {
// TMS Import
job.toConfirmRow.filter(function(obj) {
var jobRow = obj;
var strArray = [];
for (var prop in jobRow) {
if (jobRow.hasOwnProperty(prop)) {
strArray.push(jobRow[prop]);
}
}
var joinedStr = strArray.join(job.seperator);
$.ajax({
type: "POST",
crossDomain: true,
data: joinedStr,
url: job.tmsString,
contentType: "application/json;charset=utf-8",
success: function (data, status, xhr) {
console.log("TMS ID: " + data + " | " + status);
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
First format the route template correctly
[HttpPost]
[Route("api/job/import")] //Matches POST api/job/import
public int TmsImport([FromBody]string import) {
// do something...
}
Also you should post the data in the body of the request. If the payload is large then you do not want that in the URL
Ok so when you click a hyper link in my web app it just adds to the URL to the end. like so http://localhost:8080/http//:www.youtube.com. I'm using visual studio .net to make web rest APIs. The web app lunches on IIS express 10. the home page URL is http://localhost:8080/index.html.
user gets links to click
links are populated
error after user clicks link
error page
$.ajax(
{
url: "/api/Link/1",
type: "GET",
dataType: "json",
success: function (data)
{
var array = $.parseJSON(data);
$("a").remove();
for(var i=0;i<array.length;i++)
{
$("body").append("" + array[i].name + "");
}
},
error: function ()
{
}
});
//rest api called
[HttpGet]
public string GetLinkList(int id)
{
string json = "[";
using (StreamReader infile = new StreamReader("C: /Users/jkarp/Documents/visual studio 2015/Projects/Protal/Protal/App_Data/linkObjs.txt"))
{
while (!infile.EndOfStream)
json += infile.ReadLine()+",";
}
if(json.Length > 1)
{
json = json.Remove(json.Length - 1);
return json + "]";
}
return "[]";
}
Your link is malformed:
http//:www.youtube.com
The colon : is in the wrong place, it should be:
http://www.youtube.com
The link will be contained in your datasource linkObjs.txt, fix it there and the problem should go away.
I am lazy loading snippets of html on our page in order to improve performance. jQuery's load method does not provide access to the full ajax api (things like error callbacks) so I created a more robust version of it.
I am calling this method 3-5 times per page on just about every page load and am logging when there is some sort of error with ajax call. What I am finding is that about 0.3% of the time the ajax calls are failing the majority of the failures are in firefox 3.6. I am using jQuery 1.5.1 with ASP.NET server side. The 'errorThrown' parameter of the error callback reads:
[Exception... "Component returned failure code: 0x80040111 (NS_ERROR_NOT_AVAILABLE) [nsIXMLHttpRequest.getAllResponseHeaders]" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)"
and the jqXHR reads:
{"readyState":4,"status":0,"statusText":"error"}
I have confirmed with users that they are experienceing this problem and it's not just bots or some logging of an unexperienced error.
here is the code for my "load" widget
(function ($) {
$.fn.elfLoad = function (url, options) {
return this.each(function () {
var $elem = $(this);
options = $.extend({}, {
type: "GET",
dataType: "html",
data: "",
error: function (jqXHR, status, errorThrown) {
$elem.html('<div class="elf-missing-content centerText">Doh! Something did not go so well when trying to load this content. Please try again later.');
elf.ajax.logInfo("data: " + options.data + " errorThrown: " + errorThrown + " webmethod: " + options.url + "jqXHR: " + JSON.stringify(jqXHR),"elfLoad");
}
}, options);
options.success = function (data, status, jqXHR, responseText) {
responseText = jqXHR.responseText;
if (jqXHR.isResolved()) {
jqXHR.done(function (r) {
responseText = r;
});
$elem.html(responseText);
}
if (options.callback) {
var callbackArgs = {
responseText: responseText,
$elem: $elem,
status: status,
jqXHR: jqXHR
};
$elem.each(options.callback, [callbackArgs]);
}
}
options.url = url;
if (options.data) {
options.data = $.param(options.data, $.ajaxSettings.traditional);
options.type = "POST";
} else {
options.data = "";
}
$.ajax(options);
});
}
})(jQuery);
A call to it would look like this $('#container').elfLoad('url.aspx',{foo:'bar'});
Has anyone else had this problem? Any ideas? jQuery claims to have recently closed a ticket that looks like this in 1.5.1 but I see someone else is having a similar issue. http://bugs.jquery.com/ticket/8400
Thanks!
I ended up solving this issue by using a setTimeout for 2 seconds and retrying the request. So far this is working 100% of the time.