New Blog Up

by rsutton 17. March 2010 23:59
I've never liked the fact that my domain randallsutton.net has the suffix .net instead of .com, so I've decided to move my blog to a new domain I aquired a while back randallbits.com.  I'm going to try and import all my posts and redirect all the links, but for now you can update your readers and such.

Tags:

Development | IT | Misc

Can you solve this?

by rsutton 22. January 2010 07:27

There is an interesting problem I solved today that I thought I might share.  The basic idea can be solved by figuring out how to solve the following problem.


Consider this JavaScript
funcs = []
for(var i=0;i<10;i++)
       funcs[i] = function() { alert(i); }
funcs[4]();

This will alert "10".  Can you change it to alert "4"?  The key to solving this problem is being able to create a function that stores i and then will evaluate the alert later.

Also
funcs[0] alerts "0"
funcs[1] alerts "1"
...
funcs[9] alerts "9"

Get the idea?  Good luck!

Tags:

Development

Get Values Out of a Dictionary Using Reflection in C#

by rsutton 6. January 2010 04:41

As part of the project I’m currently working on I had the need to get all the values out of a dictionary without the benefit of typing, so I had to use reflection.  Here is the best was I’ve been able to come up with and hopefully it is useful to others.

    1 

    2 private void GetDictionaryValues(object obj)

    3 {

    4     var t = obj.GetType();

    5 

    6     // Handle dictionaries.

    7     if (typeof(IDictionary).IsAssignableFrom(t))

    8     {

    9         // Get the methods we need to deal with dictionaries.

   10         var keys = t.GetProperty("Keys").GetGetMethod().Invoke(obj, null);

   11         var item = t.GetProperty("Item");

   12         var enumerator = keys.GetType().GetMethod("GetEnumerator").Invoke(keys, null);

   13         var moveNext = enumerator.GetType().GetMethod("MoveNext");

   14         var current = enumerator.GetType().GetProperty("Current").GetGetMethod();

   15 

   16         // Get all the values.

   17         while ((bool)moveNext.Invoke(enumerator, null))

   18         {

   19             var key = current.Invoke(enumerator, null);

   20             var value = item.GetValue(obj, new object[] { key });

   21 

   22             // Do Stuff.

   23         }

   24     }

   25 }

   26 

Tags:

Development

Better JavaScript Object Creation

by rsutton 30. December 2009 06:36

So I’ve decided that I don’t like the two general ways of creating objects in JavaScript so I’ve decided to create my own.  This one is partially inspired by ruby :)

    1 

    2 Hello = function() {

    3     return {

    4         new: function(a,b) {

    5             return {

    6                 one: a,

    7                 two: b,

    8                 talk: function() {

    9                     alert('hello: ' + a + ' ' + b);

   10                 }

   11             };

   12         }

   13     }

   14 }();

   15 

I am using the object literal notation to create the object.  Generally this notation works well until you want multiple instances of the object you are creating.  This is why I have added the new method.  This new method acts as a constructor and will return a function.  This function creates a closure and so all the properties (one,two) and methods (talk) will be unqiue to each “instance”.

So usage would be like this:

world = Hello.new(‘my’,’world’);
universe = Hello.new(‘my’,’universe’);

alert(world.b); // “world”
alert(world.talk()); // “hello: my world”
alert(universe.b); // “universe”
alert(universe.talk()); // “hello: my universe”

As you can see each “instance” is unique.  What makes this instance unique is that you are actually not dealing with the Hello object directly, but with the new function on the hello object.  It is important to place everything inside the new function so that all the variables and functions will be unqiue to each instance.

Good luck!

Tags:

Development

Steps for using Git with SVN (Update2)

by rsutton 6. November 2009 04:18

Well I think I may have just become a Git convert today.  Yesterday I began playing with Git and quickly fell in love with how branching works.  I’ve known for a long time that switching to Git at work from SVN would not be reasonable, so I didn’t give it much thought.  Well yesterday I realized that Git can be used quite well with SVN, so here I’ve listed the commands that have made working with Git and SVN quite pleasant.  First I must mention that the best install for Windows is msysgit.  I’ve never been a fan of cygwin, so this gets around using it.

Here is what I do to initially setup the repository.

git svn init svn://myserver/trunk/MyCode
git svn fetch –rHEAD
UPDATE: If you do –rX with X being a previous revision number you will get all the history from that point forward
git svn rebase

To update to the latest just do

git svn rebase

To commit changes to SVN do the following

git svn dcommit

Now here comes the cool part.  When you are working with branches you can create a branch just using normal Git, then when you are ready pull in the changes into your master branch and when you commit to svn it will have a complete log of your changes.  Check this out.

git branch testing
git checkout testing

…makes some changes…

git commit –a –m ‘Testing 1’

…make some changes…

git commit –a –m ‘Testing 2’

Switch back to the master branch

git checkout master

Merge in the changes. 

git pull . testing (or git merge testing)

Send them off to SVN

git svn dcommit

TADAA!!!

Capture

Now this is cool ;)

This and this were very helpful in getting this working.  Thanks!

UPDATE: A couple of additional notes that are helpful.

When updating your code and there are uncommitted modifications.

git stash
git svn rebase
git stash apply
git stash clear

To revert (as they say in the SVN world)

git checkout filename

Tags:

Development

C# Object Initializer Trick (Update1)

by rsutton 19. October 2009 08:29

UPDATE: Nevermind this doesn’t work.  It passes the compiler, but gives a runtime error.  Sorry.

 

Today I found an interesting trick you can do with object initializers that I hadn’t noticed before.

    1 
    2     class MyClass
    3     {
    4         public int Id { get; set; }
    5         public string Description { get; set; }
    6         public List<string> FirstList { get; set; }
    7         public List<string> SecondList { get; set; }
    8     }
    9 
   10     class Program
   11     {
   12         static void Main(string[] args)
   13         {
   14             var mc = new MyClass
   15             {
   16                 Id = 1,
   17                 Description = "One",
   18                 FirstList = new List<string> { "123", "456" },
   19                 SecondList = { "123", "456" }
   20             };
   21 
   22             // works
   23             var l1 = new List<string> { "123", "456" };
   24 
   25             // does not work
   26             List<string> l2 = { "123", "456" };
   27         }
   28     }
   29 

If you noticed when the list of part of class that uses a setter you can use a short cut and leave out the new List<string> portion.  There interesting part is that it doesn’t work by normal assignment as shown on line 26.

The other interesting part is that this works with dictionaries.

    1 
    2     class MyClass
    3     {
    4         public int Id { get; set; }
    5         public string Description { get; set; }
    6         public Dictionary<string, int> FirstDictionary { get; set; }
    7         public Dictionary<string, int> SecondDictionary { get; set; }
    8     }
    9 
   10     class Program
   11     {
   12         static void Main(string[] args)
   13         {
   14             var mc = new MyClass
   15             {
   16                 Id = 1,
   17                 Description = "One",
   18                 FirstDictionary = new Dictionary<string, int> { { "123", 4 }, { "456", 5 } },
   19                 SecondDictionary = { { "123", 4 }, { "456", 7 } }
   20             };
   21 
   22             // works
   23             var d1 = new Dictionary<string,int> { {"123",4}, {"456",7} };
   24 
   25             // does not work
   26             Dictionary<string,int> d2 = { {"123",4}, {"456",7} };
   27         }
   28     }
   29 

Personally I find this useful while writing unit tests.  Quite often I setup objects in a particular state, so any shortcut to make this faster and cleaner is better.

Tags:

Development

JavaScript Dictionary

by rsutton 19. October 2009 08:04

Here is a JavaScript dictionary I created.  It is nice because you can get all the keys, values, and even access keys by using notation like d.key1.

    1 Dictionary = function(test) {

    2     function isKey(k) {

    3         var ret = true;

    4         if(k == 'set' || k == 'get' || k == 'exists' || k == 'remove' || k == 'keys' || k == 'values' || k == 'kvps')

    5             ret = false;

    6         return ret;

    7     }

    8 

    9     var iStore = {};

   10 

   11     return {

   12         set: function(key,value) {

   13             if(isKey(key))

   14                 this[key] = function() { return value; }();

   15             else

   16                 iStore[key] = function() { return value; }();

   17         },

   18         get: function(key) {

   19             if(isKey(key))

   20                 return this[key];

   21             return iStore[key];   

   22         },

   23         exists: function(key) {

   24             if(isKey(key))

   25                 return this[key] ? true : false;

   26             return iStore[key] ? true : false;

   27         },

   28         remove: function(key) {

   29             if(isKey(key))

   30                 delete this[key];

   31             else

   32                 delete iStore[key];

   33         },

   34         keys: function() {

   35             var ret = [];

   36             for (var i in this) {

   37                 if(isKey(i))

   38                     ret[ret.length] = i;

   39             }

   40             for(var i in iStore)

   41                 ret[ret.length] = i;

   42             return ret;

   43         },

   44         values: function() {

   45             var ret = [];

   46             for (var i in this) {

   47                 if(isKey(i))

   48                     ret[ret.length] = this[i];

   49             }

   50             for (var i in iStore) {

   51                 ret[ret.length] = iStore[i];

   52             }

   53             return ret;

   54         },

   55         kvps: function() {

   56             var ret = {};

   57             for (var i in this) {

   58                 if(isKey(i))

   59                     ret[i] = this[i];

   60             }

   61             for(var i in iStore)

   62                 ret[i] = iStore[i];

   63             return ret;

   64         }

   65     };

   66 };

Tags:

Development

JavaScript Event Hub

by rsutton 7. October 2009 09:30

I’m am currently creating a UI to do a bulk add operation and one of the main features that this form must have is speed.  It must be quick to do maneuver around the form and get at various data.  So in order to do this I have decided to go the no postbacks, ajax and JavaScript route.  The problem is trying to deal with all the interactions and maintaining the state of the form, because I will be constantly entering data and making ajax request.  In my effort simplify things I created what I call an EventHub.  The idea is really simple.  Here is the code.

    1 

    2 cw.EventHub = function() {

    3     var messages = [];

    4 

    5     return {

    6         subscribe: function(message,key,subscriber) {

    7             // setup the message subscriber list of this is a new message

    8             if (!messages[message])

    9                 messages[message] = [];

   10 

   11             // add the subscriber

   12             messages[message][key] = subscriber;

   13         },

   14         unsubscribe: function(message,key) {

   15             delete messages[message][key];

   16         },

   17         dispatch: function(message,data) {

   18             for (var key in messages[message])

   19                 messages[message][key](data);

   20         }

   21     };

   22 } ();

You subscribe to events like this.

 

EventHub.subscribe("OrderDateUpdated", "myKey", function(data) { alert('Order ' + data.id + ' Updated'); });

 

I added the key during the subscribe so that you can unsubscribe messages if needed like this.

 

EventHub.unsubscribe("OrderDateUpdated", "myKey");

 

Then you send messages like this.

 

EventHub.send("OrderDateUpdated", { id: '1234' });

 

Like I said there is nothing too complex here and it has made my life a lot easier in dealing with UI interactions.  Adding additional behavior to a form is simply a function of subscribing to the published event and then doing some work.

Tags:

Development

Memoize your functions with an extension method

by rsutton 5. August 2009 04:32

Recently I made a post on how to create memoized functions using a class.  Well today I came across a post that shows how to do the same thing using an extension method, so I thought I would share the code.

 

    public static class Extensions

    {

        public static Func<A, R> Memoize<A, R>(this Func<A, R> f)

        {

          var map = new Dictionary<A, R>();

          return a =>

            {

              R value;

              if (map.TryGetValue(a, out value))

                return value;

              value = f(a);

              map.Add(a, value);

              return value;

            };

        }

    }

 

Then you use it like so.

 

    class TestIt

    {

        public int DoIt(string parameter)

        {

            // Do lots of processing...    

 

            return 0;    

        }

 

        public void Test()

        {

            // Wrap the function and then use the Memoize extension method.

            var func = new Func<string, int>(DoIt).Memoize();

 

            // The function can then be executed as it if were a normal function.

            // This is different than before because you had to call execute.

            var result = func("process me");

        }

    }

 

The only limitation is that you have to create different extension methods based on the number of parameters.

Tags:

Development

Speed Test Reflection vs IronPython

by rsutton 30. July 2009 08:10

I was getting ready to write some code that will apply rules to an object using reflection, when I realized I could do the same thing using IronPython.  My only concern was the performance implications, because what I was doing needed to be fast.

 

Here are the results of basically setting properties on an object using both python and reflection.

image

Here is the code.  Nothing fancy.  I didn’t notice that there is a hit with the initial run, but after that IronPython is much faster.  If you look at the code you will notice that the time does not include setting up the engine, scope, etc.  You can play with those yourself, because here is the code.

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Running 1000");

            RunIteration(1000);

 

            Console.WriteLine("Running 10000");

            RunIteration(10000);

 

            Console.WriteLine("Running 100000");

            RunIteration(100000);

 

            Console.WriteLine("Running 1000000");

            RunIteration(1000000);

 

            Console.WriteLine("Running 10000000");

            RunIteration(10000000);

 

            Console.WriteLine("Running 10000000");

            RunIteration2(10000000);

 

            Console.ReadLine();

        }

 

        static void RunIteration(int iterations)

        {

            Console.WriteLine("Reflection Iteration.");

            TestReflection(iterations);

            Console.WriteLine("Python Iteration.");

            TestPython(iterations);

            Console.WriteLine("Testing Complete.");

            Console.WriteLine();

        }

 

        static void RunIteration2(int iterations)

        {

            Console.WriteLine("Reflection Iteration 2.");

            TestReflection(iterations);

            Console.WriteLine("Python Iteration 2.");

            TestPython2(iterations);

            Console.WriteLine("Testing Complete.");

            Console.WriteLine();

        }

 

        static void TestReflection(int iterations)

        {

            var test = new TestClass();

            var type = test.GetType();

 

            var st = new Stopwatch();

            st.Start();

 

            for (var i = 0; i < iterations; i++)

            {

                type.GetProperty("Id").SetValue(test, 1, null);

                type.GetProperty("Name").SetValue(test, "New Name", null);

            }

 

            st.Stop();

 

            Console.WriteLine("Time {0} ms", st.ElapsedMilliseconds);

        }

 

        static void TestPython(int iterations)

        {

            var engine = Python.CreateEngine();

            var sourceengine.CreateScriptSourceFromFile("test.py");

            var scope = engine.CreateScope();

 

            var test = new TestClass();

 

            source.Engine.SetVariable(scope, "test", test);

            source.Engine.SetVariable(scope, "iterations", iterations);

 

            var st = new Stopwatch();

            st.Start();

            source.Execute(scope);

            st.Stop();

 

            Console.WriteLine("Time {0} ms", st.ElapsedMilliseconds);

        }

 

        static void TestPython2(int iterations)

        {

            var engine = Python.CreateEngine();

            var sourceengine.CreateScriptSourceFromFile("test2.py");

            var scope = engine.CreateScope();

 

            var test = new TestClass2();

 

            source.Engine.SetVariable(scope, "test", test);

            source.Engine.SetVariable(scope, "iterations", iterations);

 

            var st = new Stopwatch();

            st.Start();

            source.Execute(scope);

            st.Stop();

 

            Console.WriteLine("Time {0} ms", st.ElapsedMilliseconds);

        }

    }

 

    public class TestClass

    {

        public int Id { get; set; }

        public string Name { get; set; }

    }

 

    public class TestClass2

    {

        public int Id2 { get; set; }

        public string Name2 { get; set; }

    }

test.py

for i in range(0,iterations):

    test.Id = 1

    test.Name = 'New Name'

test2.py

for i in range(0,iterations):

    test.Id2 = 1

    test.Name2 = 'New Name'

Tags:

Development

Powered by BlogEngine.NET 1.4.5.0
Theme by Extensive SEO

Profile

Member of the Church of Jesus Christ of Latter-Day Saints, Developer and IT Professional