Tuesday, August 24, 2010

Don't get caught up with IComparable and IComparer, just implement it.

IComparable and IComparer sounds similar but don't get caught up by their name, even though they have similar names they serve different purpose.
If we want to have an ability of sorting or comparison capability for our custom objects, then we must impelment either or both of these interfaces.

Lets start by creating an object called "Employee" and add them to a list called employees.

class Employee
    {
        public string Name { get; set; }
        public int Id { get; set; }  
    }

static void Main(string[] args)
        {
            var employees = new List<Employee>();
            employees.Add(new Employee { Id = 6666, Name = "Jack" });
            employees.Add(new Employee { Id = 1111, Name = "John" });
            employees.Add(new Employee { Id = 2222, Name = "David" });
        }

Now, if your try to sort this by
employees.Sort() then you will get and exception :


InvalidOperationException was unhandled
"Failed to compare two elements in the array."
Inner Exception : {"At least one object must implement IComparable."}

In other words, the error is asking us what we mean by sorting employees.
 Well, it is clear from the exception that we need to implement the IComparable interface to be able to sort the employees list.
IComparable is used for comparing two objects of a particular type. It can be thought of as default sort provider for our objects.
Hence, we implment the IComparable as follows :
class Employee : IComparable
    {
        public string Name { get; set; }
        public int Id { get; set; }

        // Implement IComparable CompareTo method - provide default sort order.
        int IComparable.CompareTo(object obj)
        {
            Employee c = (Employee)obj;
            return String.Compare(this.Name, c.Name);

        }
    }

The IComparable requires the implementation of a method called CompareTo.

Now if you do
employees.Sort() , it will sort based on the Name.
ICompares is similar to IComparable but it can provide additional comparison mechanisms. We may want to sort our list in descending / ascending order or may want to order our object based on several fields or properties, it is all achieveable by using IComparer.

IComparer requires the implementation of the method called Compare and takes two parameters. They are two objects we are going to compare.

We can implement IComparer as follows :
class EmployeeComparer : IComparer<Employee>
    {     
        public int Compare(Employee emp1, Employee emp2)
        {
            if (emp1 == null & emp2 == null)
            {
                return 0;
            }
            else if (emp1 == null)
            {
                return -1;
            }
            else if (emp2 == null)
            {
                return 1;
            }
            else if (emp1.Id < emp2.Id)
            {
                return -1;
            }
            else if (emp1.Id == emp2.Id)
            {
                return 0;
            }
            else
            {
                return 1;
            }
        }
    }


Once you have implmented the IComparer you will be able to use
employees.Sort(new EmployeeComparer());   to do you comparison.
References

http://www.aspfree.com/c/a/C-Sharp/Building-Csharp-Comparable-Objects-IComparable-versus-IComparer/2/
http://support.microsoft.com/kb/320727
http://codebetter.com/blogs/david.hayden/archive/2005/03/06/56584.aspx
http://dpatrickcaldwell.blogspot.com/2009/03/implementing-icomparer-in-c.html
http://www.c-sharpcorner.com/uploadfile/camurphy/csharplists03302006170209pm/csharplists.aspx

Monday, August 23, 2010

C# - Fibonacci and lambda expression using Func Delegate

All of us who deal with C# in day to day life must have come across Func<T, TResult> Delegate many times, where T is the type of the parameter of the method and TResult the type of the return value of the method that this delegate encapsulates.

Lets try using Func on the Fibonacci squence.
Fibonacci sequence is a sequence of the numbers where the next number is found by adding up the two numbers before it.
eg.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...

  • 2 is found by adding the two numbers before it(1+1)
  • 3 is found by adding the two numbers before it(1+2)

This Fibonacci Sequence can be written as a "Rule" :
                                 The Rule is xn = xn-1 + xn-2

where:
  • xn is term number "n"
  • xn-1 is the previous term (n-1)
  • xn-2 is the term before that (n-2)
There are many ways we can write the "Fibonacci" in C#:

A.
public static int Fibonacci(int n)
        {
            int previous = -1;
            int result = 1;
            for (int i = 0; i <= n; i++)
            {
                int sum = result + previous;
                previous = result;
                result = sum;
            }
            return result;
        }
B.
static int Fibonacci (int x)
{
   if (x <= 1)
      return 1;
   return Fibonacci (x-1) + Fibonacci (x-2);
}
C. Using the .Net 3.5 we can wirte this using Func

 static void Main()
{
    Func<int, int> fib = null;
           fib = n => n > 1 ? fib(n - 1) + fib(n - 2) : n;

        Console.WriteLine(fib.Invoke(10));
}

Other example of Func :
static void Main()
{
    Func<int, string> funcTest = (x) => string.Format("String is = {0}", x);
}

Sunday, August 22, 2010

Protect your Data in USB via BitLocker

Out of many data encryption packages, "BitLocker" is one of them.
We all face the same problem of securing our USB drives from the prying eyes. Well, BitLocker comes with Windows 7 Ultimate edition for our rescue and it is easy to setup.
Just Right-click your USB drive select "Turn on BitLocker" and follow the easy instructions to protect your private files.

