The 'is' operator in C#

Date Added: June 04, 2010 06:51 by By Edward
Categories: ASP.NET, Other

The 'is' operator is used to check whether the run-time type of an object is compatible with a given type, and is a "reference type". This is very handy when you have code somewhere in a business or data layer and you cannot figure out why an exception is occuring.

For example:

 

public static void RunThis()
    {
        // For this example the following obj is a class already created              
        object obj = new MyClass();
        CastCheck(obj);
    }

    public static void CastCheck(object obj)
    {
        // For this example the following classes are already created  
        Class1 a;
        Class2 b;
        if (obj is Class1)
        {
            Console.WriteLine("obj is Class1");
            a = (Class1)obj; // do something with a              
        }
        else if (obj is Class2)
        {
            Console.WriteLine("v is Class2");
            b = (Class2)obj; // do something with b              
        }
        else
        {
            Console.WriteLine("obj is neither Class1 nor Class2.");
        }
    }

 

The 'is' operator only considers reference conversions, boxing conversions, and unboxing conversions. Other conversions, such as user-defined conversions, are not considered by the is operator.

 

The 'as' operator in C#

Date Added: June 01, 2010 08:51 by By Edward
Categories: ASP.NET, Other

The 'as' operator is a "type", and is just like the cast operator except that it will return NULL on a conversion failure instead of throwing an exception. The 'as' operator is used to perform conversions between compatible types and is a "reference type". This is very handy when you have code somewhere in a business or data layer and you cannot figure out why an exception is occuring.

For example:

 

Object objValue = new Object();              
string strA = (string)objValue; //Cast throws an Exception              
string strB = objValue as string; //No exception is thrown, but strB is set to NULL

 

The 'as' operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed using cast expressions.

Iterating Through a Windows File Directory Structure

Date Added: May 15, 2010 00:51 by By Edward
Categories: ASP.NET, Other

The phrase "iterating through a directory tree" can also mean "iterating through a folder tree structure". Both statements are valid, when you talk about Windows 'directories' of 'folders'. Iteration means to access each file in each nested subdirectory under a specified root folder, to any depth, unless you specify how many levels 'down' you would like to search. You do not necessarily have to open each file. You can just retrieve the name of the file or subdirectory as a string, or you can retrieve additional information in the form of a System.IO.FileInfo or System.IO.DirectoryInfo object.

The following example shows how to iterate through files and folders in a directory tree without using recursion. You should be careful to modify this code to suit your needs.

 

