Validating a Textbox for Decimal Values

by Edward 19 May 2011 17:32

It is always a good idea to try and validate any user input, before the page is submitted or a request is made to the database. This will cut down on unnecessary "back and forth" trips to the database, and also save on performance or showing nasty error pages, if you are not handling exceptions correctly.

To validate any user input, you can use the RegularExpressionValidator control provided with the .Net framework. If you need to validate other forms of input, such as query strings, cookies, or HTML input, you can use the System.Text.RegularExpressions.Regex class.

Here is small code snippet which will accept any numeric/decimal digits (e.g. 100.05), but not any alpha-numeric (e.g. £100.05). You must also have at least one digit before and one after the decimal place. It validates for a positive or negative currency amount. If there is a decimal point, it requires 2 numeric characters after the decimal point to be valid.

<asp:TextBox ID="txtAmount" runat="server" />
<asp:Button ID="btnSaveDetails" runat="server" Text="Submit" OnClick="btnSaveDetails_Click" />


<asp:RegularExpressionValidator ID="rvDecimal" ControlToValidate="txtAmount" runat="server"
ErrorMessage="Please enter a valid amount." ValidationExpression="^(-)?\d+(\.\d\d)?$">
</asp:RegularExpressionValidator>

Tags: , , , ,

ASP.NET | Other | Technology

Useful list of ASP.Net Server Variables

by Edward 25 April 2011 06:44

Here is a list of server environment variables that can be accessed by using ASP.NET. These variables can tell us important details on the server environment in which the page is running or more information about visitors to the page.


Variable Description
ALL_HTTP Returns all HTTP headers sent by the client. Always prefixed with HTTP_ and capitalized
ALL_RAW Returns all headers in raw form
APPL_MD_PATH Returns the meta base path for the application for the ISAPI DLL
APPL_PHYSICAL_PATH Returns the physical path corresponding to the meta base path
AUTH_PASSWORD Returns the value entered in the client's authentication dialog
AUTH_TYPE The authentication method that the server uses to validate users
AUTH_USER Returns the raw authenticated user name
CERT_COOKIE Returns the unique ID for client certificate as a string
CERT_FLAGS bit0 is set to 1 if the client certificate is present and bit1 is set to 1 if the cCertification authority of the client certificate is not valid
CERT_ISSUER Returns the issuer field of the client certificate
CERT_KEYSIZE Returns the number of bits in Secure Sockets Layer connection key size
CERT_SECRETKEYSIZE Returns the number of bits in server certificate private key
CERT_SERIALNUMBER Returns the serial number field of the client certificate
CERT_SERVER_ISSUER Returns the issuer field of the server certificate
CERT_SERVER_SUBJECT Returns the subject field of the server certificate
CERT_SUBJECT Returns the subject field of the client certificate
CONTENT_LENGTH Returns the length of the content as sent by the client
CONTENT_TYPE Returns the data type of the content
GATEWAY_INTERFACE Returns the revision of the CGI specification used by the server
HTTP_<HeaderName> Returns the value stored in the header HeaderName
HTTP_ACCEPT Returns the value of the Accept header
HTTP_ACCEPT_LANGUAGE Returns a string describing the language to use for displaying content
HTTP_COOKIE Returns the cookie string included with the request
HTTP_REFERER Returns a string containing the URL of the page that referred the request to the current page using an <a> tag. If the page is redirected, HTTP_REFERER is empty
HTTP_USER_AGENT Returns a string describing the browser that sent the request
HTTPS Returns ON if the request came in through secure channel or OFF if the request came in through a non-secure channel
HTTPS_KEYSIZE Returns the number of bits in Secure Sockets Layer connection key size
HTTPS_SECRETKEYSIZE Returns the number of bits in server certificate private key
HTTPS_SERVER_ISSUER Returns the issuer field of the server certificate
HTTPS_SERVER_SUBJECT Returns the subject field of the server certificate
INSTANCE_ID The ID for the IIS instance in text format
INSTANCE_META_PATH The meta base path for the instance of IIS that responds to the request
LOCAL_ADDR Returns the server address on which the request came in
LOGON_USER Returns the Windows account that the user is logged into
PATH_INFO Returns extra path information as given by the client
PATH_TRANSLATED A translated version of PATH_INFO that takes the path and performs any necessary virtual-to-physical mapping
QUERY_STRING Returns the query information stored in the string following the question mark (?) in the HTTP request
REMOTE_ADDR Returns the IP address of the remote host making the request
REMOTE_HOST Returns the name of the host making the request
REMOTE_USER Returns an unmapped user-name string sent in by the user
REQUEST_METHOD Returns the method used to make the request
SCRIPT_NAME Returns a virtual path to the script being executed
SERVER_NAME Returns the server's host name, DNS alias, or IP address as it would appear in self-referencing URLs
SERVER_PORT Returns the port number to which the request was sent
SERVER_PORT_SECURE Returns a string that contains 0 or 1. If the request is being handled on the secure port, it will be 1. Otherwise, it will be 0
SERVER_PROTOCOL Returns the name and revision of the request information protocol
SERVER_SOFTWARE Returns the name and version of the server software that answers the request and runs the gateway
URL Returns the base portion of the URL

