Home » Asp.net

Timer in asp.net via VB


Is there any possibility to use Timer in Background of asp.net page? I need to always run the timer to monitor one field of table.

I was thinking to develop a small desktop application and run always on server, but it looks ugly idea if such kind of service can be done via asp.net it selef.

Please provide your ideas how it can be done?

Thank You


3 Answers Found


Answer 1

Hi, have you looked at using the Ajax timer  control? Take a look at this video tutorial here:



Answer 2


Yes, you can create a Timer in background of ASP.NET. Please have a try on this sample.

Firstly create a new class called “MyTimer” then paste this code in the class file.

Imports System.Timers

Public NotInheritable Class MyTimer
    Private Sub New()
    End Sub
    ' Run the checking every minute
    Public Shared timer As New Timer(60000)

    ' Enable the timer to run
    Public Shared Sub StartRuning()
        AddHandler timer.Elapsed, AddressOf timer_Elapsed
    End Sub

    ' This method will be called every minute
    Private Shared Sub timer_Elapsed(ByVal sender As Object, ByVal e As ElapsedEventArgs)

        ' write code here to query or update database

    End Sub
End Class

Then write code in Global class to enable the Timer.

    ' This is Global.asax.vb
    Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
        ' Fires when the application is started
    End Sub



Answer 3

if you have access to the server, use scheduled tasks for running some services in regular intervals. In this case, you need to create a standalone application and make an exe out of it, then schedule it.

If you are hosting application with shared hosting environment, then can use the cache expiration and run the service on intervals..

see this article




I was thinking if there is a way to stop/start ASP.NET 2.0 AJAX 1.0 Timer control from client side, regarding that, I found 2 methods _startTimer() and _stopTimer(), those were excatly what I was looking for.

bellow is a sample client code of how you can use these 2 methods:

function startTimer()
      var timer = $find(

function stopTimer()
      var timer = $find("<%=ajaxTimer.ClientID%>")

The above code assuming that you have an AJAX Timer control on the page named ajaxTimer.

Call these method from your client side code, or add them as event handlers on your target elements.

I don't know why these are not documented, or we are not supposed to use them?! Actually I don't know.

I thought that after using these methods the browser will cause a problem regarding client scripts, but both Opera and IE worked just fine without any problem. Also I didn't notice any slow down or hanging in both browsers.

Hope you find it useful.


Hey everybody!


I want to make my form freeze for 5 seconds before it resumes to the next form.

So I have a form that says : Establishing a connection....

But I don't want it to make a connection, i just want the user to think that it's making a connection.

And I then want it, when the timer reaches zero, that it would resume to the next form.

I just need the code of the timer behavior.


Any help would be greatly appreciated!



i'm going to make application but i need timer in vb.net to compute the time required to complete my application

I am very new to WCF and inherited this application today.  I need to add a timer (or something like that) in the back end to run a method every 30 minutes.  Can someone provide me some code snippet to do this?  I have worked with timers some in WinForms but not in WCF.  The service will be running (obviously) and every 30 minutes run a method that will go out and grab data and then process.  The timer part is the part I am not sure how to implement.

Any help is greatly appreciated.


I've got a WCF service that handles account management for a Silverlight 4 application. It uses PerSession as the InstanceContextMode and Required as the AspNetCompatibilityRequirementsMode so I can use ASP .NET SessionState (Silverlight only supports BasicHttpBinding, which doesn't support WCF sessions).

When the client application calls the Login method, the service sets up a System.Timers.Timer object that fires after five minutes. The client calls a KeepAlive method every thirty seconds to let the service know its still alive, KeepAlive resets the timer. The idea is if the user leaves by closing the browser or leaving the page without properly logging out, after five minutes the timer event fires and it's supposed to set some flags in the application's database. This mostly works.

The problem is that HttpContext.Current.Session is always null within the timer event. It works fine within the other methods. Since I can't access session, I can't figure out which user it is to perform cleanup.

Can I access the Session object? Is there a better way for me to maintain session state while keeping Silverlight compatibility?



i want to execute an Timer in the global.asax when the Application_Starts (it is a function to log the web accesses). I want to use a Timer (System.Threading.Timer) , that checks the entries in the database in a specified period. 

            TimerCallback timerDelegate = CheckStatus;
            Timer stateTimer = new Timer(timerDelegate, null, 0, 10000);

