Count the number of lines of code in an ASP.Net Web Application

by Heathesh 3. April 2013 05:39

The requirement was simple, count the number of lines of code in an ASP.Net Web Application including the number of HTML lines. To fulfil this requirement I thought I would whip up a quick console app.

How it works is pretty straight forward:

  1. Get the list of files it needs to do the counts for
  2. Make sure the list of files only includes the relevant file types
  3. Make sure the list skips the ASP.Net generated file types
  4. Skip folders if and when required
  5. Make sure it only counted lines of code and not comments and regions
  6. Generate a CSV file called "output.csv" with the relevant details

All the settings should be self explanatory and found in the app.config file in the project. I've included the source for the app in a zip file and saved it here:

Happy Counting!


Tags: , , ,

Development | .Net

Simple SQL proc to generate an enum class for a lookup table

by Heathesh 8. February 2012 01:40

Here's the proc I created and below is the explanation of how I went about doing this:

I'm sure every c# developer has come across a situation where they have a lookup table that they'd like to convert into an enum in code. I've actually had to do it a few times myself and each time I use some sort of cursor and t-sql to create the enum class code. So I figured why not create a procedure to do this that I could re-use?

To begin with, there's a few parameters I needed to pass into the procedure. These were:

  1. The table name
  2. The namespace I wanted of the code
  3. The DataContract namespace. Because most of the stuff I do now is WCF this was a necessity but you can obviously remove this if you want.
  4. The id field on the lookup table.
  5. The value field on the lookup table.

I've attached the proc for you to copy ( The basics of how it works is that I insert the id and value fields into a temporary table using sp_executesql, then loop through the values using a cursor and simply use print statements to output the relevant code.

To use the proc I created a simple table called Title with an Id and a Name column like so:

CREATE TABLE [dbo].[Title](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Id] ASC

I then populated the table with values like so:

INSERT INTO [Title] ([Name]) VALUES ('Mr')
INSERT INTO [Title] ([Name]) VALUES ('Mrs')
INSERT INTO [Title] ([Name]) VALUES ('Miss')
INSERT INTO [Title] ([Name]) VALUES ('Dr')
INSERT INTO [Title] ([Name]) VALUES ('Prof')
INSERT INTO [Title] ([Name]) VALUES ('Sir')
INSERT INTO [Title] ([Name]) VALUES ('Madam')
INSERT INTO [Title] ([Name]) VALUES ('Mr And Mrs')

You'll notice one of the values has spaces in it. Since enum names cannot have spaces in it when you run the proc you'll notice in the output that it adds the Description attribute with the full name of the row, this is so you can still get the value of the string. If you need help with this check out a previous post of mine on reading the description attribute: Reading the DescriptionAttribute of enumerators ...

Then I simply ran my proc like so:

'Title', -- this is the name of the lookup table
'Heathesh.Com.Entity', -- this is the namespace I wanted to appear in the code
'', -- this is the data contract namespace I wanted to appear in the code
'Id', -- this is the id field of the table
'Name' -- this is the name field of the table

And this produced my required output like so:

using System;
using System.Runtime.Serialization;
using System.ComponentModel;
namespace Heathesh.Com.Entity
/// <summary>
/// Title enum
/// </summary>
[DataContract(Name = "Title", Namespace = "")]
public enum Title
Mr = 1,
Mrs = 2,
Miss = 3,
Dr = 4,
Prof = 5,
Sir = 6,
Madam = 7,
[Description("Mr And Mrs")]
MrAndMrs = 8,

I simply then added a "Title.cs" class to my project, replaced all the code in the class with what was generated and that was it. An enum class generated using sql from a lookup table.

Please note: Don't forget to add a reference to "System.Runtime.Serialization" in your project for the WCF stuff (DataContract, DataMember, EnumMember etc.)

Happy generating!



Tags: , , ,

Development | .Net | SQL Server 2008

Using the Twitter REST API and Json.NET to see who doesn't follow you back on Twitter

by Heathesh 3. February 2012 05:09


I prefer following people that follow me back on twitter. So I normally check and generally unfollow people that aren't following me. While digging around the twitter dev site I found the REST APIs and I wanted to see what I could do with them. I figured a little console app that showed me who isn't following me back might be a decent challenge so I set off creating one.

I normally post step by step instructions of what I did in my blog posts, however this time I'm included the source code of the app so people can do whatever they want with it and I'm going to give you a basic run down of how the app works. You can download it here:

