How to read the content from a C# HttpResponseMessage in javascript? - javascript

I have a string called csv that is literally just that, things like "name,lastname,age,height,etc"
Then I send it to the backend like this..
var csv = exportRequests.GetCSV();
var filename = string.Format("{0}-{1}-{2:yyyy-MM-dd_hh-mm-ss-tt}.csv", "Request", requestStatus.ToUpperInvariant(), DateTime.Now);
var stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(csv);
writer.Flush();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = filename
};
result.Content.Headers.ContentType =
new MediaTypeHeaderValue("text/csv");
//var test = new FileDetailViewModel();
//test.Name = filename;
//test.Rows = csv;
return Ok(result);
I then read it on the backend, but where is the actual content?? Surely the bytes should be somewhere. The content property only has the headers.. This is taking place on an old system using $.ajax to make the call.
Thanks

I do not think it is possible to read content via HttpResponseMessage in JavaScript. You can only download content.
public HttpResponseMessage GetCsv()
{
var csv = exportRequests.GetCSV();
var filename = string.Format("{0}-{1}-{2:yyyy-MM-dd_hh-mm-ss-tt}.csv", "Request", requestStatus.ToUpperInvariant(), DateTime.Now);
var stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(csv);
writer.Flush();
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(stream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
new ContentDispositionHeaderValue("attachment")
{
FileName = filename
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("text/csv");
return result;
}
download script
window.open('/api/controller/GetCsv', '_blank', '');
If you want to display csv content you can use the following code
[HttpPost]
public String GetCsv()
{
return exportRequests.GetCSV();
}
script
$('#btngetcsv').click(function() {
$.ajax({
url: "/api/controller/GetCsv",
data: {},
type: "Post",
dataType: "Json",
success: function(result) {
var arr = csvToArray(result);
for (var i = 0; i < arr.length; i++) {
var name = arr[i].name;
var lastname = arr[i].lastname;
//etc...........
}
},
error: function() {
}
});
});
function csvToArray(str, delimiter = ",") {
// slice from start of text to the first \n index
// use split to create an array from string by delimiter
const headers = str.slice(0, str.indexOf("\n")).split(delimiter);
// slice from \n index + 1 to the end of the text
// use split to create an array of each csv value row
const rows = str.slice(str.indexOf("\n") + 1).split("\n");
// Map the rows
// split values from each row into an array
// use headers.reduce to create an object
// object properties derived from headers:values
// the object passed as an element of the array
const arr = rows.map(function(row) {
const values = row.split(delimiter);
const el = headers.reduce(function(object, header, index) {
object[header] = values[index];
return object;
}, {});
return el;
});
// return the array
return arr;
}

Related

Trying to download zip file from server using AngularJs and c# webapi

I know that posts with similar titles exist, but it doesn't work for me its how I try to achieve that:
WebApi
public async Task<HttpResponseMessage> ExportAnalyticsData([FromODataUri] int siteId, [FromODataUri] string start, [FromODataUri] string end) {
DateTime startDate = Date.Parse(start);
DateTime endDate = Date.Parse(end);
using (ZipFile zip = new ZipFile()) {
using (var DailyLogLanguagesCsv = new CsvWriter(new StreamWriter("src"))) {
var dailyLogLanguages = await _dbContext.AggregateDailyLogSiteObjectsByDates(siteId, startDate, endDate).ToListAsync();
DailyLogLanguagesCsv.WriteRecords(dailyLogLanguages);
zip.AddFile("src");
}
using (var DailyLogSiteObjectsCsv = new CsvWriter(new StreamWriter("src"))) {
var dailyLogSiteObjects = await _dbContext.AggregateDailyLogSiteObjectsByDates(siteId, startDate, endDate).ToListAsync();
DailyLogSiteObjectsCsv.WriteRecords(dailyLogSiteObjects);
zip.AddFile("src");
}
zip.Save("src");
HttpResponseMessage result = null;
var localFilePath = HttpContext.Current.Server.MapPath("src");
if (!File.Exists(localFilePath)) {
result = Request.CreateResponse(HttpStatusCode.Gone);
} else {
// Serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "Analytics";
}
return result;
}
}
AngularJs
$scope.exportData = function () {
apiService.dailyLog.exportAnalyticsData($scope.siteId, $scope.startDate, $scope.finishDate).then(function (response) {
debugger;
var blob = new Blob([response.data], { type: "application/zip" });
saveAs(blob, "analytics.zip");
})
};
function saveAs(blob, fileName) {
var url = window.URL.createObjectURL(blob);
var doc = document.createElement("a");
doc.href = url;
doc.download = fileName;
doc.click();
window.URL.revokeObjectURL(url);
}
And when I download a file I get information that the file is damaged. It only happens when I return zip file. It works well for csv.
After #wannadream suggestions and edited my code
else
{
// Serve the file to the client
result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(new FileStream(localFilePath, FileMode.Open, FileAccess.Read));
result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
result.Content.Headers.ContentDisposition.FileName = "Analytics";
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
I have such problem when i try to open downloaded zip.
Try accessing the WebAPI controller action through a normal browser, and see if the ZIP it downloads can open. If it can't, then your problem is in your WebAPI.
zip.AddFile("src"); and then zip.Save("src"); ? It does not make sense.
You are zipping 'src' with target name 'src'. Try another name for zip file.
zip.Save("target")
var localFilePath = HttpContext.Current.Server.MapPath("target");
Try set this:
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
I resolve it by set a type responseType
{ type: "application/octet-stream", responseType: 'arraybuffer' }
and the same thing in my apiService
$http.get(serviceBase + path), {responseType:'arraybuffer'});
This can be done using DotNetZip and set the response type as arraybuffer, check below code for complete understanding.
1.WebApi Controller
[HttpPost]
[Route("GetContactFileLink")]
public HttpResponseMessage GetContactFileLink([FromBody]JObject obj)
{
string exportURL = "d:\\xxxx.text";//replace with your filepath
var fileName = obj["filename"].ToObject<string>();
exportURL = exportURL+fileName;
var resullt = CreateZipFile(exportURL);
return resullt;
}
private HttpResponseMessage CreateZipFile(string directoryPath)
{
try
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddFile(directoryPath, "");
//Set the Name of Zip File.
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
using (MemoryStream memoryStream = new MemoryStream())
{
//Save the Zip File to MemoryStream.
zip.Save(memoryStream);
//Set the Response Content.
response.Content = new ByteArrayContent(memoryStream.ToArray());
//Set the Response Content Length.
response.Content.Headers.ContentLength = memoryStream.ToArray().LongLength;
//Set the Content Disposition Header Value and FileName.
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = zipName;
//Set the File Content Type.
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;
}
}
}
catch(Exception ex)
{
throw new ApplicationException("Invald file path or file not exsist");
}
}
2.Angular component
function getcontactFileLink(token, params) {
return $http.post('api/event/GetContactFileLink', params, { headers: { 'Authorization': 'Bearer ' + token, 'CultureCode': cc }, 'responseType': 'arraybuffer' }).then(response);
function response(response) {
return response;
}
}
function showcontactfile(item) {
usSpinnerService.spin('spinner-1');
var params = {};
params.filename = item.filename;
EventListingProcess.getcontactFileLink(accessToken, params).then(function (result) {
var blob = new Blob([result.data], { type: "application/zip" });
var fileName = item.filename+".zip";
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display:none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}).catch(function (error) {
vm.message = frameworkFactory.decodeURI(error.statusText);
//frameworkFactory.translate(vm, 'message', error.statusText);
}).finally(function () {
usSpinnerService.stop('spinner-1');
});
}