Computer - Evil Maid attack

While researching the net over the security, I came across the term "Evil Maid" attack.
So, what is the "Evil maid" attack?

Well, here's the story.
Lets assume you leave you laptop in a hotel room and go lunch/dinner. The house maid comes in to clean the room.But, she is just any ordinary house maid, while she is there she installs the boot loader and key logger, then shuts down your laptop.
You return to the hotel room, you power on your laptop, enter the passphrase, do you work.
The next day, when the maid returns, she returns, most likely to either retrieve the key and restore the previous boot loader, erasing her tracks.
Now she has access to your data, can image the drive for offline analysis and perform all sort of nasty stuffs as desired. Hence, the term "Evil Maid".

Friday, August 20, 2010

What is Encapsulation and Ripple Effects?

When we hear the word "encapsulation" we think about "the condition of being enclosed". This concept may be similar in the programming world but we got to think what is encapsulation used for?

Are we encapsulating the object to protect the object or could it be for something else?

Generally, encapsulation is often mistook for the information hiding. Of course, it can be used for information hiding but encapsulating an object is not about securing/protecting the object. "Encapsulation is about freeing your consumer from the knowledge of your implementation details. By doing so, you insulate your consumer from any ripple effect of changes to your implementation" ( from http://thetechcandy.wordpress.com/2010/01/04/encapsulation-is-not-information-hiding").

Let me elaborate this, No matter how hard we try, we will often need to go back and modify the code after an application has been deployed. This could be due to the design flaw, change in requirement or many other reason.Eventually, this can lead us to the ripple effect where we will need to change many lines of code throughout application and retest them all. Now, if we have used encapsulation correctly we can change the private data structure without affecting how an object belonging to that class gets used in client code.

WCF - The document format is not recognized (the content type is 'text/html; charset=UTF-8').

Well, I faced a strange issue today while trying to deploy my WCF Service on a server.

Everything seemed to work perfectly, and I can even see the service on my browser, until when I tried to test this through a "wcftestclient" I encountered this error message.



Error: Cannot obtain Metadata from http://192.168.0.15:8090/service.svc

If this is a Windows (R) Communication Foundation service to which you have access, please check that you have enabled metadata publishing at the

specified address.
 For help enabling metadata publishing, please refer to the MSDN documentation at http://go.microsoft.com/fwlink/?LinkId=65455.

WS-Metadata Exchange Error    URI: http://192.168.0.15:8090/service.svc  

Metadata contains a reference that cannot be resolved: 'http://192.168.0.15:8090/service.svc'.   

There was no endpoint listening at http://192.168.0.15:8090/service.svc that could accept the message.

This is often caused by an incorrect address or SOAP action.

See InnerException, if present, for more details.   

The remote server returned an error: (404) Not Found.HTTP GET Error    URI: http://192.168.0.15:8090/service.svc   

The document at the url http://192.168.0.15:8090/service.svc was not recognized as a known document type.The error message from each known type may help

you fix the problem:-

 Report from 'http://192.168.0.15:8090/service.svc' is 'The document format is not recognized (the content type is 'text/html; charset=UTF-8').'.-


Report from 'DISCO Document' is 'There was an error downloading 'http://myComputer.mydomain.local:8090/Service.svc?disco'.'.  -

The remote name could not be resolved: 'myComputer.mydomain.local'- Report from 'WSDL Document' is 'The document format is not recognized (the content type is

'text/html; charset=UTF-8').'.-

Report from 'XML Schema' is 'The document format is not recognized (the content type is 'text/html; charset=UTF-8').'.

I could not figure out what the issue was. It worked perfectly on other machine and it was basically the copy from the other server. But I was getting the above error.

After trying for couple of ours from my machine connecting to this server. I decide I will install free version of "WCFStorm-Lite" on the server and see I can download the meta-data on the 'wcftestclient'. And guess, what I was able to do it, which puzzled me more.
Why would it run on the local mahince but not over the network??

Well, the answer my friend is in the question itself. Some the DNS address of the server I was trying to connect to wasn't registered by our IT department.
Hence, what was happening was whenever I try to connect to the ip-address, to get the meta-data it was actually trying to connect to "myComputer.myDomain.local" but since "myComputer.myDomain.local" was configured for any ip-address it was getting lost.

Hence, what I had to do was to get my "IT Department" to register "myComputer.myDomain.local" for the ip-address "192.168.0.15". Even tested this my trying to "ping myComputer.myDomain.local" which resolved to 192.168.0.15.

Finally, tested the WCFTestClient and it worked like a charm.

If any of you out there are having the same issue try the solution above, it may fix your issue as well.
Good Luck.

Thursday, August 19, 2010

TestCaseAttribute a friend in NUnit

Most of us are already familiar with the NUnit. I hope we all have written lots and lots of test cases to check our code. Among many attributes of NUnit, one of my favourite is a  'TestCaseAttribute'.