The "CheckStatus" is the control function in the global.asax. But the thread only runs once, but i think it should run every 10 seconds? Where is the problem?!



I am writing a web application that needs to get new data from the webserver at regular intervals.  What I've done: I'm using a DataGridView control on the webpage to display the data from the database but when the new data is retrieved I don't want to refresh the entire page, just the DataGridView control.  To this end I've put the DataGridView control in an UpdatePanel control with the following code from my .aspx file


      <asp:UpdatePanel ID="UpdatePanelAlarmedSites" runat="server" UpdateMode="Conditional">
          <div id="DivAlarmedCogenUnits">
            <asp:GridView ID="GridViewAlarmedSites" runat="server"            AutoGenerateColumns="False" BackColor="White" BorderColor="#E7E7FF"            BorderWidth="1px" CellPadding="3"            DataSourceID="SqlDataSourceAlarmedCogenSites" GridLines="Horizontal"            BorderStyle="None">
              ...Style Tags Ommitted...
                <asp:CommandField ShowSelectButton="True" />
                <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
                <asp:BoundField DataField="AlarmState" HeaderText="AlarmState" SortExpression="AlarmState" />
              ...Style Tags Ommitted
          <asp:AsyncPostBackTrigger ControlID="TimerSelectCogenSiteData" EventName="Tick" />


As you can see from the above code I'm using an AJAX timer control to get the latest data every few seconds.  In the .aspx page:

<asp:Timer ID="TimerSelectCogenSiteData" runat="server" Interval="5000" EnableViewState="False"></asp:Timer>

 defines the timer in my webform.

In my code-behind page (VB) I run this code on the server when the timer ticks

Protected Sub TimerSelectCogenSiteData_Tick(ByVal sender As Object, ByVal e As System.EventArgs) Handles TimerSelectCogenSiteData.Tick
      ScriptManager.RegisterClientScriptBlock(Page, GetType(Page), "CallUpdatePushpins", "UpdatePushpins();", True)
    End Sub

RegisterLatLongArrays() is a subroutine that registers several javascript accessable arrays onto the page using the ScriptManager.RegisterArrayDeclaration method. 

Unfortunately every time the timer ticks and the UpdatePanel refreshes my browser (IE7) eats up more memory.  After a while the page runs super-slow and eventually crashes.

Can anybody help me with resolving this memory leak?  I've tried everything I can think of, but it seems whenever I add that asp:Timer control to a webpage it eats up memory and I can't figure out why.  I even made a new project with nothing but a ScriptManager, an UpdatePanel and a Timer and it still eats up memory on every timer tick, although it does eat up less than my application does.


Hello All,

I have a requirement where i need to access the methods of one user control in another user control.
Any pointers in this direction is greatly appreciated.

Thank you



wi As System.Security.Principal.WindowsIdentity =  _System.Security.Principal.WindowsIdentity.GetCurrent()



