Use timer to change image - asp.net

in my master page header i would like to display multiple images and have them change every 2 seconds or so. how would i go about implementing something like this?
Im using Microsoft visual studio 2010 and using vb.net
although i have just found this code, is there any way i get this to work in event handler of the timer. i understand it is not VB.net but can i use any imports?
protected void gettickvalue(object sender, EventArgs e);
{
Random RandomNumber = new Random();
int n = RandomNumber.Next(1, 9);
imgBanner.ImageUrl = System.String.Concat("images/banner_", n.ToString(), ".gif");

Considering that ASP runs server side, you probably don't want a timer running there. Your better solution is a JavaScript (client side) timer:
setInterval(function(){alert("Hello")},3000);

Related

Forcing an ASP.NET page_load

I have an ASP.NET (4.5+) app that calls an asynchronous task from Page_Load in order to obtain data for the page. I want to refresh that data every 15 minutes with out any user input.
First I tried using a timer and calling Page.ExecuteRegisteredAsyncTasks() in the timer function. No error but my async task never gets called. Just during Page_Load.
Then I tried various techniques for force a reload of the page figuring that would cause Page_Load to get called again but each attempt resulted in an exception being thrown saying that technique could not be used at that time.
The C# method I want to call every 15 minutes is defined as a private async Task.
What is the best way to call this method every 15 minutes? As I wrote above it is getting called successfully from Page_Load but never again.
You will need to use a worker of some kind. If you had a timer then every time you refreshed the page, the timer would reset, you could use possibly a session variable to keep track. This is just the nature of the page lifecycle.
One alternative is to create a service, you could use an ASMX service for this and pull the data from the client-side. Using HTML5 Local Storage to keep track of the time last updated, or even "nextTimeToUpdate" store 15+ minutes from now. Set a time out of every 1 minute to check the current DateTime and if >= nextTimeToUpdate then trigger the request via AJAX.
Since local storage persists even after the browser is closed, when the user next visits the page and the data will still be there. The data is only lost if the user shuts down their machine/cleans their browser.
Edit
Assuming you want to trigger these events server-side. Move the async task into a new class, instantiate or inject it on the page you want.
Scott Hanselman has an article on How to run Background tasks in ASP.NET. A noteworthy library Hangfire
You have to use Timer, it is best way, I think.
Just follow next steps:
In design page:
<asp:ScriptManager ID="manager" runat="server" />
<asp:Timer ID="timer" runat="server" Interval="900000" OnTick="timer_Tick" />
Then create some function (e.g. MyFunc()), and your code behind:
protected void Page_Load(object sender, EventArgs e){
MyFunc();
}
protected void timer_Tick(object sender, EventArgs e){
MyFunc();
}
protected void MyFunc(){
//do all actions, what you need, here
}

MediaPlayer MediaOpenned event is not firing on .net class

I'm trying to build a class where my thumbnail class is capturing a frame as a thumbnail of the videos users uploaded, things have gone good so far. I've written down the application on wpf app first and then decided to move to a class on my website as thumbnail.cs. Code is as shown below.
My problem is, the MediaOpenned event doesn't fire up so the execution cannot continue as its supposed to, i tried calling it myself and put a thread.sleep to handle the delay with the buffering of video and the code worked as i wanted. But i don't want to rely on sleep since it can be unstable due to server and heavy.. I need it to work with the event or something similar like that.
Any ideas or suggestions why event is not firing on .net? while working perfect on wpf? and what to do.
And millions of thanks of course!
thumbnail.cs class;
MediaPlayer myPlayer = new MediaPlayer();
public thumbnail()
{
myPlayer.Open(new Uri(#"C:\movie.wmv"));
myPlayer.Play();
myPlayer.IsMuted = true;
//this doesn't fire up
myPlayer.MediaOpened += new EventHandler(myPlayer_MediaOpened);
/*
when i do like this it works as i want but unstable and heavy because sleep
myPlayer_MediaOpened(null, null);
System.Threading.Thread.Sleep(5000);
*/
}
void myPlayer_MediaOpened(object sender, EventArgs e)
{
myPlayer.Position = TimeSpan.FromSeconds(myPlayer.NaturalDuration.TimeSpan.Seconds / 2);
RenderTargetBitmap RenderTarBitmap = new RenderTargetBitmap(400, 300, 1 / 96, 1 / 96, PixelFormats.Pbgra32);
DrawingVisual DVisual = new DrawingVisual();
DrawingContext DContext = DVisual.RenderOpen();
DContext.DrawVideo(myPlayer, new Rect(0, 0, 400, 300));
DContext.Close();
RenderTarBitmap.Render(DVisual);
myPlayer.Stop();
BitmapFrame BMPFrame = BitmapFrame.Create(RenderTarBitmap);
BitmapEncoder BMPEncoder = new JpegBitmapEncoder();
System.IO.FileStream FStream = new System.IO.FileStream(#"C:\movie.jpg", System.IO.FileMode.Create);
BMPEncoder.Frames.Add(BMPFrame);
BMPEncoder.Save(FStream);
FStream.Flush();
FStream.Close();
}
--------------------------------------------
UPDATE:
Allright so i've been trying to solve this for days now and god knows the person going to help me is directly going to heaven! Anyway i found that i'm not able to fire any event handlers related to MediaPlayer or my thumbnail.cs (which is hosted in app_code and called by a asmx webservice).
Tried some workarounds by using threads and implementing my own made event handlers checking whether movie is loaded or not.. no luck there either MediaPlayer doesn't let me touch its insides in another thread... And i didn't want to do more hack approach while able to solve with an easy event handler!
Searched the deepest google, found a thread on 2006 that a person assumed it may be a problem with x64 (well i'm using x64) but i couldn't found anything about that on msdn and hell its been 5 years!
So to sum up, i'm probably having a massive event not firing problem with either my class or my MediaPlayer control. And i need a saviour to help me catch the mediaOpenned event..
Thank you again.

Call javascript function from asp.net code behind after server side code executes

I have an asp.net button, that when clicked calls a code behind function. The function does some evaluation, and then I want to call javascript from within this asp.net function.
While pranay's answer is correct in the function call, the rest is off, here's hopefully a better explanation:
You can use ClientScript.RegisterStartupScript() to do what you want, like this:
void myButton_Click(object sender, EventArgs e)
{
var script = "alert('hi');";
ClientScript.RegisterStartupScript(typeof(Page), "ButtonAlert", script, true);
}
The format is (type, scriptKey, scriptText, wrapItInScriptTags).
If you are operating with an UpdatePanel, it's very similar, except you need to use the slightly different ScriptManager.ResgisterStartupScript(). Use the UpdatePanel as the control and type parameters in that case to be safe.
JavaScript is a client side technology.
While I suppose it would be theoretically possible to run the code on the server I don't see what benefit it would give you.
What do you actually want to achieve?

Timer Class in ASP.NET

I have this code in the asp.net application start evert, and I'm not really familar with the Timer class but what I want to do is have one Trigger that goes off every night at 11 pm, one that goes off at 5:30 in the morning and then every hour after that.
private System.Threading.Timer timer;
protected void Application_Start(object sender, EventArgs e)
{
int intervalMilliseconds = 60 * 1000;
timer = new System.Threading.Timer(new System.Threading.TimerCallback(TimedEvent), null, intervalMilliseconds, intervalMilliseconds);
}
protected void Application_End(object sender, EventArgs e)
{
if (timer != null) timer.Dispose();
}
private void TimedEvent(object stateInfo)
{
MyClass.ExecuteCode();
}
*Please no answers in the way of "don't use asp.net to do triggers because of the lifecycle".
*Again - please no posts on what not to use. I've received two post both telling me what not to use and both not related to my question which is about the Timer class and how to use it.
From your question i'm assuming you don't have full control over your hosting environment, so will try to avoid the schedule it... etc answers.
Having said that, you still need to be aware of the asp.net lifecycle, and your trigger approach is fraught with dangers.
Do you get enough traffic that the application won't end unexpectedly? Do you know the configuration of IIS, so recycling is not a worry?
I can see three approaches:
I would recommend having a page, which uses some sort of key, which is only known
by the caller. Have this page triggered by a watchmouse (See: http://www.watchmouse.com/en/), or scheduled crawler on a pc/server which will always be on, at the times you need it to be triggered.
An alternative would be to trigger a database process, which runs when needed to.
Depending on your environment, this can be scheduled too.
Another would be to check a log file, on users accessing the page, and if it is the first access within the hour, trigger your process. (Do this for whatever period you need.)
However this depends entirely on how heavily your site is accessed, and may not work reliably.
When you create your timer and hook up its tick/elapsed event, set the interval to be every 5 minutes or so.
Then in the tick/elapsed event handler, check the current time and perform an action where necessary. Obviously you will also need to record when an actino has been performed so you don't perform it at 10:58 and 11:03 pm.
Have a look at Quartz.NET, which will allow you to set up cron-like triggers.
Maybe a different way of doing what you want: Instead of relying on ASP to be active, perhaps you can just use the windows scheduler to schedule your event. It has more of the scheduling features you want and will be likely be more reliable as well as already debugged. Your timed event can be as simple as accessing http://localhost/YourApp/.aspx. You'll get the same effect with the added benefit that if your app happens to have recycled, your event will still execute as the 1st request.
You can do the kind of thing you're describing by using the inbuilt ASP.NET Cache.Add CacheItemRemovedCallback delegate. It's a bit of a roundabout way of using it, but you can do effective scheduling this way.
There's an article here showing how to do it.
More information on the CacheItemRemovedCallback here.
Edit: I know you said no services, but if you check the server and find you can use Scheduled Tasks, you can use that to run a console app on a specific schedule like some other other answers mention.

ASP.NET page contains dynamic elements, loading takes time

I am dynamically creating a table of checkboxes on my test.aspx page. The dimensions (row and column count) of the table are determined by querying the database.
In test.aspx page, I do the following:
<script language="C#" runat="server">
protected void Page_Load ( object src, EventArgs e ) {
//Query the database to get the data for rows and columns
CheckBox[] chkBox = new CheckBox[rows * columns]; //creates a collection of checkboxes
//Iterate over the query set in a double for loop to create dynamic checkboxes
}
</script>
Right now I have the number of rows=20 and columns=10, but it can increase (with the columns more likely).
I used the Net tab in Firebug to ascertain the time taken by different events and found that GetTest.aspx is taking close to 4 minutes, which is too long a time to wait.
Is there a way to being down the page load time? Is my approach to create dynamic check boxes correct?
Thanks in advance.
cheers
I'm looking at this comment:
// Query the database to get the data for rows and columns
You gloss over this, but 9 times out of 10 when a web page loads slowly it's because it's performing some slow database operation.
My guess is that either (a) you have a very inefficient database query, perhaps due to a lack of indexing, or (b) you're running a database query inside a loop somewhere (very bad).
ASP.NET can create thousands of checkboxes in less than 1 second. It's just class instantiation. The issue is somewhere else.
Enabling ASP.NET trace on the page and see where all the time is spent. Four minutes is of course way too long for any page. You list two though... test.aspx and GetTest.aspx... what is GetTest.aspx?
EDIT:
OK, you are not telling us the whole story here. What else is this page doing? Where are these controls going? I just tried this on a test page using code similar to that above and it renders in a split second.
Like I said... enable TRACE and find out what is really taking up all the time! Use the tool, that's why it's there.
Creation of controls (CheckBox) and adding to a holder from the server-side is very inexpensive. Considering you are not creating billions.
The HTML that is generated should not be big enough to take 4 minutes on a local machine.
Please check the generated HTML size to verify its mass.
If I were you then I would have written the following code on my server. Please consider.
protected void Page_Load(object src, EventArgs e) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
holderPanel.Controls.Add(
new CheckBox {
ID = string.Format("chk{0}{1}", i, j),
Text = "some text"
});
}
}
}
Consider the holderPanel is a server side asp:Panel or a simple Div with ID = "holderPanel" and runat="server"
Try disabling Firebug & see if it still takes that long. Also double check that your code didn't generate more checkboxes than you expected.

Resources