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

Dramatically Improve ASP.NET Compile Time for Less Than $1500

by rsutton 4. December 2009 04:40

One thing that really bothers me is a slow compile time.  A slow compile time causes me to do other things when compiling, which in turn causes a loss of focus.  Basically a context switch I wish to avoid.  So the other day I decided to try out an SSD drive to see if I could get an improvement, because I thought that my hard drive was the bottleneck.  My results were rather interesting.

First I would like to say that I work on a very large solution with a very large (7000+ files) ASP.NET website.  A few months ago I converted our IIS website project to a Web Application Project.  That caused our build time to go from about 5 minutes to around a minute or so.  That was a huge improvement, but we still had issues with that one minute.  The reason was because in addition to the one minute lag time caused by the build, when you went to any page for the first time you got a hesitation while the page was being compiled.  The reason this happens is the Web Application Project doesn’t fully compile the pages using the aspnet_compiler.  So for us the bottleneck is the execution of the aspnet_compiler.  For this reason I chose to use our build script as the benchmark test.  The build script spends about 80% of its time fully compiling our website using the aspnet_compiler.  All of the results are given using this benchmark.

The result before I decided to start my testing varied between programmers, but the general case outside myself was the build took about 400-500 seconds.  My machine was taking about 320s.  The main reason for that was my machine had 4 250G 7400 rpm drives in a RAID 0 with an Adaptec RAID card.  With this in mind I thought for sure the bottleneck was hard drive, but that wasn’t necessarily the case.

Here are my results:

The first two machines were brand new reasonably priced and powerful machines with a 7200 RPM hard drive.

Core 2 Quad 2.53 (350s) with SSD (270s)

Core 2 Quad 2.83 (280s) with SSD (230s)

This made me realize that the combination of CPU and Hard Drive made a difference, so I took this to the next level.  I ordered an i7 960 and I already had 2 10,000 rpm raptors so I threw those into the mix as well.

i7 960  Raptor (180s) with Raptor RAID 0 (160s) with SSD (190s)

As  you can see the raptor appeared to be beating my SSD drive and was really screaming in RAID 0.  The strange thing though was that the OS didn’t feel as good with the Raptors as with the SSD even when they were in a RAID 0.  The other thing that didn’t make sense was that the windows experience index on the drives didn’t seem to match the performance I was getting.

Raptor RAID 0 (5.9)

SSD (7.1)

That made me wonder if there was something going on when I used the onboard Intel ICH controller vs the standard IDE interface with the SSD drive, so I decided to turn on the RAID but use the SSD drive as a non-RAID disk.  This yielded much better results.

i7 960 SSD using ICH controller (155s)

Much better.  The windows experience nudged up a bit to 7.4 as well.  It appears that the standard ide controller had a bottleneck that wasn’t allowing me to take full advantage of the SSD drive.  I also tried two SSD drives in a RAID 0 and ended up with 150s and the windows experience index ticked up to 7.7, so not much of an improvement for the price.

The moral of the story is that the combination of CPU and Hard Drive are key to getting your compile times down, and the best part is that this modification costs less than $1500 from newegg.

Below I have listed the links to the hardware I used.  Hopefully this post has been useful.

CPU - http://www.newegg.com/Product/Product.aspx?Item=N82E16819115216
CPU Cooler - http://www.newegg.com/Product/Product.aspx?Item=N82E16835103055
RAM - http://www.newegg.com/Product/Product.aspx?Item=N82E16820104132
Motherboard - http://www.newegg.com/Product/Product.aspx?Item=N82E16813131365
HD - http://www.newegg.com/Product/Product.aspx?Item=N82E16820227469

NOTE: I had a 550W power supply and for now this seems to work.  It does run a little warm so it wouldn’t hurt to have a better one, but I wouldn’t recommend anything less than 550W.

NOTE2: The selection of SSD drive is very important.  I chose the OCZ Vertex Turbo, because it had sustained writes of 100 MB/s as opposed to the normal drive at 70 MB/s.  The Intel drive also rates at 70 MS/s, so be careful.  The bigger drives are more expensive, but they seem to perform even better according to the specs so if you can get a bigger drive go for it.  I would recommend going with one bigger drive as opposed to 2 smaller ones in a RAID 0, because I saw almost no improvement in RAID 0 with the SSDs.

Tags:

Embedded IronRuby and IronPython in Silverlight with Multiple Source Files

by rsutton 16. November 2009 10:17

I have yet to find a simple clear example of using multiple files when embedding IronPython or IronRuby in Silverlight, so I decided to share an example I have been working on.

NOTE: During testing have found this does not work with 0.91 or 0.92 of the DLR.  I guess there is a bug with imports and it should be fixed any day now.  Go here and click all releases to get 0.90 of the IronRuby and IronPython dlls.

Here is the code in my MainPage.xaml.cs:

    public delegate string pyFunc(string s);
    public delegate IronRuby.Builtins.MutableString rbFunc(string s);
 
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
 
            pythonblock.Text = DoPython();
            rubyblock.Text = DoRuby();
        }
 
        private string DoPython()
        {
            var setup = Python.CreateRuntimeSetup(null);
            setup.HostType = typeof(BrowserScriptHost);
 
            var runtime = new ScriptRuntime(setup);
            var engine = Python.GetEngine(runtime);
            var scope = engine.CreateScope();
 
            var mscope = engine.CreateScope();
            var module = engine.CreateScriptSourceFromFile("module1.py");
            module.Execute(mscope);
 
            runtime.Globals.SetVariable("module1", mscope);
 
            var source = engine.CreateScriptSourceFromFile("main.py");
            source.Execute(scope);
 
            var func = scope.GetVariable<pyFunc>("hello");
 
            return func("world");
        }
 
        private string DoRuby()
        {
            var setup = new ScriptRuntimeSetup();
            setup.HostType = typeof(BrowserScriptHost);
            setup.AddRubySetup();
 
            var runtime = new ScriptRuntime(setup);
            var engine = Ruby.GetEngine(runtime);
            var scope = engine.CreateScope();
 
            var mscope = engine.CreateScope();
            var module = engine.CreateScriptSourceFromFile("module1.rb");
            module.Execute(mscope);
 
            runtime.Globals.SetVariable("module1", mscope);
 
            var source = engine.CreateScriptSourceFromFile("main.rb");
            source.Execute(scope);
 
            var func = scope.GetVariable<rbFunc>("hello");
 
            return func("world");
        }
    }

Here are the source files:

main.py:

import module1
 
def hello(s):
    return module1.f1('python hello ' + s)
 

module1.py:

def f1(s):
    return 'python f1: ' + s

main.rb:

require "module1"
 
def hello(s)
    f1('ruby hello ' + s)
end
 

module1.rb:

def f1(s)
    'ruby f1: ' + s
end

 

I hope this is helpful and if anyone has any suggestions for improvement please let me know.

Tags:

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

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