Use a JavaScript Delete Confirmation in GridView Command Buttons

by Edward 08 May 2010 12:39

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.

Tags: , ,

ASP.NET

Implement a simple captcha in .Net

by Edward 05 May 2010 19:26

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!

Tags: , , , ,

ASP.NET | Other

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

by Edward 30 April 2010 17:57

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.

 

Tags: , , , ,

ASP.NET | Development Resources

const vs readonly in C#

by Edward 08 March 2010 12:36

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.

Tags: , , ,

ASP.NET | Other

Finalize vs Dispose

by Edward 03 March 2010 07:45

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.

Tags: , , , ,

ASP.NET | Other

Validate an Email Address

by Edward 27 February 2010 09:02

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();

Tags: , , ,

ASP.NET | Social Media

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

by Edward 19 February 2010 15:11

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:          }

 

Tags: , , , ,

ASP.NET | Development Resources

Calculate the amount of days between two dates

by Edward 04 February 2010 18:47

DateTime.Subtract is an easy method that sometimes get overlooked for how 'powerful' it can be. If you would like to calculate the amount of days between two date fields - of type DateTime - an easy approach is to use the "subtract" method and 'TimeSpan' class. The TimeSpan class represents a time interval, and has a dual set of properties, one set represents the time durations in integers and another set of properties, with the names prefixed with "total" represents the result in fractional values.

This is a quick example to find the number of days between two date fields.

   1:  TimeSpan timespan = Convert.ToDateTime("2010-02-04")
2: .Subtract(Convert.ToDateTime("2010-01-31"));
   3:  Console.WriteLine(timespan.Days+1);

Before subtracting DateTime objects, ensure that the objects represent times in the same time zone. Otherwise, the result will include the difference between time zones.

Tags: , ,

ASP.NET | Other

Dascode.Net now has comments enabled

by Edward 03 February 2010 18:28

My blog now has comments enabled, thanks to the latest version of Blogengine.net 1.6 that has moderation of comments. All new posts will have this functionality enabled, to allow visitors to comment on my blog entries. I will also be updating my site over the next few weeks, to improve the layout and some backend functionality. I hope you will continue to visit my site.

The following new features are now available in Blogengine.net v1.6:

  • Centralized Comment Management
  • Automated Comment Spam Filtering with ability to plug-in custom Filtering modules
  • Multiple Widget Zones (details)
  • Referrers data and Blogroll items now stored in Database when using the DB blog provider.
  • Unsubscribe Link in Comment Notification Emails
  • Referrer Data can be Stored for more than 7 days.
  • Blogroll items can now be Ordered.
  • Newsletter Widget more Intelligent - Emails sent when a post is going from an Unpublished to Published state.
  • Twitter Widget - New options and improvements
  • Page Slugs now saved in Database.
  • New Logging system to Track events and errors.
  • Unhandled Exception Handling
  • Fixes to Comment Notification Emails not being sent out correctly in some cases.
  • Outgoing Email improvements
  • Many other improvements and fixes

You can download the latest version of Blogengine.Net here.

Tags: , , ,

Other

Design Patterns 101 - The Abstract Factory Pattern

by Edward 31 January 2010 19:41

In my second article on design patterns, I am going to give you a quick overview of the "Abstract Factory pattern". Provide an interface for creating families of related or dependent objects without specifying their concrete classes.

The Abstract Factory pattern is one level of abstraction higher than the factory pattern. One of the nice things about abstraction is that it lets you "take care" of the bigger picture and you only have to worry about the "details" later. The great advantage is that you are able to rely upon some other class to fill in the details for you.

You can use this pattern when you want to return one of several related classes of objects, each of which can return several different objects on request. In other words, the Abstract Factory is a factory object that returns one of several factories.

