Archive for the ‘C#’ Category

Opening Excel Files in New Processes – Excel Launcher Helper App

Monday, June 21st, 2010

Excel Launcher 1.1 (9/1/2010)

So after some comments in the forums about my installer having problems I have updated Excel Launcher to use a new installation package (NSIS) and also made it easier to set the location of your Excel installation. NSIS did not support associating Excel files with Excel launcher so you will need to manually associate them using the technique shown at the end of this blog post. Please uninstall any existing version of Excel Launcher before installing this one.  Download Excel Launcher 1.1

  • Abandoned MS Installation package and switched to NSIS to stop bug where every time you opened a file a searching screen appeared.
  • Running Excel Launcher standalone now prompts you to set your Excel installation location every time and not just the first time

I am a multi-monitor fanatic. If  I could afford it I would have three 24″ monitors sitting on my office desk. Of course all this real estate requires good window management and fortunately Microsoft has finally improved theirs with Windows 7. Dragging windows up against the borders of a monitor causes them to fill either half or the whole monitor. This is fantastic for having side-by-side windows for work. You can also use the Windows Key + the arrow keys to quickly move windows across your monitors. Bravo!

But of course one of my most used applications does not support opening files in new processes. Excel. Why?!?! Why oh why must files always open in an existing Excel instance? This happens in other apps like Internet Explorer, but I can rip off the tabs and make them into new windows. Only Excel seems to cage me into this single window paradigm. After some googling I found a lot of people in the same boat and some very unsatisfactory workarounds including:

  • Modifying the shortcuts for all of your Excel files so that they open in a new instance – I don’t always use the same files so this is out.
  • Disabling DDE – which is no longer possible on Windows 7 and Vista
  • Dragging your Excel window to be really big and then using the internal Excel Window management – not good for multimonitor
  • Always launching a new Excel instance and choosing file -> open -> browse (sigh)

Disappointed, I resolved to manually opening new instances of Excel. But during a restless night it occurred to me – Excel does not open as a new process, but an application launcher could open new instances of Excel. What a fun programming project! I would create my own executable that would be associated with Excel file types -> xls, xlsx, csv, etc. That program would launch Excel and tell it to open the file. Bingo bango boingo we are in business.

So I sat down and within thirty minutes I had working code. I then thought it would be fun to make an installer instead of a dumb exe since there seemed to be so many people looking for this solution. Why not make it easy for them? I wish I had made it easy on myself. Four hours and many google searches later I finally have my program done and created in an installer package. In case anyone is wondering why it took so long I had to account for the fact that I am installing to the Program Files directory. With that comes access restrictions. Then I had to figure out how to read/write/store stuff to the registry. That required error handling. Auto updating research, tray application research, blah, blah blah.

Okay, enough complaining, this is what you are looking for. Download and install Excel Launcher. When you run it the first time it will prompt you for the location of your Excel application. This should be in program files or program files(x86): \microsoft office\officeXX\Excel.exe. Next associate any files that you want to open in a new Excel instance to Excel Launcher. By default XLS, XLSX and CSV files will be associated with Excel Launcher. To associate other files

  1. Right mouse button on an the file -> Open With -> Choose Default Program -> Browse
  2. Navigate to Excel Launcher.exe which should be in your program files directory
  3. Check the box for “Always use the selected program to open this kind of file.”

That’s it. Now whenever you open an Excel file it will use Excel Launcher which will create a new Excel process for you each time and open the file. As of now there is no argument passing so if you use arguments they will be ignored. If there is enough interest I may implement this for people in my copious free time.

Some ideas for improvements:

  • Prompt user to associate common file types when installing
  • Instead of storing Excel path in registry store it in an xml file in program files directory. This will allow multiple program types to leverage this functionality.
  • Allow passing of arguments through to Excel
  • Support DDE? I never really researched this so don’t even know if this is possible.

LC Design’s Technology Purchased By Major CAD Company

