I have a code that is supposed to show an image and refresh that image every 1 second. I have two .aspx pages, one saves the new image to a file, the other is to display the new image. It is not refreshing with the javascript code. it will display the new image if I hit F5 or refresh the page from the address bar, but not with the code. I cannot debug because I do not have administrative privileges on this computer (at work) so I want to try to add something like "num = num+1" and then display num in a textbox. I want to do this to see if my code is even entering the javascript at all.
Here is the code for the viewer page with the javascript:
<body>
<form id="form1" runat="server">
<div style="height: 60px">
<%--<asp:Image ID="Image1" runat="server" /> --%>
<img src="/video.aspx" id="the_image" alt="" />
<script type="text/javascript" language="javascript">
function refreshImage() {
objIMG = document.getElementById('the_image');
objIMG.src = objIMG.src.substr(0, objIMG.src.indexOf('&nocache=')); +'&nocache=' + Math.random();
}
$(document).ready(function () {
setInterval(refreshImage(), 1000);
})
</script>
<br />
</div>
</form>
</body>
If you are interested here is the code to save the new image to a file:
namespace PlayVideo
{
public partial class Video : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//This is where I originally had the function that saves the new image.
//string saveTo = #"location to save new image";
//FileStream writeStream = new FileStream(saveTo, FileMode.Create, FileAccess.ReadWrite);
using(FileStream fs = File.Open(#"C:Location of file", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
{
ReadWriteStream(fs, writeStream);
}
Response.Clear();
Response.TransmitFile("~/images/test.jpg");
}
// readStream is the stream you need to read
// writeStream is the stream you want to write to
private void ReadWriteStream(Stream readStream, Stream writeStream)
{
int Length = 256;
Byte[] buffer = new Byte[Length];
int bytesRead = readStream.Read(buffer, 0, Length);
// write the required bytes
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = readStream.Read(buffer, 0, Length);
}
readStream.Close();
writeStream.Close();
}
}
I don't really no javascrict, I got the code I'm using online. I want to just add that debug line. Can someone help? I'm using Visual Studio 2010, if you're wondering.
console.log(yourData);
and before running it press F12 and go to Console tab. Using Firefox with Firebug plugin would help too.
Depending on the browser you are using to view the page, it probably has a developer toolbar or a set of dev tools built in. You can use this to debug your javascript without needing any elevated privileges.
You can access them in IE but hitting F12.
Related
In the master page of all my web form pages I've set up an overlay which blocks user interation whenever form submitted until browser renders next page response:
<script type="text/javascript">
function overlayWhenSubmit() {
document.getElementById('spinnerOverlay').style.display = 'block';
}
//spinnerOverlay has position:fixed and top/bottom/left/right:0
</script>
protected override void OnPreRender(EventArgs e) {
this.ClientScript.RegisterOnSubmitStatement(
typeof(Page), null, "overlayWhenSubmit();"
);
base.OnPreRender(e);
}
This works great until I try to provide file download:
public static void DownloadFile(this System.Web.HttpResponse #this, string physicalFilePath) {
#this.ContentType = "application/octet-stream";
#this.AppendHeader("Content-Disposition", $"Attachment; filename=\"{Path.GetFileName(physicalFilePath)}\"");
#this.TransmitFile(physicalFilePath);
}
// ... then in some event handler in my page:
Response.DownloadFile(thePathOfFileToDownload);
The file downloads OK, but the original page keeps being overlaid and therefore unusable.
Is there a way the page can get notified when the submitted request has finished so it can turn off the overlay?
The closest thing so far is try not to popup the overlay for the control which leads to non-HTML response:
<script type="text/javascript">
function overlayWhenSubmit() {
if (!document.getElementById('noOverlayWhenSubmit').value)
document.getElementById('spinnerOverlay').style.display = 'block';
document.getElementById('noOverlayWhenSubmit').value = '';
}
function noOverlayWhenSubmit() {
document.getElementById('noOverlayWhenSubmit').value = true;
}
</script>
<input type="hidden" id="noOverlayWhenSubmit" value="" />
<asp:Button runat="server" OnClientClick="noOverlayWhenSubmit()"></asp:Button>
So, I've been working on a page that uses only local files (server is not an option, unfortunately. Not even a localhost. The struggle is real.) and I've come to a situation where I need to grab text from a .csv file and populate it to the page. I have this bit of code that works, but I need to have a file set within the function when a button is pressed. Looking up the file manually isn't an option (to visualize what I'm doing, I'm making a mock database file in the most annoying way possible (because I have to, not because I want to)).
In the page I would have something like:
<button id="myButton" onclick="getText()"></button>
<script>
var myFile = "dataset.csv";
...
</script>
The following bit of code works (in regards to having it pull the data from the csv file), but, as I said, I need to pull the text from the file when a button is pressed and just have the file name set in the script, not pulling it up manually.
<!DOCTYPE html>
<html>
<body>
<input type="file" id="fileinput" />
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</body>
</html>
From what I can tell from the API, I would need to set the file attributes to a blob in order to pass it to FileReader. How I can do this without using an input box, I have no idea. There's also a 50% chance that I am completely wrong about this since I obviously don't know how to get this done.
If someone could show me how to achieve this with regards to what I'm looking for, it would be very much appreciated. I'm absolutely stumped.
Thank you.
Note: CORS restrictons will prevent this from working in most browsers. You can use FireFox Developer Edition, which disables CORS validation.
You can use an XMLHttpRequest to load a local file:
<!DOCTYPE html>
<html>
<body>
<button onclick="readSingleFile()">Click Me</button>
<div id="outputdiv"></div>
<script type="text/javascript">
function readSingleFile() {
let xhr = new XMLHttpRequest();
let url = "relative/path/to/file.txt;
if (!url) return;
xhr.onload = dataLoaded;
xhr.onerror = _ => "There was an error loading the file.";
xhr.overrideMimeType("text/plain");
xhr.open("GET",url);
xhr.send();
}
function dataLoaded(e){
var contents = e.target.responseText;
var splited = contents.split(/\r\n|\n|\r|,/g);
for (i=0; i<splited.length; i++){
document.getElementById("outputdiv").innerHTML = document.getElementById("outputdiv").innerHTML + splited[i] + "<br>";
}
</script>
</body>
</html>
So I need to send an attachment to a document, but I have to validate if it is larger than 15mb , for so I am using this code in javascript to get the file :
var objFSO = new ActiveXObject("Scripting.FileSystemObject");
var filePath = document.getElementById(fileid).value;
var objFile = objFSO.getFile(filePath);
var fileSize = objFile.size; //size in kb
I'm having an error when I try to create ActiveXObject because my site is not "trusted " by not having a Mark of the Web
<!doctype html>
<!-- saved from url=(0023)http://www.contoso.com/ -->
<html>
<head>
<title>A Mark of the Web Example.</title>
</head>
<body>
<p>Hello, World</p>
</body>
</html>
so I wonder if it is possible to have a mark of the web in a XPage and how I could put it the body of the XPage.
My client does not want to manually place the security option , but want to use IE , please help me haha.
If there is another way to check the file size when selecting a file using javascript would be interesting.
Try this code to check file size in HTML5 should work in all modern browsers
var fileSize=0
if (typeof FileReader !== "undefined") {
var filePath = document.getElementById(fileid);
fileSize= filePath.files[0].size;
}
Check the filesize var for the max limit of you file.
Use this code if the browser is IE10 or newer and your old code if the browser is older.
You can create a Java validator for old browsers, but if the Javascript API is available (modern browsers), use it.
public class Attachment implements Validator {
private final static long BYTES_IN_1_MB = 1048576;
private final static long MAX_MB_ALLOWED = 10;
private final static String MSG_ERROR_SIZE = "File size cannot be bigger than {0} MBs";
public void validate(FacesContext fc, UIComponent uiComp, Object attach)
throws ValidatorException {
FacesMessage msg;
UploadedFile upFile = (UploadedFile) attach;
long max_bytes = BYTES_IN_1_MB * MAX_MB_ALLOWED;
// SIZE:
if (upFile.getContentLength() > max_bytes) {
String msgError = MSG_ERROR_SIZE.replace("{0}", String.valueOf(MAX_MB_ALLOWED));
msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msgError, msgError);
throw new ValidatorException(msg);
}
}
}
These validators need to be added into the faces-config.xml
<validator>
<validator-id>attachmentValidator</validator-id>
<validator-class>com.faces.validator.Attachment</validator-class>
</validator>
Then you can add the validator into the fileUpload field:
<xp:this.validators>
<!-- Validator for Attachments -->
<xp:validator validatorId="attachmentValidator">
</xp:validator>
</xp:this.validators>
I lost the web session when i tried window.location.replace("webform2.aspx") from webform1.
I tried href as well. Also I passed "/webform2.aspx" as a paramaeter.
However the session is lost on the redirection.
Can anyone help.
Webform1.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
function pageload() {
window.location.href("/webform2.aspx");
}
</script>
</head>
<body onload="pageload()">
<form id="form1" runat="server" >
</form>
</body>
</html>
WebForm1.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string str = this.Session.SessionID;
}
Webform2.aspx just an empty form and having the aspx.cs as the above code to note session id by debugging.
Update:
I maanged to acheive using the below code. However I just keep this question open to know redirection with relative URL(without session id) lose the session. One more point here is I made cookieless as true hence only my url will have the session id.
var path = window.location.href;
var i = path.lastIndexOf("/") + 1;
var loc = path.substring(0, i ).concat("webform2.aspx");
window.location.href(loc);
I used cookieless session and hence a relative URL redirection doesnt have knowledge about session, hence a new session is initiated.
I used below code to overcome the problem.
var path = window.location.href;
var i = path.lastIndexOf("/") + 1;
var loc = path.substring(0, i ).concat("webform2.aspx");
window.location.href(loc);
I can't seem to get websocket communication to work in the Play Framework version 2.1.
I created a simple test that does nothing but send messages back and forth with a push of a button. All the code for it is below. But nothing shows up except for the button.
Has anybody seen this problem or can someone tell me what I may be doing wrong in the code below?
I am using the latest version of Chrome.
Here is my simple setup.
In Application.java
public static Result index() {
return ok(index.render());
}
public static WebSocket<String> sockHandler() {
return new WebSocket<String>() {
// called when the websocket is established
public void onReady(WebSocket.In<String> in,
WebSocket.Out<String> out) {
// register a callback for processing instream events
in.onMessage(new Callback<String>() {
public void invoke(String event) {
System.out.println(event);
}
});
// write out a greeting
out.write("I'm contacting you regarding your recent websocket.");
}
};
}
In Routes File
GET / controllers.Application.index()
# Map static resources from the /public folder to the /assets URL path
GET /assets/*file controllers.Assets.at(path="/public", file)
GET /greeter controllers.Application.sockHandler()
In Index.Scala.html
#main(null) {
<div class="greeting"></div>
<button class="send">Send</button>
<script type="text/javascript" charset="utf-8">
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var sock = new WS("#routes.Application.sockHandler()")
sock.onmessage = function(event) {
$('.greeting').append(event.data)
}
$('button.send').click(function() {
sock.send("I'm sending a message now.")
});
})
</script>
}
In Main.scala.html
#(title: String)(content: Html)
<!DOCTYPE html>
<html>
<head>
<title>#title</title>
<link rel="stylesheet" media="screen" href="#routes.Assets.at("stylesheets/main.css")">
<link rel="shortcut icon" type="image/png" href="#routes.Assets.at("images/favicon.png")">
<script src="#routes.Assets.at("javascripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
</head>
<body>
#content
</body>
The problem is in
var sock = new WS("#routes.Application.sockHandler()")
you have to specify the protocol and the complete url in the format: ws://localhost:9000/greeter.
Check this question to do it in javascript: How to construct a WebSocket URI relative to the page URI?
you can use a Route's webSocketURL() method to retrieve a url that can be passed to a WebSocket's constructor. Here's an example from Play's websocket-chat sample code:
$(function() {
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket
var chatSocket = new WS("#routes.Application.chat(username).webSocketURL()")
var sendMessage = function() {
chatSocket.send(JSON.stringify(
{text: $("#talk").val()}
))
$("#talk").val('')
}
// ...
So in your code you can use something like
var sock = new WS("#routes.Application.sockHandler().webSocketURL()");
Personally I don't like intermingling interpolated code with JS, since I think that any code executing on the client should only be concerned with the state of the client, and not the server (not to mention it makes refactoring the script out into an external file impossible), so I tend to do something like this:
<div class="container app-container"
data-ws-uri="#routes.Application.WSUri.webSocketURL()">
.......
</div>
Then in my JS I can just do something like
var sock = new WS(document.querySelector(".app-container").dataset.wsUri);
// ....