Showing posts with label C# Learnings. Show all posts
Showing posts with label C# Learnings. Show all posts

Monday, 3 October 2011

Interfaces, Abstract Classes, Abstract Methods and Virtual Methods

Here is a synopsis about Abstract Classes/Methods:

  1. Only abstract classes can have abstract members.
  2. A non-abstract class that inherits from an abstract class must override its abstract members.
  3. An abstract member is implicitly virtual.
  4. An abstract member cannot provide any implementation (abstract is called pure virtual in some languages).
  5. An abstract class cannot be instantiated
I was reading some old notes of mine and got to thinking: can an abstract class have virtual methods?

The answer is 'implicitly, yes, explicitly, no' - confusing answer, yes? Point 3 above explains it. Any 'abstract' method is, in fact, 'virtual' in that it can be implemented by a deriving class - and in fact, if it is declared 'abstract', it MUST be implemented by a deriving class.

In the case of an Interface:

  1. No Interface members can provide any implementation
  2. An implementing class (note that Interfaces are 'implemented', not 'inherited' from) must implement all members of the Interface

Wednesday, 3 August 2011

UPDATE: TryGetValue Extension method for IDataReader !Version 2!

My older post XXX detailed a pattern for retrieving values from a DataReader.

This can actually be further enhanced so that you do the Cast and Check all in one line using the power of LINQ syntax:

public static bool TryGetValue(this IDataReader source, string name, Action<object> value)
        {
            try
            {
                if (source[name] != null && source[name] != DBNull.Value)
                {
                    value(source[name]);
                    return true;
                }
            }
            catch
            {
            }

            return false;
        }

Then to call it, you do something like

reader.TryGetValue("test", x => myInt = Convert.ToInt32(x));

Saturday, 23 July 2011

Email Validation: Server Side or Client Side???

Really, i think it should be both.

The last line of defense is the server side - that should be mandatory.

Client Side validation, in my opinion, is purely for the benefit of the user in that they get instant feedback on how to correct their input, before it's even a problem...other obvious benefit is that reduces resource requests on the server as it avoids having to post back to the server every time you need to validate some input.

In the event that the Client Side validation does not perform its duties, unless you validate on the server as well, you've left your site wide open for attack - so you should really have both.

If you were to only validate *some* things client side and others server side (eg REGEX validation on email syntactically client side and then server side, validate that that particular email isn't already registered on the site)

Server Side

This appears to be a popular routine around the net:

public static bool isEmail(string inputEmail)
{
   inputEmail  = NulltoString(inputEmail);
   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(inputEmail))
    return (true);
   else
    return (false);
}

Shawpnendu has another method which appears a little cleaner. He creates static Validation class which encapsulates commonly required validation routines. ValidateEmail being one of them. I prefer to call mine something more like "IsEmailValid". Using Shawpnendu's example, my derivation is:

public static class Validation
{
   public const string EmailStandard = @"^[a-zA-Z0-9._-]+@([a-zA-Z0-9.-]+\.)+[a-zA-Z0-9.-]{2,4}$";
   public static bool IsEmailValid(string emailID)
   {
      if (emailID != null)
         return System.Text.RegularExpressions.Regex.IsMatch(emailID, EmailStandard);
      else
         return false;
   }
}

// USAGE: ELSEWHERE IN CODE-BEHIND etc.
if (Validation.IsEmailValid(txtEmail.Text))
{
   //Valid Email
}
else
{
   //Invalid Email
   //Notify user
   return;
} 

Client Side

Here is an example of client side validation which takes advantage of the RegularExpressionValidator control provided as of ASP.Net 1.1:

<div class="divContainerCell">
<asp:textbox id="txtEmail" runat="server"></asp:textbox>
    <asp:requiredfieldvalidator 
controltovalidate="txtEmail" 
errormessage="Please provide your email address!" 
forecolor="Red" 
id="valRequiredEmail" 
runat="server">*</asp:requiredfieldvalidator>
 
<asp:regularexpressionvalidator 
controltovalidate="txtEmail" 
errormessage="This does not appear to be a valid email address!" 
forecolor="Red" id="RegularExpressionValidator2" 
runat="server" 
validationexpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
>*</asp:regularexpressionvalidator>
</div>

Saturday, 9 July 2011

LINQ to SQL: using First vs FirstOrDefault

In the Fisharoo examples of ASP.Net 3.5 Social Networking, there is an AccountRepository class which will retrieves populated Account entites from the database using LINQ to SQL.

Here is a snippet of the code:

        public Account GetAccountByID(int AccountID)
        {
            Account account = null;

            using (FisharooDataContext dc = conn.GetContext())
            {
                account = (from a in dc.Accounts
                           where a.AccountID == AccountID
                           select a).First();
            }
            return account;
        }

See any problems with this code?