Tags: , , , ,

Adding Padding or Space to Display a String

by Edward 26 March 2011 16:19

A simple but unknown to many developers is the two methods for padding available in the String class. Using these two methods you can add padding to the left or to the right of a string to achieve a desired length. A real world example will be to add a '0' to a string value when a area code must be a specific length.

The two methods for this example is as follows:

String.PadLeft : Right aligns and pads a string from the left.
String.PadRight : Left aligns and pads a string from the right.

The following example shows how to indent strings using method for padding:

PadLeft:

string originalString = "123";
Console.WriteLine(originalString.PadLeft(3, '0'));

PadRight:

string originalString = "123";
Console.WriteLine(originalString.PadRight(3, '0'));

You should also understand that this does not format the original value, for example formatting a integer to decimal, but just 'append' a character either on the left or the right of the string.

Tags: , , ,

ASP.NET

How to read the version number from the assembly

by Edward 19 February 2011 16:15

I was recently working on a project where it was important to display the version number of the code on the page for testing purposes as well as making sure the correct set of code goes to production. If you don't use a build server, or just copy your code over to your hosting space, then the following might be of help. By using reflection you can get the major, minor, build, and revision numbers of the assembly and the display it on your web page, or use however you need too.

The following code sample will help you with getting the version number of your application.

        private static void Main(string[] args)
        {
            //Get Application version details
            ApplicationDetails applicationDetails = new ApplicationDetails();
            string versionNumber = applicationDetails.GetVersion();
        }  
    class ApplicationDetails
{
/// <summary>
/// Gets the version.
/// </summary>
public string GetVersion()
{
return GetType().Assembly.GetName().Version.ToString();
}

}

 

You can set the version number to auto increment, by setting it in the properties window of your application.

Tags: , ,

ASP.NET | Development Resources | Other

Visual Studio 2010 SP1 BETA Released

by Edward 10 January 2011 18:56

At the end of last year(December 2010), Microsoft released a service pack for Visual Studio 2010. The service pack is still in BETA mode, and therefore must be treated as any BETA software.... handle with care!

I was happy to hear there was a new service pack on it's way, which has some bug fixes and includes fixes for the text editor when coding javascript, css, and html. One bug I wanted to see fixed was the 'crash bug' where my editor seems to crash unexpectantly when working with older versions of the .net framework. Since the install I have not had any crashes, although I must state that I have not been working a lot over the December/January period!

Visual Studio 2010 logoOther key updates to look out for, is that VS2010 SP1 BETA allows the debugger to support IIS Express. The IntelliTrace now also supports Workflows and projects that use Web Parts. There's also support for unit testing targeting .Net 3.5,  and support for Visual C++, Visual Basic, SQL Server Compact 4.0 Design-Time, with enhancements for web deployment.

If you want to download SP1 BETA, you can find the download page here, but like I said - make sure you know the risks of installing BETA software!

Tags: , , ,

ASP.NET | Development Resources | Technology

Looping and Iterating

by Edward 31 December 2010 09:44

When using recursions in Applications, you should always think about why you are not using iterations. Non-optimised code within the loops can result in exacerbated performance issues, ranging from increased memory usage to CPU spikes, causing your application to slow down or fail. You should also consider replacing recursion with looping, because each recursion adds data to stack. You should always study your code for recursive calls that can be converted to a ‘loop’ equivalent.

