TaskList in Visual Studio - Making it better

It was great to come across a new feature in Visual Studio - The TaskList. Well, yes it isn't new but, it certainly was new to me. I had never really come across this wonderful feature until last week when secretGeek blogged that code would suck less if the compiler could raise an error when a // TODO token was detected. A comment from Goran indicated that it was completely possible with the current versions of Visual Studio.

A //TODO: token.

Are shown in VS if you click TaskList. Couldn’t live without this one :)

Yeah, sure. Can’t live without it. Although the compiler doesn’t throw you an error, it indicates all parts of code where such tokens appear and hence can be taken care of easily.

 

How To Use

You can use the TaskList comments for:

  • Features to be added
  • Problems to be corrected
  • Classes to implement
  • Place-markers for error handling code
  • Reminders to check in the file

Add your comment in the code preceded by the token.        

tasklist_1

Once done, open up the TaskList from the View menu.

tasklist_2

Once the TaskList is up you will see something like this.

tasklist_3

The TaskList also allows custom tokens to be included. Go to Tools –> Options –> Environment –> TaskList.

 tasklist_4

User Tasks

You can add your own tasks in the TaskList by selecting the ‘User Tasks’ selection from the dropdown list on the TaskList toolbox. These tasks aren’t associated with code, but will allow users to add their own high level tasks.

 

Extending the TaskList

I would like to see the following additional options in the TaskList:

  • Task Alarms – which would associate an alarm with a high priority comment to help just in case you forget to take care.
  • User Tasks to be more specific (by having a file anchor like ‘Comments’) to allow user tasks to be associated with a particular line in code.

And no, I’m not waiting on Microsoft to extend it in some other version of Visual Studio. I’m starting right away to write a package that would do this for me, hopefully.

 

More Things to Remember

With Visual Basic projects, the Task List displays all of the comments in the project. With Visual C# and Visual J# projects, the Task List displays only the comments that are found in the files currently opened for edit. With Visual C++ projects, the Task List displays only the comments that are found in the file currently active in the editor.

C# 3.0 for Beginners - Extension Methods - Part 2

Custom Extension Methods

C# 3.0 enables you with the ability to extend the functionality of existing types. This means that you can write your own extension methods that would give the programmer the feeling that those are just methods provided by the existing type.

For example, System.Int32 doesn't provide you an IsEven() method which would tell you if the integer is holding an even value. It would obviously be great if you could write a method which does this, just in case you use this functionality heavily in your code. You would then write a method like this

public bool IsEven(Int32 i)
{
 if(i%2 == 0)
 {
     return true;
 }
 else
 {
     return false;
 }
}

Well, that's perfectly fine. But, I wish we could make it more easier. And I bet we can for sure, that's what extension methods are here for. No, we cannot go and implement the IsEven() method for the Int32 type, but C# 3.0 allows you to extend type functionality in a different way.

Check out the following code. I'm extending the Int32 type to expose the Int32.IsEven() extension method.

public static class MyIntegerExtensionMethod
{
 public static bool IsEven(this Int32 i)
 {
     if (i % 2 == 0)
     {
         return true;
     }
     else
     {
         return false;
     }
 }
}

public class Program
{
 static void Main(string[] args)
 {
     Int32 n = 9;
     Console.WriteLine(n.IsEven());
 }
}

Let's look at the most important part, the method signature.

public static bool IsEven(this Int32 i)

A template for the above would be

<access_modifier> static <return_type> Method_Name(this <extended_type> <instance_of_type>, <args_list>)

While <access_modifer> and <return_type> are intuitive, special attention is needed at the parameters of the method. The first parameter resembles the type which is to be extended, preceded with the 'this' keyword. The arguments that follow are the actual arguments/parameters to the method.

Another thing to remember is that extension methods should be defined as static members in a static class. The only difference between a normal method and an extension method is that the first parameter of an extension is always prefixed with the 'this' keyword. The rest are normal parameters. Also, when using the extension method you should remember to keep the extension method within the scope of its usage or you could even include it using the 'using' directive.


Usage Restrictions

  • Extension methods can access only the public members of the type being extended.
  • If you define an extension method whose signature matches with the method already existing in the extended type, priority is given to the existing method and the new extension method is ignored.