As quoted on Nunit.org "TestCaseAttribute serves the dual purpose of marking a method with parameters as a test method and providing inline data to be used when invoking that method."

This attribute helps us to run few common test on a single go and also helps us to group thest test cases together.
eg. 
        /// <summary>
        ///A test for Divide
        ///</summary>
        [TestCase(12, 3, Result = 4)]
        [TestCase(12, 2, Result = 6)]
        [TestCase(12, 4, Result = 3)]        
        [TestCase(12, 0, ExpectedException = typeof(System.DivideByZeroException),
             TestName = "DivisionByZeroThrowsExceptionType")]
        [TestCase(12, 0, ExpectedExceptionName = "System.DivideByZeroException",
             TestName = "DivisionByZeroThrowsException")]      
        public double DivideTest(int x , int y)
        { 
            return Functions.Divide(x, y);
         }
 I hope we can all use this attribute and use this functionality to make our life lot easier.

Tuesday, August 17, 2010

Adding new template to your blog.

http://about-new-blogger.blogspot.com/

http://www.betatemplates.com/2009/06/submit-site-sitemap-to-google.html

A new wave of click-jacking exploiting the browser saved password feature

A good friend of mine Anthony sent this today. I thought I will make everyone aware of this a well.

Click jacking has always been something of a not-so-useful attack due to the majority of sites that could be exploited using click jacking requiring some form of manual input.  Not so anymore. The advent of the Facebook ‘Like this’ button and variants has given attackers a new way to exploit click-jacking by hiding a transparent “Like this” button over an apparent link or other button. When the user clicks what they think is a link or innocuous button, the “Like this” button receives the click instead and signs the user up as a fan of a malicious site. This works in two ways. First, it gives immediate access to profile information and pictures that are viewable by friends, as well as the names and account ids of your personal friends. Secondly, attackers are using these tricks to build fake trust by giving pages that have links to malware or other exploits thousands of “fans”. Once trust has been established, an attacker may attempt to trick users into installing a malicious Facebook app, visit a malicious website, or to post messages on the user’s wall to attempt to socially engineer the user’s friends into being compromised as well.

Another attack vector growing in popularity involves Trojan/malware that target the saved-password feature present in modern browsers. These attacks can be fairly sophisticated, examining the user’s browser history for likely targets then using injection techniques to get the browser to auto-fill the username and password fields in a hidden form which can then be read by the software. Other variants monitor the active browser tab for password fields and attempt to capture any automatically filled information when a user visits a site they have saved credentials for. Of these, a new malicious “do it yourself” tool known as Facebook Hacker is a very striking example of how these attacks are being commoditized. Facebook Hacker presents a simple configuration form for the attacker to fill in, and a build button which will take that configuration and build an executable that contains a variety of exploit modules designed to read the protected password stores of many modern browsers, Instant messaging clients, and email applications. There are also modules to enumerate the credentials for dialup and VPN connections. The captured data is transmitted over a TLS secured link to the configured repository. Along with the password gathering, Facebook Hacker presents an additional threat as it will attempt to disable recognised anti-virus applications, firewall software, and packet inspection systems, leaving the compromised computer vulnerable to infections from other sources.

A recent study reported that of the samples captured information, 75% of users use the same password for email and other applications. For security purposes, it is highly recommended that at the minimum users should have separate passwords for all sensitive applications and only use a common password for services that do not contain sensitive or personally identifiable information. Passwords can be constructed using a scheme that incorporates the purpose of the password allowing for complex but easily remembers passwords to be used for different sensitive services.

Monday, August 16, 2010

Unit Testing , NUnit and Assert

Unit Testing
Most of us are used to testing the software once it completes the software development cycle. And many of us have a perspective of testing being just bug-fixing. Testing the software at the very end results in error detection at the very end as well, which may result in costing us more than if we had known the issue at the early stage.

Unit testing is a method by which we can test the usability of the piece of our source code. It helps us to determine the function we have written is fit to be used.
Moreover, it also helps us to determince if the function we have written still works at the later date, hence, helping us in regression testing.

NUnit
NUnit is one of the many tools we can use for Unit Testing.
It is an open source product which can be downloaded from http://www.nunit.org

NUnit requires test cases and one or more test fixtures. Each test must contain at least one assertion.

Example

Lets assume we want to test this function
 public static int Divide(int x, int y)
        {
            return x / y;
        }

To test this function in NUnit , we are required to create a test fixture and then a test itself.

[TestFixture]
    public class FunctionsTest
    {
        [Test]
        public void DivideTest()
        {
            Assert.AreEqual(4, Divide(12, 3));
        }
    }

Friday, August 13, 2010

What is Modular , Object-Based and Object-Oriented?

Lets clear our mind.
What is Modular ?
What is Object-based?
What is Object-Oriented ? How are they different?

If a language only supports encapsulation of objects it is modular.
But, if it supports encapsulation and polymorphism it is object based.
Whereas, if a language supports encapsulation, polymorphism and inheritance is it Object-Oriented.