How to automatically refresh a web-page using ASP.NET? - asp.net-2.0

I have an asp.net application that would 'simulate' real-time video. I did that acquiring multiple picture from an mysql database.
The problem is how would it be displayed on the web-page.? I refresh the page 1 second per picture, the result is the pictures are choppy and flickery.
Response.AppendHeader("Refresh", "1")
How can I make the refresh rate of the page 4times per second? or is there any implementation for it to be displayed in a continent way.
I would really appreciate if you will reply. good day (^_^)...
here is the script that i am using to read the images from the database,.
If dr.Read Then
dr.Read()
Response.ContentType = "image/jpeg" 'gets or sets the type of output stream
Response.BinaryWrite(dr.Item("file")) 'writes a stream of binary characters to the
http output stream
Else
Response.Write("There is no current active webccast.")
End If
dr.Close()

create a javascript method to change the image using xmlhttpobject and recursively set a timer
function Timer() {
setTimeout("getImage(['imageContainer1'])", 200);
t = setTimeout("Timer()", 100);
}
function getImage(params) {
var request=getXMLhttpObject();
makeRequest("ajax/ObtainImage.aspx?name='myimage'+param[1]+'.jpg",request, imageResponseHandler(request, params));
}
function getXMLhttpObject() {
return (navigator.appName == "Microsoft Internet Explorer")? new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
}
function makeRequest(url,request, Handler) {
request.open("GET", url, true);
request.onreadystatechange = Handler;
request.send(null);
}
function imageResponseHandler(request,params) {
return function() {
if (request.readyState == 4)
document.getElementById(params[0]).src = request.responseText;
}
}

I would either use some Javascript/Ajax to change the content or the meta-refresh (probally not the best for fast refresh).

Maybe you need to think about loading more than one picture onto the page and using javascript to cycle between them. Rather than refreshing the page you could get the pictures using AJAX.

If you really want to simulate video, you need to be able to display at least 15 pictures each second (15fps). Making that many requests per second isn't a great idea.
If you absolutely must do this, I'd suggest "buffering" the pictures first, before displaying them, and if possible, fetching them in batches:
buffer = [] // cache loaded images
bufferSize = 30 // load 30 images before playing
function loadImage(src) {
var img = new Image()
img.src = src
buffer.push(img)
}
function animate(target) {
if (buffer.length > 0) {
var img = buffer.shift()
document.getElementById(target).src = img.src
}
}
function bufferImages() {
for (var i=0; i<bufferSize; i++) {
loadImage('/ajax/ObtainImage.aspx?name=img')
}
}
setInterval("animate('imgTarget')", 65) // should give us about 15fps
setInterval("bufferImages()", 1000) // every second

Add this to the head of your html document.
Not the most efficient way, but it will work.
<meta http-equiv="refresh" content=".25" />

Related

Find broken images in page & image replace by another image

Hi I am using selenium webdriver 2.25.0 & faceing the some serious issues,
how to find broken images in a page using Selenium Webdriver
How to find the image is replace by another image having same name (This is also bug) using webdriver.
Thanks in advance for your value-able suggestions.
The accepted answer requires that you use a proxy with an extra call to each image to determine if the images are broken or not.
Fortunately, there is another way you can do this using only javascript (I'm using Ruby, but you can use the same code in any executeScript method across the WebDriver bindings):
images = #driver.find_elements(:tag_name => "img")
broken_images = images.reject do |image|
#driver.execute_script("return arguments[0].complete && typeof arguments[0].naturalWidth != \"undefined\" && arguments[0].naturalWidth > 0", image)
end
# broken_images now has an array of any images on the page with broken links
# and we want to ensure that it doesn't have any items
assert broken_images.empty?
To your other question, I would recommend just taking a screenshot of the page and having a human manually verify the resulting screenshot has the correct images. Computers can do the automation work, but humans do have to check and verify its results from time to time :)
The next lines are not optimized, but they could find broken images:
List<WebElement> imagesList = _driver.findElements(By.tagName("img"));
for (WebElement image : imagesList)
{
HttpResponse response = new DefaultHttpClient().execute(new HttpGet(image.getAttribute("src");));
if (response.getStatusLine().getStatusCode() != 200)
// Do whatever you want with broken images
}
Regarding your second issue, I think I didn't understand it correctly. Could you explain it with more detail?
Based on the other answers, the code that eventually worked for me in an angular / protractor / webdriverjs setting is:
it('should find all images', function () {
var allImgElts = element.all(by.tagName('img'));
browser.executeAsyncScript(function (callback) {
var imgs = document.getElementsByTagName('img'),
loaded = 0;
for (var i = 0; i < imgs.length; i++) {
if (imgs[i].naturalWidth > 0) {
loaded = loaded + 1;
};
};
callback(loaded);
}).then(function (loadedImagesCount) {
expect(loadedImagesCount).toBe(allImgElts.count());
});
});
The webdriver code counts the number of img elements, and the function executed within the browser context counts the number of successfully loaded elements. These numbers should be the same.

