Can I "insert required action here" today?

A system I'm working on requires emails to only be sent on particular days of the week. I wanted to have a key in the config that allows the days to be changed as required so there was no hard coding.

Something like a mask of the days e.g. SMTWTFS and to stop sending on a particular day you would set the appropriate day to _ (underscore) e.g. _MTWT_S so no emails would get sent on Sundays and Fridays.

So in the config I defined a new key called "SendDays" and initially gave it a value of "_MTWTF_" so that emails would not get sent on Saturdays and Sundays.

Now I just needed to map the day of the week onto the key and see if it returned an _ indicating that the emails should not be sent.

I found that you can use the DateTime.Now.DayOfWeek which returns a DayOfWeek enumerated constant indicating the day of the week - Monday, Tuesday, Wednesday... etc but I needed to have a number so I could work out the position in the list of days. A nice feature of enums is that you can convert the returned value into it's underlying int value this then gives me the correct location and it's a simple case of returning the char at that position and checking it.

Here's all the code it took:-

_sendDays = "_MTWTF_";

if (_sendDays[(int)DateTime.Now.DayOfWeek] != '_')
 ...send the emails...

0 comments: