Capture MVC View from controller - javascript

How can I get the view from the controller? I am trying to convert the page to an image and using the webclientPrint to send the image to a thermal printer.
I can not use window.print(); because the thermal printer may not accept the data and I also don't want to show the printer dialog to the user also.
Review
I want to capture whole web page and convert it to an image.
function Printlabel() {
debugger
if (navigator.appName == "Microsoft Internet Explorer") {
var PrintCommand = '<object ID="PrintCommandObject" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></object>';
document.body.insertAdjacentHTML('beforeEnd', PrintCommand);
PrintCommandObject.ExecWB(6, -1); PrintCommandObject.outerHTML = "";
}
else {
var contents = document.getElementById("PrintArea").innerHTML;
var frame1 = document.createElement('iframe');
frame1.name = "frame1";
frame1.style.position = "absolute";
frame1.style.top = "-1000000px";
document.body.appendChild(frame1);
var frameDoc = frame1.contentWindow ? frame1.contentWindow : frame1.contentDocument.document ? frame1.contentDocument.document : frame1.contentDocument;
frameDoc.document.open();
frameDoc.document.write('<html><head><title></title>');
frameDoc.document.write('<link rel="stylesheet" type="text/css" href="/Styles/labelStyle.css" media="print">');
frameDoc.document.write('</head><body>');
frameDoc.document.write(contents);
frameDoc.document.write('</body></html>');
frameDoc.document.close();
setTimeout(function () {
window.frames["frame1"].focus();
window.frames["frame1"].print();
document.body.removeChild(frame1);
}, 500);
}
setTimeout("window.open('', '_self', ''); window.close();", 5000);
return false;
}

Yes you can, pass the ActionResult from controller and getting back html from the view as a string, with this method :
private string RenderActionResultToString(ActionResult result)
{
// Create memory writer.
var sb = new StringBuilder();
var memWriter = new StringWriter(sb);
// Create fake http context to render the view.
var fakeResponse = new HttpResponse(memWriter);
var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request,
fakeResponse);
var fakeControllerContext = new ControllerContext(
new HttpContextWrapper(fakeContext),
this.ControllerContext.RouteData,
this.ControllerContext.Controller);
var oldContext = System.Web.HttpContext.Current;
System.Web.HttpContext.Current = fakeContext;
// Render the view.
result.ExecuteResult(fakeControllerContext);
// Restore old context.
System.Web.HttpContext.Current = oldContext;
// Flush memory and return output.
memWriter.Flush();
return sb.ToString();
}

Related

How to open relative information onClick on dynamically created child

I am creating timers for workers. A user can add worker with some time. After that it will create a countdown timer for that worker. Start time and target time is saved on database so i am starting timer according to that. And the timer is worked fine. Now i want that if i click on any of the created child it should i want to call my php with POST id of the Work which is added on child creation and then open detailed information of the work which was filled when worker was added. So basically i want help in post WorkID of the selected child on click and call my php script.
On Page load i am getting data like this
function GetMachineSinger() {
var http = new XMLHttpRequest();
var url = 'php/StitchTimerSinger.php';
http.open('GET', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
for(var i=0;i<jsonResponse.length;i++){
var index = jsonResponse[i];
var empname = index["EmployeeName"];
var hour = index["Hour"];
var minute = index["Min"];
var second = index["Sec"];
var available = index["Available"];
var id = index["WorkID"];
if(available<50){
addEmployee(id,empname,hour,minute,second);
}
document.getElementById("avlmc").innerHTML = available;
}
}
}
http.send();
}
addEmployee()
function addEmployee(id,emp,hr,mi,sec)
{
var employee = new Employee(id,emp,hr,mi,sec);
display.appendChild(employee.domObj);
employee.startTimer();
}
class Employee
{
constructor(id,name,hr,min,sec)
{
var self=this;
this.timer;
this.timeInSec;
this.domObj=document.createElement("div");
this.timeSpan=document.createElement("span");
this.domObj.style.backgroundColor = '#4CA';
this.domObj.style.border = 'none';
this.domObj.style.height = '100px';
this.domObj.style.width = '100px';
this.domObj.style.color = 'white';
this.domObj.style.padding = '20px';
this.domObj.style.textAlign = 'center';
this.domObj.style.textDecoration = 'none';
this.domObj.style.display = 'inline-block';
this.domObj.style.fontSize = '26px';
this.domObj.style.borderRadius = '50%';
this.domObj.style.margin = '20px';
this.domObj.style.justifyContent = "center";
this.timeInSec=hr*60*60+min*60+parseInt(sec);
this.timeSpan.innerHTML=hr+":"+min+":"+sec;
this.domObj.innerHTML=name+"<br>";
this.domObj.appendChild(this.timeSpan);
// console.log("0:"+this.timeInSec);
}
startTimer()
{
this.timer=setInterval(this.updateTime.bind(this),1000);
}
updateTime()
{
var hr,min,sec,temp;
if (this.timeInSec<=0)
{
clearInterval(this.timer);
}
else
{
this.timeInSec--;
//console.log("1:"+this.timeInSec);
sec=this.timeInSec % 60;
temp=this.timeInSec-sec;
temp/=60;
//console.log("2:"+temp);
min=temp % 60;
temp-=min;
hr=temp/60;
this.timeSpan.innerHTML=hr+":"+min+":"+sec;
if (min<10 && hr<1){
this.domObj.style.backgroundColor = '#ef5350';
}
}
}
}
Try
this.domObj.addEventListener('click', function (event) {
// do something
//for opening new window
let w = window.open('about:blank','name','height=200,width=150');
// w.document.open()
w.document.write('any HTML');
w.document.close();
});

