jump to navigation

Trigger a Timer Event at the Specific time of the Day in a Windows Service June 7, 2012

Posted by Bilal in .NET, C#, Programming.
Tags: , , , , , , , , , ,

I have used timer many times in Windows Form Application. It’s a simple control that is easy to use and implement. Lately, I was working on a Windows Service where there was a requirement of implementing a periodic job. The timer available in Windows Form is located in System.Windows.Form namespace which is definitely not available (by default) in a Windows Service. I tried to dig into the matter and I came to know that there are three types of timers available in .NET:

  • A server-based timer, which you can add to the Toolbox
  • A Windows-based timer, which is always in the Toolbox
  • A thread timer, which is available programmatically

You can find the details about these on this MSDN Link. I shall not be going into the details of implementing each and every timer, I will just try to focus on the subject. By the way, it is very much confusing for a general user to choose the best timer. Each timer is more suitable in certain circumstances. Here is an old article (since 2004) from MSDN Magazine that will give you a great insight on these timers and their differences and usage. The source code is also available there. I would highly recommend checking the page.

After a lot of tests and search I got this Stack Overflow page which was close to my requirements.

private System.Threading.Timer myTimer;
private void SetTimerValue ()
   // trigger the event at 7 AM. For 7 PM use 19 i.e. 24 hour format
   DateTime requiredTime = DateTime.Today.AddHours(7).AddMinutes(00);
   DateTime currentTime = DateTime.Now;
   if (currentTime > requiredTime)
      requiredTime = requiredTime.AddDays(1);
   // interval between the timer events is set 10 min
   TimeSpan periodTS = DateTime.Now.AddMinutes(10) - DateTime.Now;
   myTimer = new System.Threading.Timer(new TimerCallback(TimerAction), null, (requiredTime - DateTime.Now), periodTS );

private void TimerAction (object e)
   // do some work

This piece of code completed the initial requirement to trigger the timer at the specific time of the day but with the passage of time, the event trigger time started decreasing by 1 second after 10 hours, with the interval of 10 min. If the interval is decreased the error will propagate upward much quickly.

I revised the code and made some modifications:

private System.Threading.Timer myTimer;
private void SetTimerValue ()
   // trigger the event at 7 AM. For 7 PM use 19 i.e. 24 hour format
   DateTime requiredTime = DateTime.Today.AddHours(7).AddMinutes(00);
   if (DateTime.Now > requiredTime)
      requiredTime = requiredTime.AddDays(1);

   // initialize timer only, do not specify the start time or the interval
   myTimer = new System.Threading.Timer(new TimerCallback(TimerAction));
   // first parameter is the start time and the second parameter is the interval
   // Timeout.Infinite means do not repeat the interval, only start the timer
   myTimer.Change((int)(requiredTime - DateTime.Now).TotalMilliseconds, Timeout.Infinite);

private void TimerAction(object e)
   // do some work
   // now, call the set timer method to reset its next call time

ASP.NET 4 Breaking Changes February 20, 2011

Posted by Bilal in .NET.
Tags: , , , , , , , , , , , ,
add a comment

The ASP.NET 4.0 has been a core update to ASP.NET 2.0. .NET 3.0 and .NET 3.5 were based on .NET 2.0 having additional assemblies only, not the core components. If you have installed all of these frameworks 2.0, 3.0, 3.5, 4.0 and you try to upgrade your ASP.NET 2.0 application, in IIS you will be able to find 2.0 and 4.0 version of the framework only.

Below is the list of the breaking changes in ASP.NET 4.0 that could affect your existing application while upgrading.

Microsoft OpenDoor Expo Jeddah 2010 November 13, 2010

Posted by Bilal in .NET, General, Microsoft, Tech News, Tips & Tricks, Updates, Windows.
Tags: , , , , , , , , , , , , , ,
1 comment so far

Microsoft OpenDoor 2010 Saudi Arabia took place in two cities Riyadh (2nd and 3rd Nov) and Jeddah (7th Nov) at Intercontinental Hotel. It was the first time that Microsoft CEO, Steve Ballmer visited KSA and delivered the Key Note but his visit was limited to one day and it was in Riyadh only.

