Fun with C#: Create a handy calendar using Iterators

Here’s something fun with can do with C#. Imagine we need to work with dates within a given year. For instance, I want to list out all days within the year of 2017. A little Calendar class like the one below would be handy:

var calendar = new Calendar(2017);
var days = calendar;
foreach (var day in days)
{
    Console.WriteLine(day);
}

The output looks somewhat like this:

What if I wanted to list all days in january, like so:

var days = calendar. Where(d => d.Month == 1);

The output:

Last but not least, maybe I want to list all Saturdays in january:

var days = calendar.Where(d => d.Month == 1 && d.DayOfWeek == DayOfWeek.Saturday))

The output:

One could think that under the hood the Calendar class uses some sort of Collection, Array or List of DateTime objects. In reality, it uses an iterator, implemented using the yield return keywords:

public class Calendar : IEnumerable<DateTime>
{
readonly int _year;

public Calendar(int year)
{
_year = year;
}

public IEnumerator<DateTime> GetEnumerator()
{
var firstDayOfTheYear = new DateTime(_year, 1, 1);
var lastDayOfTheYear = new DateTime(_year, 12, 31);
var daysInTheYear = (lastDayOfTheYear - firstDayOfTheYear).TotalDays;

for (int i = 0; i <= daysInTheYear; i++)
{
yield return firstDayOfTheYear.AddDays(i);
}
}

IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}

Ain’t that fun and handy? 🙂

I really like this combination of IEnumerable<T>, iterators, and LINQ.

Leave a comment

Speaking at the North Houston .NET User Group this week

I’m speaking at the North Houston .NET User Group this week, on Feb 16 at 6:30pm. This is a new session I’ve put together. Check this out:

Code Review: I mean no harm

As part of the work I’ve been doing for many years, I get to do a lot of code review. I usually document things that come up doing a code review so I can share it with other developers in the teams. In this session, I share some of the code I’ve looked at, the reasons why the code raised yellow or red flags in my head, and possible solutions I’ve proposed.

Leave a comment

Speaking at the Houston .NET User Group this week

I’m speaking at the Houston .NET User Group this Thursday, February 9, at 6:30pm. Click here to find out about location and other details.

I’ll be delivering a brand new session. Check out the title:

The Software Does Not Work? Rewrite it!

What’s this session really about?

Outdated technology? Unmaintainable codebase? Politics? Those are just some of the reasons that cause software rewrites. Whether a rewrite is really what is needed or not, chances are we all work in such projects.

Do we rewrite the entire software? Can we rewrite just parts of it? Where do we start? Can we automate the process?

In the last 15 years, I’ve worked in a variety of such projects. I’d like to share the most important lessons I’ve learned in these projects. In this talk, I’ll share the different types of rewrites and techniques, what I learned from it, and how it changed my way of approaching both software rewrites as well as greenfield projects.

I want your feedback!!

I hope to see some of my readers there! If you do show up there, please rate my session afterwards and provide me some feedback here! Like I said, it’s a brand new session, so I’m looking forward to constructive criticism so I can improve my material.

Leave a comment

Fun with C#: Using delegates to get rid of switch-blocks

I’m starting a new series here: Fun with C#! The idea is to post a couple of things I do in this cool language. 🙂

When I talk about Clean Code with developers, an example that I always use is switch-blocks. Every bad code out there always features abusive use of switch-blocks. In most cases, those blocks start off very simple, with one-liners, like the sample below:

public void DoStuff(DayOfTheWeek dayOfTheWeek)
{
    switch (dayOfTheWeek)
    {
        case DayOfTheWeek.Sunday:
            Console.WriteLine("Do stuff for Sunday...");
            break;
        case DayOfTheWeek.Monday:
            Console.WriteLine("Do stuff for Monday...");
            break;
        case DayOfTheWeek.Tuesday:
            Console.WriteLine("Do stuff for Tuesday...");
            break;
        case DayOfTheWeek.Wednesday:
            Console.WriteLine("Do stuff for Wednesday...");
            break;
        case DayOfTheWeek.Thursday:
            Console.WriteLine("Do stuff for Thursday...");
            break;
        case DayOfTheWeek.Friday:
            Console.WriteLine("Do stuff for Friday...");
            break;
        case DayOfTheWeek.Saturday:
            Console.WriteLine("Do stuff for Saturday...");
            break;
    }
}

It always start off simple like that. Next thing you know, there’s another “simple change” that comes in, and now the code looks somewhat like this:

public void DoStuff(DayOfTheWeek dayOfTheWeek, TimeOfTheDay timeOfTheDay)
{
    switch (dayOfTheWeek)
    {
        case DayOfTheWeek.Sunday:
            Console.WriteLine("Do stuff for Sunday...");
            if (timeOfTheDay == TimeOfTheDay.Evening)
            {
                Console.WriteLine("Go to bed early!");
            }
            break;
		...
        case DayOfTheWeek.Saturday:
            if (timeOfTheDay == TimeOfTheDay.Morning)
            {
                Console.WriteLine("You may stay a little longer in bed...");
            }
            else
            {
                Console.WriteLine("Do stuff for Saturday...");
            }
            break;
    }
}

Then comes an if-else, a for-loop, a switch-block (yes, inside the other switch, of course), and that one method becomes a terrible mess.

Well, whenever I see a case like that, I consider changing the switch-block into a dictionary of actions. I populate a dictionary with the individual blocks of code I need executed, and then I get the delegate out of the dictionary and invoke it whenever needed. The updated code would look like this:

readonly Dictionary<DayOfTheWeek, Action<TimeOfTheDay>> _dailyActions =
new Dictionary<DayOfTheWeek, Action<TimeOfTheDay>>();

public FamousSwitch()
{
_dailyActions.Add(DayOfTheWeek.Sunday, DoSunday());
_dailyActions.Add(DayOfTheWeek.Monday, DoMonday());
_dailyActions.Add(DayOfTheWeek.Tuesday, DoTuesday());
_dailyActions.Add(DayOfTheWeek.Wednesday, DoWednesday());
_dailyActions.Add(DayOfTheWeek.Thursday, DoThursday());
_dailyActions.Add(DayOfTheWeek.Friday, DoFriday());
_dailyActions.Add(DayOfTheWeek.Saturday, DoSaturday());
}

Action<TimeOfTheDay> DoSaturday()
{
return timeOfTheDay =>
{
if (timeOfTheDay == TimeOfTheDay.Morning)
{
Console.WriteLine("You may stay a little longer in bed...");
}
else
{
Console.WriteLine("Do stuff for Saturday...");
}
};
}

Action<TimeOfTheDay> DoFriday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Friday...");
}

Action<TimeOfTheDay> DoThursday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Thursday...");
}

Action<TimeOfTheDay> DoWednesday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Wednesday...");
}

Action<TimeOfTheDay> DoTuesday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Tuesday...");
}

Action<TimeOfTheDay> DoMonday()
{
return timeOfTheDay => Console.WriteLine("Do stuff for Monday...");
}

Action<TimeOfTheDay> DoSunday()
{
return timeOfTheDay =>
{
Console.WriteLine("Do stuff for Sunday...");
if (timeOfTheDay == TimeOfTheDay.Evening)
{
Console.WriteLine("Go to bed early!");
}
};
}

public void DoStuff(DayOfTheWeek dayOfTheWeek)
{
_dailyActions[dayOfTheWeek].Invoke(TimeOfTheDay.Morning);
}

I like keeping the smaller individual methods for each operation. Most often than not, I’ll end up moving those separate methods into one separate class, and very often, will turn that one separate class into several separate classes.

Anyway…

  • I like using a dictionary of delegates instead of using switch-blocks;
  • I like having small methods a lot better than having one long method

Leave a comment

Organizing and going on with my day

My last post covered how I’ve been Organizing my Daily, Weekly, Monthly, Quarterly, Yearly activities. In this post I’ll go over how I organize and track my day.