Have fun with this great feature.

Why I will never have a girlfriend - My take

My take on Tristan Miller's paper titled Why I will never have a girlfriend.

You can find it here

What are your views on this?

C# 3.0 for Beginners - Extension Methods - Part 1

           All C# code is eventually executed by the .NET CLR. This requires the C# compiler to transform the LINQ query expressions to a format that is understandable by .NET. LINQ query expressions are transformed into method calls, which are called extension methods. These methods are slightly different from normal methods. Lets discuss them in more detail:

Consider the example that we saw in my previous posts.


    public static void GetIExplorer()
    {
        //  1. Data Source
        Process[] processes = Process.GetProcesses();
 
        //  2. Query Creation
        IEnumerable<int> query =
              from p in processes
            where p.ProcessName.ToLower().Equals("iexplore")
            select p.Id;
 
        //  3. Query execution
        foreach (int pid in query)
        {
            Console.WriteLine("Process Id : "+pid);
        }
    }


The query creation in part two transforms in a series of method calls on the data source 'processes' as follows.


    IEnumerable<int> query =
            processes.Where(p => p.ProcessName.ToLower().Equals("iexplore"))
                     .Select(p => p.Id);
 

The Select clause, however, it not essential. It may be ignored and you might retrieve a list of processes and not their process Ids. The Select clause here specifies the entity to be selected in detail, in the above example, it was the process id belonging to the selected process.

Now, you might wonder that since the Where() method was called on the 'processes' Array, the Array object might have implemented the Where() method. But, that's not quite the case here. The method Where() is called an extension method and is used for extending a type's functionality.

We have also made use of lambda expressions here. We will discuss their significance later in detail, but, for now, you can look at it as if it were a provision to select entities based in certain specified conditions. In the above code the variable 'p' indicates each element in the 'processes' array which is subjected to an expression evaluation (p.ProcessName.ToLower().Equals("iexplore")), and only if the result of the condition evaluation is true, will the item be selected as the result of the query. These are filtering expressions.

In my next post I will describe how to define and use your own extension methods.

Personalize your application executable

You've written programs and created executables, and also probably distributed them. But, it would feel strange to pass on your .EXE as just-another-exe. Windows provides a default executable icon to your generated output EXE file which looks something like this:



Well, there's nothing wrong in having such an icon for your executable file. But, the hard work who put in in implementing the functionality within the EXE certainly deserves some credit and possibly a custom designed icon.

Lets see how we can do this. It's fairly simple. Once you're done with the coding stuff and you're ready to build your exe for release, go to the Project Properties -> Application tab -> Resources Group. Here, you will find the Icon and manifest radio button, select it and select the icon you need to use for your adorable application.



Please note that the above screenshot is the Project Properties tab for VS 2008 and it would look slightly different from the one you would see in VS 2005.

You now build the application and have a look at the generated executable which would look something like:



I created this icon by adding a resource (.resx) file to my project and then adding an icon to that resource file. Scribbled a bit using an MS Paint kind of pencil and here we go, I have a brand new icon (looks familiar, something like an inverse of Red Cross, but I could only think of this one right now).

C# 3.0 for Beginners - Query Execution in LINQ

       The execution of queries written is different from what a new LINQ user would perceive it to be. The query isn’t evaluated and the result is not stored in the query variable until the foreach iteration (where the values are actually required) or a manual iteration using the underlying GetEnumerator and MoveNext methods. The query variable only stores the query commands. This is concept is referred to as deferred execution.


public static void GetIExplorer()
{
    //  1. Data Source
    Process[] processes = Process.GetProcesses();
 
    //  2. Query Creation
    IEnumerable<int> query =
       from p in processes
where p.ProcessName.ToLower().Equals("iexplore")
select p.Id;
 
    //  3. Query execution
    //  This is the part where the query is evaluated
    //  and result is stored in the query variable.
    foreach (int pid in query)
    {
        Console.WriteLine("Process Id : "+pid);
    }
}

 

As the query variable doesn’t store the results, you can execute it as many times as you like. If a data source is updated at regular intervals, you could retrieve the latest results every time you iterate over the query variable.

