Do you need the services of a computer engineer/consultant?

This post is to offer consulting services in the area of computer engineering with a tendency toward software development. Whatever fits the bill is also of my interest.

During the rest of 2010 and the start of 2011 I plan to work as a freelance developer.

Next year I want to get back to studying with a Master's degree. Though probably not an online masters.

What I want to do in the meantime...
I'm willing to work from home in a home office arrangement. Something that won't take up all my day. I prefer to have control over my work and time. So, I'm offering consulting services for whatever need you may have regarding your presence on the internet.

I can help you leverage your business putting you online. I can build your website and configure Google Analytics and AdSense if you're also interested in these services.

I can assist you with problem solving and technical issues.

Although I'm a native Brazilian, technology standards and English are my super power when it comes to software development.

If you think that outsourcing your development is rewarding, don't think twice. You'll get a great result with the work I do.

My specialties
ASP.NET MVC/P
C++, C#, Java, Objective-C, JavaScript
CSS, jQuery
LINQ, Entity Framework (EF), N/Hibernate, NoSQL
WCF, WebServices
Oracle, SQL Server, MySQL
Visual Studio, Eclipse, PL/SQL Developer
IIS, Tomcat
iPhone

I'm a rapid learner. This way if you need something done using any other technology, drop me a line and I'll consider it.

Note
I already have the tools necessary to implement any solution based on the above technologies.
Feel free to contact me using the link at the top of this page for further discussion.

My references
This blog
CV/Resume
StackOverflow profile
LinkedIn profile

Sincerely,
Leniel Macaferi
johnleniel

Automate tasks in Mac OS with Automator

This one is about an incredible application that comes with Mac OS X. Its name is Automator.

Jesus Christ, this is a life saver app!

This is the description of Automator:Automator Apple Mac OS application icon

With Automator, you can accomplish time-consuming, repetitive manual tasks quickly, efficiently, and effortlessly. Automator lets you skip the complex programming and scripting that is normally required to create automations. Instead, you assemble individual steps into a complete task by dragging these actions into an Automator workflow. Automator comes with a library of hundreds of actions. And with the Watch Me Do action, you can record an action — such as pressing a button or controlling an application without built-in Automator support — and replay it as an action in a workflow.

I have lots of MP3 files that I need to go through analyzing if I really want to keep them in my media library. During the last year I stored all those MP3 in a folder and such a folder is now 55.56 GB and contains 11840 files to be precise. That’s a lot of MP3! I keep postponing this open/listen to task but today I thought I’d start. That’s where Automator fits the job.

In this post I’ll show you how to create a simple workflow that helps moving the MP3 files to iTunes folder /Users/leniel/Music/iTunes/iTunes Media/Automatically Add to iTunes. The folder Automatically Add to iTunes is a special folder that iTunes keeps watching for new files added to it. When a file is added in this folder, iTunes automatically adds it to the media library using MP3 metadata to organize the library. When added files will reside in /Users/leniel/Music/iTunes/iTunes Media/Music.

Let’s create the workflow:

1 - Go to the Applications folder and select Automator.

2 - You’ll be presented with the following screen to choose a template for your workflow. Select Service as the template.

Types of templates available to create an Automator workflow
Figure 1 - Types of templates available to create an Automator workflow

3 - In Service receives selected, select audio files. “In” select Finder.

4 - Now select Files & Folders in Library list and then select Move Finder Items under the Actions list. Drag this action to the workflow area in the right.

5 - In Move Finder Items select the folder where you want the files to be moved to. You also have the option of showing the action when the workflow runs.

6 - Go to the File menu and select Save. Give it an appropriate name as Add to iTunes and you’re done.

The following screenshot shows the Service workflow configured:

Add to iTunes.workflow configured according to the six steps described above 
Figure 2 - Add to iTunes.workflow configured according to the six steps described above

Now, let’s use this service workflow. To do this, go to Finder and open any folder that contains audio files such as MP3. Right click the MP3 file and voila. Now there’s an extra context menu option called Add to iTunes. What a marvelous thing.

Add to iTunes context menu option in Finder when right clicking MP3 file(s)
Figure 3 - Add to iTunes context menu option in Finder when right clicking MP3 file(s)

What happens when Add to iTunes is clicked? The workflow we created will be executed and the selected file(s) will be moved to the folder specified in the workflow, in this case /Users/leniel/Music/iTunes/iTunes Media/Automatically Add to iTunes.

As you see this is totally life saver.

I can play the MP3 in iTunes and if I decide that I want to keep it in my media library I just have to select Add to iTunes.

The possibilities with Automator are endless given the amount of options in its Library and Actions lists and workflow template types.

I hope you could get an idea of what Automator can do.

Updated on 12/16/2010

If you make a slight change in step 3 above you can have this workflow add not only audio files but even entire folders to iTunes and better yet, iTunes will ask if you want to replace existing files so that you don’t end up with duplicate files in your iTunes library. This is great.

So what do you have to do? Instead of audio files, select files or folders. Just this. Save the workflow. Now right click over any folder in Finder and you’ll see that you get a new menu option under Services called Add to iTunes.

Add to iTunes context menu option in Finder when right clicking a folderFigure 4 - Add to iTunes context menu option in Finder when right clicking a folder

Notes
Service workflows are saved in /Users/YourUserName/Library/Services.

In prior versions of Mac OS, there was an option to save the workflow as a plug-in. This was necessary so that you could have a context menu option (right-click) in Finder to run the workflow. I tried to go this way but this option isn’t available in Mac OS X 10.6.4. I realized that I had to create a Service workflow when I read this question at Apple’s Support site: No Automator plug-in in 10.6?

Download
You can download this workflow at:
https://sites.google.com/site/leniel/blog/AddtoiTunes.workflow.zip

References
Automator - Your Personal Automation Assistant

Automator - Learn by example

Automator at Apple’s Mac OS – All Applications and Utilities

Automator article at Wikipedia

Learning to develop for iPhone with a Mac mini

I think you should read this one too:
Productivity and happiness going from 4 to 8 GB RAM

My 2010 Unibody Mac mini arrived on Sep 9. Now it's time to get to coding for the iPhone. That's why I bought it after all. Go code guy instead of being here writing this somewhat long post. :) Go figure. Oh wait, I need to share my experience with the rest of the world so that I can contribute to people that like to do what I do, that is, software development. So, let's share and learn together.

In this post I’ll write about hardware, software, virtual machines and iPhone development. All this takes into consideration my Windows background and my need of having Windows around while I’m using the Mac.

New hardware
I needed new hardware to learn how to develop for the iPhone platform. My Windows PC is an "old" Intel DualCore Pentium E2180 2 GHz and so I couldn't get MAC operating system also known as Mac OS X running on this hardware because the processor lacks Intel VT-x (hardware virtualization) feature. VT-x is necessary if you plan to run Mac OS in your Windows PC hardware through a virtual machine. I needed Mac OS X because currently iPhone development can only be done the proper way (read with Apple official development tools) within the Mac operating system.

I didn't want to spend a lot of money buying a new computer. So I opted for the bare minimum necessary to develop for iPhone.

While buying the mini that comes with a “somewhat” powerful Core 2 Duo P8600 2.4 GHz processor I also bought the Magic mouse and the Wireless keyboard. Mini doesn't come with a mouse or keyboard. I customized Mini with 4 GB RAM¹. Memory customization made the shipping take 2 weeks more. I bought Mini at the Brazilian Apple online store. Because I customized Mini it shipped from China and that's a long way to Brazil. If I had opted for the standard 2 GB RAM version I'd get the Mini the week I placed the order since there's stock right here in Brazil.

All this wait was to get a new development box that could make me capable of developing for iPhone and that's cheap for my pocket.

¹ - It's OK to work with 4 GB of RAM, but if you can afford 8 GB of RAM, go for that. Don't think twice. NVidia graphics card that comes with Mini also gets 256 MB of RAM. Virtual machines also like RAM. Continue reading to know why I'm mentioning this.

Mac OS Activity Monitor showing the System Memory
Figure 1 - Mac OS Activity Monitor showing the System Memory

To better understand what those Wired, Inactive memory are, read this doc:
Mac OS X: Reading system memory usage in Activity Monitor

The quality of Apple products is undeniable! I also own an iPhone and it makes me second that.

Things I really appreciate about the Mac mini set (unordered):
- Being wireless with Apples’s magic mouse and wireless keyboard. I think they're a must have with Mini.
- No noise approach when it comes to working with computers. Mini makes no noise. The only sound you'll ever listen is the hard disk and you'll only listen to it when there's no other environment sound, for example, during the night. If you opt for a SSD drive you won't get any noise at all. SSD is still expensive so that was not an option for me.
- HDMI port that allows me to connect it to my 32'' Sony Bravia HD TV for crystal bright images.
- Sound output quality (it's better than my dedicated Creative Audigy sound card on the PC)
- Small size. See the photo bellow where Mini’s size is compared with my Playstation 3 joystick (photo taken with iPhone 3GS):

Mac mini's size compared with a Playstation 3 joystick  
Figure 2 - Mac mini’s size compared with a Playstation 3 joystick

Mac + Windows
As a user of the PC movement for the past 15 years (I started with Windows 3.1 in 1995) I got it going really fast with Mac. The transition is being straightforward.

I could for sure only use Mac OS but that wouldn't give me the power I need. As I still work with Windows only applications as is the case of Microsoft Visual Studio and Windows Live Writer (that I use to write these posts) I need a way of having Windows around. For that I got Parallels Desktop. This software enabled me to have a Windows 7 virtual machine running alongside Mac OS with a beautiful integration between the two operating systems.

Virtual machine
Remember the amount of RAM memory I mentioned and showed above? It plays a big part when you’re using virtual machines because the system RAM is shared with virtual machines. So if you plan to run virtual machines in your Mac computer, you’d better get more RAM. This will give you better performance (read responsive applications) while you work avoiding the infamous Page outs.

Using a virtual machine there’s no need to reboot the machine to go to other operating system – this is cumbersome (if using Boot Camp and installing Windows in other partition I would have to do that). Actually I first installed Windows 7 using Boot Camp but then I realized that Parallels could move that Windows 7 Boot Camp partition over to a virtual machine. So I decided to go this way and used my Boot Camp partition as a virtual machine.

After going to Boot Camp solution and then using a Boot Camp partition as virtual machine I saw that Parallels Desktop also allows us to move an existing Windows PC entirely to a Mac based computer. This means that all the software, configurations and files you have on your Windows PC disk partition can be migrated to a virtual machine. I tried this but it just didn't work for me. The migration that is done using Parallels Transporter Agent failed twice in a process that takes at least 5 hours to complete. In my case it tried to migrate 197 GB of data over my wired home network. The error message I got was that the Transporter migration failed/The migration could not be completed (no me info). I tried to run this resolution but that didn’t do the trick (no problems were found on my Windows PC). If it had worked for me I wouldn’t need to install anything as everything that I had on the Windows PC would be just copied over to the virtual machine. That’d freed me of having to install everything again on the virtual machine.

No problem at all as I created a brand new virtual machine with a clean install of Windows 7.

You see, all this work allowed me to learn a lot of things along the way… Things that I wouldn’t have tried.

Tip: I found that using a new virtual machine with a clean install of Windows instead of a Boot Camp partition as a virtual machine is really better. Windows runs faster this way.

Now, the only thing I have to do is to start the virtual machine and there I'm using Windows 7 just inside Mac OS as if I were using the PC. So far so good. This satisfies my needs as a multiplatform developer.

You can put your Mac mini to sleep and you'll never have to start the virtual machine again because while sleeping Mini keeps the memory in "On" state, which means that all applications that you have open will be kept in the same state they were before you put Mini to sleep. Isn't it good? It's a kind of Hibernate we have in Windows but it's not Hibernate at all. While Mini is sleeping you get a beautiful white glowing blinking light that shows you that it's sleeping of course.

Mac software
Applications look more polished in Mac OS. Better native windows design, beautiful icons, etc. Some things are simpler in Mac OS. Take for example the application installation process. In most cases you just copy the application file to your Application folder in the dock and you’re ready to use it.

Some Windows software I use and that I can't live without are available for Mac too:
- µTorrent
- Firefox
- Microsoft Office
- Babylon
- Eclipse
- SnagIt

Mac only software that I'm using:
- TextMate
- BBEdit
- QuickSilver
- UnRarX
- Pixelmator

I'm using keyboard shortcuts a lot more with Mac.

iPhone development
Before I could feel comfortable to start learning how to develop for iPhone I had to configure my work environment first and that’s why I had to go over things such as virtual machines, etc. Now that it’s done it’s time to engage!

For those that are starting in this new world just like me, here goes what you need to get going and coding:

1st - get the official iPhone SDK that stands for software development kit. You’ll have to create an account with Apple to be able to download it and use all the features that Apple iOS Dev Center has to offer. The SDK is a big download - for the current version (Xcode 3.2.4 and iOS SDK 4.1) its size is: 2.9 GB.

Xcode is the name of the the IDE used to develop applications for iPhone. iOS is the name of the operating system that iPhone uses.

2nd - learn how to develop in this platform and that’s totally a personal path you have to follow. After learning the basics you can follow the more diverse paths depending on what types of application you want to develop.

As for learning iPhone development I'm understanding how things work with some easiness. It's always good to learn new programming languages as Objective-C, a new development environment as Xcode, etc. The easiness I'm finding here is a result of some years of coding and my familiarity with the Model View Controller pattern that is extensively used in iPhone applications.

The main learning source has been the iOS Reference Library.

Tutorials I have followed ²:

Your first iOS Application
Core Data Tutorial for iOS: Introduction
Introduction to The Objective-C Programming Language

² - I'll try to update this list while I make progress.

Updated on 8-26-2011

As I explain in a recent post titled Xcode iPhone beginner projects with GitHub integration, I decided to follow a new path to learn iPhone development. I’m learning with sample projects taken from a book and I’m committing those projects to a GitHub repository. Feel free to clone the repo: https://github.com/leniel/iPhone-Beginner-Guide

Final note
This is a new world that opens up just in front of me. In the coming weeks and months I'll be immersed in this new world.

I won't let my Windows developer part behind because I'm always answering some questions at StackOverflow and every now and then I need to write some apps to test some code.

I really love programming. Any programming language that you learn opens a new door of possibilities. This is what motivates me and moves me forward. I'm thirsty for knowledge.

Let's see what the future reserves for me in this new endeavor.

If you're also planning to develop for iPhone in the near future (because things change really fast in the technology world) this post shows you a possible start point.

Hope you've found this an interesting read and that you can learn something from my own experience.

Counting Value Frequency with LINQ (code snippet)

This post is a code snippet: a short code example to demonstrate a topic.

From now on I’ll write in this blog useful code snippets that I come to write.

A question on StackOverflow motivated me to write a simple C# console application that demonstrates a way of counting how often a value appears within a given set. I used LINQ to accomplish this.

I’ve commented the code in green so that it’s easier to understand what’s going on.

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        // Creating a list of Values that serves as the data source for LINQ query.
        List<int> values = new List<int>()
        {
            0, 1, 2, 3, 6, 2, 3, 1, 0, 4, 5, 7, 8, 9, 3, 7, 5
        };

        // For each Value in the data source, let's group by Value into g. g stores all Values grouped.
        // Using the select new constructor we create an Anonymous Type that has each distinct Value and its Count (how often it appears).
        var query = from v in values
                    group v by v into g
                    select new { Value = g.Key, Count = g.Count() };

        // A simple foreach that prints in the screen each Value and its frequency.
        foreach (var v in query)
        {
            Console.WriteLine("Value = {0}, Count = {1}", v.Value, v.Count);
        }
    }
}

This is the output:

Value = 0, Count = 2
Value = 1, Count = 2
Value = 2, Count = 2
Value = 3, Count = 3
Value = 6, Count = 1
Value = 4, Count = 1
Value = 5, Count = 2
Value = 7, Count = 2
Value = 8, Count = 1
Value = 9, Count = 1

Hope you enjoy and make good use of this code.

Feel free to comment and add any other way of doing this in a more efficient or elegant fashion.

Automate the download of a list of URLs/links

I just wanted to automate the process of downloading a list of URLs/links. I thought about asking a question at SuperUser. So I did that and got a few answers. One of those answers pointed to the piece of software that does exactly what I wanted. The software is a Firefox add-on that I had used a long time ago but couldn’t think about it for this task. Its name is DownThemAll!. Yes with an exclamation mark at the end. I think this has to do with a relief felling you feel when you’re using it.

In this post I’ll walk you through the steps necessary to get your downloads going in a really fast way (fasten your seat belt). No more downloading and saving file by file. Phew!

I’m going to use the same list of URLs I posted on my question at SuperUser.

Suppose you have a list of URLs as this one:

http://creamteam.tv/wp-content/uploads/2010/06/10-Chinatown.mp3
http://mp3muffin.com/train/burbs.mp3
http://www.knoxroad.com/wp-content/music/May/01%20World%20Sick.mp3
http://indierockcafe.com/mp3s/2010/may/5-18/bandofhorses_factory1.mp3
http://www.strangefamousrecords.com/sfr-audio/_common/sagefrancis_slowman.mp3
http://dangerbirdrecords.com/public/theoneamradio/crediblethreats.mp3
http://www.beggarsgroupusa.com/mp3/HolyFuck_LatinAmerica.mp3
http://dl.dropbox.com/u/4746099/05%20Choices%201.mp3
http://subpop-public.s3.amazonaws.com/assets/audio/6801.mp3
http://gvsbchris.com/01%20Sleep%20Paralysist.mp3
http://bantermm.com/tracks/Annuals-Loxtep.mp3
http://downloads.pitchforkmedia.com/The%20National%20-%20Bloodbuzz%20Ohio.mp3
http://stereogum.com/mp3/the%20morning%20benders%20-%20Excuses.mp3

Save this list in a text file [ .txt ] extension and name it MP3s.txt.

Now let’s get DownThemAll! and do the real thing…

1 - Install DownThemAll! add-on for Firefox. After installing restart Firefox.

2 - Go to Firefox menu and select Tools - DownThemAll! Tools - Manager... Right-click inside DownThemAll! screen.

3 - Select context menu Misc - Import from file.

4 - On Import downloads dialog window make sure you select Text Files in the dropdown list.

5 - Point to the text file MP3s.txt that contains the URLs. Click Open button.

6 - On Make your selection dialog window, DownThemAll! will load each link it finds in the text file allowing you to select which ones you want to download and the folder where you want the files to be saved as well.

7 - Make your selections, click Start button.

Here's a screenshot of it just doing the "Downloading" part:

DownThemAll! downloading the list of URLs from my question at SuperUser
Figure 1 - DownThemAll! downloading the list of URLs from my question at SuperUser

Oh… and this is the feature request on DownThemAll! trac opened 3 years ago.

Nice to see this implemented and working so well.

Congrats to DownThemAll! developers and users. Fantastic add-on.

StackOverflow: best place to share/learn programming

I’ve been spending some time of my days helping others at StackOverflow. StackOverflow (SO) is the best place to ask questions related to software programming. There you can be sure that someone somewhere will help you to find an answer to your question.

Note: I just got out of my job at Chemtech. Now I have more time to focus in other things and to think a little bit more about what I want to do next.

As a consequence I decided that I’ll try to give back and share a portion of the knowledge I acquired in these 7 years of programming experience. By means of helping others at StackOverflow I just improve what I think I already know. This is a bit controversial you may say, but I don’t think so. I’m constantly learning/unlearning and discovering new things at SO. I keep trying to sharpen my programming skills. This just happens somewhat in a recursive way. One finding leads to other that then brings you back to the main topic that then expands and so forth.

Give, and it will be given to you. Good measure, pressed down, shaken together, running over, will be put into your lap. For with the measure you use it will be measured back to you.
Luke 6:38

I’m kind of a generalist (I’m after the generalist badge), that is, I don’t tie myself to any technology. I’ll try to use the one that fits better in a given task/job be it close-source or open-source. If a technology allows me to get the thing done that’s the one I’ll choose. This is reflected in the variety of tags at my StackOverflow profile:


Of course there are well established technologies that are easier to work with as is the case of C# programming language, ASP.NET, Java, etc. Again this can be seen both on my tags and in the quantity of questions tagged with such technologies. Being easier to work with means having a greater user base throughout the world and this is reflected at StackOverflow tags as well.

The title of this post is what motivated me to write and I hope will motivate others too so that they give back a portion of what they know.

The point is this: whoever sows sparingly will also reap sparingly, and whoever sows bountifully will also reap bountifully. Each one must give as he has decided in his heart, not reluctantly or under compulsion, for God loves a cheerful giver. And God is able to make all grace abound to you, so that having all sufficiency in all things at all times, you may abound in every good work.
2 Corinthians 9:6-8

I then invite you: if you’d like to get free answers to your coding questions or if you want to write better code or if you want to start at SO and be happy or whatever related to coding problems, I suggest you to read the FAQ and create an account at SO.

You see, we should help each other. There are times that we get stuck at some coding problems for hours and we don’t know what to do to get over them. With millions of programming peers having the most varied backgrounds willing to help and sharing what they know is what makes a developer’s life valuable and exciting. At StackOverflow you find what summarizes this last phrase. In just a minute you can get an answer that’ll allow you to continue your work. If you compare minutes to hours it’s clear why StackOverflow is so fantastic.

The sum of our good programming efforts builds a better software product. LOL <(^^,)> 
By Leniel Macaferi