The registration was web based and no registration fee was mentioned. I happen to know about Professional Developer Conference (PDC) that used to have separate registration fee for students and professionals. Anyhow, for this expo, a bar code was issued to each participant against his Windows Live ID.

The Expo started with the keynote of Developer & Platform group Manager
Adel Al-Massarani about Cloud Computing and Abdurrahman Al-Qahtani
Manager Windows Phone Group, about the new Windows Phone 7. It was followed by the presentation of the Platinum Sponsors

Mobily was also a platinum sponsor but they are already making too much advertisement through different mediums. No time was given to the Gold Sponsors. All of the sponsors have their stalls in the lobby where attendees can easily get their information.

After that there were three options to go:

  • Track A for IT Professional
  • Track B for Developers
  • Track C for Technical Managers

Each track was taking place in separate hall. Attendees had full choice to attend any of the tracks at any time as per their taste.

I joined the Track B (Developers). It started with a presentation of Mohamad Halbi about Windows Azure Platform, the cloud service operating system. It was a brief but comprehensive overview of the Azure Platform right from the start to a live working demo. He showed how windows Cloud could be utilized to get a cost effective and reliable performance.

It was followed by lunch and prayer break.

The next session was about Microsoft Web platform by Abdurrahman Al-Qahtani. He demonstrated about the new Web Platform and also gave some working demonstrations.

After a break of about 15 min, the stage was conquered by Jerry Yasir about the advanced features in Microsoft Excel 2010 and its interaction with Microsoft Sharepoint 2010. He showed how we can get the graphical representation of data and its distribution/sharing with other people through SharePoint.

Then there was prayer break. Refreshment was available in the side room that can be utilized by anybody at any time.

Last session of the track was about Visual Studio 2010 from Architecture Point of view by Abdurrahman Al-Qahtani. He should that how the advanced tools in VS 2010 can help in understanding/designing the architecture of a system graphically using UML.

In the last, there was a combined closing session of all the tracks in which winners were selected through a lucky draw. Gifts include 3 web-cameras and 1 XBOX 360 and another set of 2 web-cameras and 1 Xbox360 for the female participants.

And so, a wonderful Expo by Microsoft came to an end. We wish to see more such events in the near future by international companies like Microsoft, Google, Apple, etc… Also, we expect to see Steve Ballmer in Jeddah next year.


This slideshow requires JavaScript.

Server.MapPath February 15, 2010