Dim a AsString() = HttpContext.Current.User.Identity.Name.Split("\"c)

Dim ADEntry AsNew System.DirectoryServices.DirectoryEntry _

(("WinNT://" & a(0) & "/") + a(1))

Dim Name AsString = ADEntry.Properties("FullName").Value.ToString()

this code works fine when it is running in my local machine. when i try to open the sam eapplication from remote system its giving error.

even i am getting the erron after changed the web.config file with

 <authentication mode="Windows"/>
<identity impersonate="true"/>
         <deny users="?"/><allow users="*"/>

The network path was not found.



Please help me on this isseue its urgent.



i have a little question about array in ASP.NET or vb.net.

In my classic ASP-Application i use arrays like this

dim ubbarray, txt
ubbarray = _
Array( _
Array("string1","string11","string111"), _
Array("string2","string22","string222"), _
Array("string3","string33","string333") _

for i = 0 to ubound(ubbarray)
txt = txt & "a:" & ubbarray(i)(0) & " b:" & ubbarray(i)(1) & " c:" & ubbarray(i)(2) & "<br/>"

response.write txt

The reason is, i would like to bild a little editor with some buttons and javascipt. But a script like this doesn't work in ASP.NET vb.net.

Thank you in advance for helping me.


I'm using MS VS 2010 and my controls have already been created on the aspx page. i just need a sample code to send  the email to my exchange server in VB.net side of things. thanks in advance.


Dear all,

           I need your help on how to generate HTML reports in an asp.net application.The report content should be database driven. since we have faced some problems with Crystal reports during the Deployment ,also it takes some time to load data.It affects the performance of application.   



i used the code below to try sending an e mail but did'nt work, I've gotten the mail server and port from my host company.


  Dim message As New MailMessage("sender@address", "from@address", "Subject", "Message Text")
        Dim emailClient As New SmtpClient("Email Server Name")

Hello Friends.
  I am getting an error while tryng to write to sql server. I can't figure out whats wrong. I tried over and over and through some of you may be able to see through the erro instantly. 
the error says "Invvalid "ClientID"" whcih is not true. I double checked the typos and the type. I declared it as varchar(250) and its not declared as identity field,w hich I knew I should but I didnt' in this case
Little background on the set up
I have a table named jobs where I have a jobID as the pk(autogenerated colum) and clientID which his not foreign or any kind of key, yet anyway. and rest of hte field as you see below in my code. Why am I getting this error? Any clue?
I really appreciate if you could help me.
My relevant code
If Page.IsValid Then
            Dim jobdsn As New SqlDataSource
            jobdsn.ConnectionString = ConfigurationManager.ConnectionStrings("CandidatesConnectionString").ToString()
            jobdsn.InsertCommandType = SqlDataSourceCommandType.Text
            jobdsn.InsertCommand = "INSERT INTO jobs (ClientId, jobtitle, postDate, jobdescription,StateID, CityID) VALUES (@CompanyName, @jobtitle,@postDate, @jobdescription,@StateID,@CityID )"
            jobdsn.InsertParameters.Add("CompanyName", txtUser.Text)    ' current login username I assigned to the txtuser.text
            jobdsn.InsertParameters.Add("jobtitle", txtJTitle.Text)                 'value entered by the user
            jobdsn.InsertParameters.Add("postdate", postdate)                 ' current date I assigned to the postdate variable
            jobdsn.InsertParameters.Add("jobdescription", txtDesc.Text)     ' value entered by the user
            jobdsn.InsertParameters.Add("StateID", ddlStates.SelectedItem.Value)  ' selected through the dropdown list
            jobdsn.InsertParameters.Add("CityID", ddlCities.SelectedItem.Value)     ' same as above

Complete error msg with the trace

Line 44:             jobdsn.InsertParameters.Add("StateID", ddlStates.SelectedItem.Value)
Line 45:             jobdsn.InsertParameters.Add("CityID", ddlCities.SelectedItem.Value)
Line 46:             jobdsn.Insert()
Line 47: 
Line 48:             Dim rowsaffected As Integer = 0

Source File: C:\Users\sharmila\Documents\Visual Studio 2008\WebSites\WebSite16\PostJobs.aspx.vb    Line: 46

Stack Trace:

[SqlException (0x80131904): Invalid column name 'ClientId'.]
   System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection) +1953274
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection) +4849707
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj) +194
   System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj) +2392
   System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +204
   System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async) +954
   System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, DbAsyncResult result) +162
   System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(DbAsyncResult result, String methodName, Boolean sendToPipe) +175
   System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +137
   System.Web.UI.WebControls.SqlDataSourceView.ExecuteDbCommand(DbCommand command, DataSourceOperation operation) +386
   System.Web.UI.WebControls.SqlDataSourceView.ExecuteInsert(IDictionary values) +227
   System.Web.UI.WebControls.SqlDataSource.Insert() +16
   PostJobs.btnPost_Click(Object sender, EventArgs e) in C:\Users\sharmila\Documents\Visual Studio 2008\WebSites\WebSite16\PostJobs.aspx.vb:46
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +111
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +110
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565





TeckChek, a service of International Knowledge Management (www.ikmnet.com), is currently seeking Subject Matter Experts to revise our ASP.NET 2.0 USING C# test. This web-based assessment test is designed for IT professionals to measure proficiency in using ASP.NET 2.0 written in C# to build Web applications. It measures understanding of the ASP.NET 2.0 framework and the ability to use ASP.NET 2.0 features to configure, develop, maintain and deploy scalable and reliable ASP.NET Web applications and Web services and to manage Web users. It also evaluates knowledge of C# 2.0 and Visual Studio 2005 for building ASP.NET Web applications.