Ajax code is faster or updatepanel is faster to populate dropdown in asp.net

I have 20 ajax editable drop-downs in a form. Each drop-down binds with respect to other's selectedindex change.
I have lots of record coming from the database for binding, and some operations. What will perform better?
Should I use this code to bind the drop-down:
var XmlHttp;
//Creating object of XMLHTTP For AJAX Method
function CreateXmlHttp() {
//Creating object of XMLHTTP in IE
try {
XmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (oc) {
XmlHttp = null;
}
}
//Creating object of XMLHTTP in Mozilla and Safari
if (!XmlHttp && typeof XMLHttpRequest != "undefined") {
XmlHttp = new XMLHttpRequest();
}
}
function GetAppStoreLnk(id) {
var txtnameid = document.getElementById(id);
CreateXmlHttp();
var requestUrl = "Default2.aspx?id="+txtnameid+"";
if (XmlHttp) {
XmlHttp.onreadystatechange = function() { getschemename(txtnameid) };
XmlHttp.open("GET", requestUrl, true);
XmlHttp.send(null);
}
}
function getschemename(id)
{
// To make sure receiving response data from server is completed
if(XmlHttp.readyState == 4) {
// To make sure valid response is received from the server, 200 means response received is OK
if(XmlHttp.status == 200) {
var strData = XmlHttp.responseText;
if(strData != "") {
var arrscheme = strData.split("|");
id.length = 0;
for(i=0; i<arrscheme.length-1; i++) {
var strscheme = arrscheme[i];
var arrschnm = strscheme.split("~");
id.options[i] = new Option();
id.options[i].value = arrschnm[0];
id.options[i].text = arrschnm[1];
}
} else {
id.length = 0;
id.options[0] = new Option();
id.options[0].value = "";
id.options[0].text = "Scheme Name is not available";
}
document.body.style.cursor = "auto";
}
else {
id.length = 0;
id.options[0] = new Option();
id.options[0].value = "";
id.options[0].text = "server is not ready";
document.body.style.cursor = "auto";
}
}
}
Or should I go for UpdatePanel?
Which one will be the better option for me?
Or is there a better spolution?
I want very good performance as this page is used frequently by our client, and we want to make sure it is fast.
I am using vs2010.
The AJAX route will be faster. UpdatePanels make things look like partial page loads, but in fact, it returns the whole page and just updates the section inside your UpdatePanel.
UpdatePanel does not provide the efficiency that we normally associate with AJAX. Did you know, for example, that when UpdatePanel control performs asynchronous AJAX callback to the server to update its content, the request contains all the content of a publication automatically ASP. NET conventional, including status display.
An application is more effective preferring to use asynchronous calls to WebMethods or page methods instead of using UpdatePanel.
Link : http://msdn.microsoft.com/fr-fr/magazine/cc163413.aspx
I agree with the rest of the answers, the evil UpdatePanel decreases the overall performance of the page because in order to work, it must send the whole page ViewState back and forth in order to execute the whole page life cycle on every async post
With simple AJAX calls this is totally different, the calls only get the data you need and the performance is considerably better
However - danger danger DR Robinson
Since you are using WebForms and your intention is to populate 20 DropDownLists, you can try doing it with AJAX calls and you will notice that apparently that works correctly. but if you try to post your page with one value added to a DropDownList via javascript/jquery, an exception will be thrown.
This is because ASP.Net WebForms by default validates the values posted to the server, if the values are not registered in the ViewState, a security exception will be thrown because of an attempt to tamper the page content.
Sadly you cannot disable this option at control level, you would have to disable it at page level:
<%# Page EnableEventValidation="false" ....
In WebForms this is not recommended though...

adding dynamic message at end of flash video

I am working on a Flash training video. I would like at the end of the video for a message to pop up with a dynamic confirmation code. I have the code for the confirmation code, but am having trouble creating something either at the end of the flash video or within the aspx page to trigger this message. Any thoughts or ideas of how to solve this would be greatly appreciated.
Thank You.
Depend on the purpose of the application, you can do either one. One thing to consider is does the user has to go through the flash video to obtain the code. If so, you need to organize the flow of the application in a way that the user can't cheat their way to obtain the code.
The ideal way is to have the flash called aspx page at the end of the movie to obtain the dynamic code. This can be done using URLLoader in ActionScript 3.0 or LoadVars in ActionScript 2.0.
URLLoader example
//this is the data
var data = "This is data";
//url of your aspx code
var request:URLRequest = new URLRequest("http://www.yourdomain.com/GenerateCode.aspx");
request.contentType = "text/xml";
request.data = data;
//use POST method
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
try
{
//execute the request
loader.load(request);
}
catch (error:ArgumentError)
{
trace("There is an ArgumentError.");
}
LoadVars example:
//create LoadVars object
var lv_in:LoadVars = new LoadVars();
var lv_out:LoadVars = new LoadVars();
//set onLoad event
lv_in.onLoad = function(success:Boolean)
{
//if success, meaning data has received response from .net page, run this code
if (success)
{
//lv_in.status is use to get the posted data from .Net page
statusMsg.text = "Thank you!" + lv_in.status;
}
//if fail, run this code
else
{
statusMsg.text = "Error!";
}
}
//this is the data
lv_out.data = "This is data";
//begin invoke aspx page
lv_out.sendAndLoad("GenerateCode.aspx", lv_in, "POST");
There another easier way but not the best practice i should say. The easier way would be to direct user to aspx page that generate dynamic code after users finish the flash movie. The negative side is, the page can be accessed although users did not finish the flash movie.