Thursday, January 14th, 2010

LC Design is a very small company composed of some very smart individuals. I was first approached by them a couple years ago about working on some of their ideas for increasing the efficiency of CAD. After a discussion with the founders I knew right away that they were on to something big. For years I had been using my role in SQA to shape user workflow. Technically PD is the one that makes all UI decisions, but I have a penchant for recognizing how users will view a system and through a combination of discussion and bug writing I was always able to get a user interface to be the best it could be. Their ideas were not just going to streamline user workflow they were going to revolutionize it.

So I threw my hat into their ring and started doing software development for them. At the time it seemed risky, in hindsight it seems extremely risky. Times were good when we started, but within twelve months the world economy was in free fall and all bets were off. I never gave up hope though. I knew that the ideas were great and that we had the right team for proving how good they were.

Well that gamble finally paid off when our technology was purchased by one of the major CAD players. The deal closed out on my birthday no less and it could not have been a better birthday present. The best part about the purchase is that it now gives me the opportunity to find the next great idea I believe in and bring it to fruition. Like my marathon training, you have to keep your eye both in the present and on your goal. Perseverance today pays off tomorrow.

I am certainly excited to find the next big career project in my life and make it a reality!

Multithreading Revisited

Thursday, November 19th, 2009

So I was reading an article by John Siracusa on arstechnica.com about  Snow Leopard recently and he had a great segment about Apple’s new Grand Central Dispatch technology. The idea of GCD is to allow developer’s to easily multithread code without having to do all the work that I had to go through. Before I get into that though let’s cover the basis of what GCD is. First of all GCD is a low level means of handling threads automatically. When developing for a multiprocesser system developers don’t have much knowledge of what the current system state is. Sure I have four cores, but how many are available? Once you let GCD know you want something threaded it can farm out the work for you. No checking for number of processor cores or if hyperthreading is available. Sweet.

Grand Central Dispatch also allows you to multithread in just a few lines of code. John does a great job of explaining it so hit the link above and read up if you want more in depth information on the technology. The short version is that blocks + GCD = multithreading bliss.

So all of this got me thinking about my previous article on multithreading a workload and how I could improve it. One thing that would make sense would be to use a stack instead of splitting my list up into equal parts. A stack is like a pile of paper. You can pull things off the top of the stack and expose the page underneath. So if I passed the same stack to each thread then the threads would peel off the work bit by bit until the stack was gone.

  • Once the stack is empty then the threads will terminate themselves.
  • I could add work to the stack as it is being processed (of course being careful that the threads don’t terminate before I am done collecting work)
  • I don’t have to worry about one subset of work finishing faster than another.

So let’s run a little pseudo code for this framework:

private void Multithread()
{
  Stack<int> stack = new Stack<int>(100); //stack of 100 something
  for (int i = 0; i < 100; i++) { stack.Push(i); } //fill the stack
  Thread[] threads = new Thread[System.Environment.ProcessorCount];

  //Create the threads and pass the same stack to each one
  for (int i = 0; i < threads.Length; i++)
  {
       threads[i] = new Thread(delegate() {
                      DoSomething(stack);
                    });
       threads[i].Start();
  }
<pre style="font: normal normal normal 12px/18px Consolas, Monaco, 'Courier New', Courier, monospace;">   //wait for execution to finish
  foreach (Thread thread in threads) { thread.Join(); }</pre>
}

And our worker function which will terminate once the stack has emptied

private void DoSomething(Stack<int> stack)
{
 while (stack.Count > 0)
 {
    int j = stack.Pop();
    Debug.Print(j.ToString());
 }
 return;
}

Simple Multi-threading of a Workload

Monday, September 28th, 2009

