Validate an Email Address

by Edward 27 February 2010 08: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

Design Patterns 101 - The Abstract Factory Pattern

by Edward 31 January 2010 18: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

Design Patterns 101 - The Singleton Pattern

by Edward 29 January 2010 18:53

You probably heard of it, you probably don't even know that you are implementing it, but you need it on your resume! Once you start to use design patterns you will find that your code structure is improving. This is a "101" article about the simplest pattern - the Singleton pattern.

The purpose of this pattern is to ensure that a class has only one instance, and provide a global point of access to it. Any class in your application that has access to its namespace doesn't have to create or initialize the singleton. The caller can access properties and methods through the singleton's instance property. The singleton will retain state across calls.

   1:  // Singleton pattern - Structural example
   2:   
   3:  using System; 
   4:   
   5:  namespace MyApp.Singleton.Structural
   6:  {
   7:   
   8:    /// <summary>
   9:    /// MainApp startup class for Structural
  10:    /// Singleton Design Pattern.
  11:    /// </summary>
  12:   
  13:    class MainApp
  14:    {
  15:      /// <summary>
  16:      /// Entry point into console application.
  17:      /// </summary>
  18:   
  19:      static void Main()
  20:      {
  21:        // Constructor is protected -- cannot use new
  22:        Singleton s1 = Singleton.Instance();
  23:        Singleton s2 = Singleton.Instance(); 
  24:   
  25:        // Test for same instance
  26:        if (s1 == s2)
  27:        {
  28:          Console.WriteLine("Objects are the same instance");
  29:        }
  30:   
  31:        // Wait for user
  32:        Console.ReadKey();
  33:      }
  34:    }
  35:   
  36:    /// <summary>
  37:    /// The 'Singleton' class
  38:    /// </summary>
  39:   
  40:    class Singleton
  41:    {
  42:   
  43:      private static Singleton _instance;
  44:   
  45:      // Constructor is 'protected'
  46:      protected Singleton()
  47:      {
  48:      }
  49:   
  50:      public static Singleton Instance()
  51:      {
  52:        // Uses lazy initialization.
  53:        // Note: this is not thread safe.
  54:        if (_instance == null)
  55:        {
  56:          _instance = new Singleton();
  57:        }
  58:   
  59:   
  60:        return _instance;
  61:      }
  62:    }
  63:  }


Output:

Objects are the same instance

Note: The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one.

Tags: , , ,

ASP.NET | Development Resources | Social Media

Clear all controls in a Form

by Edward 09 December 2009 15:40

You might find yourself in a situation where you would like to clear all html controls in a form using a server command. Obviously,  forms will either small or a large number of input controls like textbox, dropdownlist, checkbox and radiobutton, etc.

In  the following "button click" example I will show you how to clear each control by first finding only “form” input controls, and then clear them to their default state(in my example they have to empty).

 

   1:  protected void Button1_Click(object sender, EventArgs e)
   2:          {
   3:              //Find controls in the web form
   4:              Control formCtrl = Page.FindControl("Form1");
   5:   
   6:              //For each control in the html form
   7:              foreach (Control ctrl in formCtrl.Controls)
   8:              {
   9:   
  10:                  //Clears TextBox
  11:                  if (ctrl is TextBox)
  12:                  {
  13:                      (ctrl as TextBox).Text = String.Empty;
  14:                  }
  15:   
  16:                  //Clears DropDown Selection
  17:                  if (ctrl is DropDownList)
  18:                  {
  19:                      (ctrl as DropDownList).ClearSelection();
  20:                  }
  21:   
  22:                  //Clears ListBox Selection
  23:                  if (ctrl is ListBox)
  24:                  {
  25:                      (ctrl as ListBox).ClearSelection();
  26:                  }
  27:   
  28:                  //Clears CheckBox Selection
  29:                  if (ctrl is CheckBox)
  30:                  {
  31:                      (ctrl as CheckBox).Checked = false;
  32:                  }
  33:   
  34:                  //Clears RadioButton Selection
  35:                  if (ctrl is RadioButtonList)
  36:                  {
  37:                      (ctrl as RadioButtonList).ClearSelection();
  38:                  }
  39:   
  40:                  //Clears CheckBox Selection
  41:                  if (ctrl is CheckBoxList)
  42:                  {
  43:                      (ctrl as CheckBoxList).ClearSelection();
  44:                  }
  45:              }
  46:   
  47:          }

 

