Jquery Datatables Ajax Response - asp.net

I am trying to follow the datatable example for Ajax data source (objects) found here. I am using asp.net and have the following handler which receives my data, processes it and provides the response.
public class UsersHandler : IHttpHandler
{
private const string JsHeader = #"{{""data"" {0}}}";
public void ProcessRequest(HttpContext context)
{
IEnumerable<SystemUser> data = SystemUserLogic.LoadAllSystemUsers();
List<SimpleUser> userlist = new List<SimpleUser>();
foreach (SystemUser su in data)
{
SimpleUser simple = new SimpleUser();
simple.Id = su.Id;
simple.FullName = su.NameFirst;
simple.Email = "example#email.co.uk";
userlist.Add(simple);
}
string json = JsonConvert.SerializeObject(userlist, Formatting.Indented);
context.Response.ContentType = "text/plain";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetNoStore();
context.Response.Expires = -1;
context.Response.Write(String.Format(JsHeader, json));
}
which deliveries the correct response when I catch it in the browser and look at the data via the network traffic. My aspx page contains the following.
$('#table_id').DataTable({
"ajax": '/Handlers_New/UsersHandler.ashx',
"columns": [
{ "data": "Id" },
{ "data": "FullName" },
{ "data": "Email" },
{ "data": "KeyResource" }
]
});
However when the page loads, I am getting this error:
DataTables warning: table id=table_id - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
The outputted data looks like this,
{"data" [
{
"Id": 1,
"FullName": "Admin",
"Email": "example#email.co.uk",
"KeyResource": false
},
{
"Id": 2,
"FullName": "Jon",
"Email": "example#email.co.uk",
"KeyResource": false
},
{
"Id": 3,
"FullName": "Stephen",
"Email": "example#email.co.uk",
"KeyResource": false
}, etc.....
Please tell me why I am getting this error. Should I be manipulating the json object differently, or am I missing something with the Jquery datatables?

I have managed to fix my issue amazingly due to jsonlint. I ran my code through that and it turns out I was missing a ':' in my jsHeader. So what I had was:
private const string JsHeader = #"{{""data"" {0}}}";
and what I have now which now works is:
private const string JsHeader = #"{{""data"": {0}}}";
Hope this helps any one else encountering a similar issue.

Related

Why does HotelSearch return an ERR.NGHP-DISTRIBUTION.INTERNAL_ERROR?

I am trying to use the HotelSearch REST api. I have tested it on the Dev Studio website by Sabre and while it is slow to respond it works on a Chrome browser. I then tried to get his working in the sample app Rest2SG Sabre provide, as well as Postman. However it returns this error on both platforms:
Here is the method I have added to the sample app:
private void getHotelSearch()
{
Job job = new Job("Getting HotelSearch")
{
#Override
protected IStatus run(IProgressMonitor monitor)
{
setText("Waiting for response...");
toggleAllButtons(false);
try
{
Rest2SgRequest request =
lockId > 0 ? new Rest2SgRequest(lockId) : new Rest2SgRequest();
// for the list of available service action names
// please refer to REST documentation
// this same as action in redapp.xml authorization
request.setUrl("/v2.0.0/hotel/search");
//request.setHeaders(getContentDescription())
// previously generated document, normally developer will
// have to prepare one by himself
String payload = getRequestBody("sample.json"); // we
// preload
request.setPayload(payload);
request.setHttpMethod(HTTPMethod.POST);
request.setContentType("application/json");
request.setAuthTokenType(AuthTokenType.SESSIONLESS);
Rest2SgServiceClient client = new Rest2SgServiceClient(COM);
ClientResponse <Rest2SgResponse> rsp = client.send(request);
LOGGER.info("Rest2Sg request processing success: " + rsp.isSuccess());
if (rsp.isSuccess())
{
// check if processing ended in with success
Rest2SgResponse response = rsp.getPayload();
String responseBody = response.getResponseBody();
response.getResponseCode();
response.getResponseHeaders();
setText(responseBody);
}
else
{
printErrors(rsp.getErrors());
System.out.println(rsp.getErrors().toString());
}
}
catch (Exception e)
{
e.printStackTrace();
}
toggleAllButtons(true);
return Status.OK_STATUS;
}
};
job.schedule();
}
Here is the sample JSON:
{
"HotelSearchRQ": {
"POS": {
"Source": {
"PseudoCityCode": "43X5"
}
},
"SearchCriteria": {
"MaxResults": 20,
"SortBy": "DistanceFrom",
"SortOrder": "ASC",
"TierLabels": false,
"GeoSearch": {
"GeoRef": {
"Radius": 2,
"UOM": "MI",
"RefPoint": {
"Value": "DFW",
"ValueContext": "CODE",
"RefPointType": "6",
"StateProv": "TX",
"CountryCode": "US"
}
}
}
}
}
}
Does anyone know why I am getting the error below?
[Error [code=400, description={"errorCode":"ERR.NGHP-DISTRIBUTION.INTERNAL_ERROR","message":"Error occurred while invoking service restish:convertToOutputFormat:1.71.3","status":"Incomplete","type":"Application","timeStamp":"2022-06-20T21:00:51-05"}, type=HTTP]]
As I mentioned this JSON works on their website.
This problem is caused by missing header information. The following line needs to be added to the request:
request.setHeaders("{\"Accept\": \"application/json\"}");

bootstrapTable onLoadError's param [status], post url is ASP.NET WebMethod

now,I'm try to use bootstrapTable to load my data that using ASP.NET WebMethod.
$.ajax(): url is set like this: "url:mydata.aspx/GetData"
and this is work fine.
in the other way:
$('#mytab').bootstrapTable({
method: 'post',
contentType: "application/x-www-form-urlencoded",
url:"mydata.aspx/GetData",
toolbar: '#toolbar',
striped: true,
dataField: "res",
pageNumber: 1,
pagination:true,
queryParamsType:'limit',
queryParams:queryParams,
sidePagination:'server',
pageSize:10,
pageList:[5,10,20,30],
showRefresh:true,
showColumns:true,
clickToSelect: true,
toolbarAlign:'right',
buttonsAlign:'right',
toolbar:'#toolbar',
columns:[
{
title:'全选',
field:'select',
checkbox:true,
width:25,
align:'center',
valign:'middle'
},
{
title:'ID',
field:'ID',
visible:false
},
{
title:'登录名',
field:'LoginName',
sortable:true
},
{
title:'姓名',
field:'Name',
sortable:true
},
{
title:'手机号',
field:'Tel',
},
{
title:'邮箱',
field:'Email'
},
{
title:'注册日期',
field:'CreateTime',
sortable:true
},
{
title:'状态',
field:'Attribute',
align:'center',
formatter:operateFormatter
}
],
responseHandler:function(res){
return res;
},
onLoadError: function(status){
alert("error"+status);
}
})
function operateFormatter(value,row,index){
。。。
}
function queryParams(params){
return{
pageSize: params.limit,
pageIndex:params.pageNumber,
content:$('#search_name').val()
}
}
ASP.NET API code here
[WebMethod]
public static string GetData(int pageSize, int pageIndex, string content)
{
return "{total:200,rows:[{......}]}";
}
But now I got an error code:
[error200]has been alerted.
I want to know [onLoadError]'s error status's map
200:XXXX
400:XXXX
500:XXXX
bootstrapTable document has no error status map information.
please help........
Paste your JSON data into myjson.com and really make sure it's good json (without errors). Then post a JSFiddle with a subset of your code and using the url from the myjson.com link it provides.

yammer integration :- writing activity using open_graph

While writing activity it return exception
ex {"The remote server returned an error: (400) Bad Request."}
I'm using the following code :-
public static string PostRequesttoYammer(string postBody, string url,string authHeader = null, string contentType = null)
{
string results = string.Empty;
try
{
HTTPWebReq = WebRequest.CreateHttp(url);
HTTPWebReq.Method = "POST";
if (!string.IsNullOrEmpty(authHeader))
HTTPWebReq.Headers.Add("Authorization: Bearer " + authHeader);
byte[] postByte = Encoding.UTF8.GetBytes(postBody);
if (string.IsNullOrEmpty(contentType))
HTTPWebReq.ContentType = "application/x-www-form-urlencoded";
else
HTTPWebReq.ContentType = contentType;
HTTPWebReq.ContentLength = postByte.Length;
Stream postStream = HTTPWebReq.GetRequestStream();
postStream.Write(postByte, 0, postByte.Length);
postStream.Close();
HTTPWebRes = (HttpWebResponse)HTTPWebReq.GetResponse();
postStream = HTTPWebRes.GetResponseStream();
StreamReader postReader = new StreamReader(postStream);
results = postReader.ReadToEnd();
postReader.Close();
postStream.Close();
}
catch (Exception ex)
{
}
return results;
}
I have obtained access token after that i'm trying to write an activity on yammer network .enter image description here
The image shows the content of local variables of function.
check the bellow code:
yam.platform.request({
url: "activity.json",
method: "GET",
data: {
"activity": {
"actor": { "name": "name", "email": "name#domain.onmicrosoft.com" },
"action": "create",
"object": {
"url": "https://www.news.google.com",
"image": "url",
"description": "Testing Description",
"title": "Open Graph Title"
},
"private": "false",
"message": "testing commit"
}
},
success: function (activity) {
console.log("Activity request was successful.");
},
error: function (activity) {
console.error("There was an error with the request.");
}
});

How to read value when using model.save() or fetch()?

Man = Backbone.Model.extend({
url:'/test.aspx',
initialize: function(){
},
defaults: {
name:'Jim',
age: '38'
},
validate:function(attributes){
if(attributes.name == '') {
return "name can't be null";
}
}
});
var man = new Man;
man.set({name:'the5fire'});
man.save(); //the format is json{"name":"the5fire","age":38}
In test.aspx.cs, how can I read this value {"name":"the5fire","age":38} ?
I have tried Request.Form.ToString() but found no data there.
Chrome developer tools shows this json-format data in the "request payload" block.
update:
If I use man.fetch({ data: { Pagesize: '1', PageIndex: '111' } ), then on the server side, I can use Request.Params["PageIndex"]. But how can I get the name? the age?
You can access the raw body of the request via HttpRequest.InputStream and convert it to a string :
string jsonstring = new System.IO.StreamReader(Request.InputStream).ReadToEnd();
You would then deserialize this string to get an object, for example:
using System.Web.Script.Serialization;
JavaScriptSerializer jss = new JavaScriptSerializer();
var d = jss.Deserialize<dynamic>(jsonstring);
string name = (string)d["name"];

Can URI templates be used to match URIs to routes?

Frameworks like ASP.NET or Nancy provide a syntax that can be used for specifying routes, such as:
MapRoute("/customers/{id}/invoices/{invoiceId}", ...)
In ASP.NET routes work in two directions. They can match a request URI such as /customers/32/invoices/19 to a route, and they can resolve parameters such as { id: 37, invoiceId: 19 } into a URI.
RFC 6570: URI Templates also defines a similar, though much richer, specification for URI's that are often used to resolve URI's. For example:
UriTemplate("/customers/{id}/invoices{/invoiceId}{?sort}", { id: 37, invoiceId: 19, sort: 'asc' } )
// returns: /customers/37/invoices/19?sort=asc
My question is, can the syntax specified in RFC 6570 be used to match request URI's to routes? Is there a part of the syntax that would make it ambiguous to match a given URI to a given URI template? Are there any libraries that support matching a URI to a URI template?
I suspect it would be very difficult. Certainly things like the prefix syntax would make it impossible to regenerate the original parameters.
For things like path segment expansion
{/list*} /red/green/blue
How would you know which parts of the path were literals and which parts were part of the parameter? There are lots of fairly freaky behavior in the URITemplate spec, I suspect even if it is possible to match, it would be fairly expensive.
Are you interested in doing this for the purposes of routing?
It is simple regarding match but regarding resolve you need to replace the ASP.net part by the RFC 6570.
Unfortunately I am doing this in node with express js and this might not be helpful, but I am sure something like https://github.com/geraintluff/uri-templates (for resolving) is also available in ASP.
Here is some .js code to illustrate the rewriting of a hyperschema
USING RFC 6570 to use with express js (the advantage of the use within schema is that you could also define regexes for your uri templates):
var deref = require('json-schema-deref');
var tv4 = require('tv4');
var url = require('url');
var rql = require('rql/parser');
var hyperschema = {
"$schema": "http://json-schema.org/draft-04/hyper-schema",
"links": [
{
"href": "{/id}{/ooo*}{#q}",
"method": "GET",
"rel": "self",
"schema": {
"type": "object",
"properties": {
"params": {
"type": "object",
"properties": {
"id": {"$ref": "#/definitions/id"}
},
"additionalProperties": false
}
},
"additionalProperties": true
}
}
],
"definitions": {
"id": {
"type": "string",
"pattern": "[a-z]{0,3}"
}
}
}
// DOJO lang AND _
function getDottedProperty(object, parts, create) {
var key;
var i = 0;
while (object && (key = parts[i++])) {
if (typeof object !== 'object') {
return undefined;
}
object = key in object ? object[key] : (create ? object[key] = {} : undefined);
}
return object;
}
function getProperty(object, propertyName, create) {
return getDottedProperty(object, propertyName.split('.'), create);
}
function _rEscape(str) {
return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function getPattern(k, ldo, customCat) {
// ...* = explode = array
// ...: = maxLength
var key = ((k.slice(-1) === '*') ? k.slice(0,-1) : k).split(':')[0];
var cat = (customCat) ? customCat : 'params'; // becomes default of customCat in TS
var pattern = '';
if (typeof ldo === 'object' && ldo.hasOwnProperty('schema')) {
var res = getProperty(ldo.schema, ['properties',cat,'properties',key,'pattern'].join('.'));
if (res) {
console.log(['properties',cat,'properties',key,'pattern'].join('.'),res);
return ['(',res,')'].join('');
}
}
return pattern;
}
function ldoToRouter(ldo) {
var expression = ldo.href.replace(/(\{\+)/g, '{') // encoding
.replace(/(\{\?.*\})/g, '') // query
.replace(/\{[#]([^}]*)\}/g, function(_, arg) {
// crosshatch
//console.log(arg);
return ['(?:[/]*)?#:',arg,getPattern(arg,ldo,'anchor')].join('');
})
.replace(/\{([./])?([^}]*)\}/g, function(_, op, arg) {
// path seperator
//console.log(op, '::', arg, '::', ldo.schema);
return [op,':',arg,getPattern(arg,ldo)].join('');
});
return {method: ldo.method.toLowerCase(), args:[expression]};
}
deref(hyperschema, function(err, fullSchema) {
console.log('deref hyperschema:',JSON.stringify(fullSchema));
var router = fullSchema.links.map(ldoToRouter);
console.log('router:',JSON.stringify(router));
});

Resources