Dotnet provides a server-based timer ( and is different from System.Windows.Forms.Timer and System.Threading.Timer ), allow us to specify a recurring interval at which an event will be raised in our application(or Easy way of executing a task at specified interval).
Below example (c# console application) shows how to create a Timer ,execute a task at specified interval and how to stop Timer gracefully.
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Timers;
namespace BackgroundThread_Terminate
{
class Program
{
static void Main(string[] args)
{
using (TimerClass_example1 timerSample = new TimerClass_example1())
{
Console.ReadLine();
}
Console.ReadLine();
}
}
public class TimerClass_example1:IDisposable
{
System.Timers.Timer timer;
long _stopTimer = 0; // 0 for start , 1 for stop
ManualResetEvent manualReset = new ManualResetEvent(false);
public TimerClass_example1()
{
timer = new System.Timers.Timer(1000);
timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
timer.Start();
}
//call back function excuted on a threadpool thread.
void timer_Elapsed(object sender, ElapsedEventArgs e)
{
//always use try catch in callback
try
{
//gracefully stop timer
if(Interlocked.Read(ref _stopTimer) == 1 )
{
timer.Stop();
//signal the thread which is waiting.
manualReset.Set();
return;
}
Console.WriteLine(string.Format("Executed callback at {0}. Threadpool Thread ID:- {1}", DateTime.Now.ToString(), Thread.CurrentThread.ManagedThreadId));
//Note #1:- Uncomment below the and note the ThreadID's printed
//Thread.Sleep(2000); //[ Reason for printing different Thread is :- The Elapsed event is raised on a ThreadPool thread. If processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. Thus, the event handler should be reentrant.]
}
catch (Exception ex)
{
//log exception and you can stop excuting Timer.
}
}
public void Dispose()
{
StopAndDisposeTimer();
GC.SuppressFinalize(this);
Console.WriteLine("Timer has been disposed");
}
private void StopAndDisposeTimer()
{
Interlocked.Exchange(ref _stopTimer, 1);
//wait 5 secs for signal
if (!manualReset.WaitOne(5000, false))
{
Console.WriteLine("Timer is not stopped gracefully.");
}
timer.Dispose();
}
~TimerClass_example1()
{
Dispose();
}
}
}
Thursday, 9 April 2009
Monday, 2 March 2009
Developing Financial Applications using .Net & Matlab ( Part-1)
This video shows how we can use Algorithms written in matlab 'M' code can be used in .Net applications. (View the video in 'double size' resolution).
Matlab Code snippet
--------------------
function [ Price,AccruedInt ] = MyBndPrice(Yield, CouponRate, Settle,...
Maturity, Period, Basis)
[Price, AccruedInt] = bndprice(Yield, CouponRate, Settle,...
Maturity, Period, Basis);
end
.Net Code snippet
-------------------
private void btnBndPrice_Click(object sender, EventArgs e)
{
MWNumericArray yields = GetYields();
MWNumericArray coupon = new MWNumericArray(Convert.ToDouble(txtCoupon.Text) ) ;
MWNumericArray period = new MWNumericArray(cmbPeriod.SelectedIndex + 1 ) ;
MWNumericArray basis = new MWNumericArray(cmbBasis.SelectedIndex);
MWCharArray settlement = new MWCharArray(txtSettlement.Text);
MWCharArray maturity = new MWCharArray(txtMaturity.Text);
MyFinLib.MyFinLibclass finLib = new MyFinLib.MyFinLibclass();
MWArray[] result = finLib.MyBndPrice(2, yields, coupon, settlement, maturity, period, basis);
Display(result);
}
private double[] GetYields()
{
string[] yieldStr = txtYield.Text.Split(',');
double[] yields = new double[ yieldStr.Length ];
for (int i = 0; i < yieldStr.Length; i++)
yields[i] = Convert.ToDouble(yieldStr[i]);
return yields ;
}
private void Display(MWArray[] result)
{
DataTable dt = new DataTable();
dt.Columns.Add("Price");
dt.Columns.Add("Accrued Interest");
string[] price = result[0].ToString().Split('\n');
string[] accuredInt = result[1].ToString().Split('\n');
for (int i = 0; i < price.Length; i++)
{
DataRow row = dt.NewRow();
row[0] = price[i];
row[1] = accuredInt[i];
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
}
Matlab Code snippet
--------------------
function [ Price,AccruedInt ] = MyBndPrice(Yield, CouponRate, Settle,...
Maturity, Period, Basis)
[Price, AccruedInt] = bndprice(Yield, CouponRate, Settle,...
Maturity, Period, Basis);
end
.Net Code snippet
-------------------
private void btnBndPrice_Click(object sender, EventArgs e)
{
MWNumericArray yields = GetYields();
MWNumericArray coupon = new MWNumericArray(Convert.ToDouble(txtCoupon.Text) ) ;
MWNumericArray period = new MWNumericArray(cmbPeriod.SelectedIndex + 1 ) ;
MWNumericArray basis = new MWNumericArray(cmbBasis.SelectedIndex);
MWCharArray settlement = new MWCharArray(txtSettlement.Text);
MWCharArray maturity = new MWCharArray(txtMaturity.Text);
MyFinLib.MyFinLibclass finLib = new MyFinLib.MyFinLibclass();
MWArray[] result = finLib.MyBndPrice(2, yields, coupon, settlement, maturity, period, basis);
Display(result);
}
private double[] GetYields()
{
string[] yieldStr = txtYield.Text.Split(',');
double[] yields = new double[ yieldStr.Length ];
for (int i = 0; i < yieldStr.Length; i++)
yields[i] = Convert.ToDouble(yieldStr[i]);
return yields ;
}
private void Display(MWArray[] result)
{
DataTable dt = new DataTable();
dt.Columns.Add("Price");
dt.Columns.Add("Accrued Interest");
string[] price = result[0].ToString().Split('\n');
string[] accuredInt = result[1].ToString().Split('\n');
for (int i = 0; i < price.Length; i++)
{
DataRow row = dt.NewRow();
row[0] = price[i];
row[1] = accuredInt[i];
dt.Rows.Add(row);
}
dataGridView1.DataSource = dt;
}
Tuesday, 24 February 2009
Saturday, 21 February 2009
Tuesday, 10 February 2009
Visual Representation of SQL Joins + Set Notations
Throwing some Gyan on Sql Join/Set theory after reading an article on
Sql Joins in codeproject.
[Thanks to good old shool days set theory lectures.]
'A' & 'B' are two sets,
1) A n B = Inner Join ( 'n' -- Intersection)
2) A u (A n B) = left join ( 'u' -- union )
3) (A n B) u B = right join
4) A u B u (A n B) = outer join
5) A - B = Left join excluding inner join or relative complement
6) B - A = right join excluding inner join
7) (A - B) U (B - A) = outer join excluding inner join.
[Note:- Given the fact that Sql Joins are popular tech. interview question,you can use above stuff to impress your interviewer.I hope above set notions will help you to answer Sql Join Q?'s in a generic way rather than explaining using 'Table1' , 'Table2' etc.... ]
Sql Joins in codeproject.
[Thanks to good old shool days set theory lectures.]
'A' & 'B' are two sets,
1) A n B = Inner Join ( 'n' -- Intersection)
2) A u (A n B) = left join ( 'u' -- union )
3) (A n B) u B = right join
4) A u B u (A n B) = outer join
5) A - B = Left join excluding inner join or relative complement
6) B - A = right join excluding inner join
7) (A - B) U (B - A) = outer join excluding inner join.
[Note:- Given the fact that Sql Joins are popular tech. interview question,you can use above stuff to impress your interviewer.I hope above set notions will help you to answer Sql Join Q?'s in a generic way rather than explaining using 'Table1' , 'Table2' etc.... ]
Sunday, 1 February 2009
Thursday, 22 January 2009
Vedic Math Part-1
What is a Number? Why students afraid to play with numbers?
These questions lead me to explore more on Vedic mathematics and found some interesting tips & tricks that will help to do your math calculation easily , without the help of Calculator.
“Vedic Mathematics is the name given to the ancient system of Mathematics which was rediscovered from the Vedas between 1911 and 1918 by Sri Bharati Krsna Tirthaji (1884-1960). According to his research all of mathematics is based on sixteen sutras, or word-formulae. For example, 'Vertically and Crosswise` is one of these Sutras. These formulae describe the way the mind naturally works and are therefore a great help in directing the student to the appropriate method of solution”.
Sharing some tips/tricks that I have learned, (start practising or teach your kids :-))
How to find the square of a number?
Ans: - #1) Generic way
[ Eg:- 8 x 8 = ?
Take 10 as base ,
step i) then find how much less/surplus is 8 from 10
i.e 8 -10 = -2 ( 8 is less than 10 so -2)
step ii) add less/surplus from the actual number, this will be right hand side digit
i.e (8-2) = 6
step iii) take the sqaure of surplus/less , this will be left hand digit
(-2) x (-2) = 4
So the answers is 64.
Similarly , 7 x 7 = ( 7 + ( 7 - 10)) ( (7-10) x (7-10) ) = ( 7 - 3) (-3 x -3) = 4 9
12 x 12 = ( 12 + (12 - 10) ) ( (12 - 10) x (12 - 10) ) = (12 + 2) (2 x 2) = 14 4 ( Note:- 12 is greater than 10 , so +2 )
try 13 x 13 = ?
]
#2) Square of number that ends with 5
15 x 15 = ?
Take the suqare of lefthand digit , ie 5 x 5 =25
add + 1 to right hand digit/digits and multiply that number with actual number ie 1 x (1 + 1 ) = 2
Answers is 2 25 , i.e. (1 x (1 + 1 )) ( 5 x 5 )
25 x 25 = ( 2 x ( 2 + 1) ) (5 x 5) = ( 2 x 3 ) 25 = 6 25
more to follow…….
These questions lead me to explore more on Vedic mathematics and found some interesting tips & tricks that will help to do your math calculation easily , without the help of Calculator.
“Vedic Mathematics is the name given to the ancient system of Mathematics which was rediscovered from the Vedas between 1911 and 1918 by Sri Bharati Krsna Tirthaji (1884-1960). According to his research all of mathematics is based on sixteen sutras, or word-formulae. For example, 'Vertically and Crosswise` is one of these Sutras. These formulae describe the way the mind naturally works and are therefore a great help in directing the student to the appropriate method of solution”.
Sharing some tips/tricks that I have learned, (start practising or teach your kids :-))
How to find the square of a number?
Ans: - #1) Generic way
[ Eg:- 8 x 8 = ?
Take 10 as base ,
step i) then find how much less/surplus is 8 from 10
i.e 8 -10 = -2 ( 8 is less than 10 so -2)
step ii) add less/surplus from the actual number, this will be right hand side digit
i.e (8-2) = 6
step iii) take the sqaure of surplus/less , this will be left hand digit
(-2) x (-2) = 4
So the answers is 64.
Similarly , 7 x 7 = ( 7 + ( 7 - 10)) ( (7-10) x (7-10) ) = ( 7 - 3) (-3 x -3) = 4 9
12 x 12 = ( 12 + (12 - 10) ) ( (12 - 10) x (12 - 10) ) = (12 + 2) (2 x 2) = 14 4 ( Note:- 12 is greater than 10 , so +2 )
try 13 x 13 = ?
]
#2) Square of number that ends with 5
15 x 15 = ?
Take the suqare of lefthand digit , ie 5 x 5 =25
add + 1 to right hand digit/digits and multiply that number with actual number ie 1 x (1 + 1 ) = 2
Answers is 2 25 , i.e. (1 x (1 + 1 )) ( 5 x 5 )
25 x 25 = ( 2 x ( 2 + 1) ) (5 x 5) = ( 2 x 3 ) 25 = 6 25
more to follow…….
Subscribe to:
Posts (Atom)