Skip to content


Y-Combinator in C#

For last few days, I was trying to use lambda feature of C# to implement Y-Combinator. After few trial and errors, I was able to implement it in C# 3.5. I'm currently posting the code here and in my next blog, I'll explain how I derived it.

In this code, Y-Combinator function, is used to implement anonymous recursive-factorial function called 'factorial'.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YCombinator
{
    class Program
    {
        delegate Func<int,int> RecursiveFunction(RecursiveFunction f);

        static void Main(string[] args)
        {

            Func<Func<Func<int, int>, Func<int, int>>, Func<int, int>> Y = (f) =>
            {
                RecursiveFunction function = (h) =>
                {
                    return (x) =>
                    {
                        return f(h(h))(x);
                    };
                };
                return function(function);
            };

            Func<int, int> factorial = Y(function=>
            {
                return x =>
                {
                    return x == 0 ? 1 : x * function(x - 1);
                };
            });
            Console.WriteLine(factorial(5));
            Console.ReadLine();
        }
    }
}

Posted in Programming, Technologies.

Missing attachment detector in Gmail

It is really embarrassing to send an email with an attachment and actually forgetting to attach the file you were supposed to mail along, isn’t it? In my case, I often forget to attach files to emails if I’m typing it in hurry. Sometimes, I even end up receiving replies from recipients of those emails requesting me to eat food instead of attachments. I don’t know about you, but for me this is really embarrassing!!!!!!

Luckily, today I came across a feature in Gmail Labs, which helps you to identify missing attachments as soon as you press send button. This small functionality in Gmail warns you if you have written something like “I’m attaching” or “I am attaching” or “I have attached” in your message body and you haven’t actually attached any file. I’m not sure if it is capable of identifying any other patterns in email text which suggests that you wanted to attach something. However, I tested for above 3 patterns and I’m good with it.

To enable this feature, you will need to login to your Gmail account. Then go to Settings -> Labs, and enable ‘Forgotten Attachment Detector’. Don’t forget to click on ‘Save changes’ after that.

I would like to thank Mr. Jonathan K, for creating this useful feature in Gmail lab. It is definitely an important feature for me, and for many other people who like to eat attachments instead of food.

Posted in My Thoughts, Technologies, Tips. Tagged with , , , .

Are computers really becoming user friendly?

Gone are those days when users had to learn all the shell commands (Dos or Unix), to be able to use their PCs. Now you have Graphical User Interfaces or GUIs which allow you to do all those tasks simply by pointing and clicking at icons or menus with that small device near your keyboard called ‘Mouse’. This means that we simply need to buy a computer and sit in front of it, and soon we will be able to use it effectively to manage all required information.

But wait!!!!! As computers are becoming smarter and smarter, some new age pirates are also becoming smarter. They are now finding new ways of hacking into your computer to steal your information with use of Trojans and viruses. For example, read this report on BBC News called ‘Parking ticket leads to a virus’.

This makes me feel that nothing has changed as yet. Earlier, it was difficult to use computers because users had to learn all the commands which were required to operate it. Now, common users are often scared to use their computers for doing activities like online transactions as they need to learn all the ways to protect themselves and their data from hackers.

Well, what does this mean for software developers? Software developers must keep themselves updated about various security issues and design stable and secure system so that more and more users will be able to use technology without even having to learn things they are not supposed to. For those who think software development is easy, I agree with you. Yes, software development is easy. BUT, developing a stable, user friendly and secure application is definitely not as easy as writing ‘var x=a+b;’.

Posted in My Thoughts. Tagged with , , , .

Fixing NTLM authentication in Windows 2003

We had an application written in C# .Net, which used to communicate with Alfresco Enterprise Document/Content Management System. The application was using Alfresco’s NTLM component for authenticating users against their AD (Active Directory) user account.

The application worked perfectly while we were testing it on Windows XP system. However, on Windows 2003 64 Bit system, the application started failing as it could not authenticate users on alfresco server using NTLM.

So we had a situation where NTLM authentication used to fail only when our application was running on Windows 2003 Operating System. We tried disabling “Internet Explorer Enhanced Security Configuration”, but it didn’t help. Finally, after spending a lot of time on Google, we came across following article on Microsoft Knowledge Base:

"You may experience authentication issues when you access a network-attached storage device after you upgrade to Windows Server 2008, to Windows Vista, to Windows Server 2003, or to Windows XP"

This article talks about configuring the system to use appropriate NTLM version. In our Windows 2003 system, the value of “lmcompatibilitylevel” (Under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA subkey) was set to 2. We just changed this value to 1, and the client application started working properly in Windows 2003 system as well.

If you are also facing a similar issue on Windows 2003, then you can try the solution mentioned here. If setting the value of “lmcompatibilitylevel” to 1 makes no difference, then change this value to 0, which is the default value of “lmcompatibilitylevel” in Windows XP.

Posted in Technologies, Tips. Tagged with , , , , .

Be careful while using ‘replaceAll’ and ‘replaceFirst’ methods of String class in Java

Most of the time, while trying to replace a substring in a given string, either all its occurrences or just the first one, java programmers tend to use ‘replaceAll’ and ‘replaceFirst’ methods provided by String class in Java. Java programmers like to use these methods to replace substrings as compared to ‘replace’ method of String class because of different reasons like:

  1. ‘replaceAll’ and ‘replaceFirst’ methods use regular expressions instead of character sequence. It is pre-assumed most of the time that using these methods will allow us to replace a given pattern in future, instead of just replacing a substring.
  2. ‘replaceAll’ and ‘replaceFirst’ methods are named such that they clarify the intent of their execution.

However, while using these methods, we need to be very careful while providing the string value which would replace a given substring or a pattern. Let’s understand why with the following example:

Run the following java code:

public class StringReplace {

public static void main(String[] args){
String stringValue = "test1 test2 test1 test3";
String replaceValue = "test";
stringValue = stringValue.replaceAll("test1", replaceValue);
System.out.print(stringValue);
}

}

This code works properly. But now try running the same code by changing the value of variable ‘replaceValue’ as:

String replaceValue = "$100";

This would result in an exception of type ‘IndexOutOfBoundException’. This is because the ‘$’ symbol is used to identify a group from the regular expression which is the first parameter of ‘replaceAll’ or ‘replaceFirst’ method. We can solve this problem by:

  1. Using ‘replace’ method: This would be the good choice if you want to replace a string literal and not a pattern.
  2. Escaping ‘$’ symbol: If you need to a use regular expression, and your pattern has no groups identified, then you can escape any group identification symbols from your replace string as shown below:

String replaceValue = java.util.regex.Matcher.quoteReplacement("$100");

Posted in Programming, Tips. Tagged with , , , , , .

Taking a close look at inheritance and closures in Javascript

Let’s play with inheritance and closures in Javascript. Take a look at the following javascript code:


function BaseClass(){
	var id=200;
	this.Id=function(){
		return id;
	}
}

function ChildClass(){
	var id=500;
}

ChildClass.prototype = new BaseClass();
var childObject=new ChildClass();

In Javascript, inheritance is achieved using prototype. When we try to access any member on Javascript object, it first tries to search for the member within that object. If the member is found, then its accessed otherwise it tries to search for that member in its prototype object.

We make BaseClass the parent class of ChildClass with the following instruction:

ChildClass.prototype = new BaseClass();

Notice that ChildClass does not have a method called ‘Id’. When we make a call to method ‘Id’ on childObject, it will see that ChildClass does not have ‘Id’ method and so will take it from its prototype object which is nothing but the object of BaseClass.

Based on this knowledge, what do you think will be the output of the following instruction?

childObject.Id()

If you think it should be 500, then you are wrong. The correct answer is 200. This happens due to what is known as Closures. According to a tutorial on javascript closures by Morris Johns:

"a closure is the local variables for a function - kept alive after the function has returned"

To understand how this works in our case, let’s try to understand how javascript actually executes a call to the method ‘Id’ on childObject.

As childObject does not have a method called ‘Id’, it takes that method from its prototype and then executes it. You can imagine that Javascript performs the following steps to execute a call to the method ‘Id’ on childObject.


childObject.Id = ChildClass.prototype.Id;
childObject.Id();

But does its mean that in Javascript, it’s not possible to override the values from base class/object at all? Well, It is possible by making a small change to our code. Javascript has a keyword called ‘this’. The ‘this’ keyword points to the object in which the method being called is present. For more information on ‘this’ keyword, refer to the article ‘The this keyword’.

In our current code, we are defining a variable using keyword ‘var’ which makes it local to the function in which it is defined. Due to this, closure comes into picture and call to the method ‘Id’ always prints the value from the BaseClass. To solve this problem, we need to refer to the variable ‘id’ using ‘this’ keyword. This will tell our method to use the value from the object in which the method has been placed. In this way, when the method is placed in ChildClass object, it will print the value of ‘id’ from ChildClass and not from BaseClass. Thus, the modified code which allows overriding is given below:


function BaseClass(){
	this.id=200;
	this.Id=function(){
		return this.id;
	}
}

function ChildClass(){
	this.id=500;
}

ChildClass.prototype = new BaseClass();
var childObject=new ChildClass();

Posted in Programming. Tagged with , , .

Something useful: A WYSIWYG WordPress theme editor

Here’s an oldie but a goodie. Confounded by trying to track down fancy-looking WordPress themes? Check out this Web-

