Write grid to text file in html format - asp.net-mvc-4

I have a data grid. I want to submit this data to the server and store it in a text file.
Here's the code I have so far:
var tbl = $('table#grid tbody tr').map(function (idx, el) {
var td = $(el).find('td');
var obj = { id: idx + 1 };
for (var i = 0; i < tblhdr.length; i++) {
obj[tblhdr[i]] = td.eq(i).text();
}
return obj;
}).get();
tbl = JSON.stringify(tbl);
var request = $.ajax({
url: "../reports/S?tbl=" + tbl,//action method url which defined in controller
type: 'POST',
cache: false,
data: JSON.stringify(tbl),
dataType: 'text',
contentType: 'application/text'
});
[HttpPost,ValidateInput(false)]
public ActionResult reports(string tbl)
{
string table = tbl;
StreamWriter file2 = new StreamWriter(#"D:\Demo.txt", true);
file2.WriteLine(tbl);
file2.Flush();
file2.Close();
}
I need the data in HTML form.

Related

How to pass pdf file to Controller that requires IFormFile

I've been working on this the whole day and did my research already, I can't seem to find a solution anywhere. I have this function that calls a List in my controller, the List needs a IFormFile parameter,
here's my javascript method
function fileUploader_uploaded(e) {
const file = e.file;
const fileReader = new FileReader();
fileReader.onload = function () {
toggleDropZoneActive($("#dropzone-external")[0], false);
$("#dropzone-item")[0].data = fileReader.result;
}
fileReader.readAsDataURL(file);
const _fileReader = new FileReader();
var r = _fileReader.readAsBinaryString(file);
$("#dropzone-text")[0].style.display = "none";
$.ajax({
url: '#Url.Action("_Index", "FileUploader")',
data: { CFile: r}, // I'm trying to pass the pdf file here
cache: false,
success: function (data) {
console.log(data);
}
});
}
and this is my List in controller
public object _Index(IFormFile CFile)
{
if (CFile != null)
{
try
{
string documentText = "";
using PdfDocumentProcessor documentProcessor = new PdfDocumentProcessor();
documentProcessor.LoadDocument(CFile.OpenReadStream());
documentText = documentProcessor.Text;
string word = #"([0-9]+.[0-9]+-[0-9]+)";
Regex regex = new Regex(word);
foreach (Match match in regex.Matches(documentText))
{
sectionsList.Add(match.Value.ToString());
}
}
catch
{
Response.StatusCode = 400;
}
}
else
{
_logger.LogInformation("empty");
}
return sectionsList;
}
the CFile is always empty i tried different ways already like passing
data: { CFile: e.file}
Does anyone else have idea?
From this code data: { CFile: e.file}, you post it as the string, so it can not be recognized as a file. You need to use FormData and change the contentType.
function fileUploader_uploaded(e) {
const file = e.file;
const fileReader = new FileReader();
fileReader.onload = function () {
toggleDropZoneActive($("#dropzone-external")[0], false);
$("#dropzone-item")[0].data = fileReader.result;
}
fileReader.readAsDataURL(file);
const _fileReader = new FileReader();
var r = _fileReader.readAsBinaryString(file);
$("#dropzone-text")[0].style.display = "none";
//----------edit here---------
var form = new FormData()
form.append('CFile', file)
$.ajax({
url: '#Url.Action("_Index", "FileUploader")',
method:'post',
data: form,
cache: false,
contentType: false,
processData: false,
success: function (data) {
}
});
}
The bakend should add [FromForm].
[HttpPost]
public object _Index([FromForm]IFormFile CFile)

How to pass HTML(View) Table data to controller to save in slq table

I am calculating the some values based on data available for previous month and displaying in table format in view. I have another model where I need to pass these values and save in database. I am not inputting any value, either values are static or calculated. Values are not passed from view to controller.
I have tried the jquery/ajax but not successful.
//Controller//
[HttpPost]
public JsonResult Proccess(List<ServerCount> deviceCounts)
{
if(deviceCounts == null)
{
deviceCounts = new List<ServerCount>();
}
var startOfTthisMonth = new DateTime(DateTime.Today.Year,
DateTime.Today.Month, 1);
var FromDate = startOfTthisMonth.AddMonths(-1);
var ToDate = startOfTthisMonth.AddDays(-1);
var billMonth = startOfTthisMonth.AddMonths(-1).ToString("MMM") + "-" + startOfTthisMonth.AddMonths(-1).ToString("yyyy");
ServerCount model = new ServerCount();
foreach (ServerCount sc in deviceCounts)
{
model.BillingMonth = billMonth;
model.ServiceName = sc.ServiceName;
model.BaslineVol = sc.BaslineVol;
model.ResourceUnit = sc.ResourceUnit;
model.DeviceCount = sc.DeviceCount;
model.DeployedServer = sc.DeployedServer;
model.RetiredServer = sc.RetiredServer;
_context.ServerCount.Add(model);
}
int insertRecords = _context.SaveChanges();
return Json(insertRecords);
}
==================
Jquery
<script type="text/javascript">
$(document).ready(function () {
$("body").on("click", "#btnSave", function () {
var deviceCounts = new Array();
$("#tblServerCount TBODY TR").each(function () {
var row = $(this);
var deviceCount = {};
deviceCount.ServiceName = row.find("TD").eq(0).html();
deviceCount.BaslineVol = row.find("TD").eq(1).html();
deviceCount.ResourceUnit = row.find("TD").eq(2).html();
deviceCount.DeviceCount = row.find("TD").eq(3).html();
deviceCount.DeployedServer = row.find("TD").eq(4).html();
deviceCount.RetiredServer = row.find("TD").eq(5).html();
deviceCounts.push(deviceCount);
});
var model = $("#MyForm").serialize();
$.ajax({
type: "POST",
url: '#Url.Action("Proccess", "DeviceCountServers", new { Area = "Admin" })?' +model,
data: JSON.stringify(deviceCounts),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
alert(r + " record(s) inserted.");
location.reload();
});
});
});
</script>
I looking that data from table is saved to sql on click of button

Sensenet Content Picker Customization

I created two custom content types, ProjectContract and PaymentRequest. Under PaymentRequest, I have a reference field Contract which I would like to use to reference ProjectContract. When I am creating/changing PaymentRequest, I need the following:
how can I initialize Content Picker to display ContractNumber field of available ProjectContracts?
how can I display selected ProjectContract's ContractNumber under ReferenceField Grid control?
The SN js code and the mvc contains/returns fix field values. I did not find any setting where I can add custom fields to show.
First of all, what is the version of that SN package, because the oData.svc request will not work on older versions. It is available from 6.2.
About the oData, here is a link: http://wiki.sensenet.com/OData_REST_API
There is another way to solve it, but with this, you need to modify the existion SN codes.
You need to copy (" /Root/Global/scripts/sn/SN.Picker.js ") file into your skin folder with the same structure. (" /Root/Skins/[yourskinfolder]/scripts/sn/SN.ReferenceGrid.js ")
You need to copy (" /Root/Global/scripts/sn/SN.ReferenceGrid.js ") file into your skin folder as well.
Do not modify the original SN file, because it will be overwrite after an SN update.
Next step: copy the following code to line 1068, before the ("$grid.jqGrid({") line, into the InitGrid function.
...
var neededTypeName = "ProjectContract";
var neededFieldName = "ContractNumber";
var findField = false;
o2 = (function () {
var result = [];
var itemArray = [];
$.each(o2, function (index, el) {
el.ContentField = "";
result.push(el);
if (el.ContentTypeName == neededTypeName) {
itemArray.push([index, el.Path]);
findField = true;
}
});
if (findField) {
$.each(itemArray, function (itemIndex, itemElArray) {
var itemId = itemElArray[0];
var itemEl = itemElArray[1];
var thisLength = itemEl.length;
var thislastSplash = itemEl.lastIndexOf("/");
var thisPath = itemEl.substring(0, thislastSplash) + "('" + itemEl.substring(thislastSplash + 1, thisLength) + "')";
$.ajax({
url: "/oData.svc" + thisPath + "?metadata=no$select=Path," + neededFieldName,
dataType: "json",
async: false,
success: function (d) {
result[itemId].ContentField = d.d[neededFieldName];
}
});
});
colNames.splice(6, 0, "ContentField");
colModel.splice(6, 0, { index: "ContentField", name: "ContentField", width: 100 });
return result;
}
return o2;
})();
...
$grid.jqGrid({
...
The "neededTypeName" may contains your content type value, and the "neededFieldName" may contains the field name you want to render.
The other will build up the grid.
This will modify the Content picker table.
You need to add this code into the GetResultDataFromRow function, at line 660 before the return of the function.
...
if (rowdata.ContentField != undefined) {
result.ContentField = rowdata.ContentField;
}
...
This will add the selected item properties from the Content picker to the reference field table.
Then you need to open the SN.ReferenceGrid.js and add the following code into the init function before the "var $grid = $("#" + displayAreaId);"
var neededTypeName = "CustomItem2";
var neededFieldName = "Custom2Num";
var findField = false;
var alreadyAdded = false;
var btnAttr = $("#"+addButtonId).attr("onClick");
if (btnAttr.indexOf(neededTypeName) > -1) {
alreadyAdded = true;
colNames[4].width = 150;
colModel[4].width = 150;
colNames.splice(3, 0, "ContentField");
colModel.splice(3, 0, { index: "ContentField", name: "ContentField", width: 60 });
}
initialSelection = (function () {
var result = [];
var itemArray = [];
$.each(initialSelection, function (index, el) {
el.ContentField = "";
result.push(el);
if (el.ContentTypeName == neededTypeName) {
itemArray.push([index, el.Path]);
findField = true;
}
});
if (findField) {
$.each(itemArray, function (itemIndex, itemElArray) {
var itemId = itemElArray[0];
var itemEl = itemElArray[1];
var thisLength = itemEl.length;
var thislastSplash = itemEl.lastIndexOf("/");
var thisPath = itemEl.substring(0, thislastSplash) + "('" + itemEl.substring(thislastSplash + 1, thisLength) + "')";
$.ajax({
url: "/oData.svc" + thisPath + "?metadata=no$select=Path," + neededFieldName,
dataType: "json",
async: false,
success: function (d) {
result[itemId].ContentField = d.d[neededFieldName];
}
});
});
if (!alreadyAdded) {
colNames.splice(3, 0, "ContentField");
colModel.splice(3, 0, { index: "ContentField", name: "ContentField", width: 100 });
}
return result;
}
return initialSelection;
})();
I hope this will help but the SN version should be helpful.

MVC ResultStream only working with link

I'm creating a barcode using ASP.Net MVC
The problem is it's working with links. But it needs to work with form values.
This is my controller :
[HttpPost]
public ActionResult Barcode(BarcodeModel B)
{
string BarcodeTitle = B.BarkodTitle;
string BarcodeNumber = B.BarcodeNumber;
Codec objbar = new Codec();
Byte[] BarcodeImage = objbar.getBarcodeImage(BarcodeNumber, BarcodeTitle);
Stream Memory = new MemoryStream(BarcodeImage);
Memory.Position = 0;
var Result = new FileStreamResult(Memory, "image/png");
Result.FileDownloadName = String.Format("{0}.png", BarcodeTitle);
return Result ;
}
This is my JavaScript code :
<script type="text/javascript">
function BarkodKaydet()
{
var BarkodModel = new Object();
BarkodModel.DeweyCode = document.getElementById('DeweyCode').value;
BarkodModel.CutterNumber = document.getElementById('CutterNumber').value;
BarkodModel.Year = document.getElementById('Year').value;
BarkodModel.Bind = document.getElementById('Bind').value;
BarkodModel.Copy = document.getElementById('Copy').value;
BarkodModel.BarcodeTitle = document.getElementById('BarcodeTitle').value;
BarkodModel.BarcodeNumber = document.getElementById('BarcodeNumber').value;
$.ajax({
type: "post",
url: "#Url.Action("Barcode")",
dataType : "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(BarkodModel),
success: function (data) { console.log(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
</script>
But it's not working.
It' just working with link how I'm changing controller to ;
public ActionResult Barcode(string barcodeNumber, string barcodeText)
{
Codec objbar = new Codec();
Byte[] BarkodImage = objbar.getBarcodeImage(barcodeNumber, barcodeTitle);
Stream Memory = new MemoryStream(BarcodeImage);
Memory.Position = 0;
var Result = new FileStreamResult(Memory, "image/png");
Result.FileDownloadName = String.Format("{0}.png", BarcodeTitle);
return Result ;
}
this and change view to ;
<img src="/Home/BarcodeImage?barcodeText=Can&barcodeNo=12345" />
to this.
When the page opening, the linked image sending values to controller and showing barcode to me.
But I need;
When the form values submitting to model, ActionResult needs to create barcode from model, refresh the same page and It will show only barcodeImage to me.
How can I configure it ?
Best regards.

SAPUI5 file upload

I am creating an SAPUI5 app that needs to upload attachments. I still am very new use SAPUi5. I want to save the uploaded file to the DB. Could I use the Document service? If so please provide me with docs or tutorials to do so.
I have done that in one off my SAPUI5 apps, for the uploading function check out my gist.
Or check this for reference
onUpload: function(e) {
var fU = this.getView().byId("idfileUploader");
var domRef = fU.getFocusDomRef();
var file = domRef.files[0];
var reader = new FileReader();
reader.onload = function(oEvent) {
var strCSV = oEvent.target.result;
var arrCSV = strCSV.match(/[\w .]+(?=,?)/g);
var noOfCols = 6;
var headerRow = arrCSV.splice(0, noOfCols);
var data = [];
while (arrCSV.length > 0) {
var obj = {};
var row = arrCSV.splice(0, noOfCols);
for (var i = 0; i < row.length; i++) {
obj[headerRow[i]] = row[i].trim();
}
data.push(obj);
}
};
reader.readAsBinaryString(file);
}
Irrespective of whether you use DB or Document Service, with respect to SAPUI5,
you can use sap.ui.unified.FileUploader. Read more here
Sample XML code would be:
<sap.ui.unified:FileUploader
id="fileUploader"
width="100%"
uploadUrl=""
placeholder="Add attachment"
uploadOnChange="false"
uploadComplete="handleUploadComplete"
change="handleValueChange"
typeMissmatch="handleTypeMissmatch"
style="Emphasized"
useMultipart="false" >
</sap.ui.unified:FileUploader>
While uploading make sure, you add slug and x-csrf-token to the headerparameters.
Example:
var oFileUploader = _this.byId("fileUploader");
oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
name: "slug",
value: oFileUploader.getValue()
}));
oFileUploader.addHeaderParameter(new sap.ui.unified.FileUploaderParameter({
name: "x-csrf-token",
value: _this.oDataModel.getSecurityToken()
}));
oFileUploader.upload();
And if you are using ABAP Netweaver gateway stack, you need to implement CREATE_STREAM method in DPC_EXT classes. Also need to make sure that pareticular EventType with "media" supported in Gateway model.
uploadFile:function{
var that = this;
var count = 0;
var o = "<URI>";
var h = new sap.ui.model.odata.ODataModel(o, true);
var d = "";
h.setSizeLimit(5000);
h.forceNoCache(true);
var b = ({
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
"X-CSRF-Token": "Fetch",
});
OData.request({
requestUri: o,
method: "GET",
headers: b
}, function (e, j) {
d = j.headers["x-csrf-token"];
that.csrfToken = d;
that.getModel("oAppData").setProperty("/busyIndicators/uploadFile", true);
for (var l = 0; l < that.fileDataAD.length; l++) {
var i = "<URI>";
var h = new sap.ui.model.odata.ODataModel(i, true);
h.setSizeLimit(5000);
h.forceNoCache(true);
var b = ({
"X-CSRF-Token": that.csrfToken,
"Slug": that.fileDataAD[l].fileName + "|" + that.fileDataAD[l].fileType + "|" + "B" + "|" + reqId + "|" + 1
});
OData.request({
requestUri: i,
method: "POST",
headers: b,
data: that.fileDataAD[l].file
}, function (oData, oRes) {
count = count + 1;
if (count === that.fileDataAD.length) {
that._uploadCompleteAddDependent();
}
}.bind(this), function (oError) { }
}
});
}
where fileDataAD is buffer array