Clear all Objects from Cache

Date Added: July 30, 2010 07:20 by By Edward
Categories: ASP.NET

Caching is one of the least used but a very powerful feature of ASP.NET. It can save you time and also unnecessary trips to the database. If you need to cache any type of information in ASP.NET such as a DataSet, DataTable, or an ArrayList, you can use the cache. This works a lot like a 'session' or 'application variable', but it has some added cache-related methods as well. Scalable web applications should have the ability to store items, whether data objects, pages, or event parts of a page, in memory. This allows you to avoid recreating information, expensive database calls or even connections to 3rd party web services.

However sometimes you might want to clear all these cached objects in one go for some specific reason. Like I said web applications should be scalable and build towards high-performance. This is where you will need to use the 'Cache.Remove()' method, as the built-in cache object in ASP.NET does not support a 'Cache.Clear()' method.

Here is an example of storing a datatable and in the cache:

DataTable dtCacheExample = new DataTable();
//code here: add rows to datatable
Cache["dtCacheExample"] = dtCacheExample;

ArrayList arrCacheExample = new ArrayList();
//code here: add items to arraylist
Cache["arrCacheExample"] = arrCacheExample;

To clear the cache use the following:

// Retrieve a dictionary enumerator used to iterate through the 
// key settings and their values contained in the cache.
IDictionaryEnumerator CacheEnum = Cache.GetEnumerator;

while (CacheEnum.MoveNext) {
    Cache.Remove(CacheEnum.Key.ToString);
}

Catch System.OverflowException caused by a numeric overflow

Date Added: July 28, 2010 20:05 by By Edward
Categories: ASP.NET

As a .NET developer, you can sometimes spend hours finding errors and handling them when you do not know the core logic of the system, and decent good documentation is not that easy to come by. There are several ways to address erros, by using exceptions. Exceptions are designed to handle errors and most commonly in a "try/catch" statement.

It is good practice to not catch the generic errors, and try and debug from there. If you do this, you are unsure what your code is actually doing - which can result in the business living with the concequences. The key is to know which errors you might expect and catch those and handle them accordingly. An exception I found to be hard to track, is the "OverflowException" exception.

From MSDN: An OverflowException exception is thrown when a casting, conversion or arithmetic operation in a checked context results in an overflow. An overflow occurs when an operation produces a value too large for the destination type, infinity, or Not a Number (NaN).

For example, mathematical operations can cause these type of exceptions. A way to check for this error is to use the 'checked' keyword. The 'checked' keyword is used to detect overflow conditions. You should note that an 'OverflowException' exception occurs only in a checked context.

Here is a code example on how to check for this type of exception, and how to handle it.   

 public static void Main()
    {
        try
        {
            checked
            {
                int aInt;
                int bInt;
                int Sum;

                aInt = 2000000000;
                bInt = 2000000000;
                Sum = aInt + bInt;
            }
        }
        catch (OverflowException oExcep)
        {
            Console.WriteLine("A mathematical operation caused an overflow.");
            // Good idea to log this error and deal with it when doing debugging
            // I am using my own Logging module.
            Logger.LogException(oExcep, "A mathematical operation caused an overflow.");
        }
    }

Select unique rows from a DataTable

Date Added: July 26, 2010 07:22 by By Edward
Categories: ASP.NET, Other

The LINQ distinct select method is a powerful small method that can help you select unique entries from datatable.

The following example will return a datatable with unique results, from a datatable which can be populated from a database. The following example uses a datatable I created to show you how the LINQ distinct select method works.

The example below have a list of users, but I only want the 'user names' to be returned. They have to be unique, as I might want to use it in a report.

        /// <summary>
        /// Gets the user names.
        /// </summary>
        public static void GetUserNames()
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("UserId", typeof(int));
            dt.Columns.Add("UserName", typeof(string));
            dt.Rows.Add(1, "Joe Smith");
            dt.Rows.Add(2, "John Doe");
            dt.Rows.Add(3, "Joe Smith");
            dt.Rows.Add(4, "Jane Smith");
            dt.Rows.Add(5, "Jane Doe");

            DataTable filterTable = GetUniqueEntries(dt);

        }


        /// <summary>
        /// Gets the unique entries.
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns></returns>
        private static DataTable GetUniqueEntries(DataTable dt)
        {
            var query = (
            from row in dt.AsEnumerable()
            select row.Field<string>("UserName")).Distinct();

            DataTable dtDistinctNames = new DataTable();
            dtDistinctNames.Columns.Add("UserName", typeof(string));

            //have to return a datatable, thus loop through entries
            foreach (string item in query)
            {
                DataRow newRow = dtDistinctNames.NewRow();
                newRow["UserName"] = item;
                dtDistinctNames.Rows.Add(newRow);
            }

            return dtDistinctNames;
        }