static void Main()
        {
            //Specify the starting folder 
            string folder = "C:/myfolder/tips/dascode/";
            RetrieveTreeStructureFiles(folder);

            Console.WriteLine("Press any key");
            Console.ReadKey();
        }

        public static void RetrieveTreeStructureFiles(string root)
        {
            // Data structure to hold names of subfolders to be
            // examined for files.
            Stack dirs = new Stack(2);

            if (!System.IO.Directory.Exists(root))
            {
                throw new ArgumentException();
            }
            dirs.Push(root);

            while (dirs.Count > 0)
            {
                string currentDir = dirs.Pop();
                string[] subDirs;
                try
                {
                    subDirs = System.IO.Directory.GetDirectories(currentDir);
                }
                // An UnauthorizedAccessException exception will be thrown if we do not have
                // discovery permission on a folder or file.
                catch (UnauthorizedAccessException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                catch (System.IO.DirectoryNotFoundException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }

                string[] files = null;
                try
                {
                    files = System.IO.Directory.GetFiles(currentDir);
                }

                catch (UnauthorizedAccessException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }

                catch (System.IO.DirectoryNotFoundException e)
                {
                    Console.WriteLine(e.Message);
                    continue;
                }
                // Perform the required action on each file here.
                // Modify this block to perform your required task.
                foreach (string file in files)
                {
                    try
                    {
                        // Perform whatever action is required in your scenario.
                        System.IO.FileInfo fi = new System.IO.FileInfo(file);
                        Console.WriteLine("{0}: {1}, {2}", fi.Name, fi.Length, fi.CreationTime);
                    }
                    catch (System.IO.FileNotFoundException e)
                    {
                        // If file was deleted by a separate application
                        // or thread since the call to TraverseTree()
                        // then just continue.
                        Console.WriteLine(e.Message);
                        continue;
                    }
                }

                foreach (string str in subDirs)
                {
                    dirs.Push(str);
                }
            }
        }

 

Use a JavaScript Delete Confirmation in GridView Command Buttons

Date Added: May 08, 2010 11:39 by By Edward
Categories: ASP.NET

Every now and again you might want to use the "delete" or "update" commands from a gridview. However, once you click the button to delete the item from the list or in most cases from the database - you have no safety check. The user might make a mistake, and it can be a costly mistake. An easy way to force the user to think about this action, is to use javascript and ask the user if he/she is sure they want to delete the item.

In the RowDataBound event of the GridView control, you will find the 'Delete' command button control by specifying the cell index. All you have to do is add an 'attribute' to the control, and the "onclick" event. This will trigger a javascript confirmation alert to the user, which asks the user if he/she is sure they want to delete the item. Only when the user confirms the action, will the item be deleted.

Here is a simple example using C# and javascript.

   1:  if (e.Row.RowType == DataControlRowType.DataRow)
   2:  {
   3:      // check for controls in the gridrow cell. Index starts at 0.
   4:      if (e.Row.Cells[3].HasControls())
   5:      {
   6:         LinkButton btnDelete = ((LinkButton)e.Row.Cells[3].Controls[0]);
   7:         btnDelete.Attributes.Add("onclick", 
   8:          "return confirm('Are you sure you want to delete this item?');");
   9:      }
  10:  }

It is important to note that you should always check if the control exists or not. This will be very useful, when the 'Edit' command button is used along with 'Delete' command button.

Implement a simple captcha in .Net

Date Added: May 05, 2010 18:26 by By Edward
Categories: ASP.NET, Other

I have been having several spam messages posted to my blog entries over the last 3-4 months, which now forced me to implement a captcha for when someone comments on my blog entries. I have not made this live yet, as I am also changing something something else on my blog. A captcha is a type of "challenge-response validation" test used in computing to ensure that the response is not generated by a computer. It is mostly used to protect users from unwanted spam or falsely made comments, or for people posting url's to link to other sites, for SEO benefits.

I thought I would share a few nice and easy captcha's that can be implemented by any .Net programmer.

  1. http://subkismet.codeplex.com (A stand-alone comment spam filtering library - Community project)
  2. http://recaptcha.net/plugins/aspnet/ (user control, ready to be implemented and configurable)
  3. http://www.codeproject.com/KB/validation/aspnet_capcha.aspx (click on the correct image captcha)

Hope you find one that will work for you!

New Overload Method Available for String.Concat - available in .Net 4 Framework

Date Added: April 30, 2010 16:57 by By Edward
Categories: ASP.NET, Development Resources

A new feature I noticed while doing some prototyping some functionality with Visual Studio 2010, is the new overload method available for the 'String.Concat' method that takes an IEnumerable<T>. I found this to be very useful with LINQ query expressions.

Below is a simple example:

       

 public static void Main()
        {
            List<Employee> employees = new List<Employee>();

            employees.Add(new employees("John", "Doe"));
            employees.Add(new employees("Jane", "Doe"));
            employees.Add(new employees("John", "Code"));

            string output = String.Concat(employees.Where(employee =>
                          (employee.Surname == "Doe")));

            //write the output to screen
            Console.WriteLine(output);
        }


The Enumerable.Where extension method is called to extract the Employee objects whose 'Surname' property equals "Doe". The result is passed to the Concat<T>(IEnumerable<T>) method and displayed to the console.

 

const vs readonly in C#

Date Added: March 08, 2010 11:36 by By Edward
Categories: ASP.NET, Other

Here is a quick overview on the differences between 'const' and 'readonly' in C# and ASP.net

const: Cannot be static, and it is evaluated at compile time. It can also only be initiailized at declaration.

Example:

   1:  public class ConstTest 
   2:  {
   3:      class SampleClass 
   4:      {
   5:          public int x;
   6:          public int y;
   7:          public const int c1 = 5;
   8:          public const int c2 = c1 + 5;
   9:   
  10:          public SampleClass(int p1, int p2) 
  11:          {
  12:              x = p1; 
  13:              y = p2;
  14:          }
  15:      }
  16:   
  17:      static void Main() 
  18:      {
  19:          SampleClass mC = new SampleClass(11, 22);   
  20:          Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
  21:          Console.WriteLine("c1 = {0}, c2 = {1}", 
  22:                            SampleClass.c1, SampleClass.c2 );
  23:      }
  24:  }
  25:  /* Output
  26:      x = 11, y = 22
  27:      c1 = 5, c2 = 10
  28:   */

 

readonly: Can be either instance-level or static. The value is evaluated at run time. It can be initialized in declaration or by code in the constructor.

Example:

   1:  public class ReadOnlyTest
   2:  {
   3:     class SampleClass
   4:     {
   5:        public int x;
   6:        // Initialize a readonly field
   7:        public readonly int y = 25;
   8:        public readonly int z;
   9:   
  10:        public SampleClass()
  11:        {
  12:           // Initialize a readonly instance field
  13:           z = 24;
  14:        }
  15:   
  16:        public SampleClass(int p1, int p2, int p3)
  17:        {
  18:           x = p1;
  19:           y = p2;
  20:           z = p3;
  21:        }
  22:     }
  23:   
  24:     static void Main()
  25:     {
  26:        SampleClass p1 = new SampleClass(11, 21, 32);   // OK
  27:        Console.WriteLine("p1: x={0}, y={1}, z={2}", p1.x, p1.y, p1.z);
  28:        SampleClass p2 = new SampleClass();
  29:        p2.x = 55;   // OK
  30:        Console.WriteLine("p2: x={0}, y={1}, z={2}", p2.x, p2.y, p2.z);
  31:     }
  32:  }
  33:  /*
  34:   Output:
  35:      p1: x=11, y=21, z=32
  36:      p2: x=55, y=25, z=24
  37:  */

In summary, the distinguishing factor between the two modifiers in C# is that const items are dealt with at compile-time, while the values of readonly fields are specified at run time. This means that assignment to readonly fields may occur in the class constructor as well as in the declaration.

Finalize vs Dispose

Date Added: March 03, 2010 06:45 by By Edward
Categories: ASP.NET, Other

Class instances often encapsulate control over resources that are not managed by the runtime such as database connections, console app window handlers, etc. Therefore, you should provide both an explicit and an implicit way to free those resources.

Dispose() is called by the user. It serves as the same purpose as finalize() - to free unmanaged resources. However, you should implement this when you are writing a custom class, that will be used by other users. Overriding Dispose() provides a way for the user code to free the unmanaged objects in your custom class.

Finalize() is called by the runtime. It is a destructor, called by the Garbage Collector(GC) when the object goes out of scope. Implement it when you have unmanaged resources in your code, and want to make sure that these resources are freed when the Garbage collection happens.

Note that even when you provide explicit control by way of Dispose(), you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.

Validate an Email Address

Date Added: February 27, 2010 08:02 by By Edward
Categories: ASP.NET, Social Media

In most cases it is "good practice" to validate the user input because of many reasons (i.e. security, reliability, spamming, etc.) - email validation is probarly the most common validation of them all.

The following regular expression(regex) will check for a valid email address in which Only letters (a-z or A-Z), numbers (0-9), hyphens (-), underscore (_) and periods (.) are allowed and no special characters are accepted.

   1:              // Write to console
   2:              Console.Write("Check Email Address: ");
   3:              
   4:              // get input
   5:              string inputEmail = Console.ReadLine();
   6:              string sValid;
   7:              //regular expression - change this to your requirement
   8:              string sRegex = @"^([a-zA-Z0-9_-.]+)@(([[0-9]{1,3}" +
   9:                    @".[0-9]{1,3}.[0-9]{1,3}.)|(([a-zA-Z0-9-]+" +
  10:                    @".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$";
  11:              Regex reg = new Regex(sRegex);
  12:              
  13:              if (reg.IsMatch(inputEmail))
  14:              {
  15:                  sValid = "valid";
  16:              }
  17:              else
  18:              {
  19:                  sValid = "not valid";
  20:              }
  21:              
  22:              Console.WriteLine("Email Address " + 
  23:                  inputEmail + " is " + sValid);
  24:              Console.Read();

String.IsNullOrWhiteSpace - New method available in .NET Framework 4

Date Added: February 19, 2010 14:11 by By Edward
Categories: ASP.NET, Development Resources

String.IsNullOrWhiteSpace - New method available in .NET Framework 4

I found a very nice addition to the .NET Framework(version 4) while experimenting with code in Visual Studio 2010. There is a new method called "IsNullOrWhiteSpace", which is more powerful than the more familiar "IsNullOrEmpty" method. Incase you were wondering, the "IsNullOrEmpty" method is still available to be used.

For example, the common whitespace symbol " " represents a blank space, as used between words and sentences. The most common whitespace characters may be typed via the space bar or the Tab key. Depending on context, a line-break generated by the Return key (Enter key) may be considered whitespace as well. This brings concerns when using the "IsNullOrEmpty" method.

Introducing "IsNullOrWhiteSpace"! In the .NET Framework 4, string.IsNullOrWhiteSpace() will return true if a string is full of whitespace characters. I found this very helpful when dealing with getting XML data from external web services.

Here is a short example of how to use this new method.

   1:          static void Main(string[] args)
   2:          {
   3:              // set some test values
   4:              string[] testValues = { null, String.Empty, "ABCDE", 
   5:                            new String(' ', 20), "  	   ", 
   6:                            new String(' ', 10) };
   7:              //loop through the list and return result
   8:              foreach (string value in testValues)
   9:              {
  10:                  Console.WriteLine("Return is: " + 
  11:              String.IsNullOrWhiteSpace(value));
  12:              }
  13:              // we want to see the return
  14:              Console.ReadLine();
  15:          }

 

About DasCode.Net

I'm a ASP.NET web developer and code enthusiast. Blogging about everything .Net related.

Code... that's .net