Sunday, July 10, 2011

Bitmap Mapping

Between a busy job, house hunting and a much needed vacation I've fallen out of the habit of blogging. My first post back I want to talk about an undocumented feature for LINQ to LDAP and why I'm thinking of removing it.

Currently LINQ to LDAP supports mapping images stored in a directory as Bitmaps. I thought this was cool since all you had to do was map it with an image type and it just worked (updates as well in the new 2.0 changes). However, I've left it undocumented since Bitmaps use GDI+ and if you're not careful you can introduce a memory leak. Imagine blindly querying for all users in your directory and suddenly there's 10,000 (assuming you're in a large organization or university) bitmaps being loaded up.

So if this feature gets removed here is how you could still support images:

[DirectorySchema("OU=Users,DC=mycompany,DC=com", ObjectClass = "User")]
public class User : IDisposable
{
     [DirectoryAttribute("Photo")]
     public byte[] PhotoBytes { get; set; }
     
     private Bitmap _photo;
     public Bitmap Photo
     {
          get
          {
               if (PhotoBytes == null) return null;
               
               if (_photo == null)
               {
                    _photo = new Bitmap(new MemoryStream(PhotoBytes));
               }
               return _photo;
          }
          set
          {
               if (_photo != null) _photo.Dispose();
               if (value == null)
               {
                    _photo = null;
                    PhotoBytes = null;
               }
               else
               {
                    _photo = value;
                    using (var stream = new MemoryStream())
                    {
                         _photo.Save(stream, ImageFormat.Png); //whatever format
                         PhotoBytes = stream.ToArray();
                    }
               }
          }
     }

     public void Dispose()
     {
          if (_photo != null) 
          {
               _photo.Dispose();
               _photo = null;
          }
     }
}

So is this even a big deal? Will anyone care if I removed bitmap mapping?

No comments:

Post a Comment