How to append div by ajax

i'm trying to retrieve values from database after that how can i pass those values from that static method and append to div in ajax ,Here is the C# code for that
[WebMethod]
[ScriptMethod]
public static string[] Cdetails(Cmpny cmpny)
{
StringBuilder html = new StringBuilder();
string strCname = cmpny.Cname;
string strCvalue= cmpny.Cvalue;
string strLvl = cmpny.Clevel;
int intLvl = Convert.ToInt32(strLvl);
List<string> company = new List<string>();
if (intLvl == 1)
{
SqlConnection conn = new SqlConnection(HttpContext.Current.Session["ConnectionString"].ToString());
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select Clientid,C_Name,C_website,Status,CreatedDate,CreatedBy,ModifiedDate,ModifiedBy from clientDetails where Clientid=#Clientid and C_Name=#C_Name";
cmd.Parameters.AddWithValue("#C_Name", strCname);
cmd.Parameters.AddWithValue("#Clientid", strCvalue);
cmd.Connection = conn;
conn.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
company.Add(string.Format("{0}-{7}", sdr["Clientid"], sdr["C_Name"], sdr["C_website"], sdr["Status"], sdr["CreatedDate"], sdr["CreatedBy"], sdr["ModifiedDate"], sdr["ModifiedBy"]));
}
}
conn.Close();
}
}
//else
//{
// return strLvl.ToArray();
//}
return company.ToArray();
}
and ajax method is here
<script type="text/javascript">
function OnTreeClick(evt) {
var src = window.event != window.undefined ? window.event.srcElement : evt.target;
var nodeClick = src.tagName.toLowerCase() == "a";
if (nodeClick) {
var nodeText = src.innerText || src.innerHTML;
var nodeValue = GetNodeValue(src);
var nodePath = src.href.substring(src.href.indexOf(",") + 2, src.href.length - 2);
//alert(nodePath.toLowerCase());
if (nodePath.indexOf("\\") > -1)
{
var level = "2";
// alert("Second level ");
}
else
{
var level = "1";
// alert(" first level ");
}
//var nodestat =
alert("Text: " + nodeText + "," + "Value: " + nodeValue );
var cmpny = {};
cmpny.Cname = nodeText;
cmpny.Cvalue = nodeValue;
cmpny.Clevel = level;
$.ajax({
type: "POST",
url: "CS.aspx/Cdetails",
data: '{cmpny: ' + JSON.stringify(cmpny) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
div_ClientLoc.innerHTML = response.d;//here how can i append those tag and div_ClientLoc is div id
// window.location.reload();
}
});
return false;
}
return true;
}
function GetNodeValue(node) {
var nodeValue = "";
//alert(node.href.toLowerCase());
var nodePath = node.href.substring(node.href.indexOf(",") + 2, node.href.length - 2);
// alert(nodePath.toLowerCase());
var nodeValues = nodePath.split("\\");
if (nodeValues.length > 1)
nodeValue = nodeValues[nodeValues.length - 1];
else
nodeValue = nodeValues[0].substr(1);
return nodeValue;
}
can anyone please explain me how can i solve this problem
You are overwriting the html of div_ClientLoc by assigning the result to innerHTML. You can use jQuery append() method to append the response result in existing html of div_ClientLoc.
$("#div_ClientLoc").append(response.d);
Or you can also append the result in div_ClientLoc.innerHTML by using Addition Assignment Operator += instead of assignment operator = like as under
div_ClientLoc.innerHTML += response.d;
You need to get a hold of the element that you are appending to, then insert the HTML.
You can use document.getElementById('div_ClientLoc') to get your target element.
insertAdjacentHTML will insert the content at beforeend, which is before the closing tag.
document.getElementById('div_ClientLoc').insertAdjacentHTML('beforeend', response.d);