To begin with, I used the Twitter REST API to get a Json dataset of all the people I follow and all the people following me (I created a setting called "UserToCheck" in the app.config file so you can simply change this to any twitter handle to run the check for that account). I used Json.NET ( to parse this Json into a simple list of user ids for each of the above. Then I simply iterated through the list and for anybody who wasn't following me I used another Twitter REST API call to get back that user's details in another Json dataset.

In order to make the user's detail more "user friendly" I created a simple class called TwitterUser and using the "DescriptionAttribute", reflection and Json.NET I populated this object with the Json dataset. Then I simply write out each screen name of whomever is not following me but from the code you will see you have a fully populated TwitterUser object which you could do quite a bit with (like display their twitter pic, bio etc.).

I'm pretty sure the code is pretty self-explanatory, but as usual if you have any questions feel free to contact me using my Contact page (

Happy tweeting!


Tags: , , , , , ,

Development | .Net

Parallel processing of a list of items using a dynamic number of threads

by Heathesh 20. June 2011 01:46

While working on a project I came across an interesting problem. I had a list of items to process and I wanted to run a certain number of those items at the same time and let the number of items running at the same time be set in a settings file. To illustrate how I did this, let's start of with the items I was going to process. In this case let's say I had a class called "Queue" and each "Queue" item was something I need to do some work with.

    /// <summary>
    /// Queue entity
    /// </summary>
    public class Queue
        /// <summary>
        /// Gets or sets the id
        /// </summary>
        public int Id { get; set; }

        /// <summary>
        /// Gets or sets the name
        /// </summary>
        public string Name { get; set; }

Now in my application, I have a list of these Queue items and I want to be able to process more than one at a time, and I want to be able to set how many items I'm processing at a time in a settings file. So I added a setting file called "QueueSettings.settings" and added a setting called NumberOfThreads which I set to "3".

Now let's pretend my List of queued items to process looks like this:

            List<Queue> queuedItems = new List<Queue>();
            queuedItems.Add(new Queue { Id = 1, Name = "Apple" });
            queuedItems.Add(new Queue { Id = 2, Name = "Banana" });
            queuedItems.Add(new Queue { Id = 3, Name = "Orange" });
            queuedItems.Add(new Queue { Id = 4, Name = "Pear" });
            queuedItems.Add(new Queue { Id = 5, Name = "Peach" });

And for simplicity sake, the method that actually processes the Queue item looks like this:

        /// <summary>
        /// Process the queued item
        /// </summary>
        /// <param name="queue"></param>
        private static void processQueuedItem(Queue queue)
            Console.WriteLine("Processed: {0} - {1}", queue.Id, queue.Name);

Now we need to create a method that will call the above method as we require. So we first add the following namespace to our application:

        using System.Threading.Tasks;

Then we create the method that does the actual processing:

        /// <summary>
        /// Processes the queued items
        /// </summary>
        /// <param name="queuedItems"></param>
        /// <param name="threadsToUse"></param>
        private static void processQueuedItems(List<Queue> queuedItems, int threadsToUse)
            //calculate how many times we need to loop, by determining how many times we'll do a full set of
            //items and adding one for the remainder of items. For example, if you have 5 items and you're threading
            //3 at a time, you need to run twice, once to do the first 3, then once to finish off the last 2
            int timesToLoop = ((queuedItems.Count % threadsToUse) > 0 ? 1 : 0) + queuedItems.Count / threadsToUse;

            //set a current record number which we will use to make sure we don't process the same item
            //more than once
            int currentRecordNumber = 0;

            //loop through the amount of times we need to loop
            for (int i = 0; i < timesToLoop; i++)
                if ((currentRecordNumber + threadsToUse) > queuedItems.Count)
                    //this means we're doing the remainder of items
                    int lastThreadsToUse = (queuedItems.Count % threadsToUse);
                    Console.WriteLine("Processing {0} items", lastThreadsToUse);

                    //run in parallel the number of remainder items by calling the process queued item method
                    Parallel.For(0, lastThreadsToUse, _ => processQueuedItem(queuedItems[currentRecordNumber + _]));
                    //this means we're doing a full set of items
                    Console.WriteLine("Processing {0} items", threadsToUse);

                    //run in parallel the number of threads we've been passed by calling the process queued item method
                    Parallel.For(0, threadsToUse, _ => processQueuedItem(queuedItems[currentRecordNumber + _]));

                //increment the current record number by the number of threads we've processed
                currentRecordNumber += threadsToUse;

I'm using a Console application to test this, hence all the Console.WriteLine calls. The method should be self explanatory, it determines how many times it should run and then runs the relevant number of threads each time it is required until it's done. But just for complete disclosure sake, here's the "Main" method of my console app to show you how I tested this:

        /// <summary>
        /// Main application thread
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
            //create a dummy list of queue items
            List<Queue> queuedItems = new List<Queue>();

            queuedItems.Add(new Queue { Id = 1, Name = "Apple" });
            queuedItems.Add(new Queue { Id = 2, Name = "Banana" });
            queuedItems.Add(new Queue { Id = 3, Name = "Orange" });
            queuedItems.Add(new Queue { Id = 4, Name = "Pear" });
            queuedItems.Add(new Queue { Id = 5, Name = "Peach" });

            //get the number of threads we want to run in parallel from the setting file we
            //created before
            int threadsToUse = QueueSettings.Default.NumberOfThreads;

            //call the method to do the threading etc.
            processQueuedItems(queuedItems, threadsToUse);

Happy Threading!

Tags: , , ,

Development | .Net | Visual Studio 2010 | VS2010

Powered by BlogEngine.NET (with enhancements by Heathesh)
Theme by Mads Kristensen (with tweeks by Heathesh)


Microsoft Certified Professional

Microsoft Certified Technology Specialist

Answer Questions


Tag cloud


<<  September 2017  >>

View posts in large calendar