As of the time of this writing, for stats purposes, I have 4257 reputation,18 badges, 2 questions asked and 288 questions answered at SO. A pretty good amount of answers as a start for someone who’s also after the fanatic badge. I can assure you I’m more than half way there already. Badges are not the point of this post but they make the whole thing a little bit more motivating. Badges at SO are recognitions that come with time just as in real life. The more you share the more recognition you earn.

I take my hat off to the people that started such great site. I hope that it grows even more in the years to come with more and more users trying to learn this admirable profession of software developer that in my humble opinion is the best one. I’m biased towards it after all.

At SO we just happen to have pretty good discussions about anything related to programming including What’s your favorite “programmer” cartoon? and Is a master’s degree overkill? ranging to the more diverse topics. In one of those really interesting discussions I found this brilliant saying that I think holds true in this world:

When you finish your bachelor's, you think you know everything; When you finish your master's, you realize you know nothing; When you finish your doctorate, you realize nobody knows anything, including whether or not you needed to finish a doctorate to realize that.
By Unknown

Although I haven’t taken a master’s or doctorate course yet I can write about the bachelor’s part. When I finished the bachelor’s I already knew that I didn’t know nothing. I think that when I finish the master’s I’ll realize nobody knows anything. One less step to realize that. What will happen then if I take a doctorate course? Simply put: (no one knows nothing ) ^ Googol I think. :)

Final Note: I also put in practice this same share and learn principle at ProZ.com.

Further references
I suggest you check these two posts by Jon Skeet:

Writing the perfect question
Answering technical questions helpfully

Manipulating Properties and Methods with Reflection

Today I’m going to write about a simple yet powerful way to manipulate properties and methods of a given type. We’ll set values to properties and invoke methods through the use of reflection.

Maybe you haven’t had the chance to use reflection or maybe you even don’t know what is reflection.

Reflection is one of the most powerful features a programming language has as is the case of C# programming language that I’ll be using in this post.

In just one phrase extracted from Wikipedia we can define what is reflection:

Reflection is the process by which a computer program can observe and modify its own structure and behavior. The programming paradigm driven by reflection is called reflective programming.

Our objective is to manipulate the property value and methods of a type by means of reflection, that is, we’ll have access to these properties and methods by looking at the type’s metadata.

Let’s exemplify with a specific case that I came into while I was working on my first project at Chemtech: we had our ASP.NET solution divided into specific projects in what we call the MVP pattern. I suggest that you to read the post Model View Presenter pattern with Castle in ASP.NET to get a grasp of it.

In a given task I had 15 static textboxes inside an .aspx page (View) and I needed to set their values inside the Presenter. What is the best way to do it? Should you hardcode each and every textbox setting their values? It’s not an elegant solution. So how to get over it? Using reflection to get the type’s metadata. Let’s see how it is easy.

Let’s get to the code:

private void BindProperty(string viewPropertyName, object propertyValue)
{
    // Getting the property I want to use.
    PropertyInfo propertyInfo = typeof(IMyView).GetProperty(viewPropertyName);

    // Verifying if the property was acquired with success.
    if (propertyInfo != null && propertyInfo.CanWrite)
    {
        // Set the property value.
        propertyInfo.SetValue(view, propertyValue, null);
    }
}

Reflection allows us to make a generic piece of code, that is, with only one method we can set the value of all the textboxes.

The above method receives the property name as a parameter and we also pass to the method the value we want to assign to the property.

This same approach can be used with methods. Let’s see an example:

private void BindMethod(string viewMethodName, object[] methodParameters)
{
    // Getting the method I want to use.
    MethodInfo methodInfo = typeof(IMyView).GetMethod(viewMethodName);

    if (methodInfo !=null)
    {
// Call/Invoke the method with the desired parameters. methodInfo.Invoke(view, methodParameters); } }

Again we have a generic piece of code that can be used to call whatever method we want passing whatever parameters we want.

To use PropertyInfo and MethodInfo we declare the namespace System.Reflection.

We could make these methods even more generic by passing the view object (type) we want as a parameter. Bellow I show a class named ReflectionUtil with such modifications:

/// <summary>
/// Utility class for Reflection operations.
/// </summary>
public class ReflectionUtil
{
    /// <summary>
    /// Sets a value to a property through the use of Reflection.
    /// </summary>
    /// <param name="obj">Object that owns the property</param>
    /// <param name="propertyName">Property name</param>
    /// <param name="propertyValue">Value to be set</param>
    public static void BindProperty(object obj, string propertyName, object propertyValue)
    {
        // Getting the property I want to use.
        PropertyInfo propertyInfo = obj.GetType().GetProperty(propertyName);

        // Verifying if the property was acquired with success.
        if (propertyInfo != null && propertyInfo.CanWrite)
        {
            // Set the property value.
            propertyInfo.SetValue(obj, propertyValue, null);
        }
    }

    /// <summary>
    /// Calls a method through the use of Reflection.
    /// </summary>
    /// <param name="obj">Object that owns the method</param>
    /// <param name="methodName">Method name</param>
    /// <param name="methodParameters">Method parameters</param>
    public static void BindMethod(object obj, string methodName, object[] methodParameters)
    {
        // Getting the method I want to use.
        MethodInfo methodInfo = obj.GetType().GetMethod(methodName);

        if (methodInfo != null)
        {
// Call/Invoke the method with the desired parameters. methodInfo.Invoke(obj, methodParameters); } } }

OK. Now that we have the methods defined, let’s use them.

I’ll use the application I’ve shown in Model View Presenter pattern with Castle in ASP.NET as the base for this post.

IMyView interface declares the following members:

public interface IMyView : IBaseView
{
    event EventHandler FirstLoading;

    void MyMethod();

    string TextBox1Text { set; }
    string TextBox2Text { set; }
    string TextBox3Text { set; }
    string TextBox4Text { set; }
    string TextBox5Text { set; }
    string TextBox6Text { set; }
    string TextBox7Text { set; }
    string TextBox8Text { set; }
    string TextBox9Text { set; }
    string TextBox10Text { set; }

    void FillGridView1(List<object> values);
    void FillGridView2(List<object> values);
}

MyView implements what’s in IMyView interface:

public partial class MyView : Page, IMyView
{
    private MyPresenter presenter;

    .
.
.
#region Implementation of IMyView public event EventHandler FirstLoading; public void MyMethod() { Response.Write("Reflection power"); } #region TextBoxes public string TextBox1Text { set { TextBox1.Text = value; } } public string TextBox2Text { set { TextBox2.Text = value; } }

.
.
. #endregion #region Methods public void FillGridView1(List<object> values) { GridView1.DataSource = values; GridView1.DataBind(); } public void FillGridView2(List<object> values) { GridView2.DataSource = values; GridView2.DataBind(); } #endregion #endregion }

Inside the Presenter MyPresenter I implement the logic with the following:

/// <summary>
/// Specific FirstLoading implemented by each inheritor
/// </summary>
protected override void FirstLoading()
{
    view.MyMethod();

    // Useful technique to avoid calling 10 lines of code.
    for (int i = 1; i <= 10; i++)
    {
        ReflectionUtil.BindProperty(view, string.Format("TextBox{0}Text", i), (i * i).ToString());
    }

    // Useful technique to avoid writing methods almost identical just to change a method call.
    for (int i = 1; i <= 2; i++)
    {
        // Do some common logic here...

        // Call a specific method with Reflection.
ReflectionUtil.BindMethod(view, string.Format("FillGridView{0}", i), new object[] { new List<object> { i * 2, i * 3, i * 4, i * 5 } }); // Do some common logic here... } }

When we run the web app, we get the following result:

Reflection result

I covered just a simple use case of reflection in this post but it’s useful in our day to day job.

The technique implemented in this post allows us to write clean and generic code. I have already used it in another project which allowed me to write as few lines of code as possible. Let’s say it decreased from 250 sloc to 25 sloc. A reduction of 10 times sloc.

Last note
I read the article Survival of the Fittest: Natural Selection with Windows Forms on MSDN Magazine when I was on the 9th period of the Computer Engineering course studying Artificial Intelligence. From this moment on I started to visualize the importance of reflection and how powerful it is. The referenced article discusses about Genetic Algorithms and the author’s sample code makes extensive use of reflection. Great read if you’re interested enough! Oh, I even translated this article to Portuguese at that time. I want to put it online so that others can benefit from it. :o)

Visual Studio 2010 C# ASP.NET Web Application
You can get the Microsoft Visual Studio Project at:

http://sites.google.com/site/leniel/blog/ReflectionWebApp.zip

To try out the code you can use the free Microsoft Visual Web Developer 2010 Express Edition that you can get at: http://www.microsoft.com/express/Web/