Entries Tagged 'Programming' ↓

Implementing Method_Missing in C#

Heart of the ruby on rails magic in creating a very expressive and eloquent web development framework is the use of ruby’s method_missing.

Following is an example of method_missing in action :

class Roman
  def romanToInt(str)
    # ...
  end
  def method_missing(methId)
    str = methId.id2name
    romanToInt(str)
  end
end

Continue reading →

F# – Functional Approach

Functional programming is becoming more and more mainstream these days. C# 3.0, Python & Ruby have embodied many of the functional approaches. Microsoft even is releasing F# as first class language in Visual Studio 2010. F# is complaint in syntax with OCaml. Back in the day (at UC Santa Cruz) I wrote a language translator using OCaml and loved the symbolic computation capability a functional language provides.

In this version of interesting programming concepts, I would like to highlight type system based pattern matching available in F#/OCAML, its very unique and extremely useful if you are parsing a structured list or working on a symbol table:

type Expr = 
  | Num of int
  | Add of Expr * Expr
  | Mul of Expr * Expr
  | Var of string
  
let rec Evaluate (env:Map<string,int>) exp = 
    match exp with
    | Num n -> n
    | Add (x,y) -> Evaluate env x + Evaluate env y
    | Mul (x,y) -> Evaluate env x * Evaluate env y
    | Var id    -> env.[id]

In fact listed below is most of the code for code-generator main loop from my tool translating Berkeley Logic Interchange format (BLIF) to Reactive Modules :

let emit_atoms() =
  let vemit_atom a b = begin
    match b with 
      Symb(Input,_,None) -> ()
    | Symb(_,_,None) -> emit_unmarked_atom a
    | Symb(_,_,TableAtom
         (Controls(p),Awaits(q),Relations(r))) ->
           begin
         emit_atom_start ();
         emit_table_io_stmts p q;
         emit_init_update ();
         emit_relations p q r;
         emit_atom_end ();
           end
    | Symb(_,_,ResetAtom
         (Controls(p),Awaits(q),Relations(r))) ->
           begin
         emit_atom_start ();
         emit_reset_io_stmts p q;
         emit_init_update ();
         emit_relations p q r;
         emit_atom_end ();
           end
...
    | Symb(_,_,SameAs(t)) -> ()
    | _ -> raise (Failure("Unknown Error"))
  end
  in          
  Hashtbl.iter vemit_atom symTab;

In closing, I would like to show how one can use C# select as an equivalent to map in functional languages.

// Get elements in the store where filenames are GUIDs
public IEnumerable<Guid> GetKeys()
{
    string[] files = Directory.GetFiles(_StorePath);
    // functional equivalent: return files.map(|t| new Guid(t))
    return (files.Select( p => new Guid(
            Path.GetFileName(p))));
}

Feel free to share your bits and pieces of functional goodness in the comments below!

Memoization

I have been meaning to write short posts about interesting programming concepts and alternative programming movements (like alt.net). Topic of this post is an interesting programming concept called Memoization and its implementation in C# as a method attribute.

Memoization is an optimization technique which speeds up a program by remembering the values returned by function calls for specific input values, its also known as tabling.

Many of the new languages (Ruby, Python, C#) provide a very neat way to implement Memoization and many functional languages (Lisp, OCaml) have it as a first class construct for the runtime. Here is a my cheap implementation showing how one can use an integer based Memo attribute in C#

class Test
{   [Memo]
    public int DoSomething(int i)
    {
        for (int k = 0; k < 10000; k++)
        {
            int j = 0;
            j = j + 500;
        }
        Console.WriteLine("DoSomething " + i);
        return i + 5;
    }
}

Here is a simple driver which implements the Memoization :

static void Main(string[] args)
 {
     Debug.WriteLine("Invoking Memoizable Code");
     
     Type t = typeof(Test);
     Test objT = new Test();

     // Implement Memoization
     Dictionary<int, int> memoize = new Dictionary<int, int>();
     MethodInfo[] mi = t.GetMethods();
     foreach (MethodInfo m in mi)
     {
         foreach (Attribute a in m.GetCustomAttributes(false))
         {
             if (a is MemoAttribute)
             {
                 for (int i = 0; i < 2; i++)
                 {
                     int j;
                     if (memoize.TryGetValue(i, out j))
                     {
                         Debug.WriteLine("Remembered " + i);
                         continue;
                     }
                     else
                     {
                         j = (int) m.Invoke(objT, new object[]{i});
                         memoize[i] = j;
                         Debug.WriteLine("Memorized " + i);
                     }
                 }
             }
         }
     }
     Console.ReadLine();
 }

May be in comments you can suggest ways to implement a more generic Memo attribute (similar to Python’s @memo).

Security Resources for .NET Web Applications

Web applications have a class of security vulnerabilities, at times much widespread and trivial than the infamous buffer overflow.

.NET Web Application Security

.NET Web Application Security

Here are some interesting Security resources on .NET Web Application:

Please leave a comment if you know of any valuable security resources.

Whats your “editor” personality

Emacs? Vi? Visual Studio? TextMate?? Whats your favorite editor?

I started with Emacs and got to a point where I could write some elisp to work with a new language, but it just was too heavy weight and more often seemed to be bloat and cruft than necessary. Then I moved to Microsoft and gradually my editor became Visual Studio (and Notepad). It happened that way since it turned out to be a common denominator, and Visual Studio has amazing intellisense~

However more of late I have think vi (especially Vim) is a great tool. Since i work a lot with Non Microsoft programming language Vi seems to be the just right choice and it lean and mean!! Yep i do kick myself for not defecting to this camp earlier in my education.

Very recently @ OSCON i got in conversation with _those_ mac guys who love TextMate. It really interesting how TextMate has put the realm of XML declaration for a language as powerful as Context free grammer, and CSS with all the design and color gu – in to the editor world. It has an amazing community managed code / snippet repository which folks can use to share code with one another…!

Zemanta Pixie