Quickly loop through a table in SQL Server

This is an fast and easy way to loop through the table without having to deal with cursors which exact a heavy toll on the database.  Especially useful for quick scripts.

For this you'll need a unique key on the table.  It won't work without it and you'll be stuck with the cursors.  If this unique key is indexed (which it should be), then this routine will even be faster.

Let say you have to loop through all the values in table SampleTable.  Table has structure like this:

     ID      int identity (1,1)
    ,Name    varchar(50)
    ,Address varchar(100)

And the code to loop through it:

DECLARE @minID int
-- get the first record
SELECT @minID = min(ID) FROM SampleTable
-- loop until we have no more records
    -- do actual work, for instance, get the Name and Address for this ID
    SELECT Name, Address FROM SampleTable WHERE ID = @minID
    -- get the next record
    SELECT @minID = min(ID) FROM SampleTable WHERE @minID < ID

author: Angry Hacker | posted @ Thursday, November 01, 2012 9:48 AM | Feedback (0)

How to determine whether an assembly is 32 bit, 64 bit or AnyCPU.

And how to determine whether it’s managed or unmanaged.

With proliferation of libraries around the .NET world, sometimes you need to determine how the DLL was compiled or even whether it’s managed or not.

Just give me the TL;DR

Download the Bitness command line utility, or the source code from which it was built.  Usage: the app takes a single command line parameter.  If the parameter is a file, it’ll interrogate that file.  if the parameter is a folder, it’ll loop through all the DLLs in that folder.  In the absense of any command line parameters, it’ll process all files in the current directory.  Requirements: .NET 4.0 Framework.

Is it managed or not?

This one is easy enough.  The PE (Portable Executable) header present in all Windows executables reveals whether the DLL is managed or not.  I am not going to go over the PE format. 

   1:  private static bool IsManagedAssembly(string fileName)
   2:  {
   3:      Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
   5:      try
   6:      {
   7:          BinaryReader reader = new BinaryReader(fs);
   8:          //PE Header starts @ 0x3C (60). Its a 4 byte header.
   9:          fs.Position = 0x3C;
  10:          uint peHeader = reader.ReadUInt32();
  11:          //Moving to PE Header start location...
  12:          fs.Position = peHeader;
  13:          uint peHeaderSignature = reader.ReadUInt32();
  14:          ushort machine = reader.ReadUInt16();
  15:          ushort sections = reader.ReadUInt16();
  16:          uint timestamp = reader.ReadUInt32();
  17:          uint pSymbolTable = reader.ReadUInt32();
  18:          uint noOfSymbol = reader.ReadUInt32();
  19:          ushort optionalHeaderSize = reader.ReadUInt16();
  20:          ushort characteristics = reader.ReadUInt16();
  22:          long posEndOfHeader = fs.Position;
  23:          ushort magic = reader.ReadUInt16();
  25:          int off = 0x60; // Offset to data directories for 32Bit PE images
  26:          // See section 3.4 of the PE format specification.
  27:          if (magic == 0x20b) //0x20b == PE32+ (64Bit), 0x10b == PE32 (32Bit)
  28:          {
  29:              off = 0x70;  // Offset to data directories for 64Bit PE images
  30:          }
  31:          fs.Position = posEndOfHeader;
  33:          uint[] dataDictionaryRVA = new uint[16];
  34:          uint[] dataDictionarySize = new uint[16];
  35:          ushort dataDictionaryStart = Convert.ToUInt16(Convert.ToUInt16(fs.Position) + off);
  37:          fs.Position = dataDictionaryStart;
  39:          for (int i = 0; i < 15; i++)
  40:          {
  41:              dataDictionaryRVA[i] = reader.ReadUInt32();
  42:              dataDictionarySize[i] = reader.ReadUInt32();
  43:          }
  44:          if (dataDictionaryRVA[14] == 0)
  45:          {
  46:              fs.Close();
  47:              return false;
  48:          }
  49:          else
  50:          {
  51:              fs.Close();
  52:              return true;
  53:          }
  54:      }
  55:      catch (Exception)
  56:      {
  57:          return false;
  58:      }
  59:      finally
  60:      {
  61:          fs.Close();
  62:      }
  63:  }

Great, it’s Managed.  How was it compiled?

If the DLL is managed, we now need to determine whether the assembly is compiled for x86, x64 or AnyCPU.  For that will load the assembly into memory and interrogate its PE type.

   1:  private static PortableExecutableKinds GetManagedType(string fileName)
   2:  {
   3:      Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);
   4:      PortableExecutableKinds peKind;
   5:      ImageFileMachine imageFileMachine;
   6:      assembly.ManifestModule.GetPEKind(out peKind, out imageFileMachine);
   7:      return peKind;
   8:  }

Note that instead of using Assembly.Load I am using Assembly.ReflectionOnlyLoadFrom.  The reason for this is that if you attempt to Assembly.Load a 64 bit assembly from a 32 bit process, you’ll get a BadFormatException error.  Instead we use Assembly.ReflectionOnlyLoadFrom which only interrogates its PE header.  From there it’s a simple matter of using the switch statement.

   1:  switch (peKind)
   2:  {
   3:      case PortableExecutableKinds.ILOnly:
   4:          Console.WriteLine("Managed AnyCPU");
   5:          break;
   6:      case PortableExecutableKinds.Required32Bit:
   7:          Console.WriteLine("Managed x86");
   8:          break;
   9:      case PortableExecutableKinds.PE32Plus:
  10:          Console.WriteLine("Managed x64");
  11:          break;
  12:      case PortableExecutableKinds.Unmanaged32Bit:
  13:          Console.WriteLine("Managed but states that it's unmanaged???");
  14:          break;
  15:      case PortableExecutableKinds.NotAPortableExecutableImage:
  16:          Console.WriteLine("Managed but cannot determine anything else");
  17:          break;
  18:      default:
  19:          throw new ArgumentOutOfRangeException();
  20:  }

The last two enum members should be extremely rare and indicate that the assembly is somewhat corrupted.

It’s Native!  64-bit or 32?

If the DLL happens to be native, we can determine whether it’s compiled for 64 bit or 32.  (There is no such thing as AnyCPU in the native world). 

   1:  private static MachineType GetDllMachineType(string dllPath)
   2:  {
   3:      //see http://www.microsoft.com/whdc/system/platform/firmware/PECOFF.mspx
   4:      //offset to PE header is always at 0x3C
   5:      //PE header starts with "PE\0\0" =  0x50 0x45 0x00 0x00
   6:      //followed by 2-byte machine type field (see document above for enum)
   7:      FileStream fs = new FileStream(dllPath, FileMode.Open, FileAccess.Read);
   8:      BinaryReader br = new BinaryReader(fs);
   9:      fs.Seek(0x3c, SeekOrigin.Begin);
  10:      Int32 peOffset = br.ReadInt32();
  11:      fs.Seek(peOffset, SeekOrigin.Begin);
  12:      UInt32 peHead = br.ReadUInt32();
  13:      if (peHead != 0x00004550) // "PE\0\0", little-endian
  14:          throw new Exception("Can't find PE header");
  15:      MachineType machineType = (MachineType)br.ReadUInt16();
  16:      br.Close();
  17:      fs.Close();
  18:      return machineType;
  19:  }
  21:  private static bool? UnmanagedDllIs64Bit(string dllPath)
  22:  {
  23:      switch (GetDllMachineType(dllPath))
  24:      {
  25:          case MachineType.IMAGE_FILE_MACHINE_AMD64:
  26:          case MachineType.IMAGE_FILE_MACHINE_IA64:
  27:              return true;
  28:          case MachineType.IMAGE_FILE_MACHINE_I386:
  29:              return false;
  30:          default:
  31:              return null;
  32:      }
  33:  }
The UnmanagedDllIs64Bit method tells us whether the DLL is 64 bit or not.  Keep in mind that in addition to x86 and x64, Windows through its history supported many other architectures, for which you can interrogate the return value of GetDllMachineType method.  What other ones?  PowerPC, MIPS, DEC/Compaq Alpha, the upcoming ARM port of windows and many others. 

author: Angry Hacker | posted @ Saturday, March 03, 2012 7:57 PM | Feedback (0)

Modest suggestion for Windows 8

Modest suggestion for Windows 8 - Windows Live Writer_2012-02-22_23-11-49Like many, I read about Windows 8 on ARM and the upcoming Office 15.  For those, who don’t know, Windows on ARM (WOA) will be a tablet experience, much like the iPad.  But unlike the iPad, it will have a hidden full Windows desktop right behind the smooth Metro interface.  The whole purpose of this hidden desktop will be to run Office 15.

Many people are salivating at the prospect of Windows 8, thinking it’s going to be great.  Me?  I think it’s a train wreck about to hit the wall. 

So, it turns out that Office 15 is not written for the Metro interface (aka WinRT), but for the good old ARM ported Win32. And that is the reason why it must run on the Windows desktop.  To add insult to injury, only Office 15 will be allowed to run in the Desktop mode.  That’s right, mere mortals will not be able to target the desktop on Windows ARM tablets, only Metro.

This is a horrible idea for many reasons.  For one, it’s going to be a jarring experience.  You tap the Word icon, there is probably going to be an epilepsy inducing flicker as the tablet switches to the desktop.  Then you’ll see the desktop, then Word will come to life.  If you want to email the document from Word, the tablet (via yet another flicker) will take you to Metro’s built-in mail compose window and then back to word.  If you want to copy and paste, you’ll take a trip back to Metro, copy something and then back to Word.  Insanity.

Other reasons?  Bad blood with the development community.  Why can Microsoft target the Desktop, but no one else can?  Want more reasons?  Windows 8 Metro win8_arm_01interface is like a beautiful woman.  The experience is superbly fluid to the point where it rivals the iPad. With the desktop switching, you are slinging dirt at her.  She is not a beautiful any longer.

I have a modest proposal for Microsoft.  Forget the desktop on ARM.  Just forget it – the tablet is NOT a PC.  It just isn’t.  Just target Office 15 to the Metro interface and you’ll have the most juicy, molten and smooth tablet on the market.  When WOA tablets hit the market, there shouldn’t even be a whiff of the desktop.

But what if manufacturers want to create Windows PCs or laptops based on ARM?  What then?  The fact is that ARM chips are simply not fast enough to rival x64 from Intel/AMD.  The PCs running ARM won’t be a reality this year or next.  And when it is a reality, guess what, Microsoft will already have a desktop based product that runs on ARM.  The point is that Windows 8 should have a desktop interface when shipping a form factor requiring that (PCs, laptops) and a Metro interface for tablets and phones.  And thou shall not mix the two.

author: Angry Hacker | posted @ Wednesday, February 22, 2012 11:16 PM | Feedback (0)

Sane defaults for connecting from Windows to Mac via VNC

So you’ve turned on Screen Sharing on your Mac and now you want to control it from your Windows computer.  Quickly, you find out that you can’t use the Remote Desktop Connection because the Mac uses the VNC protocol. 

I downloaded the UltraVNC client and the results were less than encouraging:

  • The connection was slow.
  • Right-click did not work.  That is not 100% correct – it worked when you clicked the mouse wheel.
  • Double-click didn’t work either.

Turns out you gotta do some tweaks to fix the last two (will get to the first problem later).  In the Options dialog, uncheck Emulate 3 Buttons, and check Swap mouse buttons 2 and 3.
 Connection Options

Finally, after dismissing the Options dialog, check Save connection settings as default, before you click the Connect button. Otherwise, you’ll have to repeat this procedure every time.
Ultr@VNC Viewer

Switching those 2 checkboxes solved the problem for me.  I was able to easily right-click on items and double-click them.  Somehow the entire setup felt faster too.  Speaking of speed, VNC feels a lot more sluggish than Remote Desktop and there isn’t a whole lot you could do to produce dramatic improvements.  However, there are some debatable gains to be had if you follow these simple rules (none of them will make you happy though):

  1. Be on a fast network.
  2. Don’t be on a slow network.
  3. Reduce the screen resolution on the Mac.  Short of replacing your network, this will probably yield biggest impact.
  4. In VNC Options, reduce the amount of colors to 256 or 8.  Of course, it will look like something out of the nineties, but it was (very) marginally faster.  The transferred byte count was smaller at least.
  5. You can disable animations on the Mac to make it “feel” faster, but again, I didn’t like the result, though it did feel faster.  Just make sure you know how to restore the defaults later.

author: Angry Hacker | posted @ Saturday, September 10, 2011 11:52 AM | Feedback (0)

10 commandments of going to LEGOLAND.

legolandI think LEGOLAND is easily the best theme park in Southern California for kids 3-10.  Why?  The crowds are not nearly as large as Disneyland, Universal Studios and the like.  There is more for the kids to do.  It is flat out funner and more educational than any of the other theme parks in the area.

This is not a guide about what rides to hit up.  Rather, these are hard learned rules about making your visit really pleasant and insanity-free.  Here we go, in no particular order.

  1. When driving from Los Angeles, there is a viewpoint several miles past San Clemente. Besides the fantastic view of the ocean, you’ll find that a huge family of squirrels lives right off the cliff.  They love crackers and take them right from people’s hands.  Bring some, the kids will love feeding them furry creatures.
  2. If you are going to let your kids do face painting, do it after visiting the Pirates section (e.g. all water attractions).  Yes, learned the hard way.
  3. Bring a bathing suit, seriously.  LEGOLAND has several water rides and your kids are likely to get soaked head to toe. 
  4. To that end, park a small backpack on yourself.  This way you can carry all the stuff (bathing suits, possibly a towel, food the kids haven’t finished, etc…).  Make sure it has a small rubberized mesh pocket on the side (most do).  Why?  Go to next point.
  5. Before you get to the water rides, you are likely to see The Garden Restaurant.  It’s by the entrance to Miniland.  If you get a combo there, you’ll get a drink in a nice and tight plastic container.  They have fountain drinks.  So you can get free refills all day there.  It’s central location makes it convenient.  Well, actually I don’t know if they allow free refills.  That is what I did and no one said anything.  Anyway, the deal with the rubberized mesh pockets on the backpack is that they are perfect for the drink containers.
  6. When should u go?  Let’s start with when not to go: Saturday during the summer vacation.  This is kind of a no-brainer.  My favorite time to go is during the school year, when the school is having a day off due to a teacher conferences.  There are at least 2 or 3 each year.  Imagine spending no more than 4 or 5 minutes in line (worst case scenario) on ANY ride.
  7. The food in the park is expensive, no doubt about it.  And the kids will surely get hungry, also no doubt about it.   So if you are planning to be in the park from 11 to 8, you need to plan it out so that the food cost doesn’t actually exceed the cost of the ticket.  So before getting to the park, stop at some restaurant and have a good meal.  Then have one filling meal inside the park and finish up with another one after getting out of the park.
  8. If you are the type that brings food, you will likely have to leave the park and walk all the way back to the parking lot to your vehicle.  Try and setup the day, so that you only have to do it once, because it is quite a long haul.  Meanwhile, bring some snacks with you into the park (that’s where the backpack comes in) to tide the kids over till the trip to the parking lot.
  9. Suntan lotion.  Bring it.  Summer or winter.
  10. Height restrictions.  The park has various height restrictions for various rides.  If you have small kids, it is very likely that either you or an older sibling will have to ride with a younger one.  That is why it is advisable to have an even number of people in your party.  Believe me when I tell you that it is NO FUN to have go on a ride, that does nothing but go around, with each kid separately. 

author: Angry Hacker | posted @ Thursday, June 30, 2011 9:00 PM | Feedback (7)

Car Locator for Windows Phone 7 available for free.

CarLocatorI’ve decided to split out the Car Locator application into a free and paid versions. The free version will be ad supported.  The only functional difference between the two versions is that the freebie is missing the history feature (which basically gives you a chronicle of all your vehicle searches). 

Why?  Simply because a free app always gets a lot more eyeballs. And I am not really making an earth-shaking amount of money with it.   Plus I want to do more with the app – thus user feedback is important.  Now that Microsoft has announced the Mango version of the Windows Phone 7 OS, which includes features I’ve been wanting, I can take the app in a new direction.  Specifically, it looks like sockets are a “go”, so I can throw in a lot of peer to peer features, such as helping multiple lost people find their way via the application. 

Anyway, go get the freebie goodness. 

author: Angry Hacker | posted @ Saturday, April 23, 2011 5:12 PM | Feedback (8)

10 things to do if you have high cholesterol

