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>
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.

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.
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.
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.
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.

by Edward
25 September 2010 17:21
Boxing and unboxing is an important concept in C#’s type system. With Boxing and unboxing you can link between value types and reference types by allowing any value of a value type to be converted to and from type object. When you 'box' a value type, it wraps the value inside a System.Object and stores it on the managed heap. Unboxing does the reverese, it extracts the value type from the object.
The following code snippet demonstrates boxing and unboxing:
public static void Main() {
Int32 v = 5; // Create an unboxed value type variable
Object o = v; // o refers to a boxed version of v
v = 10; // Changes the unboxed value to 10
Console.WriteLine(v + ", " + (Int32) o); // Displays "10, 5"
}
Here is a more simple example:
Boxing:
int i = 5;
object o = i; // boxing
Unboxing:
o = 5;
i = (int)o; // unboxing
by Edward
10 September 2010 08:03
If you are like me, and you like to extend your code, or do interesting things with .Net, then this article on zip archives might be helpful. SevenZipLib is a lightweight, easy-to-use managed interface to the 7-zip library which you can use in your .Net applications. You can easily use the library to read, extract or create zip archives.
Below is a few examples I took from the CodePlex website:
List files
using (SevenZipArchive archive = new SevenZipArchive("library-dascode.rar"))
{
foreach (ArchiveEntry entry in archive)
{
Console.WriteLine(entry.FileName);
}
}
List files in an encrypted archive
using (SevenZipArchive archive = new SevenZipArchive("DasCodeArchive.rar", ArchiveFormat.Unknown, Password))
{
foreach (ArchiveEntry entry in archive)
{
Console.WriteLine(entry.FileName);
}
}
Perform an integrity check
using (SevenZipArchive archive = new SevenZipArchive("ASPNET_Tips_Tricks.zip"))
{
bool checksOK = archive.CheckAll();
Console.WriteLine(checksOK ? "Archive is OK." : "Archive is not OK");
}
Extract entries to a directory
using (SevenZipArchive archive = new SevenZipArchive("extract_code_tips_archive.7z"))
{
archive.ExtractAll(TargetDirectory);
}
Extract entries to a directory (alternative)
using (SevenZipArchive archive = new SevenZipArchive("extract_entries_code_tips_archive.7z"))
{
foreach (ArchiveEntry entry in archive)
{
entry.Extract(TargetDirectory);
// You can also use archive.Extract(entry.FileName, TargetDirectory)
}
}
You can download it from the CodePlex site:
SevenZipLib Library
by Edward
25 August 2010 08:05
There are many ways to remove duplicate elements from a generic List collection in the C# language, but some are easier to implement then other, or some might not fit your code. An easy solution, is using the LINQ extension methods can be very useful when you have a List collection. It is lightweight, and is can also be implemented anywhere in your solution.
For my example, I used the Linq "Distinct" method (System.Linq) to get a unique list of categories for books. I first get a list of my books from the database, and then use the "distinct" method, and then also cast the list back to a generic list with the duplicate items removed.
/// <summary>
/// Returns the distinct list of categories.
/// </summary>
/// <returns>List<string></returns>
private static List<string> ReturnDistinctListofCategories()
{
// List with duplicate elements.
List<string> list = new List<string>();
list.Add("code");
list.Add("coding");
list.Add("asp.net");
list.Add("tips");
list.Add("code");
list.Add("coding tips");
list.Add("asp.net tips");
// We now have a list with duplicate items
// Get distinct elements and convert into a list again.
List<string> distinctClientList = list.Distinct().ToList();
//DEBUG: Test the result
foreach (string value in distinctClientList)
{
Debug.WriteLine(value);
}
return distinctClientList;
}
I hope this can help you. Like I stated before, there are numerous ways to do the same as my code.
by Edward
17 August 2010 21:22
Microsoft announced that they are going to unveil Internet Explorer 9 (IE9) "Beta" next month(September 2010), at an event in San Francisco titled Beauty of the Web. While the browser wars for top spot are now between Internet Explorer, Firefox, Chrome and Opera, the latest version of IE9 will have to catch-up quickly. Microsoft seems to have missed a golden opportunity to make up for the failures of IE6 and IE7. Even Safari is making IE seem like an old browser and that is not even a target Windows platform browser.
By bringing out IE9 Microsoft seems to take something from Firefox Chrome. Some of the key features are that there are improved standards supports, as it scored an impressive 95% on the Acid 3 CSS test. IE9 also have better JavaScript and graphics performance, compared to previous versions. IE9 also implements enough of the HTML5 specification to raise the hope that stuffing rich content into browser plug-ins might not always be necessary.
As Microsoft is stating on its IE blog "IE9 offers consistent, fully hardware-accelerated text, graphics, and media, both audio and video", let’s hope Microsoft is starting to catch up and will continue to give users what they want from a browser experience.