The code below demonstrates the Abstract Factory pattern creating parallel hierarchies of objects. Object creation has been abstracted and there is no need for hard-coded class names in the client code.

 

   1:  // Abstract Factory pattern - Structural example
   2:   
   3:  using System;
   4:   
   5:  namespace MyApp.AbstractFactory.Structural 
   6:  {
   7:      /// <summary>
   8:      /// MainApp startup class for Structural
   9:      /// Abstract Factory Design Pattern.
  10:      /// </summary>
  11:      internal class MainApp
  12:      {
  13:          /// <summary>
  14:          /// Entry point into console application.
  15:          /// </summary>
  16:          public static void Main()
  17:          {
  18:              // Abstract factory #1
  19:              AbstractFactory factory1 = new ConcreteFactory1();
  20:              Client client1 = new Client(factory1);
  21:              client1.Run();
  22:   
  23:              // Abstract factory #2
  24:              AbstractFactory factory2 = new ConcreteFactory2();
  25:              Client client2 = new Client(factory2);
  26:              client2.Run();
  27:   
  28:   
  29:              // Wait for user input
  30:              Console.ReadKey();
  31:          }
  32:      }
  33:   
  34:      /// <summary>
  35:      /// The 'AbstractFactory' abstract class
  36:      /// </summary>
  37:      internal abstract class AbstractFactory
  38:      {
  39:          public abstract AbstractProductA CreateProductA();
  40:          public abstract AbstractProductB CreateProductB();
  41:      }
  42:   
  43:      /// <summary>
  44:      /// The 'ConcreteFactory1' class
  45:      /// </summary>
  46:      internal class ConcreteFactory1 : AbstractFactory
  47:      {
  48:          public override AbstractProductA CreateProductA()
  49:          {
  50:              return new ProductA1();
  51:          }
  52:   
  53:          public override AbstractProductB CreateProductB()
  54:          {
  55:              return new ProductB1();
  56:          }
  57:      }
  58:   
  59:      /// <summary>
  60:      /// The 'ConcreteFactory2' class
  61:      /// </summary>
  62:      internal class ConcreteFactory2 : AbstractFactory
  63:      {
  64:          public override AbstractProductA CreateProductA()
  65:          {
  66:              return new ProductA2();
  67:          }
  68:   
  69:          public override AbstractProductB CreateProductB()
  70:          {
  71:              return new ProductB2();
  72:          }
  73:      }
  74:   
  75:      /// <summary>
  76:      /// The 'AbstractProductA' abstract class
  77:      /// </summary>
  78:      internal abstract class AbstractProductA
  79:      {
  80:      }
  81:   
  82:      /// <summary>
  83:      /// The 'AbstractProductB' abstract class
  84:      /// </summary>
  85:      internal abstract class AbstractProductB
  86:      {
  87:          public abstract void Interact(AbstractProductA a);
  88:      }
  89:   
  90:      /// <summary>
  91:      /// The 'ProductA1' class
  92:      /// </summary>
  93:      internal class ProductA1 : AbstractProductA
  94:      {
  95:      }
  96:   
  97:      /// <summary>
  98:      /// The 'ProductB1' class
  99:      /// </summary>
 100:      internal class ProductB1 : AbstractProductB
 101:      {
 102:          public override void Interact(AbstractProductA a)
 103:          {
 104:              Console.WriteLine(this.GetType().Name +
 105:                                " interacts with " + a.GetType().Name);
 106:          }
 107:      }
 108:   
 109:      /// <summary>
 110:      /// The 'ProductA2' class
 111:      /// </summary>
 112:      internal class ProductA2 : AbstractProductA
 113:      {
 114:      }
 115:   
 116:      /// <summary>
 117:      /// The 'ProductB2' class
 118:      /// </summary>
 119:      internal class ProductB2 : AbstractProductB
 120:      {
 121:          public override void Interact(AbstractProductA a)
 122:          {
 123:              Console.WriteLine(this.GetType().Name +
 124:                                " interacts with " + a.GetType().Name);
 125:          }
 126:      }
 127:   
 128:      /// <summary>
 129:      /// The 'Client' class. Interaction environment for the products.
 130:      /// </summary>
 131:      internal class Client
 132:      {
 133:          private AbstractProductA _abstractProductA;
 134:          private AbstractProductB _abstractProductB;
 135:          
 136:          // Constructor
 137:   
 138:          public Client(AbstractFactory factory)
 139:          {
 140:              _abstractProductB = factory.CreateProductB();
 141:              _abstractProductA = factory.CreateProductA();
 142:          }
 143:          
 144:          public void Run()
 145:          {
 146:              _abstractProductB.Interact(_abstractProductA);
 147:          }
 148:      }
 149:  }

Output:

ProductB1 interacts with ProductA1
ProductB2 interacts with ProductA2


The Usage of this pattern makes it possible to interchange concrete classes without changing the code that uses them, even at runtime! However, employment of this pattern, as with similar design patterns, may result in unnecessary complexity and extra work in the initial writing of code. Used correctly the "extra work" pays off in the second instance of using the Factory.

Tags: , ,

ASP.NET | Development Resources | Social Media

About DasCode.Net

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

Code... that's .net

Month List