Sunday, August 16, 2015

.Net Sound Timer

This tutorial show you how to set sound timer depend on the number of order. It plays sound for notification whenever the number of order change.
Sound Timer

Firstly, copy the following javascript to <head> tage.
<script type="text/javascript">
    function EvalSound(soundobj) {
        var thissound = document.getElementById(soundobj);
        thissound.play();
    }
</script>
Secondly, copy the following code to <form> tag.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer ID="Timer1" runat="server" Interval="5000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:Label ID="lblOrder" runat="server" Text=""></asp:Label>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="Timer1" />
    </Triggers>
</asp:UpdatePanel>
<audio id="audio1" src="sound/Console_beep.mp3" preload="auto" autobuffer>
</audio>
In code-behind, the following snippet should be there.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        string dt = DateTime.Now.ToLongTimeString();
        string count = DAL.GetOrderCount();
        lblOrder.Text = string.Format("There are {0} records at {1}.", count, dt);
        Session["count"] = count;
        
    }
}
protected void Timer1_Tick(object sender, EventArgs e)
{
    string dt = DateTime.Now.ToLongTimeString();
    string count = DAL.GetOrderCount();
    if (count != Session["count"].ToString())
    {
        lblOrder.Text = string.Format("There are {0} records at {1}.", count, dt);
        ScriptManager.RegisterStartupScript(Page, GetType(), "PlaySound", "EvalSound('audio1');", true);
    }
    Session["count"] = count;
}
It uses "Northwind" database and connection string in web.config seem like below:
<connectionStrings>
<add name="sqlConn" providerName="System.Data.SqlClient" connectionString="Server='(local)';uid='sa';pwd='p@ssw0rd';Database='Northwind';Pooling=False;" />
</connectionStrings>
It has the following code snippet in the DAL class. It uses the Microsoft.Practices.EnterpriseLibrary.Data.dll to shorten the code.
private static Database getDatabase()
{
    Database database = null;
    try
    {
        database = DatabaseFactory.CreateDatabase("sqlConn");
    }
    catch (Exception exception)
    {
               
    }
    return database;
}
public static string GetOrderCount()
{
    string count = "";
    try
    {
        count = getDatabase().ExecuteScalar("GetOrderCount").ToString();
    }
    catch (Exception exception)
    {
        
    }
    return count;
}
The "GetOrderCount" stored procedure is as shown below:
USE [Northwind]
GO
ALTER PROCEDURE [dbo].[GetOrderCount]
AS
BEGIN
    SELECT COUNT(*) FROM Orders;
END
This application demonstrates a simple use of the Timer control with UpdatePanel combining HTML5 audio element in a real world example.

No comments:

Post a Comment