Monday, April 24, 2006

Vim, addictive insanity?

For reasons beyond my understanding I have started to do a heavy amount of editting with G/Vim again. It's a drift back into my college days where strange incantations of *nix, Emacs and Vim were a daily fact and joy of life. Recently I found some add-ins for Visual Studio that enable most Vim bindings inside of Visual Studio. And thus the slide into no mouse edits continues

"ay$

Thursday, April 20, 2006

Getting a Haircut

I have a very simple hair cut; clippers at 3/4 inch. Trust me it's not a very difficult hair cut and in fact I do it myself almost all of the time. Yesterday I decided that a professional should do it every now and again. So I hopped over to a local shop during my lunch break.

Sat down and told the person the hair cut I wanted. They were quite surprised and questioned if I really wanted a 3/4 inch cut. I understood because it was a while back that I last cut my hair and it was around 2 inches at this point. After relating this information they didn't seem to believe me and brought out the guard. I confirmed that's the one I wanted and they set out to work.

A bit later I was quite curious why the clipper's didn't run over the top of my head. The barber started with scissors instead. Not terribly disturbed by this I said nothing. To my shock they shortly later informed me they were done. The hair on the top of my head was clearly longer than the sides.

I told them to take it down some more and that I wanted it all the same length. They agreed but still used the scissors!!! The barber informed me that they didn't like to use clippers on the top of heads. Whatever, just get the haircut right. Several minutes later they pronounced me done.

Can you guess? Yes, the hair on top of my head was still longer. Even worse, I could tell the hair at the backside of the top of my head was even longer. So now I have 3 lengths of hair 3/4 sides, 1 inch top and 1 1/2 inch top back. I paid and left before they could add a few more random lengths. I finished the job this morning with my own clippers.

Why on earth won't they just use the clippers!!! It's so simple.

Wednesday, April 19, 2006

Thread Security changes in 2.0

While I was looking into CAS changes in 2.0 I found some very good news about thread changes in 2.0.  In .NET 2.0 both Thread.CurrentPrincipal and the Thread Impersonation token are now propagated amongst threads including ThreadPool.QueueUserWorkItem.  The latter was a great pain to developers in .NET 1.0 particularly because Thread.CurrentPrincipal did not propagate and it created a lot of funny code to deal with the CAS impacts. 

This MSDN article delves into these changes.  http://msdn.microsoft.com/msdnmag/issues/04/11/NETMatters/

Monday, April 17, 2006

Viability of Recycling

A lunch a few days ago, a co-worker mentioned watching a show that discussed the viability of recycling from both an economic and environmental standpoint. The show reported that excluding aluminium recycling was neither economically or environmentally viable for any other material. Quite a bit surprised I did some research of my own and found out that the show is working from a lot of factual data (couple of quick links below).

Recycling in a vacuum is obviously good for the environment. But the focus of the show is that most people don’t consider the cost of what happens behind the scenes of recycling. The major factors are ...

  • Cost of gathering the recycled goods
  • Amount of polution created by gathering the recycled goods
  • Viability of recycling individual materials. For intstance, plastic is a tricky product to recycle and can only be mixed in certain ways
  • Several types of recycling, i.e. paper, create new forms of waste that also must be transported and disposed of
  • The overall percentage of consumers willing to take the time to properly sort out their recycling is too low

Aluminum recyling does seem to be a huge win for both parties. For instance it is a relatively light material that does not have to be separated as carefully other materials (say plastic). Also their is a huge cost savings to the manufactures because they can create a recycled aluminum can for less than 10% of a new can. The first link above stastes that 95% of all cans are now made from recycled material

Interesting research topic to say the least.

Thursday, April 13, 2006

Follow up: PInvoke with 32 and 64 bit

Recently after I made my original post titled “PInvoke with 32 and 64 bit”, a developer emailed me. They pointed out that there is an internal structure that dynamically resizes based on the architecture; IntPtr. IntPtr will be size of the native chip pointer value. So for values like size_t that map to the pointer size, you can use the Address field of IntPtr.

This approach has some small down sides.

  1. The type you are marshaling must have the same size as IntPtr for all of the architecture's you run on
  2. If you expose an interop API that uses IntPtr in this manner, you have to find a good way to inform your users that they really need to pass the value in the address of the IntPtr

A way to get around #2 is to define your own type (like I did with SizeT) and just wrap an IntPtr. If you have no other fields in your type it will Marshall like an IntPtr. You can provide friendly properties that assign values into the IntPtr's Address property.

If you have a type who's size does not change in the same way as IntPtr then you'll probably have to go the custom marshal route

Wednesday, April 12, 2006

Chat with the Encarta Bot

There is a MSN Messenger bot for Encarta online.  It’s quite fun to chat with for a bit.  Unless you’re questions are very direct it’s not that helpful though. 

PInvoke with 32 and 64 bit machines

One of the big difficulties still remaining in .NET 2.0 is the interoping with native API's which takes in types that have different sizes on 32 and 64 bit machines. For most API's this is not a problem. But for many, including most of the memory API's for example, the signature is technically different from 32 to 64 bit with respect to parameter size.

The problem occurs if any of the API’s parameters have a different size on 32 and 64 bit.  IMHO, most common Win32 API parameters are composed of types that do not have different sizes on 64 bit (DWORD, UINT, LONG, etc …).  The biggest culprit for me has been size_t.

Unfortunately there is no predefined solution for these types in .NET 2.0.  So one has to be devised.  The biggest issue is that you typically run the same .NET binary or 32 and 64 bit.  So we need a type whose size is determined at runtime based on hints from the platform.  Defining a type like this just isn’t possible with .NET.  The best recourse is to define a fixed size type and a custom marshaler that will make the runtime size decision. 

As a proof of concept I added a type SizeT to my interop library and a custom marshaling class to do the dirty work for 32 and 64 bit platforms.  Here are the definitions. 

 public sealed class SizeT
 {
  private ulong m_value;

  public ulong Value
  {
   get { return m_value; }
   set { m_value = value; }
  }

  public SizeT(ulong val)
  {
   m_value = val;
  }

  [SuppressMessage("Microsoft.Usage", "CA2225")]
  public static implicit operator SizeT(ulong value)
  {
   return new SizeT(value);
  }

  [SuppressMessage("Microsoft.Usage", "CA2225")]
  public static implicit operator ulong(SizeT value)
  {
   return value.Value;
  }
 }

 public sealed class SizeTMarshaler : ICustomMarshaler
 {
  [SuppressMessage("Microsoft.Usage", "CA1801", Justification="data parameter is a hidden requirement of the API")]
  public static ICustomMarshaler GetInstance(string data)
  {
   return new SizeTMarshaler();
  }

  #region ICustomMarshaler Members

  public void CleanUpManagedData(object ManagedObj)
  {
   // Nothing to do
  }

  public void CleanUpNativeData(IntPtr pNativeData)
  {
   Marshal.FreeCoTaskMem(pNativeData);
  }

  public int GetNativeDataSize()
  {
   return IntPtr.Size;
  }

  public IntPtr MarshalManagedToNative(object ManagedObj)
  {
   SizeT value = (SizeT)ManagedObj;

   IntPtr ptr = Marshal.AllocCoTaskMem(IntPtr.Size);
   if (IntPtr.Size == 4)
   {
    Marshal.StructureToPtr((uint)value.Value, ptr, true);
   }
   else if (IntPtr.Size == 8)
   {
    Marshal.StructureToPtr(value.Value, ptr, true);
   }
   else
   {
    throw new ArgumentException("Invalid Pointer Size");
   }

   return ptr;
  }

  public object MarshalNativeToManaged(IntPtr pNativeData)
  {
   if (IntPtr.Size == 4)
   {
    uint val = (uint)Marshal.PtrToStructure(pNativeData, typeof(uint));
    return new SizeT(val);
   }
   else if (IntPtr.Size == 8)
   {
    ulong val = (ulong)Marshal.PtrToStructure(pNativeData, typeof(ulong));
    return new SizeT(val);
   }
   else
   {
    throw new ArgumentException("Invalid Pointer Size");
   }
  }

  #endregion
 }

 

There are two ways to determine if your interop API's are affected by the move to a 64 bit platform.

  1. Brute Force. Find all of the native types that you use and determine if there are different on 64 bit
  2. Turn on FxCop Portability rules and it will catch the majority of your errors.

Tuesday, April 11, 2006

Cross Posting Test

This is my first attempt at cross-posting to multiple blogs.  Sorry for the spam.

Monday, April 10, 2006

Conflicting documentation for HeapCreate

Yet another reason to enable FxCop is it double checks some interop defines (Portability and Interop groups). After enabling FxCop on one of my home brewed interop libraries I was surprised that it complained I had some 64 bit portability problems with my HeapCreate and other Heap* API's.

This API in particular caught me off guard because I did a 64 bit portability check of my interop library recently I specifically looked up that function. I verified that Heap* used DWORD's for sizes which compile to 32 bit numbers on 64 bit.

After the FxCop warning I took yet another look and sure enough HeapCreate is defined to take in DWORD's.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/wcekernl/html/_wcesdk_Win32_HeapCreate.asp

However in my experience FxCop is generally correct if a bit paranoid in places. After confirming it caught slip ups in a different interop API I decided to triple check my Heap* definitions. When in doubt go to the source (winbase.h in this case). Sure enough FxCop is correct and msdn is wrong. Doing a more refined search I found that the correct documentation is available on windowssdk.

http://windowssdk.msdn.microsoft.com/library/default.asp?url=/library/en-us/memory/base/heapcreate.asp

I consider this further proof that FxCop is a great tool that should be used for any library development (home and most especially professionally).

In retro-spec if you take a very close look at the first link you'll notice it's actually the API for WinCE. I find it strange that it turns up higher in search results that the normal documentation.

Lessons in Code Access Security: PropertyGrid

I've started experimenting with Code Access Security at home. This derives from my desire to better understand .NET security and my recent fascination with ClickOnce applications.

This weekend I learned a hard lesson in security. I have a couple of ClickOnce apps. ClickOnce Visual Studio integration has a great feature that will root around in your code and attempt to determine the minimal permission set needed to run your application.

I started playing with this on one of my relatively simple applications. It contains several forms and opens up a couple of WebRequest objects but nothing terribly special. However the analysis said that my app needed to run with Full Trust (highest level). Unfortunately the app did not provide any more information besides that.

It took an hour of rooting around but in the end I discovered the culprit was the PropertyGrid instance on my form. It turns out that the PropertyGrid requires "Full Trust" to be used even though it's not noted in the documentation.

Thursday, April 06, 2006

Simple Things


Sometimes it's the simple things. Several times when coding Winforms apps I've run into a situation where I need to know the current state of the mouse or keyboard. It's one of those tasks that for some reason I am unable to get a hit on a search engine.

Fortunately though the information is quite easy. You can access the current state of the keyboard or mouse at any time via the static methods on the Control class


  • MousePosition

  • MouseButtons

  • ModifierKeys

Sunday, April 02, 2006

Funny Watson Picture


DSC00528
Originally uploaded by jaredp110680.
Snapped some pictures of the dogs before I left for work on Thursday. This picture I got of Watson is hillarious.

Hot Sauce Lesson Learned

Although this should be an obvious lesson, never get hot sauce in your nose.

No, I didn't decide to snort hot sauce or any variant of that. Instead I was eating a pork chop with hot sauce and while I was chewing had a sudden half sneeze. This sent a spray of sauce backwards through my nostril. Let me tell you that it was fairly unpleasant for a good 10 minutes.