Posted by Bilal in .NET, APS, C#, Microsoft, Visual Studio 2005, Visual Studio 2008.
Tags: , , , , ,
add a comment

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(“.”) returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath(“..”) returns the parent directory
  • Server.MapPath(“~”) returns the physical path to the root of the application
  • Server.MapPath(“/”) returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let’s say you pointed a web site application (http://www.example.com/) to the root of your domain


and installed your shop application (as virtual directory in IIS and marked as application) in


If, you call Server.MapPath in following request:



  • Server.MapPath(“.”) returns D:\WebApps\shop\products
  • Server.MapPath(“..”) returns D:\WebApps\shop
  • Server.MapPath(“~”) returns D:\WebApps\shop
  • Server.MapPath(“/”) returns C:\Inetpub\wwwroot
  • Server.MapPath(“/shop”) returns D:\WebApps\shop

If Path starts with either a forward (/) or backward slash (\), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn’t start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: In C#, @ is the verbatim literal string operator meaning that the string should be used “as is” and not be processed for escape sequences.

Source: Link

Some Visual Studio ShortCut Keys January 31, 2010

Posted by Bilal in .NET, Keyboard Shortcuts, Tips & Tricks, Visual Studio 2005, Visual Studio 2008.
Tags: , , ,



F3 Finds the next occurrence of the previous search text.
F5 Start debugging
F7 Jump to code behind file from .aspx files
F8 Moves the cursor to the next item, such as a task in the Task List window or a search match in the Find Results window. Each time you press F8, you move to the next item in the list.
F9 Toggle breakpoint
F12 Go to definition of identifier under cursor
Ctrl+F5 Start without debugging
Ctrl+F2 Jump to the Navigation Bar (hit TAB to get to the right side)
Ctrl+F3 Find word under cursor
Ctrl+TAB Toggle between windows in Visual Studio
Ctrl+I Incremental search (this is way better than Ctrl+F)
Ctrl+J Force IntelliSense for field members
Ctrl+C (with nothing selected) Copy whole line
Ctrl+Enter Open line above line cursor is on
Ctrl-X or Ctrl-L (with nothing selected) Cut whole line
Ctrl+] Bounce cursor between matching parentheses/brackets/braces
Ctrl+PageDown Toggle between Design and Source views in .aspx files
Alt+W, L Close all windows
Ctrl+K, Ctrl+C Comment out selection
Ctrl+K, Ctrl+U Uncomment selection
Ctrl+K, Ctrl+D Format document
Ctrl+K, Ctrl+X Insert snippet (or just type in the snippet name and hit TAB, TAB)
Ctrl+K, Ctrl+S Surround selected lines with snippet
Ctrl+K, Ctrl+K Toggle bookmark on/off
Ctrl+K, Ctrl+P Jump to previous bookmark
Ctrl+K, Ctrl+N Jump to next bookmark
Ctrl+M, Ctrl+M Open/close current fold
Ctrl+M, Ctrl+O Fold all methods
Ctrl+R, Ctrl+R Enables or disables word wrap in an editor.
Ctrl+Shift+B Build solution
Ctrl+Shift+C Displays the Class View window
Ctrl+Shift+Enter Open line below line cursor is on
Ctrl+Shift+F Global Search
Ctrl+Shift+F9 Delete all breakpoints
Ctrl+Alt+A Displays the Command window, which allows you to type commands that manipulate the IDE.
Ctrl+Alt+I Displays the Immediate window, where you can evaluate expressions and execute individual commands.
Ctrl+Alt+K Displays the Task List window where you customize, categorize and manage tasks, comments, shortcuts, warnings and error messages.
Ctrl+Alt+L Open the Solution Explorer (to find your file after you just closed them all)
Ctrl+Alt+T View Document Outline
Ctrl+Alt+0 Displays the Output window to view status messages at run time
Ctrl+Alt+R Open browser within VS.NET
Ctrl+Alt+U Displays the Modules window, which allows you to view the .dll or .exe files used by the program. In multiprocess debugging, you can right-click and select Show Modules for all Programs.
Ctrl+Alt+X Open Toolbox
Shift+Alt+Enter View editor in full screen mode

Source: http://virendrablogs.blogspot.com/2009/12/visual-studio-list-of-some-shortcut.html

OpenFileDialog.SafeFileName March 10, 2009

Posted by Bilal in .NET, C#, Microsoft, VB, Visual Studio 2005, Visual Studio 2008.
Tags: , , , , , ,

I had developed an application in VS2008 with .NET 2.0 . The application was deployed using the VS2008 deployment project  with .NET Framework as pre-req. AutoCAD 2009 was already installed on all the client machines so the pre-req conditions were satisfied so .NET Framework was not skipped during the installation of the application.

Later on,  I made a clean installation of WIN XP SP3 on my development machine. I skipped VS 2008 because I could not find its proper usage. VS2005 was sufficient for me.

Today, I got the a request for some updates in the application. For this purpose, I converted it to VS2005. On building the application is got the error about OpenFileDialog.SafeFileName. It was really a strange thing as the application was working smoothly on all the client machines.

SafeFileName returns only the File Name from the whole path. Although, I got the problem solved by doing some string operations:
String safeName = opdg.FileName.Substring(opdg.FileName.LastIndexOf("\\") + 1);
// 1 has been added to skip the \

I Googled about it and it was disclosed that this property is available in .NET Framework 2.0 SP1 which is installed along with VS2008.

Missing Items in Visual Studio 2005 Menu February 22, 2009

Posted by Bilal in .NET, C#, Microsoft, SQL Server 2005, Tips & Tricks, VB, Visual Studio 2005.
Tags: , , , , , ,
1 comment so far

I noticed some missing menu items in the VS2005 (like clean, rebuild, and many others) but i continued by using the commands from other locations; until I got stucked!  I wanted to export a form as a template but the Export was not available in the File menu.
The details of my environment are:

Since, I installed Resharper for the first time, the first option that came to my mind is that its due to Resharper. I tried to explore different options in the Resharper and VS specially the Key Mapping but no result. I was only left with the option to uninstall Resharper and I did it. But to my surprise, the problem was still there.
In such a situation, I call my rescue agent GooGle. The first suggestion provided by the agent worked well and my problem was solved.
I had installed SQL Server 2005 for the first time (initially, I was using SQL 2000 as per client requirements) but I don’t considered it bcoz it’s a Microsoft product and it was least expected to interfere in the scenario. I was WRONG. This problem occurred due to a bug in it.

Here is the solution provided by Microsoft.

Hope it will also solve your problem if u faced such an issue.

Constansts in C#: const VS readonly July 1, 2008

Posted by Bilal in .NET, C#, Uncategorized.
Tags: , , , , ,

Pop quiz: What’s the difference between these three declarations? And, more importantly, when should you use each one?

private const int _Millenium = 2000; 
private static readonly 
 DateTime _classCreation = DateTime.Now; 
private readonly DateTime _InstanceTime = DateTime.Now;

The first creates a compile-time constant, the second creates a run-time class constant, and the third creates a run-time object constant. While developing a typical program you’ll use all three constructs, so it pays to understand the difference. This article will explain the differences between these three constructs and show you when to use each.

Compile-time Constants

Let’s begin with compile-time constants. The symbols you define for compile-time constants are replaced with the value of the constant at compile time. Therefore this construct:

if (myDateTime.Year == _Millenium)

compiles to the same IL as if you had written:

if (myDateTime.Year == 2000)

The compiler replaces the symbol with the value of the constant. This is the main point to compile-time constants: These symbols don’t exist in the IL, only in your C# source. Once compiled, you have the same IL as if you had used the numeric constants in your code.

This implementation of compile-time constants places other restrictions on declaring constants and assigning values to them. First, compile-time constants can only be used effectively for primitive types, enums, or strings. Primitive types are the built-in integral and floating-point types. These are the only types that allow you to assign meaningful constant values as part of the initialization process.

The only constant value you can assign to reference types is null. The reason for this restriction is that you cannot use the new operator when you assign a constant value. In other words, the following construct won’t compile:

private const DateTime _classCreation = 
  new DateTime(2000, 1, 1, 0, 0, 0);

In practice, this restricts us to value types and strings. Any other reference type must be null. User-defined value types simply won’t work at all. For example:

struct MyStruct
 // ... 

private static const MyStruct _s;   // Doesn't compile.

So, a compile-time constant can only be used for primitive types. The IL generated for a compile-time constant contains the value, not the symbol. The value is “burned in” at compile time.

readonly Values

readonly values are also constants, in that they cannot be modified after the constructor has executed. readonly values are different, however, in that they’re set at run time. You have much more flexibility in working with run-time constants. For one thing, run-time constants can be of any type; as long as you can assign them in your constructors, they will work. I could make readonly values from DateTime structures; I could not create DateTime values with const.

Secondly, you can use readonly values for instance constants, storing different values for each instance of a class type. As we saw at the start of this article, the value of _instanceTime is different for every instance of the object being created.

The most important distinction is that readonly values are resolved at run time. The IL generated when you reference a readonly constant reference the readonly variable, not the value.

Decisions, Decisions

The main difference between const and readonly fields is in their flexibility. Suppose you’ve defined both const and readonly fields in an assembly named Infrastructure:

public class UsefulValues
  public static readonly UsefulInteger = 5; 
  public const AnotherUsefulInteger = 10; 

Then, in an assembly named Application you reference those values:

for (int i = UsefulValues.UsefulInteger;  i < UsefulValues.AnotherUsefulInteger; i++)
 Console.WriteLine("value is {0}", i); 

If you run your little test, you see the following obvious output:

Value is 5
Value is 6
Value is 9

Time passes and you release a new version of the Infrastructure assembly with the following changes:

public class UsefulValues
  public static readonly UsefulInteger = 105; 
  public const AnotherUsefulInteger = 120; 