This is a part-time, contract, telecommuting position. You will be reviewing and revising existing content and adding new content to the test. Some creative thinking and creative writing involved. Small project but prompt and successful completion will put you in line to work on future tests (upcoming C#, VB, .NET, etc. tests). Compensation based on total content revised and added.

If you are interested, please submit a copy of your resume to Craig Sernotti at csernotti@ikmnet.com.


Required ASP.NET,vb.Net Developer with 1-6 years of experience or more.

who are presently in Dubai .
Email CV to cvjobs4u@gmail.com 


Hello, this is my first post :). I have the following issue with ASP.NET 4 VB.NET with MVC Framework 2 installed. 

The code in GLOBAL.ASAX to rename images like "domain.com/images.aspx?id=1&ref=5&size=500" is the following:

  Private Sub RegisterRoutes(ByVal Routes As RouteCollection)
    Routes.MapPageRoute("Image", "images/{Ref}/{Size}/{Id}/{Title}", "~/Image.aspx", False, New RouteValueDictionary(New With {.Title = "", .Id = "", .Size = "", .Ref = ""}))
  End Sub
  Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
  End Sub

It works OK, because now I can open the images with this format: "domain.com/images/5/500/1/1/this-is-my-seo-filename".

But like you can see, the image file do not contain the ".jpg" to the end of the url. I tried to add in GLOBAL.ASAX some code like:

Routes.MapPageRoute("Image", "images/{Ref}/{Size}/{Id}/{Title}.jpg", "~/Image.aspx", False, New RouteValueDictionary(New With {.Title = "", .Id = "", .Size = "", .Ref = ""})) 

This code convert the URL to "domain.com/images/5/500/1/1/this-is-my-seo-filename.jpg" but when I open the url in the browser I received "HTTP ERROR 404 Not Found".

How can I use the extension ".jpg" or whatever extension, in a asp.net routing url with ASP.NET 4 VB.NET? Thank you.


I want to know how to do Active Directory Authentication in my intranet web application, if someone could please explain me the steps I need ...

So far I created a simple login page and I am using the login control.  my questions are how do I configure the application, how do I interface the login control so it will take the user to next page once they input their usual active directory username and password.



Hi I Want to know garbage collector works in .net there is something heap and stack funda.so can u please tell me from where i get reference of whole funda of that.and i have another question is that Please see below the code.here i declare one dt and get some data in it.and i don't want that dt after data come in text boxes.so in finally method i do dispose using dt.dispoe().

but after that i write little code to check whether the dt correctly dispose or not.so i check with if

condition after disposing.you can check code given below for that condition.as per condition it gives me "Nikunj" Ouput in message box it meanse dt is not disposed after calling the dispose method.so can u please tell me why?And i Want to know about all resources which i used i want to know how can i free it.whether it is variable,object,datatable,datareader etc..... if it is any where with example then please give me link.and if it's from msdn then it's better. i want to know from Microsoft that how Microsoft Suggest to do that.


Private Sub grd_expense_DoubleClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles grd_expense.DoubleClick
        Dim dt As DataTable
            i = grd_expense.Item(0, grd_expense.CurrentRow.Index).Value
            dt = oClsDataaccess.Get_dataTable("Select Expense_Id,Expense_Name,Comment From dbo.Tbl_Expense where Expense_Id=" & i)

            If dt.Rows.Count > 0 Then
                txtexpense.Text = dt.Rows(0)("Expense_Name").ToString()
                txtcomment.Text = dt.Rows(0)("Comment").ToString()
            End If
        Catch ex As Exception
            LogHelper.Error("Expnese_Master:grd_expense_DoubleClick" & ex.Message())
            If dt.Rows.Count > 0 Then
                MsgBox("Nikunj", MsgBoxStyle.Information)
                MsgBox("Dilip", MsgBoxStyle.Critical)
            End If
        End Try
    End Sub

And Finally i want ask to microsoft that is there any bug in this fourm or any updation is working at 25-Jan-2011 at 01.00 a.m. because it doesn't shows me sub category of fourm

and fires alert that select fourm.if u want screen shot then tell me i will provide you. And I think here this Provision must be there so i can directly put image also.

I am new to programming and have just finished one of my first projects. I would like to possibly sell this application, but I need to figure out how I'm going to get the app. protected.

I plan on selling the program as a digital download and was wondering what the steps would be to issue serial licenses to the people who will purchase it.

Can anyone please direct the first few steps? It would be greatly appreciated.

Aaron C.

<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure