twitter

Bonafide Ideas Rss

Featured Posts

Microsoft Visual C++ MVP Award for 2013 G’day Community, Firstly, I’d like to wish you all a happy new year 2013, full of health, blessings & success Secondly, I’m happy to announce that Microsoft has awarded me with an MVP (9th consecutive year) in the Visual C++ category, therefore I’d like to thank God, my daughter, my wife (for all of her patience & understanding),...

Read more

Analysing assemblies and finding out possible leaks... Today’s post is about… A command line utility I wrote a few days back for analysing and finding out possible leaks by not disposing of objects properly. Before we get into the nuts and bolts of the utility, please find attached two files which are: MSIL Instruction Set Specification (Required to do any MSIL manipulation) Utility’s...

Read more

CyberNanny: Remote Access via Distributed Components This article is about an application called CyberNanny, which I recently wrote to allow me to remotely see my baby daughter Miranda at home from anywhere at any time. It’s written in Visual C++ (MFC) and it comprises different technologies such as Kinect and its SDK, Windows Azure, Web services and Office automation via Outlook. The project...

Read more

DDD Sydney - Slide deck Hi community, Please feel free to grab the slides I used at DDD Sydney from here Regards,   Angel

Read more

Developer… Developer… Developer Sydney! Hi Community, I would like to invite you all to “Developer… Developer… Developer Sydney”. This event will be held at UTS on Saturday 30th June 2012. I’ll be presenting “Building Windows 8 applications natively with Visual C++”. I look forward to seeing you there. Best Regards, Angel

Read more

Analysing assemblies and finding out possible leaks by not disposing of objects properly

Category : .NET, Visual C#

Today’s post is about… A command line utility I wrote a few days back for analysing and finding out possible leaks by not disposing of objects properly.

Before we get into the nuts and bolts of the utility, please find attached two files which are:

  1. MSIL Instruction Set Specification (Required to do any MSIL manipulation)
  2. Utility’s Source code

It’s well-known that every single object that implements IDisposable must be disposed by:

  1. Calling the Dispose method explicitly
  2. Enclosing the object that implements IDisposable within an using statement

Said that, let’s have a look at the code snippet shown below

public class LeakyClass {

    public void LeakyMethod() {

        var conn1 = new SqlConnection();

        var conn2 = new SqlConnection();

        conn2.Dispose();

 

        using (var conn3 = new SqlConnection()) {

            // Do something here...

        }

    }

}

This is the generated MSIL from the code snippet

Figure12

 

As you can see, three objects of type SqlConnection are created and two of them are disposed. When enclosing the object within an using statement what really happens is that a try… finally…  block is produced. As you can see the Dispose method is a callvirt which is a “Call to a virtual method” and it’s virtual because it was implemented from the IDisposable interface. MSIL similar to assembler has some Op codes, actually there are 256 (0×100) Op codes being [Dec = 111 | Hex =0x6f] (callvirt) and this is the one we’ll use in our utility.

The way as our utility works is described as follows:

  1. An assembly is loaded for analysis as specified in argument (eg.:  -a "C:\myassembly.dll")
  2. The Inspect method is called which performs the analysis on the modules & types referenced in the assembly
    private static void Inspect(Assembly current) {   

     var flags = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

     var stats = new Dictionary<string, DisposableStats>();

     current.GetModules().ToList().ForEach(x => x.GetTypes().ToList()

        .ForEach(y => y.GetMethods(flags).ToList().ForEach(z => InspectMethod(x, z))));

    }

  3. The InspectMethod is called only processing the variables (objects) which implement IDisposable
    private static void InspectMethod(Module module, MethodInfo method) { 

      var body = method.GetMethodBody();

     

       if (body != null) {

            var variables = body.LocalVariables;

            var disposable = variables.Where(x => x.LocalType.GetInterfaces()

                             .Where(y => !string.IsNullOrEmpty(y.Name) && 

                                    y.Name.Equals("IDisposable")).FirstOrDefault() != null);

      

            var count = disposable.Count();  

            var key = new MethodDescription(method.ReflectedType.ToString(), method.Name);

     

            if (count > 0 && !stats.ContainsKey(key)) 

                stats.Add(key, IdentifyDisposableObjects(body.GetILAsByteArray(), count, module));    

        }

    }

  4. Then we call IdentifyDisposableObjects method that takes as an argument an array of bytes containing the MSIL of the method. We take into account only callvirt (0x6F) op code.
    private static DisposableStats IdentifyDisposableObjects(byte[] ilasm, int disposable, Module module) { 

        int position = 0, offset = 0, token = 0;

        var retval = new DisposableStats(disposable);

     

        while (position < ilasm.Length) {

            var method = string.Empty;

            var value = ilasm[position++];  

     

            // Is it a callvirt? 

            if (value == 0x6F) {

                offset = position - 1;

                token = ReadInteger(ilasm, ref position);

     

                if ((!string.IsNullOrEmpty(method = module.ResolveMethod(token).Name)) && 

                    method.Equals("Dispose", StringComparison.OrdinalIgnoreCase))

                     retval.DisposedCount++;         

            } 

          }  

      return retval;

    }

  5. We do this for every method in the assembly, and add this information to a dictionary that’s later dumped as a report.

Figure13

If you have a copy of reflector, please feel free to check the results of the report with reflector’s disassembly… You’ll be amazed with the amount of objects that are being left behind and not being disposed.

Regards,

Angel

TechEd 2011– Session Recording

Category : .NET, API, Microsoft, MVP, TechEd, Visual C#, Visual C++

Hi Community,

Please find below the session recording for my presentation at Teched.  You can check it out on Channel 9 too Smile

 

Best Regards,

Angel

Differences between C++ Templates and C# Generics

Category : .NET, TechEd, Visual C#, Visual C++

Hi Community,

Yesterday during my presentation at TechEd I was asked by someone in the audience, if C# Generics were similar to C++ templates and I said… “The syntax might be similar but they’re different, and C++ templates have been with us for a long time now, actually… C# has borrowed from some other languages certain features – I’m not gonna mention which ones, in the case of C# Generics’ syntax it’s a bit C++ like”.  I told the person who asked me the question to discuss this in more detail after the session, but unfortunately he left while I was answering some post session questions. There are a couple of papers below which explain this in detail.

So this blog post is to clarify a bit my statement as previously mentioned.

Best Regards,

Angel

TechEd 2011 presentation material

Category : .NET, API, Microsoft, MVP, TechEd, Visual C#, Visual C++

blogBling_150x150_02

 

Hi community,

Please feel free to download the presentation material & demos here.

Enjoy your TechEd experience!

Best Regards,

Angel

Carmichael’s numbers generator – C#

Category : .NET, Microsoft, TechEd, Visual C#, Visual C++

Hi community,

Please find below a code snippet I wrote last night for generating the Carmichael’s numbers.

This demo was written in C# and it implements TPL to take advantage of multiple processors.

It is intended to be demoed at Tech-Ed Australia along with its counterpart written in C++ implementing PPL.

See you in two weeks time at Tech-Ed on the Gold Coast Smile

Best Regards,

Angel

using System;

 

using System.IO;

 

using System.Linq;

 

using System.Text;

 

using System.Threading;

 

using System.Threading.Tasks;

 

using System.Collections.Generic;

 

using System.Collections.Concurrent;

 

using System.Runtime.InteropServices;

 


 

namespace Test2 {

 

    class Program {

 

        [DllImport("kernel32.dll", CallingConvention = CallingConvention.StdCall)]

 

        private static extern int GetTickCount();

 


 


 

        /// <summary>

 

        /// Is_carmichaels the specified n.

 

        /// </summary>

 

        /// <param name="n">The n.</param>

 

        /// <returns></returns>

 

        static bool is_carmichael(int n) {

 

            if (n < 2) { return false; }

 


 

            int k = n;

 


 

            for (int i = 2; i <= k / i; ++i) {

 

                if (k % i == 0) {

 

                    if ((k / i) % i == 0) { return false; }

 

                    if ((n - 1) % (i - 1) != 0) { return false; }

 

                    k /= i;

 

                    i = 1;

 

                }

 

            }

 

            return k != n && (n - 1) % (k - 1) == 0;

 

        }

 


 

        /// <summary>

 

        /// Time_calls the specified functor.

 

        /// </summary>

 

        /// <param name="functor">The functor.</param>

 

        /// <returns></returns>

 

        static int time_call(Action functor) {

 

            int begin = GetTickCount();

 

            functor();

 

            return GetTickCount() - begin;

 

        }

 


 


 

        /// <summary>

 

        /// Mains the specified args.

 

        /// </summary>

 

        /// <param name="args">The args.</param>

 

        static void Main(string[] args) {

 

            int numItems = 10000000;

 

            int numProcs = Environment.ProcessorCount;

 


 

            var vectors = new ConcurrentBag<List<int>>();

 


 

            Parallel.For(0, numProcs, (int i) => {

 

                var v = new List<int>();

 

                for (int j = numItems / numProcs * i; j < numItems / numProcs * (i + 1); ++j)

 

                    v.Add(j);

 

                vectors.Add(v);

 

            });

 


 

            Console.WriteLine("Counting carmichael numbers");

 


 

            // Serial

 

            int sum, sum2, sum3;

 

            var sums = new List<int>(numProcs);

 

            var sums2 = new List<int>(numProcs);

 

            var sums3 = new List<int>(numProcs);

 


 

            int serialTime = time_call(() => vectors.ToList().ForEach(x => sums.Add(x.Count(z => is_carmichael(z)))));

 


 

            sum = sums.Sum();

 


 

            Console.WriteLine(string.Format(" {0} ms, num carmichaels {1}", new object[] { serialTime, sum }));

 


 


 

            // Parallel

 


 

            var task1 = Task.Factory.StartNew(() => {

 

                int parallelTime2 = time_call(() => Parallel.ForEach(vectors, x => sums2.Add(x.Count(z => is_carmichael(z)))));

 

                sum2 = sums2.AsParallel().Sum();

 

                Console.WriteLine(string.Format(" {0} ms, num carmichaels {1}", new object[] { parallelTime2, sum2 }));

 

                var task2 = Task.Factory.StartNew(() => {

 

                    int parallelTime3 = time_call(() => Parallel.ForEach(vectors, x => sums3.Add(x.Count(z => is_carmichael(z)))));

 

                    sum3 = sums3.AsParallel().Sum();

 

                    Console.WriteLine(string.Format(" {0} ms, num carmichaels {1}", new object[] { parallelTime3, sum3 }));

 

                }, TaskCreationOptions.AttachedToParent);

 

            });

 


 

            task1.Wait();

 


 

            Console.ReadKey();

 

        }

 

    }

 

}

 

I’ll be speaking at TechEd Australia 2011

Category : .NET, Microsoft, MVP, TechEd, Visual C#, Visual C++

teched_emailsig_02

Hi Community,

I would like to let you know that I’ll be presenting at TechEd Australia about “Making the most of .NET with C++ for interop, performance and productivity”

Stay tuned!

Regards,

Angel

Upcoming Speaking Engagements

Category : .NET, Microsoft, MVP, Visual C#, Visual C++

Hi Community,

I would like to invite you to “Targeting Windows 7: Light up features with Visual C++ 2010” webcast on July 1, 2011 @ 10:00 AM (Bogota’s time). I will be also presenting at UTS for the “.NET in the Enterprise” class on 31 May, 2011.

As usual, I’ll upload and share with you the slide deck and demos after the presentation.

Regards,

Angel

Memory Inspector Source Code on CodePlex

Category : .NET, API, Microsoft, MVP, Visual C#, Visual C++, Visual Studio

Hi Community,

 

Please feel free to download the Memory Inspector Source Code from here and if you like it, feel free to join the project!!!

 

Regards,

 

Angel

Memory Inspector

Category : .NET, API, Microsoft, MVP, Visual C#, Visual C++, Visual Studio, Win32

 

Hi Community, please find here an Add-In I just published for Visual Studio on Visual Studio Gallery. It’s called “Memory Inspector” and in a few words…  “it’s a tool for analyzing memory usage and allocations made by an application and its dependent modules. It also allows to collect  information about the memory use at a given time, thus facilitating baseline and comparison between execution environments”.

 

Best Regards,

 

Angel