64 Bytes

just a few characters short of a code base.

Making a “zoom to image” double click with Seadragon AJAX. (Part 1-The Problem)

clock December 21, 2008 04:05 by author josh

   Recently Microsoft released its deep zoom technology implemented in JavaScript using Ajax.  Using the Deep Zoom Composer I made a quick composition with it to test it out.  Part of this was random curiosity and part was because I was actually looking for something like this to build a High Res photo album.

   While things are very intuitive as you could click to zoom in, use your scroll wheel to zoom in or out, pan with a mouse drag etc.. A feature that seemed very obvious (especially for photo albums) was some kind of “Zoom to fit” feature.   My thought was, if I double click on  specific picture in my gallery then I want to zoom that image to fit the screen..  Double click again should zoom me back out.

While this idea seems simple there are actually a few challenges that must be dealt with Like:

  • Event wiring isn’t obvious at first (thank you Aseem Kishore at MS for pointing me in the right direction)
  • Seadragon doesn’t know there are multiple images. All it does is manage zooming and scrolling on a large canvas. 
  • There are event collisions due to single clicks firing with double clicks.
Before we dive into all of the issues let’s take a look at what we want things to look like when we are done.. The below example will allow you to do all the normal Sea dragon things (single click zoom, scroll zoom, pan, full screen, etc) and  it will let you zoom to fit any photo by double clicking on it.. And you can Zoom back out by double clicking again.


Now that we know the problem and we see how the solution works let’s talk about how we got here. Basically there are 4 steps..
  1. Compose a deep zoom composition and export it to Seadragon Ajax & update the export to use the current Seadragon API.
  2. Override Seadragon’s Mouse events in JavaScript
  3. Map all of the images using Seadragon’s coordinate system
  4. Build a way to detect and manage double clicks.
So in the next post  I’ll take you thru getting all setup and having a sample composition ready and running locally in your own web browser.



www.delphiquery.com - Because everyone should write at least one "toy" app :-)

clock November 24, 2008 05:10 by author josh

I'm pleased to announce this "toy" app a friend and I wrote.. www.delphiquery.com. The app is pretty strait forward. A person asks a question and its voted on for a few minutes. The results are then emailed back to them once the poll closes (currently 5 ~ 10 minutes).  

The REAL reason we wrote this little app was to play with MVC and LINQ to SQL. I have to say the experience was very pleasent.. the Jquery ajax calls worked easy to build, and it was so VERY nice to actually know my client IDs inside my HTML . Also With a little bit of routing voodoo we got it to do some interesting things routing wise for having all of our controller actions ALSO available via JSON or XML as API calls.

I'll post more about the whole Actions as API techniques later. But for now.. Here it is, as silly as they come.. 



Need more Flags

clock September 5, 2008 04:33 by author josh

Right, so first off I am no great fan of having 10,000,000 flags.. But sometimes you run into a situation where you need to pass around a datastructure with ump-teen million flags so you end up turning it into an enum of type flag and doing bitwise OR and AND to  to operate on your flags something like

enum Flags
{
    FLAG1 = 1,
    FLAG2 = 2,
    FLAG3 = 4
}

And somewhere in your code you would have

Flags myCurrentVal = Flags.FLAG2;
bool Method HasFlag(Flags enum)
{
   return ((enum & myCurrentVal) != 0)
}

Ok sure, that works and it doesn't suck to bad.. but it has limitations.. First off, you can only have 32 or 64 flags (depending on int or long) in your enum.. Not a big deal unless you are doing something like field level security on a very complex form that includes workflow. And frankly while simple to use these things always make some on the team roll there eyes and "Dear god, no more bitwise logic"..

So in an effort to help my flag loving client have flags and my bitwise hating teammates not have to deal with & and | more than they have to I threw togeather an flag class that will support up to Int32.MaxValue flags (not wise, but it would handle it).

So here is the flags base class, its a generic base class that takes an enum in its inherited implementation

public abstract class  FlagsBase where T : struct
    {
        private bool[] _SetFlags;
        private int _flagLength;
        public int FlagLength
        {
            get { return _flagLength; }
        }
        public FlagsBase()
        {
            Type enumType = typeof(T);
            if (enumType.IsEnum)
            {
                int length = getFlagsLength(enumType);
                _SetFlags = new bool[length];
                for (int i = 0; i < _SetFlags.Length; i++)
                {
                    _SetFlags[i] = false;
                }
                _flagLength = length;
            }
            else
            {
                throw new ArgumentException("The Generic type of " + typeof(T).ToString() + " is not an enum. This base class only supports enums.");
            }
        }

        protected int GetFlagInt(T flag)
        {
            return (int)Enum.Parse(typeof(T), flag.ToString());
        }

        public bool GetFlagValue(T flag)
        {
            int flagval = GetFlagInt(flag);
            if (flagval <= _SetFlags.Length)
            {
                return _SetFlags[flagval];
            }
            return false;
        }

        public void SetFlagValue(T flag, bool newValue)
        {
            int flagval = GetFlagInt(flag);
            if (flagval <= _SetFlags.Length)
            {
                _SetFlags[flagval] = state;
            }
        }

        public T Flag(int position)
        {
            return (T)Enum.ToObject(typeof(T), position);

        }

        private int getFlagsLength(Type enumType)
        {
            return Enum.GetValues(enumType).Length;
        }
    }

So what we have here is a generic class that takes an enum as its type. So you make an enum and the length of that enum is used to create a private bool[].. Now each value in the enum becomes a point in the array and has a bool to back it. Easy sleasy as I like to say.

If I want to add new values to my flags set, I just add them to the enum and everything just keeps on working. Here is an example implementation and "use"

enum WebUI_FIELDS
{
   field1,
   field2,
   field3,
   field4,
   field5,
   field6,
   field7,
   field8,
   field9,
   field10,
   field11,
   field12,
   field13,
   field14,
   field15,
   field16,
   field17,
   field18,
   field19,
   field20,
   field21,
   field22,
   field23,
   field24,
   field25,
   field26,
   field27,
   field28,
   field29,
   field30,
   field31,
   field32,
   field33,
   field34
}
public class WebUIFieldSecurity : FlagsBase
    {
        public WebUIFieldSecurity ():base()
        {
        }
    }

And using it may look something like this

void SetupSecurity(IPrincipal user)
{
   WebUIFieldSecurity mysec = new WebUIFieldSecurity();
   if(user.IsInRole("UseField1"))
   {
       mysec.SetFlagValue(WebUI_FIELDS.field1,true);
   }
   SetupPageSecurity(mysec);
}
void SetupPageSecurity(WebUIFieldSecurity sec)
{
     field1.ReadOnly = sec.GetFlagValue(WebUI_FIELDS.field1);
     field2.ReadOnly = sec.GetFlagValue(WebUI_FIELDS.field2);
     field3.ReadOnly = sec.GetFlagValue(WebUI_FIELDS.field3);
     field4.ReadOnly = sec.GetFlagValue(WebUI_FIELDS.field4);
}

See how nice and easy that is.. And readable.. Personally I like readable.. and If I need to add more flags, I just grow my enum.. no worring about bit masks, using Hex numbering to set my flags to the right values or being limited to less than 100 flags.. Granted if you need more than 64 flags then things may be a little crazy already. But one never knows, and at least with this you won't care :-).



Context Singletons

clock September 1, 2008 05:27 by author josh
So more often then not I want to share something in a "singleton" fashion across a call stack. But a true singleton wouldn't work because the objects I want to share are usually not thread safe or its not a best practice to persist them across threads. NHibernate has a Session manager pattern that is very similar to what I want and so I extended on that principal making what I call a "Context" Singleton.  Its simply just a little base class that will store itself in right context and as such will also "die out" once that context has ended.

Here is the helper class


public abstract class ContextSingletonBase: IDisposable
    {
        private static string CONTEXT_PREFIX = "ContextSingleton:";

        protected static object _getObject(string key)
        {
            if (isWCF)
            {
                return WcfInstanceContext.Current.Items[ContextSingletonBase.CONTEXT_PREFIX + key];
            }
            else if (isHttp)
            {
                return System.Web.HttpContext.Current.Items[ContextSingletonBase.CONTEXT_PREFIX + key];
            }
            else
            {
                return CallContext.GetData(ContextSingletonBase.CONTEXT_PREFIX + key);
            }
        }
        protected static void _setObject(string key, object obj)
        {
            if (_getObject(key) != null)
            {
                if (isWCF)
                {
                    WcfInstanceContext.Current.Items.Remove(ContextSingletonBase.CONTEXT_PREFIX + key);
                }
                else if (isHttp)
                {
                    System.Web.HttpContext.Current.Items.Remove(ContextSingletonBase.CONTEXT_PREFIX + key);
                }
                else
                {
                    CallContext.SetData(ContextSingletonBase.CONTEXT_PREFIX + key, null);
                }
            }

            if (isWCF)
            {
                WcfInstanceContext.Current.Items.Add(ContextSingletonBase.CONTEXT_PREFIX + key, obj);
            }
            else if (isHttp)
            {
                System.Web.HttpContext.Current.Items.Add(ContextSingletonBase.CONTEXT_PREFIX + key, obj);
            }
            else
            {
                CallContext.SetData(ContextSingletonBase.CONTEXT_PREFIX + key, obj);
            }
        }
        private static bool isWCF
        {
            get
            {
                return (WcfInstanceContext.Current != null);
            }
        }
        private static bool isHttp
        {
            get
            {
                if (isWCF)
                {
                    return false;
                }
                if (System.Web.HttpContext.Current != null)
                {
                    return true;
                }
                return false;
            }
        }
        internal class WcfInstanceContext : IExtension
        {
            private readonly IDictionary items;

            private WcfInstanceContext()
            {
                items = new Hashtable();
            }

            public IDictionary Items
            {
                get { return items; }
            }

           public static WcfInstanceContext Current
            {
                get
                {
                    if (OperationContext.Current != null)
                    {
                        WcfInstanceContext context =
                            OperationContext.Current.InstanceContext.Extensions.Find();
                        if (context == null)
                        {
                            context = new WcfInstanceContext();
                            OperationContext.Current.InstanceContext.Extensions.Add(context);
                        }
                        return context;
                    }
                    return null;
                }
            }

           public void Attach(InstanceContext owner) { }

           public void Detach(InstanceContext owner) { }
        }

        #region IDisposable Members

        public void Dispose()
        {
            _dispose();
        }

        protected abstract void _dispose();

        #endregion
    }


 So you will notice I test for several contexts.. This is because going down to CallContext is not always safe.. First off for Http Applications the executing thread can actually change.. If it changed and you weren't using HttpContext you would end up loosing your ContextSingleton. (Granted HttpContext is infact using CallContext at its core, using HttpContext will handled that potential thread switch out for you).  I also check for a WCF context.. This is because (and I'm not 100% sure about this) WCF services are handled diffrently depending on the connection point. Using the WCF Context instead of CallContext removes any "wierdness" that may occure.

So this was just a base class and on its own missing the "Singleton" part of the whole design.. Its mostly intrested in the storage of said singleton and not the actual access or storeage of it. So what does an Implemented Context Singleton look like?

Well here is an overly simple one that stores a Linq2Sql Data Context... you can see the pattern is pretty much pure "singleton" but instead of the Instance being a static field its a property and it calls back to the above static classes that then look in the approproate context for the actual instance of the helper.. In this way your interact with the class as if it were a traditional singleton but it only persists inside its appropriate context (Http, WCF or Call)..



  public class Helper:ContextSingletonBase
    {
        private static string KEY = "SingletonKey";
        public static Helper Instance
        {
            get
            {
                Helper h = GetHelper();
                if (h == null)
                {
                    h = MakeHelper();
                }
                return h;
            }
        }

        private static Helper MakeHelper()
        {
            Helper h = new Helper();
            Helper._setObject(Helper.KEY, h);
            return h;
        }

        private static Helper GetHelper()
        {
            object helper = Helper._getObject(Helper.KEY);
            if (helper != null)
            {
                return (Helper)helper;
            }
            return null;
        }

        private DataContext _dc;
        public DataContext DC
        {
            get
            {
                if (_dc == null)
                {
                    _dc = new DataContext();
                }
                return _dc;
            }
       }

        protected override void _dispose()
        {
            _dc.Dispose();
        }

}


One thing I would love to do is actually replace the Contexts code I have with some kind of provider model.. Use a bit of code (or settings) to detect the approriate context and return that.. That way the ContextSingletonBase wouldn't have to be depended on .NET 3.0 (like it is now) and its code wouldn't grow in complexity as other contexts become known (I only did this for Call, Http and WCF because those are the only contexts I've run into and Call is kind of the catch all.. But who knows, Silverlight might have its own... .NET compact framework might have one, etc... you can see how seporateing the context storage from the ContextSingleton helper could become a good thing..



I still ♥ Ruby on Rails...

clock May 20, 2008 07:23 by author josh

Over the summer I finally dug into this whole "MVC" thing for web development. Naturally I began with the Mecca of them all Ruby on Rails.  This was a twofold learning experience for me..  First off it was Ruby a meta-language that bends like read in the wind.  And second was Rails, the darling framework that seems to have been sent by the demi-gods of software to help all suffering web developers.

But all of this joy was not without its flaws. Ruby is (as I mentioned before) all but un-deployable on a windows platform. After all Ruby is a single threaded/multi-process language (great for Unix where you don't actually have threads). But this limitation makes it an un-workable option on a windows box. Since then I have dug into Monorail, and now am neck deep in ASP.NET MVC. Heck I'm even a committer on the MVCContrib project. And while these projects are great they are still missing some magic. 

In short I still have stars in my eyes when I think of RoR.. This brings up the question, Why? (ya simple question).  I've been thinking about this a bit and I think (for me) the issue boils down to just a few issues.

First off is the RoR mantra "Convention over Configuration".  This mantra is actually quite deep; and while it can be a touch annoying at times (class naming can get silly) it's actually insanely smart. I have probably downloaded 15 different rails projects and had a working knowledge of the app and how to tweak each one in less than an hour. This is because the sites structure is described 1 way and 1 way only. More over I have been able to hand over projects in no time flat. In short, getting up to speed on a rails project is a no brainer.  ASP.NET MVC missed the mark on this in a big way in my book. MS, wisely from an OO perspective, laid everything out in a strong override-able and design. If you don't like routing, just implement a new router, don't like the view engine, just replace it. MVCContrib continued this with implantations of DI containers like Winsor, Structure Map, etc.. To muddy the situation further, MVCContrib implements multiple View Engines allowing developers to choose between ASPX, NHTML, NVolocity etc.. With all of that we diverge from Convention, and in doing so remove elegance for the privilege of flexibility (* Flexibility I am sure I will be thankful for when I migrate some of my Monorail apps to ASP.NET MVC over the summer).  Monorail is also bad about this (although not as much) with multiple view engines and a solid OO framework; but monorail has a community that has become kind of set in their ways. And so, while not set in stone, some conventions have settled in.  But going back to the rails mantra "Convention over Configuration"; nether ASP.NET MVC or Monorail prescribe to this philosophy more over they are the opposite "Here's a convention, but here are 108 tools to ignore it with " (I jest). 

    The second great feature of rails is the data model versioning and deployment methodology. You want a new data model, you add a new class to your data model describing the changes. Deploy the new version to your dev db, then code. Once your are done you run your deployment in test, evaluate your unit tests and push to prod; all very elegantly and with little effort. Linq for SQL has a great model but you design the app to the data (pulling your object structure from your tables) not the other way around.. So the same model change in Linq starts at the DB (with change scripts so you can manually run them in test and prod later) then re build your mode, code, test, run scripts in test, run unit tests, and deploy using your ant script that took 2 days to write. That's a lot of work and unfortunately Castle active record isn't much better.

    No don't get me wrong I really enjoy using Monorail and ASP.NET MVC has real promise. But when you take these three MVC frameworks and you look at developer efficiency and experience RoR is closest to my heart!



Linq Abstraction Screencast (or My first screencast, hope you like it).

clock December 16, 2007 07:52 by author Josh

Here it is, My first screencast. Like I pomised this screencast is about abstracting Linq Providers so that you can use what ever provide you want and keep your Business layer igorant.

(By the way, this i my first screencast, so no promises about quality. Oh and sorry for the annoying watermark. I know how to turn it off for the next screencast).



Abstracting your Linq so it can be come one with IOC.

clock December 13, 2007 01:22 by author Josh

Last night I sat down and played with how I could abstract my linq so I could use any provider I wanted. This has been a common request on some of the forums I've been reading and so I figured I would give it a shot. Now this post is just a teaser, I am going to use this topic as my first screencast so expect that to show up here sometime this weekend.

Goals for my experiment (or what I'll be doing in my screencast):

  1. Allow multiple diffrent providers (save Linq to XML due to casting constraints in Linq to XML) to expose the same objects up to a single business class
  2. Make a factory where by settings could be uses to pass the correct provider to its caller such that the caller is provider ignorant about the Linq it is using.
  3. Validate that there are no obvious performance hits caused by this (Most importantly tha linq to SQL doesn't do something "wacky" that caues it to speu crazy SQL rather than sain SQL).

I am happy to say I achived all of these goals, and now you'll just have to wait to see how :-)..



64bytes.com is now running BlogEngine.NET

clock November 22, 2007 18:04 by author josh

Nothing to major here, just made a move to use the BlogEngine.NET from using SUBTEXT. This will include a few minor visual changes, but most everything was under the hood ;-).

The biggest pain was mapping all the old posts to the new permalink format. This entailed a bit of hackery to the 404 page so that I could map all of the old posts to there new URLS.

The main cause for the change was so that I could use a blogging client to write my posts. As I am (in theory) going to start doing weekly screen-casts; I figure a little better posting experience was a good thing



System.Web.MVC + DLR + Linq = Rails killer?

clock October 11, 2007 16:33 by author josh

     Looks to me like Microsoft isn't taking the whole Rails movement lying down. First off they have IronRuby. But why stop there? I just read thru and watched the screencasts from the MVC demo at Alt.Net (click here to watch them, and yes you do want to read and watch them!) and I have to say I am quite impressed.

      It really does look like the boys at MS realized that RoR and Monorail and other MVC platforms brought a real value add for some (in my book many) web development scenarios and as such are moving to Microsoft the Web MVC development experience. Now add in the DLR (I do love what it can offer because I have become a big fan of Dynamic languages) and top it off with LINQ (or DLINQ) and you have a very compelling argument to develop your next RoR or Monorails app using all microsoft goodness.

   So the good and bad of it for me..

The good: Microsoft level of dependability, scaleability, performance, etc..

The bad: I want all my projects on one platform. I really don't want to mix and match my apps between MonoRail and System.Web.MVC and RoR! One MVC to rule them all Damnit!!!!! Its an in-determinit amount of time away (the Screencasts are of an internal experimental build).



Ktomics has a new site.

clock October 1, 2007 08:21 by author josh

In an effort to become more of a company and less of a "shop", we have developed and deployed a new site for Ktomics.. The new site also has our new logo and tag line :-).. Its pretty nice (if I do say so myself), so check it out :-).. www.ktomics.net.

(oh a techical note on the products. Gift Scanner is about 90% complete with eval/alpha versions in field testing. Gift Scanner is written with a .NET client and .NET/MonoRail on the server side. Given my problems with RoR for Windows I have made the transition to MonoRail for projects moving forward. Passvault is running on a cluster of Mongrals and is still a Ruby on Rails application).




Calendar

<<  March 2010  >>
MoTuWeThFrSaSu
22232425262728
1234567
891011121314
15161718192021
22232425262728
2930311234

View posts in large calendar

Add to Technorati Favorites

Sign in