The following code snippet makes use of recursive calls to accomplish a small task of string concatenation.

        static Array arr = GetArrayOfStrings();

        static int index = arr.Length - 1;
        String finalStr;

        public Validate()
        {
            finalStr = Recursive(index);
        }

        /// <summary>
        /// Recursives the specified index.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <returns></returns>
        string Recursive(int index)
        {
            if (index <= 0)
            {
                return string.Empty;
            }
            else
            {
                return (arr.GetValue(index) + Recursive(index - 1));
            }
        }

        private static Array GetArrayOfStrings()
        {
            //code here
        }
Rewritten, the following code now avoids creating new data on the stack for each successive call and avoids an additional method call to itself.

        static Array arr = GetArrayOfStrings();

        static int index = arr.Length - 1;
        String finalStr;

        /// <summary>
        /// Concates the specified array.
        /// </summary>
        /// <param name="array">The array.</param>
        /// <returns></returns>
        string Concate(Array array)
        {
            StringBuilder sBuilder = new StringBuilder();

            for (int i = array.Length; i > 0; i--)
            {
                sBuilder.Append(array.GetValue(i));
            }

            return sBuilder.ToString();
        }

        private static Array GetArrayOfStrings()
        {
            //code here
        }

The following key points summarises how you can improve iteration and loop efficiency(From MSDN):

  • Avoid repetitive field or property access.
  • Optimize or avoid expensive operations within loops.
  • Copy frequently called code into the loop.
  • Consider replacing recursion with looping.
  • Use for instead of foreach in performance-critical code paths.

 

Tags: , , , ,

ASP.NET

Finalize and Dispose Guidelines

by Edward 23 December 2010 19:50

Difference between Finalize and Dispose:

Finalize Method(): Releases unmanaged resources and performs other cleanup operations before the SmiConnection is reclaimed by garbage collection.

void Finalize ();

Dispose Method(): Closes the connection to the database. It is intended for use by SQL Server.  For other databases, use the hosting mechanism provided by that database.

void Dispose ();

The following are guidelines/recommendations for using Finalize and Dispose(From MSDN):

  • Call Close or Dispose on classes that support it.
  • Use the using statement in C# and Try/Finally blocks in Visual Basic .NET to ensure Dispose is called.
  • Do not implement Finalize unless required.
  • Implement Finalize only if you hold unmanaged resources across client calls.
  • Move the Finalization burden to the leaves of object graphs.
  • If you implement Finalize, implement IDisposable.
  • If you implement Finalize and Dispose, use the Dispose pattern.
  • Suppress finalization in your Dispose method.
  • Allow Dispose to be called multiple times.
  • Call Dispose on base classes and on IDisposable members.
  • Keep finalizer code simple to prevent blocking.
  • Provide thread safe cleanup code only if your type is thread safe.

 

Tags: , , ,

ASP.NET | Other

Microsoft Offers Development Software at No Cost - for 3 years

by Edward 29 November 2010 21:44

Last year Scott Guthrie from Microsoft announced on his blog that Microsoft is launching a new program called 'Websitespark'. This program is designed for independent web developers and web development companies that build web applications and web sites on behalf of others.  It enables you to get software for FREE. What is the catch? A one-time $100 Program Offering Fee is due upon exit or upon the end of the 3 year term! I thought I would share this with you, to encourage you to register and download this software.

Once you have enrolled, you can access the following software.

  • For design, development, testing and demonstration of new websites – for a total of up to three users per Web design and development company:
    • Visual Studio Professional
    • Expression Studio (1 user) and Expression Web (up to 2 users)
    • Windows Web Server 2008 R2
    • SQL Server 2008 Web Edition
  • For production use – that is, to deploy and host new websites developed using Program software – using a total of up to four processors per Web design and development company, of the following (physical or virtual) dedicated servers:
    • Windows Web Server 2008 R2
    • SQL Server 2008 Web Edition
In addition to software, Microsoft WebsiteSpark offers Web development and design companies the opportunity to:
  • Get Business Opportunities: Get opportunities to expand your customer base and drive new business through showcasing your capabilities and connecting with partners, by featuring your talents in Microsoft marketing and business networking vehicles.
  • Get Support and Training - benefits include:
    • 2 professional support incidents
    • Online support through Managed newsgroups on MSDN is no longer available. Priority support is now provided in MSDN forums and other Microsoft online properties
    • Access to broad community support through connections with Network Partners, Hosting Partners and peers with complementary services and technologies

You can register for the program by visiting the Microsoft Websitespark portal.

Tags: , ,

Development Resources | Other | Technology

Generate a Random Password Using C#

by Edward 01 November 2010 19:15

Every website that holds important or sensitive data, should have some type of password policy. In my example below you can generate your own random password, that will be secure and not easy to read. For example when a new user is created and you can't think of a password, or you need the password to be as random as possible. This password generator method will generate secure, random password examples for you to use.

Select the password length, and the type(eg: if you do not want symbols in your password), and your password will be generated for you.

This is how you would call the password generator method:

            Debug.WriteLine("Type 1: " + GenerateRandomPassword(20, 1));
            Debug.WriteLine("Type 2: " + GenerateRandomPassword(20, 2));
            Debug.WriteLine("Type 3: " + GenerateRandomPassword(20, 3));
            Debug.WriteLine("Type 4: " + GenerateRandomPassword(20, 4));

The method that generates the password(this is for example purposes):

        /// <summary>
        /// Generates the random password.
        /// </summary>
        /// <param name="passwordLength">Length of the password.</param>
        /// <param name="type">The type of password needed.</param>
        /// <returns></returns>
        private static string GenerateRandomPassword(int passwordLength, int type)
        {
            const string allowedChars = "abcdefghijkmnopqrstuvwxyz";
            const string allowedCharsWithCaps = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
            const string allowedCharsWithCapsAndNumbers = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789";
            const string allowedCharsWithCapsAndNumbersAndSymbols = "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ0123456789!@$?_-";

            char[] chars = new char[passwordLength];
            Random rd = new Random();
            string passwordCombinations;

            switch (type)
            {
                case 1:
                    passwordCombinations = allowedChars;
                    break;
                case 2:
                    passwordCombinations = allowedCharsWithCaps;
                    break;
                case 3:
                    passwordCombinations = allowedCharsWithCapsAndNumbers;
                    break;
                case 4:
                    passwordCombinations = allowedCharsWithCapsAndNumbersAndSymbols;
                    break;
                default:
                    passwordCombinations = allowedChars;
                    break;
            }

            for (int i = 0; i < passwordLength; i++)
            {
                chars[i] = passwordCombinations[rd.Next(0, passwordCombinations.Length - 1)];
            }

            return new string(chars);
        }


Quick Tip: Including numbers and symbols in a mixed case password will generally create a more secure password, which would be exponentially harder to recover using a brute force password discovery method. Also remember that this code sample is for demostration only, to give you a starting point on creating passwords.

Tags: , ,

ASP.NET | Other

Writing to the Windows EventLog

by Edward 22 October 2010 08:50

Writing to the Windows application log, can be a benefit for developers to troubleshoot applications. It's easier to write to the event log, then to a file or the database - but you should use the application log for logging problems, not for debugging or writing a lot of junk. The idea behind this is to notify administrators or other developers in case there were a failure.

It's important to know that you need administrative rights on the computer to create a new event source. If you are writing to an existing log with an existing log source, it should work. If you write to an event log, you must remember to specify or create an event Source. The Source registers your application with the event log as a valid source of entries.

Here is small sample of code to get you started.

First you need to add System.Diagnostics namespace on your Using Directives:

using System.Diagnostics;

Next, copy the following method to your code file, and call it from another method.

        /// <summary>
        /// Writes to the event log.
        /// </summary>
        /// <param name="sCallerName">Name of the caller.</param>
        /// <param name="sLogLine">The log line.</param>
        public static void WriteEventLog(string sCallerName, string sLogLine)
        {
            try
            {
                if (!EventLog.SourceExists(sCallerName))
                {
                    EventLog.CreateEventSource(sCallerName, "MyApp");
                }

                // Create an EventLog instance and assign its source.
                EventLog myLog = new EventLog();
                myLog.Source = sCallerName;

                // Write an informational entry to the event log.   
                myLog.WriteEntry("Writing to event log.", EventLogEntryType.Information);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

Below is a screenshot of how this sample code will write to the eventlog.

Tags: , ,

ASP.NET | Other

About DasCode.Net

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

Code... that's .net

Month List