Recently I was faced with a prescreening programming question that involved a straightforward problem with one caveat that made it significantly more difficult. I had to compute some 800 trillion+ solutions in as close to 20ms as possible. It only took me a couple days to write an algorithm that could theoretically solve the answer… but it would have taken weeks to run. Eventually I figured out the shortcut to get my run time to less than a second, but carving away each tenth of a second thereafter took some creativity. One obvious way of making up some time would be to make use of the near ubiquity of multicore processors these days. Fortunately the workload was simple enough to split up. I had a large list of objects and I had to do “something” to each element. By splitting the list and farming out the workload to the number of processors in the system I carved off a nice 40% time savings on a segment of my project. Again we will be working in C#.

Jump to final code

Generally the code flows like this:

  1. Add references
  2. Find the number of processors on the current system
  3. Split your workload into pieces
  4. Create a thread for each piece
  5. Wait for the threads to complete before continuing main program execution.

First off add a reference to the System.Threading namespace

using System.Threading;

Next find the number of processors

int numProcs = System.Environment.ProcessorCount;

For my workload I am splitting a list into equal parts. I have to ensure that when I split the list I don’t repeat any of the elements, nor do I leave any elements behind if the list isn’t evenly divisible by the number of processors in the system. It would also be more efficient to check the length of the list and see if it is worthwhile to multithread it. If you only have one list item then multiple threads aren’t going to do you much good.

List<N> myList = new List<N>();
int iRange = list.Count / numProcs;       //# of elements in the list to get
int iStart, iEnd;                        //portion of list that we will get

//for each processor get a piece of the workload
for (int i = 0; i < iProcs; i++) {
     //set start and end values to get
     iStart = iRange * i;
     if (i == iProcs - 1)  //for last processor use the rest of the list
          iEnd = buildRows.Count - iStart;
     else
          iEnd = iRange;

     //Get the subset of list items
     List<N> listSubset = myList.GetRange(iStart, iEnd);
}

Now for the multithreaded part. You create a new thread by creating a new Thread object and specifying a ThreadStart. A ThreadStart represents a method in your program and acts as a delegate. A delegate is an object that refers to a method and can call a method. In this example I want to execute a method on each item in my list. So I create a delegate that points to this method. There are multiple ways to set this up, but the most straightforward way I found is in this example code.

Thread myThread = new Thread(
     delegate() {
          foreach (N item in listSubset) { item.DoSomething();  }
     }
);

You call thread.Start() to begin executing the delegate. However, your main application thread will continue running simultaneously. If you want to wait for all your worker threads to finish before continuing with the main thread you must call thread.Join();. This tells the current thread to wait for the specified thread to finish. Let’s tie everything together now.

private void MultiThreadWorkLoad(List<N> myList) {
    int numProcs = System.Environment.ProcessorCount; //number of processors
    int iRange = buildRows.Count / iProcs;   //# of elements in the list to get
    int iStart, iEnd;       //portion of list that we will get
    Thread[] threads = new Thread[iProcs];      //array of threads

     //for each processor get a piece of the workload
     for (int i = 0; i < numProcs; i++) {
          //range of values to get
          iStart = iRange * i;
          if (i == numProcs - 1)  //for last processor use the rest of the list
               iEnd = buildRows.Count - iStart;
          else
               iEnd = iRange;

          List<N> listSubset = buildRows.GetRange(iStart, iEnd);
          Thread myThread = new Thread(
              delegate() {
                      foreach (N item in listSubset) { item.DoSomething();  }
              }
          );
          myThread.Start();
          threads[i] = myThread;
    }

    //all threads should complete before we continue with main program execution
    foreach (Thread thread in threads) { thread.Join(); }
}

Getting Started With Windows Voice Recognition

Tuesday, August 25th, 2009

This article will quickly get you up and running with Windows Voice Recognition by using the .NET library System.Speech. After completing these steps you will be able to translate audio files or speech into your microphone. Examples are in C#.

  1. Add references to the System.Speech namespace
  2. Create a SpeechRecognition object
  3. Setup event handlers for your audio source
  4. Load a grammar libary
  5. Set audio parameters
  6. Scan the audio and output word recognition

(more…)