based theme editor that lets you tweak every nook and cranny of a theme then spit it back to your server to go live. You can add columns, change fonts and backgrounds, even throw in a customizable tag cloud–all with no coding experience required. All you need is a little creativity and some working knowledge of drop-down menus.

While some WordPress themes have excellent built-in support for doing this right from the WordPress dashboard,

many more don’t, and trying to figure out all the little things like text color is made far easier with a WYSIWYG editor than with WordPress’ built-in editing tools.

Advanced users can throw in graphics or design elements they’ve hosted elsewhere on their server (as long

as it’s got a URL to link up to), and when all is said and done each bit of the theme can be grabbed as an individual file to whatever theme you’re currently using. This is an easy way to try out new fonts and colors without making a mess out of your existing style.css file.


Source: Web Development

Posted in Tips.

Is JavaScript more object-oriented than other programming languages?



I started my career as a web developer before the dot.com crash. I learnt all about HTML, IIS, ASP, SQL Server and JavaScript. Equipped with the knowledge I built a few dynamic websites and carried my laptop with me to all my interviews and walked out of an interview with a job as a senior web developer. Before .NET existed, creating scalable and maintainable web application was not easy. ASP had a VB scripting engine. It was not scalable and it did its best to glue the web front end design with the backend database access. Most of the middle tier business logic and data access work had to be done using COM. Looking back you couldn’t build an elegant web application without .NET. JavaScript was used a lot in front-end web development mainly for client-side validation, scrolling tickers and special effects. But most developers never took Javascript seriously as a programming language. I know I didn’t but who would have guess that AJAX gave Javascript a more important position in the world of web development. Its power is hidden in the browser!

If you are not a Javascript developer, you will find writing client-side AJAX application in JavaScript a daunting task. That was one of the reasons Microsoft extended Javascript so that the Javascript language more closely resembles .NET languages such as C# and VB.NET. Actually JavaScript is an object-oriented programming language but there are a lot of C# and VB.NET OO type programmers who found coding in JavaScript less palatable.

In fact I read that some argue JavaScript is more object-oriented than C# or VB.NET. In C# and VB.NET, there are objects and classes and an object is an instance of a class but a class does not exist in its own right. In JavaScript, there are no classes. Classes do not exist. Only objects exist in JavaScript. One of the best feature of JavaScript is you can easily extend it. What is your thought on this?

Douglas Crockford shares his knowledge on JavaScript through his article “A Survey of the JavaScript Programming Language” which I think all web developers should read for a more in depth understanding of JavaScript as a programming language.

Here’s what Douglas Crockford say about JavaScript.

1. JavaScript is not Java. Neither is it a subset of Java. JavaScript shares C-family syntax with Java, but at a deeper level it shows greater similarity to the languages Scheme and Self. It is a small language, but it is also a suprisingly powerful and expressive language.

2. It is not a toy language, but a full programming language with many distinctive properties.

3. JavaScript contains a small set of data types. It has the three primitive types boolean, number, and string and the special values null and undefined. Everything else is variations on the object type.

4. Objects can easily be nested inside of other objects, and expressions can reach into the inner objects.

5. Arrays in JavaScript are hashtable objects.

6. Functions in JavaScript look like C functions, except that they are declared with the function keyword instead of a type.

7. Functions which are used to initialize objects are called constructors. The calling sequence for a constructor is slightly different than for ordinary functions.

8. Named variables are defined with the var statement. When used inside of a function, var defines variables with function-scope. The vars are not accessible from outside of the function.

Source: Development

Posted in Programming.

Binding HTML Form Fields To Javascript Objects

Consider that I have a object called 'person' with a property called 'Name' which returns me the name of a particular person. I want to assign this object property to a form element such that:

  1. The form element will display the value of object property (In our case, the value of person.Name)
  2. If I change the value in form, then it should automatically get assigned to the object property

In C#, it could be done by using the following piece of code:

nameTextBox.DataBindings.Add("Text", person, "Name");

I really like the way DataBinding works and would really like have something like this when I'm working on web applications to bind a object property to input elements in HTML forms. So I decided to write a small javascript that would allow me to bind object properties to form elements. For example, I wanted to write something like this:

<input type="text" object="person" property="firstName" />

Thanks to the power of Javascript and prototype library, I was able to use data binding in html forms using code:


function initializeFormBinding()
{
	var formElements = document.getElementsByTagName('input');
	$A(formElements).each(function(formElement)
				{
					Element.extend(formElement);
					initializeFormElement(formElement);
				});
}

function initializeFormElement(formElement)
{
	if (!(formElementHasObjectAttribute(formElement) &amp;&amp; formElementHasPropertyAttribute(formElement)))
		return;
	var objectName = getAttributeValue(formElement,'object');
	var propertyName = getAttributeValue(formElement,'property');
	window.eval('formElement.value = '+objectName+'.'+propertyName);
	window.eval('formElement.onchange=function(){ '+objectName+'.'+propertyName+' = formElement.value; }');
}

function formElementHasObjectAttribute(formElement)
{
	return getAttributeValue(formElement,'object')!=null;
}

function formElementHasPropertyAttribute(formElement)
{
	return getAttributeValue(formElement,'property')!=null;
}

function getAttributeValue(element, attributeName)
{
	return element.readAttribute(attributeName);
}

Lets see how to use this: First, create a javascript object. For example:


var person = {};
person.firstName = '';
person.lastName = '';
person.age = '';
person.country = '';

After that call initializeFormBinding() function using onLoad attribute of body tag. For example:


<body onLoad="javascript:initializeFormBinding();">

Now, in each of your input elements, put the name of the object in 'object' attribute and name of property in 'property' attribute as follows:


<form>
First Name:
<input type="text" object="person" property="firstName" /><br>
Last Name:
<input type="text" object="person" property="lastName" /><br>
Age:
<input type="text" object="person" property="age" /><br>
Country:
<input type="text" object="person" property="country" /><br>
</form>

Thats it.... If you initialize properties of person object, you would see those values in respective form elements. On the other hand, if you modify the value in a particular input element then it would get reflected in the corresponding object property. Anybody is free to use this code in their applications.

Download a small example application..

Posted in Programming. Tagged with , , , , , .

Using JSON in Alfresco WebScripts

In my current project, we are using Alfresco for the content repository and all the extra functionalities required are developed using Webscripts. While working on one functionality, I had to serialize javascript objects to JSON and also deserialize it. For doing this, there is a nice javascript code on Alfresco Wiki for converting the object to JSON and vice versa. But to use it, you need to make some slight modifications to the code. The original code doesn't generate proper JSON code and also has a syntax error in method to obtain the javascript object back from the JSON string. So here is the proper code for handling JSON:

 
/*
   json.js
(modified 2006-09-07): added support for RHINO
(modified 2006-05-02): json.parse, json,stringify added
  USAGE:
  var jsObj = JSON.parse(jsonStr);
  var jsonStr = JSON.stringify(jsObj);
*/
if (!this.json) {
  var json = (function () {
      var m = {
              'b': 'b',
              't': 't',
              'n': 'n',
              'f': 'f',
              'r': 'r',
              '"' : '\"',
              '': ''
          },
          s = {
              array: function (x) {
                  var a = [], b, f, i, l = x.length, v;
                  for (i = 0; i &lt; l; i += 1) {
                      v = x[i];
                      f = s[typeof v];
                      if (f) {
                          v = f(v);
                          if (typeof v == 'string') {
                              a[a.length] = v;
                              b = true;
                          }
                      }
                  }
                  return '['+a.join()+']';
              },
              'boolean': function (x) {
                  return String(x);
              },
              'null': function (x) {
                  return "null";
              },
              number: function (x) {
                  return isFinite(x) ? String(x) : 'null';
              },
              object: function (x) {
                  if (x) {
 
                      if (x instanceof Array) {
                          return s.array(x);
                      }
                      if (x.hashCode) return s.string(+x.toString());
 
                      var a = [], b, f, i, v;
                      for (i in x) {
                          v = x[i];
                          f = s[typeof v];
                          if (f) {
 
                              v = f(v);
 
                              if (typeof v == 'string') {
                                  a.push(""+s.string(i)+':'+ v+"");
                                  b = true;
                              }
                          }
                      }
                      return '{'+a.join()+'}';
                  }
                  return 'null';
              },
              string: function (x) {
                  if (/["x00-x1f]/.test(x)) {
                      x = x.replace(/([x00-x1f\"])/g, function(a, b) {
                          var c = m[b];
                          if (c) {
                              return c;
                          }
                          c = b.charCodeAt();
                          return 'u00' +
                              Math.floor(c / 16).toString(16) +
                              (c % 16).toString(16);
                      });
                  }
                  return '"' + x + '"';
              }
          };
 
     return {
        parse: function(s) {
           try {
              return !(/[^,:{}[]0-9.-+Eaeflnr-u nrt]/.test(s.replace(/"(.|[^"])*"/g,""))) && eval('(' + s + ')');
           } catch (e) {
              return false;
           }
        },
        stringify: s.object
     };
  })();
}

Here is how to use this code to serialize a javascript object:

 
	o={};
	o.name = "Name";
	o.id = 1;
	j = json.stringify(o);

Also, to obtain the object back from JSON string, you can use following method:

 
	x = json.parse(j);

Posted in Programming, Technologies.