Tags: ,

ASP.NET | Social Media

Firefox 4.0 to target Internet Explorer and Google Chrome?

by Edward 30 July 2009 07:19

Firefox logo

It looks like Mozilla has been playing mind games with Microsoft, and targeting the Internet Explorer 8 browser. Just a few days after Mozilla gave us a sneak preview of the 3.7 version of Firefox, they have been making "mockups" available of Firefox 4.0 to the public.

The open source browser maker has added colour over Firefox 4.0's location bar. It will turn green when a user starts typing, will blend with the bar when at rest, flashes blue on hover and transforms into red when a page is loading.

This all to attract more users to use Firefox as their default browser, and to get users to switch from IE to Firefox without seeing to much of a difference. The key point they are trying to raise is that Firefox is the most flexibile and customisable browser available today!

One of the standout changes that Firefox is looking at, is the location of the search bar at the top. It looks like the search bar will be similiar to the IE8 and Google Chrome designs, where the tabs will be either above the search bar, or below. This will give it a more sleak look.

Firefox 4.0 mockup

It really looks like Firefox is going beyond their usual designs, and really trying to make Firefox the browser to have. You bet it’s going to get more great features, as it’s going to be some time until we can browse the web with this lbrowser!

If you are already a Firefox fan, and would like to have a sneak peek of Firefox in 2010, you can visit the following link.

Tags: , , ,

Development Resources | Social Media | Technology

Convert.ToString vs .toString

by Edward 24 July 2009 06:38

I have seen numerous applications where developers use ".toString" to convert a value to string. However lets say you are trying to convert a value from a database field that does allow NULL to inserted... what will happen if you cast this value to a string from int?

For my examples I left the entry in the database NULL.

Example with "Convert.ToString()":

// This will set the variable test to null:
// Use a datareader to return result from database
string age = Convert.ToString(dt.Rows[i][1].ToString());

Console.WriteLine(age);

If you run this code snippet in your own code, you will see NULL is written assigned to the variable.

Example with "toString()":


// This will throw an exception:
// Use a datareader to return result from database
string age = dt.Rows[i][1].ToString();

Console.WriteLine(age);

If you run this code snippet in your own code, you will see that the code will break. The problem with this statement is that null doesn't have a ".ToString()" method. It will throw a NULL reference exception error.

To summarise, it is best practice to CONVERT a value to string, if you are not sure what value you are getting back, then to CAST it to a string.

Tags: , ,

ASP.NET | Social Media

The Agile Development Checklist

by Edward 22 July 2009 17:48

I am a fan of the Agile methodology in developing software. It brings results, it is very effective if followed correctly, and widely used within numerous companies. Agile is people driven, instead of process driven. Have a good team of motivated developers, is worth more then the process. However there are rules around this too. The most efficient and effective method of conveying information to and within a development team is face-to-face conversation.

What is Agile development?

Agile software development refers to a group of software development methodologies based on iterative development, where requirements and solutions evolve through collaboration between self-organizing cross-functional teams. The term was coined in the year 2001 when the Agile Manifesto was formulated. Some people came together, exchange ideas and came up with the Manifesto for Agile Software Development.

Agile Development consists of a series of interdependent planning and delivery rhythms(uniformities). These agile rhythms, while quite simple conceptually, have proven not so simple to implement. Yet this cyclical series of meetings and events delivers the reliable beat which allows teams to find their own agile rhythm.

While no single document delivers all of the ammunition agile teams need to get the rhythm, this set of agile meeting and facilitation checklists offers an easy framework to help guide software development teams through the various agile cycles.

