Thursday, April 12, 2012

How to use conditional operator(?:) in c# in a string?

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression.

The condition must evaluate to true or false. If condition is truefirst_expression is evaluated and becomes the result. If condition is falsesecond_expression is evaluated and becomes the result. Only one of the two expressions is evaluated.
Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.
This is what MSDN says. :)
Now: it might help you to know how to use conditional operator when generate a string. I will give you a simple method which receives a input parameter and according to that will generate a link.


public string GenerateLink(string Option)
    {
        string Response = "";
       Response = "<a href=\"YourPage.aspx?option=" + ((Option == "holiday") ? "goHoliday" : "goAndWork").ToString() + "\">Click</a>";
        return Response;
    }

So, don't hesitate to use conditional operator whenever you are in need of it.
Have a nice day.

Friday, April 6, 2012

How to verify if two strings are equal in Sql?

This question might appear to you when you want to verify credentials for a user at login.
I found out that for SQL these two conditions will give the same result.
1. if(@Password = 'test')
or
2. if(@Password = 'test ')
(note the space)
So there is a problem.
I found out a simple solution for comparing these two strings. When you compare strings you have to hash them. So we are going to use Hashbytes function. Here you can find more details.
For our example we can verify like this:
if ( HASHBYTES('MD5', convert(nvarchar(50), @Password )) = HASHBYTES('MD5', 'test ' ))
will return expected result.
One think to note: it is important to keep in mind datatype. Datatypes must be the same otherwise you won't get the same hash. Md5 has in mind even data types when converting ;)

Hope will help you.