Nov182008

IComparable, IEquatable

I am still reading the book about writing more effective c# code. One of the chapters is talking about using IComparable and IEquatable for comparions, and checking equality. The news interfaces are strongly typed, so the code is less, cleaner, and nicer; however, for a lot of purposes you may want to support old style override Equals(object obj) too, and as good practive whenever you overwrite Equals, you should overwrite GetHastCode, especially if you are using LINQ or update wont work.

here is a simple code from one my project that does it all 

[code:c#]

 public class Restriction:IComparable<Restriction>,IEquatable<Restriction>
    {
        /// <summary>
        /// Restriction Unique ID, should be assigned by DB
        /// </summary>
        /// <remarks>if it is <1 then throws ArgumentOutOfRangeException</remarks>
        private int ID_;
        public int ID
        {
            get{ return this.ID_;}
            set
            {
                if (value<1)
                    throw new ArgumentOutOfRangeException("ID can not be less then 1");
                this.ID_ = value;
            }
        }
        /// <summary>
        /// Restriction rule
        /// </summary>
        /// <remarks>If it is empty or null, will throw ArgumentNullException
        ///          If len(Rule)>MAX_RESTRICTION_LEN throws ArgumentOutOfRangeException
        /// </remarks>
        /// <seealso cref="Constants"/>
        private string Rule_;
        public string Rule
        {
            get { return this.Rule_; }
            set
            {
                if(String.IsNullOrEmpty(value))
                    throw new ArgumentNullException("Rule can not be empty or null");
                if(value.Trim().Length==0)
                    throw new ArgumentNullException("Rule can not be empty or null");
                if(value.Trim().Length>Constants.MAX_RESTRICTION_LEN)
                    throw new ArgumentOutOfRangeException("Length of Rule can not be bigger than MAX_RESTRICTION_LEN");
                this.Rule_ = value;
            }
        }

        public Restriction(int ID, string Rule)
        {
            this.ID = ID;
            this.Rule = Rule;
        }

        public int CompareTo(Restriction other)
        {
            if (other == null)
                return 1; // any non null object > null
            int rVal = Comparer<string>.Default.Compare(this.Rule.ToLower().Trim(),
                                                        other.Rule_.ToLower().Trim());
            return rVal;
        }

        public bool Equals(Restriction other)
        {
            if (Object.ReferenceEquals(other, null))
                return false;
            return this.Rule.ToLower().Trim() == other.Rule.ToLower().Trim();
        }

        public override bool Equals(object obj)
        {
            if (obj.GetType() == typeof(Restriction))
                return this.Equals(obj as Restriction);
            return false;
        }

        public override int GetHashCode()
        {
            return this.Rule.ToLower().Trim().GetHashCode();
        }

        public override string ToString()
        {
            return this.Rule;
        }
    }

[/code]



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Nov102008

Refactor code, Design Practices

I start reading "More Effective C# from Bill Wagner". It is a really nice book, unlike the other books i read, with this book i start reading random chapters. Actually not that random, the chapters that i like more :) I will highly recommend this book btw.

So lets take a look at the Item 17: Create Composable APIs for Sequences

here is a simple code from the book:

[code:c#]

public static void Unique(IEnumerable<int>num)
{
   Dictionary<int,int>uniqueVals = new Dictionary<int,int>();
   foreach(int num in nums)
   {
      if(!uniqueVals.ContainsKey(num))
         {
    uniqueVals.Add(num,num);
    Console.WriteLine(num);
         }
   }

[/code] 

 So what's wrong with the code above? First of all, the code is writing the unique numbers to the console on a passed IEnumerable<int>. However, the function is doing more than 1 principal job, it does 2 different things. First it loops through the numbers, collects the unique numbers in a dictionary, and second, it writes the numbers to the console. Because of 2 unrelated jobs being assigned to this function, it is not easy to reuse the code, and also not easy to  unit test the code. If you could seperate this 2 jobs into 2 different functions, it will be easier to unit test this code and also reuse this code. Let's try to do refactor code as step 1 progress:

[code:c#]
public static Dictionary<int,int> Unique(IEnumerable<int>num)
{
   Dictionary<int,int>uniqueVals = new Dictionary<int,int>();
   foreach(int num in nums)
   {
      if(!uniqueVals.ContainsKey(num))
         {
    uniqueVals.Add(num,num);
 }
   }
   return uniqueVals;


private static void PrintUniques(IEnumerable<int>numbers)
{
      Dictionary<int,int>uniqueVals = Unique(numbers);
      foreach(int num in uniqueVals )
      {
         Console.WriteLine(num);
      }

[/code] 

Now we divided the function into 2  functions, and they can be easily reused as they only do 1 task, also it is easier to unit test it (to unit test PrintUniques function, you can use StreamWriter instead of console). However we can easily refactor this code more :), using "yield". Yield is an interesting function, it returns the value while you are iterating one at a time. One big advantage is you dont have to load the whole array into the memory, so if in any part of your loop, you have an exit from the iteration, you wont end up having everything loaded in the memory and not using it :) So you will get the value, and the index pointer will move to the next element, for the next step in the iteration. This is kinda like lazy loading in LINQ. Here is the code again:

 [code:c#]

public static IEnumerable<int> Unique(IEnumerable<int>num)
{
   Dictionary<int,int>uniqueVals = new Dictionary<int,int>();
   foreach(int num in nums)
   {
      if(!uniqueVals.ContainsKey(num))
         {
    uniqueVals.Add(num,num);
            yield return num;
 }
   }


private static void PrintUniques(IEnumerable<int>numbers)
{
      foreach(int num in Unique(numbers))
      {
         Console.WriteLine(num);
      }

[/code] 

 Hope it is clear and easy to understand. Let me know if you have any questions. 



Tags: ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Nov082008

Validating Url, Email, IP

In one of the project i am working at, i need to validate a url, an email and ip address. I googled so many regular expressions, and almost %99 of the ones i found had some issues :). I collected the working one, in an extension class, so that i can use extensions to validate now. Here is the class i have:

[code:c#]

  public static  class Validations {

 

        public static bool IsValidEmail(this string Email)

        {

            if (String.IsNullOrEmpty(Email))

                return false;

            string strRegex = @"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}"+

                                @"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" +

                                @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$";

            Regex re = new Regex(strRegex);

            if (re.IsMatch(Email))

                return (true);

           

           return (false);

        }

 

        public static bool IsValidIPAddress(this string IP)

        {

            if(String.IsNullOrEmpty(IP))

                return false;

            IPAddress ipAddress;

            bool valid = IPAddress.TryParse(IP, out ipAddress);

            return valid;

        }

 

        public static bool IsValidUrl(this string Url)

        {

            if(String.IsNullOrEmpty(Url))

                return false;

            string strRegEx = @"^(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)?@)"+

                            @"?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,4}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*"+

                            @"(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?$";

           Regex re = new Regex(strRegEx);

            if(re.IsMatch(Url))

                return true;

            return false;

        }

    }

[/code] 

Have fun :) 



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Nov072008

Nov 11th - 13th - Irvine Tech Days 08

If you are like me, who could never attend a pdc in your life :), but also curious about the new stuff before even they are released, this is the event for you. It is kinda like pdc, but FREE :)
You will find interesting topics such as C# 4.0, Silverlight from a well known speakers, and it is at IRVINE :)

check it out:  http://www.msdnevents.com/orangecounty/



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Nov062008

Tips and Tricks from SANS

i am taking sans web security training. here are some live tips and tricks :)

 

  • If you have file upload to the server, dont let users pick the filename (directory traversal)
  • if you have file upload to the server, dont upload the files to a folder where u can execute scripts (iis/wwww)
  • escape every input, sanitize everything, users are evil
  • there are some tools out on the internet, that lets attackers' life easier.
  • buffer overflow attacks can cause DoS so know the language you are using on the server side.
  • watch out for unicode attacks. dont just look for <> ...
  • once the user logins to your system, change the session id to prevent session hijacking.
  • remote file include attack is very common in php environments.n If you have a web site that lets the user to choose the templates. and you pass the template file in the querystring, this could be manipulated. check and sanitize the querystring .NET is stopping these kind of attacks, as a developer you have to try hard to write remote file attack vulnerable code.
  • try to have a centralized validation, try to have retrieve and validate in one function
  • javascript can be disabled very easily :) dont trust on javascript validation.

 



Tags:

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses

Nov032008

const vs readonly

Probably you already know that, const variable must be assigned a value when they are defined, however readonly values can be assigned a value during the construction time,after they are declared. Is there any other differences we should know? Well, let's look at a simple class:

[code:c#]

 public class constref
    {
        public const int MagicNumber = 5;
        public readonly int MagicNumber2 = 10;
    } 
[/code] 

I declared a simple class, that has 2 public members, a const and a readonly, after i compile this, and using ildasm i look at dll file. Here is what i got for the constant value MagicNumber:

[code:c#]
.field public static literal int32 MagicNumber = int32(0x00000005)
[/code] 

The variable is converted into a static int32 and its value is assigned right away. This means, if any other dll is referencing this dll,  when they dereference MagicNumber, at the compile time, the value of MagicNumber will be replaced to that library. Example: Assembly B is referencing the MagicNumber variable inside this constref class, and in the code it has something like: constref.MagicNumber => this will be replaced with 5 during compilation.  Which also means, if you change the constref code, and set the const value to 8, and dont compile Assembly B, assembly B will still have 5 (the old value).

Let's look at the readonly variable after compile: 

[code:c#]
//this is the decleration:
.field public initonly int32 MagicNumber2

//this is the constructor created by compiler:
 .method public hidebysig specialname rtspecialname 
       instance void  .ctor() cil managed
{
  // Code size       16 (0x10)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldc.i4.s   10
  IL_0003:  stfld      int32 constvsreadonly.constref::MagicNumber2
  IL_0008:  ldarg.0
  IL_0009:  call       instance void [mscorlib]System.Object::.ctor()
  IL_000e:  nop
  IL_000f:  ret
} // end of method constref::.ctor
[/code] 

This time, the value isnt assigned at the declare time (even though that is what we did), but it is assigned at the constructor. One big advantage is that, if we apply the same scenario, Assembly  B derefencing the value of MagicNumber2, will be using runtime values. So we change the source for constref class, and assign 20 to MagicNumber2, and just recompile constref, we dont have to compile Assembly B to reflect the new changed



Tags: ,

E-mail | Permalink | Trackback | Post RSSRSS comment feed 0 Responses