I keep a note titled Daily Execution in Evernote. Every morning, I review my Daily, Weekly, Monthly, Quarterly, Yearly note to check what’s in the calendar for the day ahead of me. I look for things that have to happen at a set time (such as a meeting) as well as things that have to happen on this day, but not at a specific time.

This is a template of what my Daily Execution note looks like:

I try not to pollute this note with too much information. If I have a meeting, I create a note for that meeting, put all the details I need in there, and then just add a link to it on my Daily Execution note. If the meeting is a place I have to drive to, I’ll add the address to the note, so I can easily tap on it on my phone and pull up directions. If it’s a phone call, I put the phone number on the note, so I can simply tap on it on my phone.

This note is my single source of truth for my day. It needs to give me a clear idea as to what I need to do on this day, and it needs links to other notes with further information about those things.

I check this note several times all day long.

 

Many times I’m checking it on my phone, so I try to make it easy to look up information I need.

As the days go by, I jot down quick notes on things I just did. I use vJournal on my Mac or iPhone for that:

vJournal keeps a note in Evernote with timestamps for everything logged that day:

The iOS version of vJournal also adds location information to the note. I like that because sometimes I’m driving by some place and I see something I want to check out later (for instance, a stakepark I didn’t know of). Logging that info to vJournal allows me to easily find out when I saw the place and where it was so I can go back there later.

At the end of the day, I review my Daily Execution note, as well as the note created by vJournal. I verify what I had to do that got done and what didn’t get done, and create new tasks, calendar entries, etc, accordingly.

Once I’m done reviewing that information, a copy all of the content in my Daily Execution note, paste it at the bottom of my note created by vJournal, tag it with “daily log”, rename the note to follow the format YYYY-MM-DD (which allows me to quickly find my log for a specific day), and move the note into a Archive notebook.

For the records, I started using the approach of having a single Daily Execution note about two years ago. The approach of keeping a daily log I’ve started all the way back in 2010 (as of today, I have 2349 notes tagged “daily log”)!!

As far as keeping a daily log like that, I can’t tell you how helpful it has been. I’m often going back to it to help recompose my memory on things I’ve done, people I’ve met, places I’ve been, ideas I’ve had, etc.

I’ve been changing how I do these things slightly over the years, trying new things out, but the basic idea has been sticking around and it works well for me.

, ,

Leave a comment

Organizing my Daily, Weekly, Monthly, Quarterly, Yearly

A few years ago I found this great YouTube video:
Evernote Tips: How to use Evernote to achieve your goals

I really like the approach presented there and thought I could adapt it to the way I was already organizing things. One part of the approach is to have a note titled “Daily, Weekly, Monthly, Quarterly, Yearly”. See below what that note looks like:

I have a shortcut to that note, as I’m constantly going back to it, often multiple times every day. Even though I have other calendars I need to use (Google Calendar, Outlook Calendar, etc), I consider my note in Evernote as my single source of truth: everything that’s really important for me has to be in that note, as it makes very easy for me to see the immediate stuff as well as things that are expected to happen in the future.

Let’s see how that note is organized.

Things that happen every week

In that section I want to see things that happen every week on a specific day. For instance, I need to fill out timesheet on Friday, and I’d like to post to this blog every Tuesday.

Current month

Here I want to see the most important things in the current month. I try not to put to much info in the calendar itself. Instead, I create a separate note for each entry containing all the info I need about it, and then I add a link to that note to the calendar.

Months in the current year

Here I want to see all months in the current year, and things that are expected in those months. Notice that I’ll only put here things for which I know the month, but do not know the actual date (either because it could be any day within that month, or because I don’t really have the actual day yet). When I do have the date, then I move it to another specific place (more on it later).

Things in specific periods

Here’s where I put things I may want to remember in specific periods. For instance, I like doing a monthly review in the first couple of days in the following month. Or, I like remembering that December is a short, unusual month because of the holidays, and I use that information when I’m about to do planning for that month.