How to log contents of HTML5 drag and drop file that is 60MB+ without hanging for minutes?

I have a file that i want to drop on a page and read file contents. its a CSV with 9 columns. My drop command outputs file contents like this:
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.files[0];
var fileReader = new FileReader();
fileReader.onload = function (e) {
console.log(fileReader.result)
};
fileReader.onerror = function (e) {
throw 'Error reading CSV file';
};
// Start reading file
fileReader.readAsText(data);
return false;
}
When I drag and drop a simple file that is a couple kilobytes or 1MB, I can see the output of the contents of the file. However given a large CSV file, it takes many many minutes before it shows up. Is there a way to make it so that there is some streaming maybe where it does not look like its hanging?
With Screw-FileReader
You can get a ReadableStream and do it in a streaming fashion
'use strict'
var blob = new Blob(['111,222,333\naaa,bbb,ccc']) // simulate a file
var stream = blob.stream()
var reader = stream.getReader()
var headerString = ''
var forEachLine = function(row) {
var colums = row.split(',')
// append to DOM
console.log(colums)
}
var pump = function() {
return reader.read().then(function(result) {
var value = result.value
var done = result.done
if (done) {
// Do the last line
headerString && forEachLine(headerString)
return
}
for (var i = 0; i < value.length; i++) {
// Get the character for the current iteration
var char = String.fromCharCode(value[i])
// Check if the char is a new line
if (char.match(/[^\r\n]+/g) !== null) {
// Not a new line so lets append it to
// our header string and keep processing
headerString += char
} else {
// We found a new line character
forEachLine(headerString)
headerString = ''
}
}
return pump()
})
}
pump().then(function() {
console.log('done reading the csv')
})
<script src="https://cdn.rawgit.com/jimmywarting/Screw-FileReader/master/index.js"></script>
If you prefer using the old FileReader without dependencies, pipe's and transform
'use strict'
var blob = new Blob(['111,222,333\naaa,bbb,ccc']) // simulate a file
var fr = new FileReader()
var headerString = ''
var position = 0
var forEachLine = function forEachLine(row) {
var colums = row.split(',')
// append to DOM
console.log(colums)
}
var pump = function pump() {
return new Promise(function(resolve) {
var chunk = blob.slice(position, position + 524288)
position += 524288
fr.onload = function() {
var value = fr.result
var done = position >= blob.size
for (var i = 0; i < value.length; i++) {
var char = value[i]
// Check if the char is a new line
if (char.match(/[^\r\n]+/g) !== null) {
// Not a new line so lets append it to
// our header string and keep processing
headerString += char
} else {
// We found a new line character
forEachLine(headerString)
headerString = ''
}
}
if (done) {
// Send the last line
forEachLine(headerString)
return resolve() // done
}
return resolve(pump())
}
// Read the next chunk
fr.readAsText(chunk)
})
}
pump().then(function() {
console.log('done reading the csv')
})

getting "undefined" when i print json array with js