.NET C# exporting to excel via JS post using ExcelPackage

I'm not sure what I'm missing here. I've got a button that when clicked, I'm using javascript to call a controller. This controller should create an excel file and return it to the user giving them the ability to download/save the file. I've tried a few different methods, but can't manage to get it to work. Here's my javascript side:
function exportList() {
var val = $("#team-dropdown").val();
const date = new Date().toISOString();
const param = {
"Date": date,
"GroupID": 1
}
$.ajax({
url: "#Url.Action("ExportToExcel", "Home")",
type: "POST",
data: param
});
}
Here's my server side:
public FileResult ExportToExcel(DateTime date, int groupID)
{
Load l = new Load();
List<Load> loadList = l.GetLoadsForGroup(date, groupID);
var fileDownloadName = "fileName.xlsx";
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("New workbook");
ws.View.ShowGridLines = true;
ws.DefaultColWidth = 25;
ws.Cells[1, 1].Value = "Order #";
var currRow = 2;
foreach (var load in loadList)
{
ws.Cells[2, 2].Value = load.LoadNumber;
}
var fs = new MemoryStream();
pck.SaveAs(fs);
fs.Position = 0;
var fsr = new FileStreamResult(fs, contentType);
fsr.FileDownloadName = fileDownloadName;
return (fsr);
}
Not sure what the best way to do this is. If there's a better way, please feel free to elaborate.
Your method looks fine. In that case you just need to use a html form to post instead of using the js function.
Alternatively, if you would like to use a ActionResult you can write:
public ActionResult ExportToExcel()
{
Load l = new Load();
List<Load> loadList = l.GetLoadsForGroup(date, groupID);
var fileDownloadName = "fileName.xlsx";
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("New workbook");
ws.View.ShowGridLines = true;
ws.DefaultColWidth = 25;
ws.Cells[1, 1].Value = "Order #";
var currRow = 2;
foreach (var load in loadList)
{
ws.Cells[2, 2].Value = load.LoadNumber;
}
Response.Clear();
Response.ContentType = contentType;
Response.AddHeader("content-disposition", "attachment; filename=\"" + fileDownloadName + "\"");
Response.BinaryWrite(pck.GetAsByteArray());
Response.Flush();
Response.End();
return View();
}
And you get the same result as your method.

update function on ajaxObject

When a button is clicked on the webpage a table of data is displayed. I want to scrape that data but I can't find where it comes from in the website source code.
This is the tag for the button:
<button type="submit" onclick="divChangeStateOn('load-raw-0062294377Amazon.com'); getRaw('0062294377', 'Amazon.com', 'lr-0062294377Amazon.com',this);"style="margin-bottom: 4px; width: 120px; text-align: left;" name="load-raw"><img src='images/workstation.png'/> raw data</button>
I believe that the getRaw function is where the data comes from (I'm not positive about this) so I looked at the javascript code for the getRaw function
function getRaw(asin, store, res, caller)
{ document.getElementById(res).innerHTML = '<p align="center" valign="top"><img align="center" src="phpmy_loading.gif"></p>';
var poststr = "raw=" + encodeURI(asin) +
"&site=" + encodeURI(store);
var updateResults = new ajaxObject(res, 'extra.php', caller);
updateResults.update(poststr);
}
I have been having a hard time finding any documentation about ajaxObject and can't find any information about the update function. What is ajaxObject.update doing and is it possible for me to access the data that appears when the button is clicked?
function divChangeStateOn(divID)
{ var divElem = document.getElementById(divID);
divElem.style.display = 'block';
}
EDIT: The link to the source code view-source:http://www.ranktracer.com/account_workstation.php it might be password protected but I was just using the demo version
EDIT 2:
I am basically trying to write a script that replicates the Ajax http request. This where I am at, it doesn't work and I am especially concerned about where data = uri
x = time.time()
print x
timestamp = datetime.fromtimestamp(x/1000.0)
print timestamp
uri = "raw=0062294377&site=Amazon.com&timestamp="+str(timestamp);
url = "lr-0062294377Amazon.com"
length = str(len(uri))
headers = {'X-Requested-With': 'XMLHttpRequest',
"Content-type": "application/x-www-form-urlencoded",
"Content-length": length,
"Connection" : "close"}
s = Session()
r = s.post(url= url, data= uri, headers= headers)
The entire code for ajaxObject is present in the link you provided. Please let us know what help you are expecting here?
function ajaxObject(layer, url, caller) {
if (caller) {
disableButton(caller, 'disable');
}
var that = this;
var updating = false;
this.callback = function() {}
var LayerID = document.getElementById(layer);
this.update = function(passData) {
if (updating == true) {
return false;
}
updating = true;
var AJAX = null;
if (window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX == null) {
alert("Your browser doesn't support AJAX.");
return false
} else {
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4 || AJAX.readyState == "complete") {
if (caller) {
disableButton(caller, 'enable');
}
LayerID.innerHTML = AJAX.responseText;
delete AJAX;
updating = false;
that.callback();
}
}
var timestamp = new Date();
var uri = passData + '&timestamp=' + (timestamp * 1);
AJAX.open("POST", url, true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", uri.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.send(uri);
return true;
}
}
}

How to show multiple images that are aligned in the center of the body using javascript

I have a JavaScript function that detects the browser in user, Now i want to be able to append to my HTML document with images corresponding to the type of browser in use. I.e. if im using chrome i want to show img1 img2 img3 and have them all aligned in the center of a body, if im using firefox than only img4 img 5 img 6 would show and so on. I am able to show one image however even if my body is set to align center the images will be left aligned.
From what i understand you can use
var img = document.createElement("img");
img.src = src;
document.body.appendChild(img);
And this will append the image to your body.
So my HTML is more or less as follows.
<html>
<body align="center">
<div id='container' ></div>
<script>
function waitForWhichBrowser(cb) {
var callback = cb;
function wait() {
if (typeof WhichBrowser == 'undefined')
window.setTimeout(wait, 100)
else
callback();
}
wait();
}
waitForWhichBrowser(function() {
var o = document.getElementById('container');
try {
//Catches the browser metadata -- Name,Version Num,Platform
Browsers = new WhichBrowser({
useFeatures: true,
detectCamouflage: true
});
var str = Browsers + " ";
var res = str.split(" ",1); //Parse string from WhichBroswer function to isolate browser name
//o.innerHTML = ' ' + res;
if(res == 'Chrome'){
var img = document.createElement("img");
var img2 = document.createElement("img2");
var img3 = document.createElement("img3");
img.src = "images/img1.png";
img2.src = "images/img2.png";
img3.src = "images/img3.png";
document.body.appendChild(img);
document.body.appendChild(img2);
document.body.appendChild(img3);
}
if(res == 'Firefox'){
var img4 = document.createElement("img4");
var img5 = document.createElement("img5");
var img6 = document.createElement("img6");
img4.src = "images/img4.png";
img5.src = "images/img5.png";
img6.src = "images/img6.png";
document.body.appendChild(img4);
document.body.appendChild(img5);
document.body.appendChild(img6);
}
if(res == 'Internet'){
//Do the same for internet explorer with img7 img8 img9
}
//Else clause
if(res != 'Chrome' && res!='Firefox' && res!='Internet'){
window.location.href = "WindowsChromeDownload.htm"; //Instead of making a separate default download page for an unspecified browser I linked the else case to the chrome landing page since it's the most common browser
}
//When this statement was left in all browsers would redirect to the else case
//else{
//window.location.href = "WindowsDefaultDownload.htm";
//}
} catch (e) {
o.innerHTML = 'Error';
}
});
</script>
</body>
</html>
So my question is,
How can i get all my images to allign center?
Is it possible to add the images to a container inside of my body instead of the body itself. For example
<html>
<body>
<script>
//Location where it detects browser and appends images
</script>
<div id='display'>
<!-- Display images from javascript here -->
</div>
</body>
</html>
To add and center your images #display div do this:
first in your js..
var display = document.getElementById('display');
then replace your body.append() with this:
display.appendChild(img)
then in your css add this:
#display { text-align:center;}
extra btw:
if you wanted to make your script more efficient and readable you could rewrite your function like so:
waitForWhichBrowser(function() {
var o = document.getElementById('container');
var imgsrc = [];
var display = document.getElementById('display');
try {
//Catches the browser metadata -- Name,Version Num,Platform
Browsers = new WhichBrowser({
useFeatures: true,
detectCamouflage: true
});
var str = Browsers + " ";
var res = str.split(" ", 1); //Parse string from WhichBroswer function to isolate browser name
if (res == 'Chrome') imgsrc = ["images/img.png", "images/img2.png", "images/img3.png"];
if (res == 'Firefox') imgsrc = ["images/img4.png", "images/img5.png", "images/img6.png"];
if(res == 'Internet') imgsrc = ["images/img7.png", "images/img8.png", "images/img9.png"];
//Else clause
if(res != 'Chrome' && res!='Firefox' && res!='Internet'){
window.location.href = "WindowsChromeDownload.htm"; //Instead of making a separate default download page for an unspecified browser I linked the else case to the chrome landing page since it's the most common browser
}
for (var i = 0; i < imgsrc.length; i++) {
var img = document.createElement("img");
img.src = imgsrc[i];
display.appendChild(img);
}
//When this statement was left in all browsers would redirect to the else case
//else{
//window.location.href = "WindowsDefaultDownload.htm";
//}
} catch (e) {
o.innerHTML = 'Error';
}
});
Just text-align the container to center:
http://jsbin.com/notocube/1/edit?html,output

How to create embed code for other sites

I have a service of job portal which other users can use for their sites and blogs. they copy embed code from my site, paste it in their site and display job board in their webpage. how create this embed code anyone can help me.
Here is example monster.com publisher website.
click Get sample code button.
<div id="MonsterJobSearchResultPlaceHolderIy8AAA_e_e" class="xmns_distroph"></div>
<script type="text/javascript">
(function() {
var oScript = document.createElement('script');
oScript.type = 'text/javascript';
oScript.async = true;
oScript.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'publisher.monster.com/Services/WidgetHandler.ashx?WidgetID=EAAQgDMlA5vzabXFzuv86ZpLpA--&Verb=Initialize';
var oParent = document.getElementsByTagName('script')[0];
oParent.parentNode.insertBefore(oScript, oParent);
})();
</script>
<a id="monsterBrowseLinkIy8AAA_e_e" class="monsterBrowseLink fnt4" href="http://jobsearch.monster.com/browse/">View More Job Search Results</a>
there are many ways to reach your goal. As you didn't explain your need explicitly, I just provide a simple example:
<script type='text/javascript' charset='utf-8'>
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
iframe.src = 'URL OF CONTENT YOU WANT TO PROVIDE';
iframe.width = 'THE WIDTH YOU WANT';
iframe.height = 'THE HEIGHT YOU WANT';
</script>
modify the code according to your need
escape this code in your html
have fun with your awesome embedded widget!
How To Create Embed With Javascript in .cs
Note: localhost:3197/website/js/embed/form.js'; // give your js path
FormBuilder(921,'MjEzNjkxMjU='); in this method first parameter give your form height and second your form name or Id. there Id is encoded format
StringBuilder sb = new StringBuilder();
sb.Append("<script type='text/javascript'>");
sb.Append("(function(d, t) { var s = d.createElement(t), options = {");
sb.Append("'async':true };");
sb.Append("s.src = ('https:' == d.location.protocol ? 'https://' : 'http://') + 'localhost:3197/website/js/embed/form.js';");
sb.Append("s.onload = s.onreadystatechange = function() {");
sb.Append("var rs = this.readyState; if (rs) if (rs != 'complete') if (rs != 'loaded') return;");
sb.Append("try { frm = new FormBuilder("+Form Height+",'"+FormId+"');frm.initialize(options);frm.display(); }");
sb.Append("catch (e) {}};");
sb.Append("var scr = d.getElementsByTagName(t)[0], par = scr.parentNode; par.insertBefore(s, scr);");
sb.Append("})(document, 'script');</script>");
txtjavascript.Value = sb.ToString(); // text box name
After Create embed script Simple and Easy Way Paste this script where you want to show in other page after that
(function(d, t) { var s =
d.createElement(t), options = {'async':true }; s.src = ('https:' ==
d.location.protocol ? 'https://' : 'http://') +
'localhost:3197/website/js/embed/form.js'; s.onload =
s.onreadystatechange = function() {var rs = this.readyState; if (rs)
if (rs != 'complete') if (rs != 'loaded') return; try { frm = new
FormBuilder(921,'MjEzNjkxMjU='); frm.initialize(options);
frm.display(); }catch (e) {}}; var scr =
d.getElementsByTagName(t)[0], par = scr.parentNode;
par.insertBefore(s, scr);})(document, 'script');
After That in your js file Create fuction like this and create iFrame ans create querystring where you fetch the form from database.
function FormBuilder(fHeight, formid) {
var iframe = document.createElement('iframe');
iframe.style = "height:" + fHeight + "px; width:100%; border:none";
iframe.setAttribute('allowTransparency', true);
iframe.frameBorder = "0";
iframe.scrolling = "no";
iframe.src = "http://localhost:3197/form/show-form?id="+ formid;
document.body.appendChild(iframe);
}

Categories