Entire current year, day by day

As soon as I know exactly the date for something expected to happen, I put it in this section. It makes very easy for me to see at a glance everything going on the entire year. When I’m planning for a month that’s about to start, I look here to see how the calendar needs to be populated. I also put here birthdays that I absolutely cannot forget.

Five years in the future

This is where I keep things expected for the next five years in the future. If I know the exact date, I’ll add that information, too. It can also be something like “passport expires on Month/Day. Look into getting new one 6 months earlier.”. If I don’t have a date, I’ll at least add a note so I’ll always have a reminder of something important that needs attention.

Beyond

If there’s something I know should happen beyond five years in the future (for instance, an important document that’ll expire and need renewing), then I list it under a Beyond section at the bottom of that note, including the year and note.

Review it often

As I mentioned earlier, I review this note at least once a day. Since I put everything really important in this note and review it often, I get peace of mind knowing I won’t forget these things.

, ,

Leave a comment

2016: Annual Review

As I did last year, here goes my 2016 Annual Review!

1. What went well in 2016?

Meditation: I’ve blogged about this last year. In summary, mindful meditation has been working well for me. It has helped me a lot through situations where I’d handle badly in the past.

Professional blog: I wanted to make this blog you’re reading more active (write more posts), and I’ve succeeded on it. In 2015 I had only posted twice, whereas in 2016 I posted 23 times.

Personal project related to my experiences living in the US: This was one of the things that didn’t go well in 2015. It almost slipped through the cracks again in 2016, but I finally got the ball rolling, and the Brazuca nos Uessei channel on YouTube was finally born! The first video came out late last year, but I’ve been posting new videos frequently ever since. I already have many videos recorded and am working on editing them.

Stop thinking about it and just do it: on my last year’s review I said I was working toward “less ideas, more action”. It’s very fulfilling following that approach and seeing a new project going from idea to production within 4 months. Even more so when the clients are still so happy almost a year later.

Back to doing presentations: I had been missing going out to speak at conferences, meeting old buddies, networking. It was great speaking again at Houston Tech Fest 2016. Even though I felt rusty and off-paced, I needed the action to get the ball rolling in this area.

Joining Improving: This was something that was bound to happen, and for me it was one of the highlights of last year.

Best for last… Relocating to the USA!: my yearly review last year mentioned a “Personal/Professional secret project” that didn’t go so well. This was it; my relocation back to the US. As I mentioned back then, I had done everything I could do, but the holdup wasn’t on my end. I’ve even set a Plan B in motion, and shortly after I did that, Plan A actually came through. Long story short, I’m permanently back to the USA.

2. What didn’t go so well?

Project I had to drop: early last year I was working on a side project that I though had potential (I still do). However, a good friend who was working with me on it faced personal problems and couldn’t continue, while I had so much going on with my relocation to the US that I just had to put that one project aside. I’m fine with it, though, because I did learn things while I worked on it, and maybe one day I can go back to it.

3. What am I working toward?

Playing catch up professionaly: in the last 5 years or so I’ve been focused on delivering the projects I was working on, and didn’t spend much time on keeping up with what was going on out there, as far as technologies are concerned. That was great, don’t get me wrong; delivering working software AND seeing the businesses grow on top of it, for me, is WAY more fulfilling then staying up to date with bleeding-edge technologies that may just die within a version or two. That said, I do want to spend more time this year revisiting some things I should know more, while learning new things that have been proven solid options.

Serious Hobbies: I have a couple of hobbies that I take seriously, and I’m making sure I put time and effort into them this year.

Continous Improvement: I am making an effort to improve both both as a person as well as a professional on a daily basis. Some days are harder than the others, but I’m surrounding myself with an environment that keeps me on track.

Conclusion

The year of 2016 was great. Obviously, there were ups and downs. However, for years I’ve been keeping a lot of things I’m grateful for, and my 2016 list looks great and inspires me to an even better year.

Leave a comment