I want to parse json array it came down from json.jsp, but when i access parse.js it displays undefined
Here is parse.js
$(document).ready(function() {
$('#login').click(function(event) {
$.get('json.jsp', {
}, function(responseText) {
var myJSONObject1 = responseText;
var myJSONObject = JSON.parse(myJSONObject1);
var len = myJSONObject.length;
var out = "";
for (var i = 0; i < len; i++) {
var student = myJSONObject[i];
out += "<li>"+student.ircEvent + "<li>" + student.method+"<li>"+student.regex;
}
document.getElementById("ajaxResponse").innerHTML = out;
});
});
});
and my json.jsp is,
<%
response.setContentType("plain/text");
User user = new User("RAM","ram#gmail.com");
User user1 = new User("Ravi","ravi#gmail.com");
User user2 = new User("Raghu","raghu#gmail.com");
List list = new ArrayList();
list.add(user);list.add(user1);list.add(user2);
String json = new Gson().toJson(list);
response.getWriter().write(json);
%>
when i access parse.js file, it displays undefined
any ideas......
Just use $.ajax and set the dataType to json. No need to parse anything. jQuery does it for you. http://api.jquery.com/jquery.ajax/
jQuery(document).ready(function($) {
$.ajax({
url: 'json.jsp',
type: 'get',
dataType: 'json',
success: function(data) {
if (data.length) {
var ajaxResponse = document.createElement('table'),
tbody = document.createElement('tbody');
for (var i in data) {
if (data.hasOwnProperty(i)) {
var tr = document.createElement('tr'),
key = document.createElement('td'),
keyText = document.createTextNode(i),
value = document.createElement('td'),
valueText = document.createTextNode(data[i]);
key.appendChild(keyText);
tr.appendChild(key);
value.appendChild(valueText);
tr.appendChild(value);
tbody.appendChild(tr);
}
}
ajaxResponse.appendChild(tbody);
$("#ajaxResponse").append(ajaxResponse);
}
else alert("No data returned!");
}
});
});

Trying to sort repeater rows with this jQuery

I am trying to sort repeater rows with this jquery . But I am not able to save sort items. Please help me . how can save sorting in database as well as in .aspx page?Thank you in advance
<script language="javascript" type="text/javascript">
$("#defaultList").sortable();
$(document).ready(function () {
$("#defaultList").sortable(
{
update: function (ev, ui) {
var result = $('#defaultList').sortable('toArray');
updateSequenceNumber(result);
}
}
);
});
function updateSequenceNumber(items) {
var originalIdAndSequenceNumber = '';
var index = 0;
for (i = 0; i <= items.length - 1; i++) {
if (items[i].length == 0)
continue;
var item = $('#' + items[i])[0];
originalIdAndSequenceNumber += item.attributes["originalId"].nodeValue + ":" + index.toString();
originalIdAndSequenceNumber += "|";
index = index + 1;
}
persistPositionUsingAjax(originalIdAndSequenceNumber);
}
function persistPositionUsingAjax(originalIdAndSequenceNumber) {
$.ajax(
{
type: "POST",
dataType: "text",
url: "AjaxService.asmx/UpdateSequenceNumber",
data: "s=" + originalIdAndSequenceNumber,
success: function (response) {
}
}
);
}
my ajax method:
[WebMethod]
public string UpdateSequenceNumber(string s)
{
s = s.TrimEnd('|');
string updateQuery = #"update dnn_Table_1 set SortId = {0}
where ImageId = {1}";
StringBuilder sb = new StringBuilder();
string[] originalIdAndSeqNumberArray = s.Split('|');
foreach (var originalIdAndSeqNumberCombined in originalIdAndSeqNumberArray)
{
var tempArray = originalIdAndSeqNumberCombined.Split(':');
int originalId = Convert.ToInt32(tempArray[0]);
int sequenceNumber = Convert.ToInt32(tempArray[1]);
sb.Append(String.Format(updateQuery, sequenceNumber, originalId));
sb.Append(System.Environment.NewLine);
}
UpdateInDatabase(sb.ToString());
return "Hello World";
}
private void UpdateInDatabase(string updateQuery)
{
SqlDataProvider sqd = new SqlDataProvider();
string ConnectionString = sqd.ConnectionString;
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(updateQuery, conn);
command.CommandText = updateQuery;
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
What status code does the ajax call return?
To me it looks like a 500. You are building an update statement that after a few iterations will look something like this
update dnn_Table_1 set SortId = 3 where ImageId = 2update dnn_Table_1 set SortId = 2 where ImageId = 4update dnn_Table_1 set SortId = 7 where ImageId = 6
That just won't work. Try eihter constructing the SQL update differently or move UpdateInDatabase into the foreach loop.
There might be other issues which I didn't spot, but this might be a starting point.
Hope that helps

Categories

Resources