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

Oct282008

Lazy loading, immediate loading, performance

While i am still reading the linq book i mentioned yesterday, i also  keep working on the projects at work (i need money to pay the bills). One of the pages i did using linq was very slow, and i ran the profile and guess what, lot's queries were sent to the  database by linq. I decided to read more about linq :) before i use it in the production system. At chapter 4, i read about lazy loading and immediate loading, and decided to share it here. I am sure all of you know about linq and its lazy loading mechanism, although this is most of the time performance saver, if you dont really look into your code, this also could kill your app. Here is a simple code example using northwind database (the code is from "Programming LINQ" Ms Press)

[code:c#]

var query = from c in Customers
                  where c.Orders.Count>20
                  select c;

foreach(var row in query){
    Console.WriteLine(row.CompanyName);
    foreach(var order in row.Orders){
         Console.WriteLine(order.OrderID);
    }

[/code] 

The bold part is the performance killing part, each time you ask for row.Orders, LINQ makes a query to the Orders table to get the related Orders, and this row.Count times inner query. However if you have loaded the Orders while you are loding the Customers, then you dont need this inner query. So you should really look at your code and decide if you need lazy loading or immediate loading. BTW here is the immediate loading:

[code:c#]
DataLoadOptions loadOptions = new DataLoadOptions();
loadOptions.AssociateWith<Customer>(c=>from o in c.Orders
                                                               where o.OrderDate.Value....);
loadOptions.LoadWith(Customer>(c=>c.Orders);
db.LoadOptions = loadOptions;

[/code] 

You should really buy and read this book btw :)

 



Tags:

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

Oct272008

Store? Linq?

Today while i was reading "Programming Microsoft LINQ" book, i learnt a very interesting attribute of an entity that i like to share.  So let's assume you have Student class which has FirstName, LastName etc members, and let's assume this class is a entity in LINQ; the pseudo code could like this:

[code:c#]

[Table] public class Student
{
     [Column]
      public string FirstName{
             get{ return this.FirstName_.ToLower();     }
             set{ this.FirstName_ = value.ToLower();}
     [Column}
     public string LastName{....

[/code] 

 When you create an instance of this class, and try to change the value of FirstName from the class instance, the getter and setter functions will be called. However when this is a linq entity, this change a little bit. If you try to update a value using linq over here, the scenario changes a little bit. If you use the above code and use linq to update the entity, linq will use getter setter functions. However if you decorate the member with "Storage" such as:

 

[code:c#]

[Table] public class Student
{
     [Column(Storage="FirstName_"]
      public string FirstName{
             get{ return this.FirstName_.ToLower();     }
             set{ this.FirstName_ = value.ToLower();}
     [Column}
     public string LastName{....

[/code] 

Now Linq will skip the getter and setter functions and will directly access to the private member to update it :)

so watch out.

 

 



Tags:

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

Oct262008

MVC Presentation at CodeCamp

oday i was a speaker at the socalcodecamp for the first time. First let me talk about what i think about this codecamp as a listener :).

I saw that the presentation titles do not really match with presentation contents. Usually the titles are too much promising, raising the bar, and ... content is totally different. Another interesting thing is that, i was expecting lots of talks about MVC and Silverlight but didnt find much. It was usually patterns, methodoligies. So hopefully next codecamp will be full of mvc and silverlight :). 

Besides this, the campus was nice, though there was a parking problem as some of the gates were closed, and i think when you host an event that you expect a few hundred people to few thousand people, you should give a map that tells you where the restrooms and restaurants are.

As a speaker, i was very much excited i guess during the presentation, but i think i did good :). I will upload the slides and some of the photos too, this presentation motivates me to come up with a few more presentations for the next codecamp.

 Here is my presentation file in powerpoint format:

Introduction to MVC.pptx (224.09 kb)

 I find this MVC thing really fun to play with, it is simple, easy but requires sometime to learn it.  Once you get the concept, i am sure you will enjoy it.

Especially when you start writing unit tests, not only it gives you more confidence about the stability of your code, but also you start learning how to code loosely coupled  objects. I am a newbie in unit testing, but even myself, when i write the function( i apply TAD sometimes), i think, ok how am i going to do test this, when there is these dependicies, and i start refactoring the code. Anyways :) you will find tens of photos at my facebook profile :)

have fun 

 



Tags: ,

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

Sep272008

MVC, YABE, Rhino.Mocks

i start studying MVC, had no idea about it last week, was doing all my work using asp.net. After attending a few user groups, and reading Scott Guthrie's blog i decided to study it. A very newbie, little knowlegde but trying to learn. Whenever i have time, trying to contribute a little to a open source blogging project called YABE (Yet Another Blogging Engine) hosted at codeplex. Mostly i am doing unit testings, and using rhino mocks to unit test some of the functionalities, as i am also kinda new to rhino.mocks, i am learning this too :). 

 



Tags:

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