Category Archives: .NET

How to run code daily at specific time in C# Part 2


Few months ago I wrote blog post about how to run code daily at specific time. I dint know that the post will be the most viewed post on my blog. Also there were several questions how to implement complete example. So today I have decided to write another post, and extend my previous post in order to answer thise question as well as to generalize this subject in to cool demo called Scheduler DEMO.

The post is presenting simple Windows Forms application which calls a method for every minute, day, week, month or year. Also demo shows how to cancel the scheduler at any time.

The picture above shows simple Windows Forms application with two  numeric control which you can set starting hour and minute for the scheduler. Next there is a button Start to activate timer for running code, as well as Cancel button to cancel the scheduler. When the time is come application writes the message on the Scheduler Log.

Implementation of the scheduler

Scheduler is started by clicking the Start button which is implemented with the following code:

/// <summary>
/// Setting up time for running the code
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void startBtn_Click(object sender, EventArgs e)

    //retrieve hour and minute from the form
    int hour = (int)numHours.Value;
    int minutes = (int)numMins.Value;

    //create next date which we need in order to run the code
    var dateNow = DateTime.Now;
    var date = new DateTime(dateNow.Year, dateNow.Month, dateNow.Day, hour, minutes, 0);

    listBox1.Items.Add("**********Scheduler has been started!*****");

    //get nex date the code need to run
    var nextDateValue=getNextDate(date,getScheduler());

    runCodeAt(nextDateValue, getScheduler());


When the time is defined then the runCodeAt method is called which implementation can be like the following;

/// <summary>
/// Determine the timeSpan Dalay must wait before run the code
/// </summary>
/// <param name="date"></param>
/// <param name="scheduler"></param>
private void runCodeAt(DateTime date,Scheduler scheduler )
    m_ctSource = new CancellationTokenSource();

    var dateNow = DateTime.Now;
    TimeSpan ts;
    if (date > dateNow)
        ts = date - dateNow;
        date = getNextDate(date, scheduler);
        ts = date - dateNow;

    //enable the progressbar

    //waits certan time and run the code, in meantime you can cancel the task at anty time
    Task.Delay(ts).ContinueWith((x) =>
            //run the code at the time

                //setup call next day
                runCodeAt(getNextDate(date, scheduler), scheduler);


The method above creates the cancelationToken needed for cancel the scheduler, calculate timeSpan – total waiting time, then when the time is come call the method methodToCall and calculate the next time for running the scheduler.

This demo also shows how to wait certain amount of time without blocking the UI thread.

The full demo code can be found on OneDrive.

New Features in C# 6.0 – Auto-Property Initializers

Initialize property is repetitive task, and cannot be done in the same line as we can can done for fields. For example we can write:

public class Person
 private string m_Name="Default Name";
 public string Name {get;set;}
 public Person()


As we can see Property can be initialized only in the constructor, beside the filed which can be initialized in the same line where it is declared. The new feature in C# 6.0 defines Auto-Property initializer alowing property to be initialized like fields. The following code snippet shows the Auto-Property Initializer;

public class Person
 static string m_Name="Default Name";
 static string Name {get;set;}=m_Name;

New Features in C# 6.0 – Null-Conditional Operator

This is blog post series about new features coming in the next version of C# 6.0. The first post is about null conditional operator.

The NullReferenceException is night mare for any developer specially for developer with not much experience. Almost every created object must be check against null value before we call some of its member. For example assume we have the following code sample:

class Record
 public Person Person  {get;set;}
 public Activity Activity  {get;set;}
public static PrintReport(Record rec)
  string str="";
   if(rec!=null && rec.Person!=null && rec.Activity!=null)
     str= string.Format("Record for {0} {1} took {2} sec.", rec.Person.FirstName??"",rec.Person.SurName??"", rec.Activity.Duration);

  return ;

We have to be sure that all of the object are nonnull, otherwize we get NullReferenceException.

The next version of C# provides Null-Conditional operation which reduce the code significantly.

So, in the next version of C# we can write Print method like the following without fear of NullReferenceException.

public static PrintReport(Record rec)
  var str= string.Format("Record for {0} {1} took {2} sec.", rec?.Person?.FirstName??"",rec?.Person?.SurName??"", rec?.Activity?.Duration);


As we can see that ‘?’ is very handy way to reduce our number of if statements in the code. The Null-Conditional operation is more interesting when is used in combination of ?? null operator. For example:

 string name=records?[0].Person?.Name??"n/a";

The code listing above checks if the array of records not empty or null, then checks if the Person object is not null. At the end null operator (??) in case of null value of the Name property member of the Person object put default string “n/a”.

For this operation regularly we need to check several expressions agains null value.
Happy programming.


My .NET Native session on MobilityDay 2014


MobilityDay conference is one of the best conference in the region about mobile technologies. It is one day conference, with several slots and great speakers from the whole Europe. Also most of the speakers hold MVP award. Every year I am visiting this conference as attender or as a speaker, because I spend great times there.

This year I am going to visit this conference as a speaker for the second time and I am very happy for that. I will be speaking about .NET Native precompilation techologiy which ordinary .NET application converts in to super fast application, as the same as VC++ would do. This is long waiting technology from Microsoft and the next version of the .NET will be armed with this great feature.

Come to Zagreb at Thursday at Hotel Antunovic and spend great time on the best conference about mobile technology.

Here is a quick infor about the session:

(C# Productivity) + (C++ Performance) = .NET Native

Level: 300
Hall: Dvorana 3
Time: 17:00 – 17:45
NET developers for years are faced with opinions that NET applications do not have the performance of native applications, and the reason is compiling IL code during execution of the application. On the other hand, there is a mountain of unnecessary library as an integral part of the NET Framework to create a “dependency” on the application themselves. Mirosoft in the next version of the NET Framework and Visual Studio wants to offer an entirely new way of distributing NET applications by offering the same compile the IL code, which is then over the NET native compilers translate into machine code in the same way as it would appear one VC ++ applications. With this move, Microsoft NET allows developers to develop high-performance applications, while retaining the maximum productivity of writing code that has C #. The lecture will present a Native NET compiler, and how to develop with him NET applications, high performance and which do not depend on the NET Framework.


Get every new post delivered to your Inbox.

Join 555 other followers