Whether you had a heart attack, a bypass surgery, having trouble clearing a flight of stairs or simply have dangerously high cholesterol, there are easy things you can do to get yourself healthier. Much, much healthier.

  1. Watch out for sodium. Most likely your arteries are clogged, your cholesterol is high or some such thing. Sodium contributes to that, massively. You can probably find sodium-free or law sodium replacements for most of the foods that you eat. Case and point, you can get salt-free turkey at pretty much any deli of any supermarket.
  2. Packaged food. Most packaged food contains massive amounts of sodium. Why? Because it allows the food to stay fresher, longer. As an extension to that, it can stay longer on supermarket shelves. Unfortunately, you’ll have to cut it all out. One of the biggest culprits – pretty much every soup sold in the supermarket. So forget Campbell’s, cook your own.
  3. What to eat at fast food restaurants? Contrary to popular opinion, there is some healthy food at the fast food joints. Case and point: Asian Salad at both McDonalds and Jack in the Box. Or Skinless Chicken Breast meal at El Pollo Loco. Or, when at a Subway or any other sandwich shop, ask them to give you wheat bread, forget the cheese, mayo and oils.
  4. Healthy Dining Finder. If you are really in a bind, just hit up the Healthy Dining Finder, enter the zip code and you are in. You’ll be surprised to see how many restaurants offer a somewhat healthy diet.
  5. Cut out the mayo. So the mayo may not be the biggest contributor to your problems but it’s the canary in the mine. Just so that we are on the same page, one mayo packet from a typical fast food joint contains 11 grams of fat and 100 calories (99 of them from fat). And who only gets a single packet? Check out the caloric ratio pyramid for mayo and you’ll see what I mean. So, if you are eating this, you are probably eating other junk as well. Try dropping mayo for just a month and as long as nothing else in your diet changes, you’ll see the dramatic difference in your weight. Go crazy on mustard instead.
  6. Say bye-bye to stressful people in your life. One of the least understood causes of cholesterol and heart problems is stress and yet practically all health care providers, from doctors to nurses, agree, just based on observation, that it’s a major cause. So this is a no brainer – just do it, you’ll be happier for it.
  7. Exercise. Much has been written on this subject over and over again. The only thing I’ll add is that you do not need to run out and get a fitness club membership. Instead, make it a habit to walk about half an hour every day. It’s easy to get started. For instance, instead of driving to lunch, walk there.  Better yet, drive there with coworkers and then walk back on your own with an iPod in tow.
  8. New diet. High cholesterol is likely to cause you some problems, maybe even kill you. That’s not enough motivation? And when I say diet, I don’t mean eat less, I mean eat differently. Dean Ornish, an accomplished researcher in the field of heart disease, has several books on this topic. My favorite is Reversing Heart Disease. It’s almost 20 years old, but really full of information that makes sense today as well. A lot of what he says about food just makes sense. He also spends a lot of ink talking about stress reduction – he does it with yoga and meditation – which is not my bag, baby, but you get the point. The coolest thing about the book are the recipes for healthy meals, which take up good third of it. The bottom line about Ornish’s recommendations: eat as much of vegetables, fruits and grains as you want to. Gorge yourself on strawberries and cherries, if you like them. With the dairy products, moderation should be used. With meats, fish and fowl, avoid as much as you can, if you can’t give them up. And forget about anything commercially prepared (yeah, Campbell soup, I am looking at you), that has more than 2 grams of fat per serving. Try and avoid anything with high-fructose syrup and it wouldn’t be a bad idea to lower your sugar intake too. I know this sounds daunting, but try this: buy yourself a ton of your favorite fruits (like cherries and mangoes) and whenever you are hungry just eat them. Give it a week and see how it feels.
  9. Educate yourself. There ain’t no substitute for knowledge. Don’t walk around carrying ignorance like it’s a badge of honor – it does no one any good.
  10. Medication. Yes, if all else fails, there is always Lipitor. But without other life changes, Lipitor is always fighting an uphill battle. As your doctor will tell you, the medication always works best in conjunction with other life changes.

author: Angry Hacker | posted @ Saturday, April 23, 2011 7:00 AM | Feedback (5)

Experience on the Windows Phone 7 App Store

That’s Not Funny on the Windows Phone 7

After the unexpected success of the ‘That’s Not Funny’ application on the Android platform and its spectacular failure on the iPhone, I thought I’d port it over to Windows Phone 7, and see how it does there.

The application is stupid simple and basically plays various sounds that could be used as a comeback for a bad joke.  As always, the app is free and is ad supported.

Ad Revenues

I released the app on 11/8/2010.  Initially the uptake was slow and the impressions increased over time from about 300 a day at the beginning to an average of a 1000 a day around DecemAber.  The ad revenues were about a dollar a day until about 12/18/2010.  Then, inexplicably, the revenue tripled even though the impressions remained the same.  Since then the impressions picked up a bit and so have the revenues.

So far, the application has made $99 in ad revenues, which basically covers my App Store fee. 


In addition, the application did pretty ok in the charts.  It reached #21 in the Entertainment category and #227 overall towards the end of year.   Currently, as of writing, it is #54 in Entertainment and #367 overall. 

Development Experience

Despite the app being pretty simple, there were a couple of things to learn.  I had to figure out how to use the List control, which is more complicated than it needs to be and really requires the Silverlight Toolkitgesture APIs to be useful.  In addition, there were the Media, Resources and Advertising APIs to pick up.  The emulator is significantly different from the devices, in particular, users reported that sounds loop, which never ever showed up in the emulator.  However, these are all small, easily fixable issues.

I’ve developed apps for iOS, Android and BlackBerry before jumping on WP7 platform.  I have to say that Microsoft created a really fun development environment.  It is far easier to develop on it than any of the competitors.  It’s going to be successful.

author: Angry Hacker | posted @ Saturday, January 08, 2011 1:19 AM | Feedback (0)

My iPhone 3GS is now faster

After I upgraded my phone to iOS 4.x, it felt slower.  Not outright slow, but a bit sluggish here and there.   I chalked it up to the upgrade and just lived with it. 

Last week, my cable modem internet connection went out.  In blind panic, I decided to jailbreak the phone, purchase MyWi and use it to tether my laptop.  The jailbreak did not go so well.  For one the version of Cydia that is installed is actually for the wrong OS and won’t even run.  I am stunned that the jailbreak is even being offered – it is so useless.

So I tried to reverse the jailbreak, which made things even worse – my apps would not sync, the iPod app would not even start, the settings would not “take”, etc…complete mess.  I tried to restore from backup – it did not help.  So I figured I’ll just start from scratch. 

I restored the OS and when asked which backup to use, I selected no backup – in other words, a new iPhone.  And that is what I got.  After that I was able to sync all my apps, music, podcasts, photos, contacts, etc....  There was a bit more work setting up the email, but that’s about it.

The greatest thing about this is that the phone is really snappy now – it’s like I removed all the cruft it’s been saddled with.  Feels new.

author: Angry Hacker | posted @ Tuesday, December 28, 2010 10:20 PM | Feedback (0)

Building a robot.

I’ve been wanting to a build a robot for a long time.  The problem is that I can’t do hardware: when someone says, “well, just drop the electricity down from 5 volts to 3.3”, I am like what???  So when I saw the Robot Kit that can be programmed with a .NET MicroFramework, I knew I had to have it.  But I want more than just a disconnected programmable robot.  I want one that’s connected to the world.  I was inspired by brilliant folks at anybot.com and a belief that I can build one for a fraction of the $15k they want for theirs.

So to that end, my first project is to build a robot that’s can be controlled from the browser.  To make that happen, I needed the following:

  1. The Robot Kit – purchased.
  2. A Wi-Fi board – purchased.
  3. A working, really low level, Web Server – more on that later .
  4. A web app that’s served from the flash on the Robot Kit.

So a week ago I got the Robot Kit in the mail.  I put it together in about 20 minutes.  Installed all the necessary software (e.g. drivers, Visual Studio 2010, .NET MicroFramework, GHI Electronics libraries for the their chip).

Next, I plugged the robot in, created a small program (mostly taken from sample code), deployed it to the robot and let it fly. Here are the results of my effort.

First Robot Demo
Technorati Tags: ,,

author: Angry Hacker | posted @ Saturday, October 02, 2010 6:26 PM | Feedback (0)