Reverse a String using C#

Date Added: August 06, 2010 18:49 by By Edward
Categories: ASP.NET, Other

This week I was asked by a friend how you would reverse a sentence, with minimial effort and that works in all scenarios. This was a nice challenge for me, so started working on something.

I first though of using recursion with a substring method to reverse the sentence, which worked fine, however this looked a bit messy and I thought it might impact on the performance of the program. I searched MSDN and the ASP.NET website for an alternative option, and surprisingly I found an article which Justin Rogers wrote, which did exactly what I was looking for... You can use the 'Array.Reverse()' method that is already provided to you by the .Net framework.

Here is an example of how to efficiently reverse the characters in a string:

static public string Reverse(string str)
{
    char[] charArray = str.ToCharArray();
    Array.Reverse( charArray );
    return new string( charArray );
}

Input: Hello World
Output: dlroW olleH


The example above is just for demostration. In my case, I was using large strings, therefore this method was the preferred option. In some cases you can use recursion with a substring method, which will be a better choice on performance.

I though I would share Justin's article, so you can read it here.

Clear all Objects from Cache

Date Added: July 30, 2010 08: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 21: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 08: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.

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

Date Added: June 24, 2010 20: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 '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.

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.

About DasCode.Net

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

Code... that's .net