You distribute the Infrastructure assembly without rebuilding your Application assembly. What do you suppose happens?

You’ll get no output at all. The loop now uses the value 105 for its start, and 10 for its end condition. The const value of 10 was placed into the Application assembly by the C# compiler. Contrast that with the UsefulInteger value. It was declared as readonly; it gets resolved at run time. Therefore, the Application assembly makes use of the new value without even recompiling the Application assembly. Simply installing an updated version of the Infrastructure assembly is enough. The point here is that updating the value of a public constant is really an interface change. Updating the value of a readonly constant is easily upgradeable.

Using readonly constants will also generate a smaller assembly. Every time you use a const value, the compiler inserts the value of the constant. When you reference a readonly value, the compiler references that symbol. Repeatedly storing the actual values in the IL will result in a larger assembly than repeatedly referencing the same location. This particular argument does not apply to strings because .NET replaces duplicate strings using a process called string interning. The result is that const strings generate more or less the same IL as readonly strings.

Are there any advantages to using const over readonly? Yes; constants can be used in places where readonly values cannot, namely attributes. You can use const values as the parameters to attribute constructors; you cannot use readonly values, or variables. So, when you define objects to use when constructing attributes, those values used for attribute parameters must be const; readonly doesn’t work. Figure 1 shows an example of a simple attribute to tag classes with their state.

[AttributeUsage (AttributeTargets.Class)]
public class ClassStateAttribute : Attribute
 public enum CodeState
 Experimental = 0x01,
 Stable = 0x02,
 Released = 0x04
  public const CodeState Release2Upgrade =
 CodeState.Released | CodeState.Experimental;  
  public readonly CodeState TheState;  
  public ClassStateAttribute (CodeState s) 
 TheState = s; 
 [ClassState (ClassState.Release2Upgrade)] 
public class NewCode
 // Etc. 

Figure 1: A simple attribute to tag classes with their state.

You could not, however, rewrite it using readonly values, as shown in Figure 2.

 [AttributeUsage (AttributeTargets.Class)] 
public class ClassStateAttribute : Attribute
  public enum CodeState
 Experimental = 0x01, 
 Stable = 0x02, 
 Released = 0x04
 // Won't work:   Only constant values can be used. 
 // Not read only. 
  public static readonly CodeState Release2Upgrade =
 CodeState.Released | CodeState.Experimental; 
  public ClassStateAttribute(CodeState s) 
 TheState = s; 
 [ClassState (ClassState.Release2Upgrade)] 
public class NewCode
 // Etc. 

Figure 2: Readonly values won’t work on our simple example.

The readonly type doesn’t work to initialize an attribute. The actual value of the object must be available at compile time for the attribute to get created correctly. Therefore, only values declared as const (or enums) can be used in this instance.

I always get questions about the relative performance of const and readonly values. Frankly, I’ve never been able to measure any difference between the two; for any operation I’ve tried, they are equivalent. The table in Figure 3 summarizes the different use cases I’ve discussed, and offers my recommendations.




Comments and Recommendations

Primitive constant



Use const. Primitive types that will never change should be const.

Release Dependent const, primitive type



Use static readonly. Any constant value that might change should be readonly, not const.

Other constants



Use static readonly. It’s the only one that works.

Immutable members



Use (instance) readonly. It’s the only option, and immutability is enforced by the compiler.

Enumerated values



Enumerated values must be const.

Values used to construct attributes



These must be constants.

Figure 3: Recommendations for the use cases discussed in this article.


There are some small performance gains to be realized from using const instead of readonly, but you give up quite a bit of flexibility. You’ll need to recompile every assembly that uses a const value. In the case of readonly you need only update the definition. This flexibility greatly overrides the minimal performance gains from using const as the key. Minimize your use of const to attribute parameters and enums. Everything else should be declared readonly instead.


PInvoke.net May 16, 2008

Posted by Bilal in .NET, C#, VB, Website Review, WIN32 API.
Tags: , , ,
add a comment

Address: www.pinvoke.net

Its an excellent site which explain the use of WIN32 DLLs in .NET code ( C# or VB).


How to Provide a managed wrapper for an unmannaged code.