Deferred execution

The figure shown above shows information about the query variable ‘query’. The Results View section shows the results of query execution and it also informs the user that “Expanding the Results View will enumerate the IEnumerable” i.e. perform the query execution for debugging.


Forcing immediate execution of queries
    Immediate execution of queries is forced for queries that perform aggregation functions over the data retrieved from query evaluation. These functions include Count, Max, Min, Average etc. These queries execute without an explicit foreach statement because the query itself would use a foreach statement to calculate the result.

The following query returns the number of processes identified as “IExplore.exe”.

 

//  Calculate the number of "iexplore" processes
int numberOfProcesses = query.Count();


Execution results can be cached (if need be) for temporary processing using the ToList() and ToArray() methods as shown below:

 

//  Caching results using ToList() and ToArray() methods.
List<int> queryResult =
(from p in processes
 where p.ProcessName.ToLower().Equals("iexplore")
 select p.Id).ToList();
 
Array inferredQueryResult =
(from p in processes
 where p.ProcessName.ToLower().Equals("iexplore")
 select p.Id).ToArray();



C# 3.0 for Beginners - Learning LINQ - An Overview

I’m probably quite late to provide an overview on LINQ, which is by now a lot more popular than the time when I actually had started hearing about it.

 Well, this is expected to be a series of posts that would help other rookies like me who haven’t yet started learning LINQ yet. So, lets get started. To begin with I’m providing here an overview of LINQ (Language Integrated Query).

 LINQ was introduced by Microsoft with the objective to reduce the complexity of accessing and integrating information. With the LINQ project, Microsoft has added query facilities to the .Net Framework that apply to all sources of information, not just relational or XML data. Everyday programmers write code that accesses a data source using looping and/or conditional constructs etc. The same constructs can be written using query expressions that are far lesser in code size. LINQ makes it possible to write easily readable and elegant code. The examples that follow will imply how easily understandable LINQ code can be.

 LINQ defines a set of standard query operators that you can use for traversal, filter and projection operations. These standard operators can be applied to any IEnumerable<T> based information source. The set of standard query operators can be augmented with new domain-specific operators that are more suitable for the target domain or technology. This extensibility in the query architecture is used in the LINQ project itself to provide implementations that work over both XML (LINQ to XML) and SQL (LINQ to SQL) data. Lets write some code to understand the query operators in more detail:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;
 /// <summary>
/// Using standard query operators.
/// </summary>
public static void GetIExplorer()
{
    //  1. Data Source
    Process[] processes = Process.GetProcesses();
     //  2. Query Creation
    IEnumerable<int> query = from p in processes
  where p.ProcessName.ToLower().Equals("iexplore")
                             select p.Id;
     //  3. Query execution
    foreach (int pid in query)
    {
        Console.WriteLine("Process Id : "+pid);
    }
}
  All LINQ query operations consist of three distinct operations:

  1. Identify the data source
  2. Query creation
  3. Query execution

 

Calling the method would show you the currently running Internet Explorer processes (their process ids). The heart of the method lies in the following statement of our program.

 

IEnumerable<int> query = from p in processes
                         where p.ProcessName.ToLower().Equals("iexplore")
                         select p.Id;

 The expression on the right hand side of this statement is called the query expression. The output of this expression is held in the local variable ‘query’. The query expression operates on one or more information sources by applying the query operators from the standard or domian specific set of query operators. We have used standard query operators here namely where and select.

 The from clause select the list of processes which becomes the input for the where operator which filters the list and selects only those elements that satisfy the condition specified with the where operator. The selected elements are then processed by the select operator that determines any specific information selection for each element.

 The above statement can also be written using explicit syntax as shown below:

 

IEnumerable<int> query = Process.GetProcesses()
               .Where(s => s.ProcessName.ToLower().Equals("iexplore"))
               .Select(s => s.Id);

This form of query is called a method-based query and the arguments to the query operators are called lambda expressions. They allow query operators to be defined individually as methods and are connected using the dot notation. I will deal with lambda expressions in my following posts.

 

«July»
SunMonTueWedThuFriSat
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678