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 = "";
            //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:
here's how the entire view will look like:

And here's the page after running the application:

        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;
            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
            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;
                    high = guess;
                guess = (low + high)/2f;
            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)?



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

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.

Wednesday, November 11, 2009

A Quick Tip: Operations are not Methods.

In the industry of software development people always use the terms Operation and Method interchangeably. Often time this is true, other times it's not!
To begin let's define what the two terms exactly mean --in terms of Object Oriented Design?

[From Fowler's UML Distilled]

      An operation is something that is invoked on an object --the procedure declaration.
    A method is the body of the procedure.
I guess it's obvious how related and close the two terms are. But sometimes they can be quite different.
For example if you have A super class Employee that defines an abstract operation Work() and 3 sub classes of Employee (Manager, Programmer, and SalesRep) that override the inherited operation Work() then in this case you have 1 operation and 3 methods. 1 defined operation in the base class and 3 different implementations.

Monday, November 9, 2009

Opps! A Leak! In .NET!!

Are you a smart, happy, hard-working C guy?

If yes then, well ..  you probably want to skip this post.
Do you use .NET? Are you aware of the magician called GarbageCollector? Do you like it? Because I do!

Past -- Rewinding a little ... <<<
In the times before dawn, every-day programmers needed to do a lot of work to manage their application's memroy. My hero C guy -I used to be a hero too by the way- was forced to keep track of every malloc to free it when it's no longer needed.

Now -- Fastforwarding ... >>>
Everyone (Well, almost everyone) uses a lanaguage that supports automatic memory management tools. For me as a .NET guy, I use C# and I'm very happy with what the GarbageCollector does for me (I think most .NET guys are). However, unlike everyone (again almost) else thinks, it's trivially easy to introduce memory leaks in .NET.

First let's ask Wikipedia, What is Memory Leak?  Let me quote the answer here.

A memory leak or leakage in computer science is a particular type of memory consumption by a computer program where the program is unable to release memory it has acquired

I used to think that as long as I don't use unmanaged resources (explicitly) I'm safe. The GC will free all the managed objects from memory once I'm done using them (or when there is no references to these objects). Guess what? I was mistaken!!

One more point from this Wikipedia article:
Languages that provide automatic memory management, like Java, C#, VB.NET or LISP, are not immune to memory leaks. For example, a program could create a circular loop of object references which the memory manager is unable to recognize as unreachable.

GC frees only objects that has become unreachable. If the object is still reachable, somehow (probably your mistake), then GC will not free it. Which introduces a leak ...

To be honest, with nowadays super computers, usually leaks are not a problem unless your app is really big, and runs continously for a really long period of time; this is when those tiny drops can fill the cup.

What causes those leaks?
There are quite a few reasons why a .NET app migh leak memory. The main reasons are:
1- Static References
2- Event With Missing Unsubscribtion
3- Dispose method not invoked.

In this post, I will talk about the most famouse one (the one that got me bitten): Events.
Yes, people always remember to subscribe to events, but few unsubscribe from their events.

What happens when an observer subscribes to a publisher's event is that the publisher maintains a reference to the observer in order to call the event handler on that observer. This means that unsubscribtion from events is required to delete this reference. And that is what got me bitten hard!

So, how to detect memroy leaks?
There are plenty of tools that can help you track your application progress and take snapshots and analyze the memory status of your application. Here's a list of some of those tools:
  1. JetBrains dotTrace
  2.  .NET Memory Profiler
  3. ANTS Profiler
And many others ...

I will post about other types of memroy leaks in .Net in the coming posts. So stay tuned!

Tuesday, November 3, 2009

Bitten by the dynamic Keyword and Overload Resolution in C#

I came a cross a very scary piece of code Today on the web, take a look at the following C# 4.0 code:

using System;
using System.Dynamic;

namespace DynamicDemo
    class Program
        static void Main(string[] args)
            dynamic d = new ExpandoObject();
            d.Shoot = "Booom!";

        void DoSomeThing(dynamic d)

How would the previous code work?
Well, you would say that this code wouldn't compile because the static method "Main" is calling an instance method "DoSomething", right?
Wrong! This code will actually compile!! Yes, it will fail at runtime, but let's say why this piece of code behaved so freakingly scary. First let me show you another example:

using System;
using System.Dynamic;

namespace DynamicDemo
    class Program
        static void Main(string[] args)
            dynamic d = new ExpandoObject();
            d.Shoot = "Booom!";
Unlike the first example, this last example will not compile. All of this is related to how C# resolves method overloads.

If you examined section of the C# 3.0 specification, you will learn about the Overload Resolution mechanism that C# follows, here's the steps in short:

  1. Each overload is examined, and the best overload is selected according to the arguments. 
  2. C# determines whether the overload is accessible from the current instance or static context.
  3. If the overload selected from step 1 is not accessible then a compile-time error is thrown.
This overload resolution is done through compilation, but with dynamic, overload resolution is delayed until runtime, and it happens in the very same way as the above three steps (but at runtime of course).
So, at the first sample, the runtime has found the best overload to be the instance method "DoSomething" and then, determined that the selected target is not accessible for that call --as it's not accessible for static calls-- so the runtime threw a RuntimeBinderException exception.

For the second sample code, with no dynamic, the compiler finds out that "DoSomething" doesn't exist in the current context, so it will generate a compile-time error.

If you want to learn more about Overload Resolution, read the C# Specification.

Do you think this was scary enough, or am I being just too coward?

C# 4.0 Now Consumes Indexed Properties

If you dealt with COM Interop before, then you probably know what Indexed Properties mean. If you don’t, hang on with me and you will know in the coming few lines. Consuming Indexed Properties is a new feature to C# 4.0 Beta2. This is used to improve syntax like the following:
var excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
This syntax can now be improved to get rid of get_Range(“A1”) and use an indexer accessor instead, here’s how C# 4.0 Beta 2 can do for you to improve this:
var range = excel.Range[“A1”];
So now, every time you use COM Interop and have to call get_x() and set_x(), you can now replace this with the new indexer syntax. I have to tell you –Well, you might have guessed it- that this is just a syntatic sugar, the compiler will do emit calls to get_x() and set_x() ultimately.

I think this little syntax improvement is pretty neat, however, people shouldn’t ask the very expected question “Well, now we can consume indexed properties in c#, why can’t we create it? we wanna create indexed properties! Indexed properties is a legal right! blah blah .. “. If C# allowed us to create indexed properties then I think, this will add an ambiguity that isn’t worth anything here. I mean take a look at the following code and tell me what would it mean to you, if C# enables you to create indexed properties?
Does it mean that SomeProperty is a type that implements an indexer, or SomeProperty is a property that requires an indexer? See the ambiguity?

What’s your thoughts on this, dear reader?

Monday, November 2, 2009

Moved to Blogger

Yes, though this is my first post here, I’ve been into blogging before! I’ve been maintaining my old blog for a while now. I decided to go on and try Blogger. I’m not unsatisfied with Wordpress at all, actually, I quite like it. I just wanted to try Blogger. And since the best way to try something is, well, actually try it, I decided to move my latest blog posts to here.

Blogging for Cowards 101:

  1. What is a coward?
    A coward is an intelligent trained professional, armed with a powerful brain and likes to explore new things, wastes his time banging onto a modern typing machine, hates compilers, loves WoW, and ultimately is scared of the world ending without him learning enough

  2. What is Programming?
    We will figure it out together!

  3. How can this blog help you?
    Sharing is caring, you know? Yeah, I’m scared too. I will share any new stuff I learn about onto this blog, I will even share my own thoughts (don’t waste your time on those)

So, are you with me, are you a coward? I hope so. Life is not fun without learning, and 2012 is so close, we have a lot work to do! Time is running out, life is running out. So let’s get started, shall we? Ladies and Gents!?