Wednesday, December 30, 2009

.NET 4.0 Dynamic with ASP.NET MVC

.NET 4.0 ships with a lot of cool, new stuff. For C# the major new feature is the support of dynamic programming. The idea with dynamic support in C#, in short, is that you can statically type a variable as dynamic (yeah, this sounds funny, statically typed as dynamic, I know) in which case the compiler will not check any methods or property binding on this object, rather it will defer all of these resolutions to runtime.
It's not just that, but with dynamic support you can also declare your own objects to act as dynamic objects by implementing IDynamicMetaObjectProvider or -- as a shortcut -- by extending DynamicObject. Both types exist in the namespace System.Dynamic.
There's also a very famous type called ExpandoObject.
ExpandoObject is a dynamic object that you can simply create properties on it at runtime.
Now the trick that I want to use, is to declare my views to extend the generic System.Web.Mvc.ViewPage. This will allow me to pass to my view any dynamic object and access its properties through the Model property of the view. 
Here's a code example:
 using System.Dynamic;
    using System.Web.Mvc;

    public class ArticlesController : Controller
    {
        public ViewResult Index()
        {
           
            dynamic x = new ExpandoObject();
            x.Title = "Programming for Cowards";
            x.Url = "http://galilyou.blogspot.com";
            //I even can nest
            x.Author = new ExpandoObject();
            x.Author.Name = "Galilyou";
            return View(x);
        }
    }
In the above code I declare an ExpandoObject and start to set some properties on it like Title, Url, etc.
I do this by simply using the syntax var.Property = value; which will automagically create a property on the dynamically created object which type will be the type of value.
If you look closely you would notice that  the Author property is an ExpandoObject itself. This nesting is allowed to as many levels as you want.
Here's how my view looks like:
< %@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

Note, the view is declared to extend System.Web.Mvc.ViewPage
Now you can use the values of the model like so:
Model.Url
Model.Title
Model.Author.Name
here's how the entire view will look like:

And here's the page after running the application:



Disclaimer: 
        You shouldn't do this in a large scale application. View model objects are still the best tool for the       job when the application grows. However, if you want to quirk something pretty quickly -- a small thing-- you might get away with that.
Hope this helps.

Back to Basics: Square Root Implementation in Python and C# (Newton's Method)

In my last post I introduced to you an extra simple algorithm to calculate square roots, it's called the Bi Section method. The Bi (pronounced by) part comes form the word binary. This is due to the fact that each time we pick a guess we pick it at a point in the middle between an upper bound and a lower bound. This technique is very useful in many cases in computer science (e.g. Binary Search is a very famous example of that).

As you see the Bi Section method is really simple, however, it's not that effective.
This time I will introduce a different method to calculate square roots, this method is called "Newton-Raphson's method", it's named after Issac Newton, and Joseph Raphson.



This method is known to be really effective --especially when the initial guess is near from the correct answer-- and it's considered to be the  best known method for finding successively better approximations to the zeroes (or roots) of a real-valued function
Explaining this method will require a certain amount of familiarity with Calculus and Algebra, so I'm not going to delve into this here. However, I will show you the code to do it in Python and C# (which, surprisingly you will find very simple). 


First, the code in Python:





def sqrtWithPrecisonNR(x, precision):   
    assert x >= 0, 'x must be non-negative, not' + str(x)
    assert precision > 0, 'epsilon must be positive, not' + str(precision)
    x = float(x)
    guess = x/2.0    
    diff = guess**2 -x
    ctr = 1
    while abs(diff) > precision and ctr <= 100:
        guess = guess - diff/(2.0*guess)
        diff = guess**2 -x
        ctr += 1
    assert ctr <= 100, 'Iteration count exceeded'
    print 'NR method. Num. iterations:', ctr, 'Estimate:', guess
    return guess

Second, the code in C#: 



float SqrtWithPrecisonNR(float x, float precision)
        {
            if (x < 0 || precision <= 0)
                throw new ArgumentException("x, and precission gotta be non negative numbers");
            float guess = x/2.0f;
            float diff = guess*guess - x;
            int counter = 1;
            while(Math.Abs(diff) > precision && counter <= 100)
            {
                guess = guess - diff/(2.0f*guess);
                diff = guess*guess - x;
                counter++;
            }
            if(counter > 100)
                throw new Exception("100 iterations done with no good enough answer");
            Console.WriteLine("Num of Iterations: {0} , estimate: {1}", counter, guess);
            return guess;
        }

Now, I want you to try this method with the last one and see the difference.
Here's a helper function that will test the two methods with input 2 as the root and 0.000001 precision:



def testMethods():
    sqrtWithPrecision(2, 0.000001)
    sqrtWithPrecisionNR(2, 0.000001)    

You should see that the Newton's method is much faster and this difference in speed will be totally apparent when you try it on bigger numbers.

For more details about the Newton's method including the mathematical stuff see here

Tuesday, December 29, 2009

Back to Basics: Square Root Implementation in Python

Two days ago a friend of mine who is a computer science student asked me about the simplest square root algorithm that I know about. Well, I know how pesky students suffer when trying to computer square roots, so I had to choose an easy one.






I know about the famous Cramack method but this sounds complicated to me (though it's the most efficient method AFAIK). So I preferred the goody (Guess, Evaluate, Improve) method. So for example if I want to calculate the square root of the number let's say, 2, my strategy will be like the following: 


1- Pick a guess (1 for example)
2- Evaluate that guess: is 1 * 1 near enough to 2 (see the bold near enough expression!)
3- If the guess is not near enough, Improve it. 


Note that I didn't use the term "equals" when evaluating the expression, rather I used the term "near enough" and this is because, with numbers that are not full squares (like 2 for example), the square root is going to be a floating point number (square root of 2 = 1.414213562373095). Now if you multiply this number --the square root of 2-- by itself, you should expect to have 2 as an answer. Well, that's not gonna happen, rather you're going to get (2.0000000000000004). This is happening due to the way that computers handle floating point numbers --which is a topic of other series of posts by itself. In this case if you used the term equals (or == operator) when evaluating the guess you will never make it, and your program will not halt. That's why I carefully used the term near enough. Defining what near enough means is your choice now, for certain situations you might consider a number that is less than the square root by 0.1 is near enough or 0.001 or 0.0001, etc. This depends on the level of precision that you need for your specific scenario.


The implementation: 
Here's a python implementation of this algorithm.







## calculates the square root of a positive number
## with the passed in precision
def sqrtWithPrecision(x, precision):
    ## The precision must be greater than zero,
    ## root must be a positive number
    assert(precision > 0, str(precision), 'is not a valid value, it must be a positive integer')
    assert x > 0, 'root can not be a negative number'
    low = 0
    high = max(x, 1)
    counter = 0
    guess= (low + high) /2.0
    while abs (guess ** 2 -x) > precision and counter <= 100:
        if(guess ** 2 < x):
            low = guess
        else:
            high = guess
        guess = (low + high) / 2.0
        counter += 1
    assert counter <= 100, '100 iterations done and no good answer'
    ## printing the number of iterations,
    ## in productive code, you might want to remove the next line
    print 'Num of iterations:', counter, 'Estimate:', guess
    return guess

And here's a c# example:

float sqrtWithPrecision(float x, float precision)
        {
            if (x < 0 || precision <= 0)
                throw new ArgumentException("x, and precission gotta be non negative numbers");
            float low = 0;
            float high = Math.Max(1f, x);
            float guess = (low + high)/2f;
            int counter = 0;
            while( Math.Abs(guess * guess - x) > precision && counter <= 100)
            {
                if (guess * guess < x)
                    low = guess;
                else
                    high = guess;
                guess = (low + high)/2f;
                counter++;
            }
            if(counter > 100)
                throw new Exception("100 iterations done with no good answer");
            Console.WriteLine("Num of Iterations: {0} , estimate: {1}", counter, guess);
            return guess;
        }

What Can You Learn From Us? What Can We Learn From You?

Today I got a very interesting question from one of my Twitter friends splattne. The question was:

Here's how I answered the question:

Wow, that's a big one!
I really like your question, Stefan. This kind of constructive thinking is one of the most important methods we can use to avoid conflicts (which might eventually develop wars, and bad stuff).
I will start by what I think that we can learn from you: 


1- Hardwork:

 yes, we're lazy people. Even for the poorer countries (like mine) people are satisfied by working less and gaining less (less than enough). 

2- Democracy:

 I'm not gonna through a discussion with this because it's very obvious for everyone that democracy in our countries is just a shallow word. I mean, come on, every president is preparing for his son to take his place nowadays. This is happening in Egypt, Libya, Tunisia, and many others. 

3- How to learn and teach: 

Education systems in most (if not all) of the Arabic countries are ridiculously inefficient. Chemistry students here enters the chemistry lab one or two times for the whole semester. 

What can you learn from us: 


1- Socializing:

Around here the social relationships are much much better that there in US and Europe. 

2- Conviction:

 Though poor is everywhere, we are not so obsessive with money! A little can satisfy us. 

3- Harmony: 

Different races live together with harmony and love. I've never heard (in an Arabic community) that some one shot another because of his skin color.

At the end, the thing that can really teach you a lot is the Arabic History. We are a bunch of shallow nations nowadays, our influence on the outer environment is very weak, but once we were a real example of a united, well educated, merciful, and highly organized nation.
Thank you again for asking this question Stefan, and I really hope if my answer helps.


What do you think dear reader? What else can we learn from the Europeans/Americans (the good things)? And what can they learn from us(only the good things)?

FormSpring



ASK ME ANYTHING

Today I came a cross this site. The main idea here is that people can ask each other questions and get them to answer them. It also integrates with a lot of other sites like Twitter, Blogger, etc. There are a lot of my twitter friends on FormSpring.
I think the idea is simple and very appealing. Take a look at it and feel free to ask me anything http://formspring.me/Galilyou

Thursday, December 10, 2009

Pretty Neat Extensions For Google Chrome

Today I took a quick whirl to look at some of the avilable extensions for Google Chrome.  And here are some of those that I find interesting:



  1. Wave Notifier : As the name implies it's a notification plugin for Google Wave. Wave Notifier let's you know if you have any new waves or replies and display a counting number holding the number of the new waves. You don't have to keep your wave page open and switch to it every minute or so to see if you get a new wave, or if x of your friends replied to a wave you sent to them. 
  2. Xmarks Bookmark Sync: A bookmarks plugin that synchronizes your bookmarks to Xmarks. You just login using your Xmarks account (or register if you don't already have one) and then you can click the Xmarks button and then click Sync Now.
  3. Google Translate: Translate any web page using Google Translator just for one click. 
  4. Blog This: This is actually a cool one --still overwhelmingly buggy though. It lets you post to your blogger blog from any webpage. 
  5. Google Mail Checker: A notification for Gmail that let's you know whenever you get new emails.
  6. Google Reader Notifier: Notifies you with your new Google Reader items.
  7. Google Calendar Notifier: Same as the two above, it notifies you with your calendar events.
  8. Doc Viewer: Automatically views PDF/PPT documents using Google Docs Viewer.
  9. IE Tab: Yes, it's an Internet Explorer tab inside Google Chrome! 
  10. Speed Tracer: This one is actually the rock star of all of these extensions (at least  for me). You enable it, and then it goes and analyze the processing of a web page that you are requesting. It displays very useful graphs and charts that are extremely helpful for you as a developer to inspect and discover areas of improvements in your web site. More on the very thing later, stay tuned!
Those were some of the many extensions available now for Google Chrome. Go ahead and take a look at the official extensions page from Google here.

Those were some of what I liked, what do you like dear reader?

Sunday, December 6, 2009

Which Isolation Framework?

In the world of unit testing Isolation Frameworks are everywhere. Isolation Frameworks are very handy tools to help you create mock objects. According to Wikipedia:
mock objects are simulated objects that mimic the behavior of real objects in controlled ways”




In the world of .NET there are a lot of tools out there to be used as Isolation Frameworks. There have been a lot of debate around the best isolation framework –Including this StackOverflow question.
If you have used any mocking framework, and felt like it’s a good tool to use, please vote on the poll on the left to this post or leave a comment about your experience with your preferred isolation framework.