XMLHttpRequest POST

I need to upload and save an image onto the server. I am using an XMLHttpRequest POST to send the image to the server and calling a class named imageSave.aspx.
I am finding difficulty in "catching" the image from server side (imageSave.aspx) and saving it onto the server.
Does anyone please have some tips as to how this is done or maybe link to a good article or something?
Code used to perform the http POST....
xhr = new XMLHttpRequest();
// Update progress bar etc
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
}
else {
// No data to calculate on
}
}, false);
// File uploaded
xhr.addEventListener("load", function() {
progressBarContainer.className += " uploaded";
progressBar.innerHTML = "Uploaded!";
}, false);
xhr.open("post", "imageSave.aspx", true);
// Set appropriate headers
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
// Send the file
xhr.send(file);
Much appreciated,
JP
Read this other answer:
What data formats can AJAX transfer?
It'll get you an idea of why you can't upload an image using XMLHttpRequest.
UPDATE: Check this control of AJAX Control Toolkit - it'd be what you want! - :
http://www.asp.net/ajax/ajaxcontroltoolkit/samples/asyncfileupload/asyncfileupload.aspx

Downloading data posted to server as a file from Flex

This should be trivial, and I'm pretty sure I did it once before.
I'm trying to post data up to a server and have it bounced back to me as a file download, prompting the native browser file download box. I know the server part works just fine becasue I can post from a demo web form, but when I run the following Flex 3 code, I can't even get the request to fire.
var fileRef:FileReference = new FileReference();
private function saveXmlAsFile(event:MouseEvent):void
{
var fileRequest:URLRequest = new URLRequest();
fileRequest.method = URLRequestMethod.POST;
fileRequest.url = "http://foo.com/dataBounce";
var urlVariables:URLVariables = new URLVariables();
urlVariables.content = "Test content to return" ;
// fileRequest.contentType = "application/x-www-form-urlencoded ";
urlVariables.fileName = "test.xml";
fileRef.addEventListener(SecurityEvent.ALL, onSecurityError);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError2);
fileRef.addEventListener(IOErrorEvent.NETWORK_ERROR, onNetworkError);
fileRef.addEventListener(Event.COMPLETE, onComplete);
try
{
fileRef.download(fileRequest, "test.xml");
}catch(error:Error) {
model.logger.error("unable to download file");
}
}
Note, when the call to fileRef.download is called, I can't see any request being made across the network using the traditional Firebug or HTTPWatch browser tools.
EDIT: I should add that this is for < Flash Player 10, so I can't use the newer direct save as file functionality.
Any suggestions? Thanks.
You need to add fileRef.upload to trigger the upload.
Also I would move the download statement to the onComplete so the file isn't requested before it's been uploaded.
Your explanation is pretty clear, but when I look at your code, I'm feel like I'm missing something.
The code looks like you're trying to do half of the upload part and half of the download part.
I think the code you currently have posted would work to trigger a download if you set the .method value to GET. I believe you will also need to include the filename as part of the .url property.
However, to post something and then trigger a download of it, you need two separate operations - the operation to post the data and then an operation to download it, which should probably be called from the upload operation's onComplete handler.
OK, I believe I figured out one of the things that's going on.
When you don't set the URLRequest.data property, it defaults the request method to "GET".
So, the working code looks like, with the data set to the posted URL variables:
private var fileRef:FileReference;
private function saveRawHierarchy(event:MouseEvent):void
{
var fileRequest:URLRequest = new URLRequest();
fileRequest.method = URLRequestMethod.POST;
fileRequest.url = "http://foo/bounceback";
var urlVariables:URLVariables = new URLVariables();
urlVariables.content = "CONTENT HERE";
urlVariables.fileName = "newFileName.xml";
fileRequest.data = urlVariables;
fileRef = new FileReference();
fileRef.addEventListener(Event.COMPLETE, onComplete);
try
{
fileRef.download(fileRequest, "appHierarchies.xml");
}catch(error:Error) {
model.logger.error("unable to download file");
}
}
Not sure what was wrong about the request not being made before, though.

Resources