This code snippet will return you a list of users where 'username' are unique. There eliminating duplicate names from the list. There are alternative ways to do this type of functionality - this blog entry is created to show you how easy it can be to use LINQ with C# code.

Generating XML Comments with GhostDoc

Date Added: July 20, 2010 07:26 by By Edward
Categories: ASP.NET, Development Resources, Other

GhostDoc is a free Visual Studio extension which I stumbled accross while looking for something to help me with commenting my code. GhostDoc automatically generates XML documentation comments for methods and properties based on their type, parameters, name, and other contextual information. It takes the 'pain' out of commenting each method word for word - saving you time doing what you do best - coding!

Most documentation created will be a waste of time for a developer, and usually when there is no time to waste a developer might find the documentation is slowing him down. For any decent documentation to be useful, a developer must know that when the documentation was initially generated it was both correct and complete, it has also been updated as the project scope changed, or amendments was made to the code. I ofter find code to out of sync with documentation, which leaves me with lots of 'catch up' to do, before I feel in control and productive.

You can set it up, so when you right click on a method the "Document This" option becomes available that allows you to generate summary comments for your method.

GhostDoc comments

Here is an example of summary comments I created using this tool.       

        /// <summary>
        /// Checks for SQL injection.
        /// </summary>
        /// <param name="userInput">The user input.</param>
        /// <returns></returns>
        public static string checkForSQLInjection(string userInput)
        {
        // code here
       }

It is also supported in the following versions of the Visual Studio IDEs:

  • Visual Studio 2010
  • Visual Studio 2008
  • Visual Studio 2005

Supported Languages:

  • VB.NET
  • C#

Download it from here:

http://visualstudiogallery.msdn.microsoft.com/en-us/46A20578-F0D5-4B1E-B55D-F001A6345748

Using the Environment class for getting and setting various operating system related information

Date Added: June 24, 2010 19:21 by By Edward
Categories: ASP.NET, Other

The "Environment" class of the System namespace is handy for getting and setting various operating system related information. The "Environment" class to retrieve information such as the current directory, network details, machine name, OS versions, environment variable settings, contents of the call stack, time since last system boot, and the version of the common language runtime.

There is a lot of information that can be extracted with the "Environment" class. Below is a small code snippet that might help you get started.

public static void GetEnvironmentDetails()
        {
            Console.WriteLine();
            Console.WriteLine("-- Environment members --");

            //  Invoke this sample with an arbitrary set of command line arguments.
            Console.WriteLine("CommandLine: {0}", Environment.CommandLine);

            String[] arguments = Environment.GetCommandLineArgs();
            Console.WriteLine("GetCommandLineArgs: {0}", String.Join(", ", arguments));
            //  <-- Keep this information secure! -->
            Console.WriteLine("CurrentDirectory: {0}", Environment.CurrentDirectory);
            //  <-- Keep this information secure! -->
            Console.WriteLine("MachineName: {0}", Environment.MachineName);
            Console.WriteLine("OSVersion: {0}", Environment.OSVersion);
            Console.WriteLine("StackTrace: '{0}'", Environment.StackTrace);
            //  <-- Keep this information secure! -->
            Console.WriteLine("SystemDirectory: {0}", Environment.SystemDirectory);
            Console.WriteLine("TickCount: {0}", Environment.TickCount);
            //  <-- Keep this information secure! -->
            Console.WriteLine("UserDomainName: {0}", Environment.UserDomainName);
            Console.WriteLine("UserInteractive: {0}", Environment.UserInteractive);
            //  <-- Keep this information secure! -->
            Console.WriteLine("UserName: {0}", Environment.UserName);
            Console.WriteLine("Version: {0}", Environment.Version);
            Console.WriteLine("GetFolderPath: {0}",
                         Environment.GetFolderPath(Environment.SpecialFolder.System));

            String[] drives = Environment.GetLogicalDrives();
            Console.WriteLine("GetLogicalDrives: {0}", String.Join(", ", drives));
        }


    

The 'is' operator in C#

Date Added: June 04, 2010 05: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 07: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 14, 2010 23: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 10: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 17: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!