I didn't...but after running it the during development when my Account table had no records...ie i was running the Application and Registering the very first user ever...the above code threw this exception on the LINQ code:

System.InvalidOperationException: Sequence contains no elements

This is happening because the LINQ query is returning an empty set and then you're trying to call .First() on it.

I don't understand why this was written this way...especially for the GetByID method...it seems quite likely to me that there would be instances where this code could be called with an ID of an account that doesn't exist.

Either way, its easy fixed by using the FirstOrDefault() method instead...this will simply assign 'null' to the 'account' variable in the event that the LINQ query returns an empty set - lovely!

Friday, 1 July 2011

C# const char[]

Today i learnt, to my dismay, that you can't have a char array and make it a const

In fact, the compiler told me:

"A const field of a reference type other than string can only be initialized with null."

So after some searching i found that i could either:

1. Use a string type and make it a const
 - but i need to pass back a char[] to i'd have to do some converting of sorts...

2. Use an ENUM
 - again i'd need to do some converting but there is always the convenient ENUM.GetValues() method but that'll only return the int values...

So instead, i declared a private local char[] variable as well as a public Accessor method but no Mutator, effectively then making it a 'const':

private static char[] _digits = {'0','1','2','3','4','5','6','7','8','9'};

/// <summary>
/// An array with characters representing digits from 0 to 9
/// </summary>
public static char[] DIGITS
{
    get { return _digits; }
}

Tuesday, 28 June 2011

C# Property vs Attribute

Ever wondered what these two terms really mean?

Well, its a potentially lengthy discussion...but after a quick research, the general synopsis can be summed up with a couple of sentences:

1. Properties relate to the "Has a..." relationship and Attributes relate to the "Is a..." relationship
eg A Car "Has a" set of Doors whereas a Car "Is..." Drivable

2. In OOP we are modelling 'things' and we have 'mechanisms' to model them with. In this context Properties are used to help 'model the things' and attributes are used to 'describe the mechanisms'
eg A Car has a property Color and the class used to model the car has an attribute 'Serializable'

[Serializable]
public class Car{
    ...
    public string Color{ ... }
}

If it's all still confusing for you see this great post by Eric on 'Properties vs Attributes'

Monday, 27 June 2011

Object and Collection Initialization

C# 3.0 Introduced a short hand you can use while instantiating new instances of objects.

You can change the following code:

Car myMustang = new Car();
myMustang.Manufacturer = "Ford";
myMustang.YearOfMake = "1969";

To something much neater like:

Car myMustang = new Car()
{
     Manufacturer = "Ford",
     YearOfMake = "1969"
};

You can also nest the object initialization:


Car myMustang = new Car()
{
     Manufacturer = "Ford",
     YearOfMake = "1969",
     Seat = new Seat 
     {
            Material = "Leather";
            Color = "White";
     }
};

And it also works for Collections:


List<Car> myGarage = new List<Car> 
{
     new Car()
     {
          Manufacturer = "Ford",
          YearOfMake = "1969"
     },
     new Car()
     {
          Manufacturer = "Lamborghini",
          YearOfMake = "1983"
     }
 };

Click here to check out MSDN or more information on Object and Collection Initializers.

Click here to see how to initialize a Dictionary using Object Initializers.

Tuesday, 14 June 2011

TryGetValue Extension method for IDataReader

Ever had that situation where you have a method which will FILL your data entity with data returned from various sources (eg Stored Procedures).

Each source might push different data into the reader so you're not sure exactly which ones will be in the reader at any particular time.

So instead of hard coding things like:


            if (reader["Bonet_ID"] != DBNull.Value)
            {
                car.BonetID = Convert.ToInt32(reader["Bonet_ID"]);
            }


You can create an Extenstion method for the IDataReader like this:


        /// <summary>
        /// Determines if a field name exists in an IDataReader and, if so, its value is not null
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static bool TryGetValue(this IDataReader source, string name, out object value)
        {
            value = DBNull.Value;

            try
            {
                value = source[name];
            }
            catch
            {
                // Do nothing because value is null already
            }

            return (value != DBNull.Value);
        }

And now you can change your code to do this nifty little diddy instead:



            if (reader.TryGetValue("Bonet_ID", out temp))
            {
                car.BonetID = Convert.ToInt32(temp);
            }

Saturday, 4 June 2011

How to get an Enum member from an integer

Useful when you've got a number and you want to convert that number to an enum


Convert an Integer to an Enum Member

.Net Naming Conventions

Check out this page if you're ever wondering how to name your .Net elements:

Namespaces, Classes, Interfaces, Strcuts, Enums, variables, et al.

.net Naming Conventions and Programming Standards

Monday, 23 May 2011

C# Composition vs Aggregation

Here lies a good, simple explanation of what Composition and Aggregation concepts are and how to implement them in C#.

Read the comments at the bottom too for further insight...

C# Composition vs Aggregation