My controller like this:
[HttpPost]
public ActionResult Error_Search([DataSourceRequest] DataSourceRequest request, object[] ParaSearch)
{
object[] obj = new object[5];
obj[0] = Convert.ToInt32(ParaSearch[0]);
obj[1] = ParaSearch[1].ToString();
obj[2] = Convert.ToDateTime(ParaSearch[2]).AddDays(-10);
obj[3] = Convert.ToDateTime(ParaSearch[3]);
obj[4] = ParaSearch[4];
List<Vsoft.Lists.Model.SYS.SYS_Error> lst = new List<Vsoft.Lists.Model.SYS.SYS_Error>();
ResultMessage result = new Vsoft.Lists.DALEntity.SYS.DAL_Error().SelectToList(ref lst, obj);
return Json(lst.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
It will return Json(lst) correct.. but I can't bind it to datasource and refresh Grid after Ajax Call like this :
var requestData = { ParaSearch: arrObject };
$.ajax({
url: '#Url.Content("~/Error/Error_Search")',
data: JSON.stringify(requestData),
type: 'POST',
traditional: true,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function (xhr) {
result = false;
alert('Error: ' + xhr.statusText);
},
success: function (lst) {
var grid = $("#Grid").data("kendoGrid");
grid.dataSource.data(lst);
grid.refresh();
},
async: true,
processData: false,
cache: false
});
Can AnyOne help me to solve this ?
Thanks All !
If ajax return is good enough, then using setDatasource api call should be your friend.
success: function (lst) {
var grid = $("#Grid").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
data: lst });
grid.setDataSource(dataSource);
}
EDIT: using read (read is just wrapper over $.ajax)
Hope you have configured your grid like:
.DataSource(dataSource => dataSource
.Ajax()
.PageSize(20)
.Read(read => read.Action("Error_Search", "Error", new { ParaSearch = []}))
)
Then, wire up some event from where ParaSearch is originating and use read call as:
<script>
function someEvent(e) {
var requestData = { ParaSearch: arrObject };
grid.dataSource.read(requestData);
}
</script>
Related
Hey after struggling to download the excel from server below is the solution i found very easy.But API side they will just read the path and send the files.
How can i differentiate the file type?
If server files are in your project directory or server , we would like to down load the excel or any file directly. Added the below implementation which works only for excel.
API(.net):
public ActionResult Download()
{
string fileName = WebConfigurationManager.AppSettings["filename"];
var filePath = System.Web.HttpContext.Current.Server.MapPath("~/" + fileName);
if (System.IO.File.Exists(filePath))
{
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}
else
{
var response = new WebServiceStatus()
{
code = -1,
data = null,
message = "File is Not available"
};
var data = JsonConvert.SerializeObject(response);
return HandleTrivialHttpRequests(data);
}
}
Angular V7
//Declaration
headers: HttpHeaders;
options: any;
//Constructor or u can have for specific method
this.headers = new HttpHeaders({ 'Content-Type': 'application/json' });
this.options = {
observe: 'response',
headers: this.headers,
responseType: 'arraybuffer'
};
//Service request:
this.httpClient.post('http://localhost:8080/api/report', this.data,
this.option)
.pipe(
catchError(err => this.handleError(err))
).subscribe(response => {
Helper.exportExelFile(response, 'FileName');
});
//In component or in helper function in one class, I have used helper
function which can be reused in other places also
import * as FileSaver from 'file-saver';
function exportExelFile(data, filename) {
const blobValue = new Blob([data['body']], {
type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
});
FileSaver.saveAs(blobValue, filename + '.' + FileType.EXCEL);
}
export const Helper = {
exportExelFile
};
I have this code in my ng2 component:
data => {
let blob = new Blob([data], { type: "text/csv" });
FileSaver.saveAs(blob, "data.csv);
}
Then there is a file saved, but the contents of the file read:
Response with status: 200 OK for URL: https://MYURL/URI/data.csv
My backend is node/express, do I have to create a stream for this or does it work with direct file access like in the old days?
This is my backend at the moment, how can I alter it to return a stream?
'use strict';
const Transactions = require('../../models').transaction;
module.exports = function * details(req, res) {
logger.debug(' Get TME details ' + req.currentTME._id);
const transaction = yield Transactions.findOne({
_tme: req.currentTME.id
}).lean();
return res
.json({
status: constants.status.SUCCESS,
timemodel: req.currentTME,
linkedInfo: {
transaction
}
});
};
Full Server Call:
request(url: string, data: any, method: RequestMethod, showErrorDialog = true): Observable<any> {
const requestOptionsArgs: RequestOptionsArgs = {
url: this.baseUrl + url,
method: method,
headers: this.createHeaders(),
body: JSON.stringify(data)
};
this.log.info(this.getCurl(requestOptionsArgs), this);
const requestOptions: RequestOptions = new RequestOptions(requestOptionsArgs);
return this.intercept(
this.http.request(new Request(requestOptions)).timeout(3000),
requestOptionsArgs,
showErrorDialog
).share();
}
I have a knockout script that have a defaut viewmodel with few fields values. When I have entered the data in the form and submit, it is not sending any updated value back. For example, the zipcode stays the value I defined on the defaul load. Here is the code
$(function () {
ViewModel.zipCode.subscribe(function (value) {
$.get("/api/abc/GetCounties?zipCode=" + value, null, ViewModel.county, 'json');
}.bind(this));
});
var ViewModel = function (data) {
var self = this;
self.zipCode = ko.observable(data.zipCode);
self.dateOfEvent = ko.observable(new Date());
//Enrollment reasons
self.enrollmentReasons = ko.observableArray(new Array());
$.get("/api/abc/reasons", null, self.enrollmentReasons, 'json');
//county from Zipcode subscribed
self.county = ko.observableArray(new Array());
$.get("/api/utilityapi/GetCounties?zipCode=" + data.zipCode, null, self.county, 'json');
self.selectedChoice = ko.observable();
self.applicants = ko.observableArray();
self.applicants.push(new getaquoteapplicant());
//IsValid zip subscribed
self.isValidZip = ko.observable(false);
//operations
self.addApplicant = function () { self.applicants.push(new getaquoteapplicant()) };
self.removeApplicant = function (getaquoteapplicant) { self.applicants.remove(getaquoteapplicant) };
self.save = function () {
$.ajax({
url: '/xyz/start',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data),
success: function (result) {
window.location.replace('/getaquote/planoptions', result);
}
});
}
}
var getaquoteapplicant = function () {
var self = this;
self.coverageFor = [
{ name: "Self" },
{ name: "Spouse/Life Partner" },
{ name: "Son" }
];
self.dateofBirth = ko.observable();
self.tobaccoUser = [
{ name: "Yes", value: true },
{ name: "No", value: false }
];
};
var defaultmodel = {
dateOfEvent: new Date(),
selectedChoice: 4,
zipCode:55044
}
ViewModel = new ViewModel(defaultmodel);
ko.applyBindings(ViewModel);
`
The problem could be that you are running the knockout binding even before the page is loaded or that you trying to access the ViewModel before it is created in the code execution order. One last thing is that always better to create a new instance of the model rather than the assigning it to itself.
I have created them in the fiddle below. It seems to work
https://jsfiddle.net/ramkiFiddle/npsgq8uL/1/
$(document).ready(function() {
var viewModel = new ViewModel(defaultmodel);
ko.applyBindings(viewModel);
});
I am trying to use Node.js to programmatically build Jenkins jobs that take Git parameters.
I am sending the parameters as post data, as shown below. However, no matter what value I assign to ref, Jenkins runs the build with the default parameter value (specified in the job's configuration). I have tried passing in the parameters as query strings in the URL, but that also did not work.
I am using Jenkins v1.651.1 and Node v6.2.0.
var jobOptions = {
url: requestedJobObject.url + 'build',
method: 'POST',
port: 8080
};
// parameters = { "name": "ref", "value": "origin/master" }
if (!_.isEmpty(parameters)) {
var jsonParametersString = JSON.stringify({"parameter": parameters});
var parameterParam = encodeURIComponent(jsonParametersString);
parameters.json = parameterParam;
jobOptions.headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': querystring.stringify(parameters).length
};
jobOptions.url += 'WithParameters';
postData = querystring.stringify(parameters);
}
// jobOptions contains auth field & separates url into hostname and path
// makes an http request to jobOptions and calls req.write(postData)
makeRequest(jobOptions, callback, responseCB, postData)
makeRequest makes an http request:
function makeRequest (object, callback, responseCB, postData) {
var accumulator = '';
var parsedUrl = u.parse('//' + object.url, true, true);
var options = {
hostname: parsedUrl.hostname,
port: object.port || 8080,
path: parsedUrl.path,
method: object.method || 'GET',
auth: getAuthByHost(parsedUrl.hostname)
};
if (object.headers) {
options.headers = object.headers;
}
var response = null;
var req = http.request(options, function(res) {
response = res;
res.on('data', function (data) {
accumulator = accumulator + data.toString();
res.resume();
});
res.on('close', function () {
// first assume accumulator is JSON object
var responseContent;
try {
responseContent = JSON.parse(accumulator);
}
// if not object, use accumulator as string
catch (err) {
responseContent = accumulator;
}
callback(responseContent, response.statusCode);
if (responseCB) {
responseCB(res);
}
});
});
req.on('close', function () {
// first assume accumulator is JSON object
var responseContent;
try {
responseContent = JSON.parse(accumulator);
}
catch (err) {
responseContent = accumulator;
}
callback(responseContent, response.statusCode);
if (responseCB) {
responseCB(response);
}
});
if (postData) {
req.write(postData);
}
req.end();
}
try this, it works for me:
var auth = 'Basic yourUserToken';
var jobOptions = {
url:'jenkinsHostName:8080/jenkins/job/jobName/' +'build',
method: 'POST',
port: 8080
};
var parameter = {"parameter": [{"name":"ref", "value":"origin/master"}]};
var postData;
if (!_.isEmpty(parameter)) {
var jsonParametersString = JSON.stringify(parameter);
jobOptions.headers = {
'Authorization':auth,
'Content-Type': 'application/x-www-form-urlencoded',
};
jobOptions.url += '?token=jobRemoteTriggerToken';
postData = "json="+jsonParametersString;
console.log("postData = " + postData);
}
var callback;
var responseCB;
makeRequest(jobOptions, callback, responseCB, postData) ;
It is based on your code. I removed the querystring - it seems that it returned an empty string when performed on the parameters object. I change /buildWithParameters to /build - it didn't work the other way.
In addition, verify that when you pass the 'Content-Length' in the header, it doesn't truncated your json parameters object (I removed it ).
also note that I used the user API token, that you can get at http://yourJenkinsUrl/me/configure and click the "Shown API Token" button.
Not sure about this, as I don't know Node.js -- but maybe this fits: the Jenkins remote access API indicates that the parameter entity in the json request must point to an array, even if there's just one parameter to be defined.
Does the change below fix the problem (note the angle brackets around parameters)?
[...]
var jsonParametersString = JSON.stringify({"parameter": [parameters]});
[...]
//Prepare ‘Account’ object and call create function
function createAccount() {
var new_nit = new Object();
// Set text field
new_nit.Name = "Maddy";
createRecord(new_nit, "new_nitSet", createAccountCompleted, null);
}
// This callback method executes on succesful account creation
function createAccountCompleted(data, textStatus, XmlHttpRequest) {
var nit = data;
alert("Account created; Id: ");
}
// This function creates record by making OData call
function createRecord(entityObject, odataSetName, successCallback, errorCallback) {
//Parse the entity object into JSON
var jsonEntity = window.JSON.stringify(entityObject);
// Get Server URL
var serverUrl = Xrm.Page.context.getServerUrl();
//The OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (successCallback) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
if (errorCallback)
errorCallback(XmlHttpRequest, textStatus, errorThrown);
else
alert("Error on the creation of record; Error – "+errorThrown);
}
});
}
I'm using above code to create a entity called nit. I have json2 and jQuery js files in web resource. When i run this code on button click, i'm getting error as No Transport. when i searched , i got to know that this error is because of cross site scripting. How to enable cross site scripting or how to get rid of this error.
function createAccount() {
var gid = Xrm.Page.getAttribute("new_syllabus").getValue();
var stamail = new Object();
stamail.new_name = "Maddy";
stamail.new_gid = gid;
var myurl = "http://" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
//alert(gid);
// alert(Xrm.Page.data.entity.getId());
var jsoEntity = JSON.stringify(stamail);
var createRecordReq = new XMLHttpRequest();
var ODataPath = myurl + "/XRMServices/2011/OrganizationData.svc";
createRecordReq.open("POST", ODataPath + "/new_nitSet", false);
createRecordReq.setRequestHeader("Accept", "application/json");
createRecordReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
// createRecordReq.onreadystatechange = function () { requestCallBack(this); };
createRecordReq.send(jsoEntity);
var newRecord = JSON.parse(createRecordReq.responseText).d;
}
Instead of using ajax i used above code. Its working fine.