The Agile Development 'Rhythms':

  • Strategy - Projects and product development efforts ideally start with a vision associated with a business need or direction. This vision is then typically framed in context of a strategy and associated goals and objectives during a management team planning session.
  • Release - Releases represent the large-grained delivery cycle in agile development. Releases typically range between one and six months, but may extend longer in some environments. Releases begin with a release planning meeting where product owners (or product managers, project leads, etc.) work to define and prioritize a candidate set of features that are then estimated by the team.
  • Iteration - Also known as Sprints, iterations are short, fixed-length subsets of releases, generally in the 1-6 week time frame. Iterations represent the execution heartbeat of the project. During, each iteration the team’s goal is to deliver useful software.
  • Daily - Every day the team is focused on completing the highest priority features in the form of working, tested software. As features are delivered within the iteration, they are reviewed and accepted, if appropriate, by the product owner. Each day a short, 15-minute standup meeting facilitates the communication of individual detailed status and any impediments or issues.
  • Continuous - Agile development teams are constantly driving towards a state of continuous, adaptive planning, collaboration, design, development, testing and integration. This commitment fosters a dynamic, highly productive environment in which automation is critical and the output is always high-quality, valuable working software.

Some examples of Agile practices:

  • Test Driven Development (TDD)
  • Behavior Driven Development (BDD)
  • Continuous Integration
  • Pair Programming
  • Planning poker

 

Tags: ,

ASP.NET | Development Resources | Social Media

Microsoft vs Apple - Its war

by Edward 16 July 2009 14:08

Microsoft's chief operating officer says they are planning to open their retail stores "right next door to Apple" in the few months. Microsoft and Apple have been fighting it out for years over who has the best operating system. Microsoft's Windows platform runs on the most PC's in the world, while Apple are known for the design sense.

Microsoft logo

The approach is new but consistent with Microsoft's advertising strategy. Its online and TV campaigns have taken to always comparing against Apple, often juxtaposing Apple's supposedly higher prices versus inexpensive Windows systems.

Microsoft plans to showcase their latest technologies like Zune HD, Xbox 360, and then there is the Microsoft tabletop. If Microsoft uses some of these popular items as cornerstones for their retail presence, and even allows the chance to get first-looks at some of these things, they may be on to something.

Tags: , ,

Social Media | Technology

Windows 7 Pre-Order Offer

by Edward 13 July 2009 06:35

Windows 7 Home logo

Microsoft has announced that you can pre-order Windows 7 Home Premium E for £49.99** or Windows 7 Professional E for £99.99**. This pre-order offer begins on 15th July, 2009 and it will end on 9th August, 2009. Windows 7 will be officially released on 22 October at a price from £119.99 for the Windows 7 Home Premium E platform.

Minimum recommended specifications for Windows 7:

  • 1GHz or faster 32-bit (x86) or 64-bit (x64) processor
  • 1GB RAM (32-bit) / 2GB RAM (64-bit)
  • 16GB available disk space (32-bit) / 20GB (64-bit)
  • DirectX 9 graphics processor with WDDM 1.0 or higher driver

Windows 7-E?

In Europe, due to regulations imposed on Microsoft, the company has announced that Windows 7 will not ship with the company's own Internet Explorer in Europe because of allegations that Microsoft was restricting choice to European consumers. Due to the removal of Internet Explorer, European customers will not be able to upgrade their Vista installations and will have to perform clean installations of Windows 7. Microsoft has said that it may offer the option to install Internet Explorer via Windows Update

The offer is available through participating retailers. Each retailer will tell you how to get your copy when Windows 7 is released. For more information visit this link.

Windows 7 desktop

 Windows 7 desktop experience

Tags: ,

Development Resources | Social Media | Technology

Microsoft releases Silverlight 3

by Edward 09 July 2009 18:37

Silverlight logo

The latest version of Sliverlight, Silverlight 3, was released today - a day earlier then expected, as it was supposed to be out officially on July 10 only. Silverlight 3 supports Internet Explorer version 6/7/8, Firefox 2/3 and Safari 3/4 browsers - currently there is no support for Opera or Chrome browsers.

Microsoft has rolled out Silverlight 3 with a lot of new stuff including the Smooth screening feature. Silverlight is a browser plugin that enables rich media experience, audio playback, vector graphics and animation.

Microsoft's Silverlight is a direct rival of Adobe Flash and is available for download from Microsoft's Silverlight site.

Some key highlights:

  • Support for Higher Quality Video & Audio.
  • Empowering Richer Experiences.
  • Improving Rich Internet Application Productivity.
  • Advanced Accessibility Features.
  • Out of Browser Capabilities.

Silverlight allows you to move and drag maps around

ICE - Silverlight player

Tags: , , ,

ASP.NET | Development Resources | Social Media | Technology

About DasCode.Net

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

Code... that's .net

Month List