Overriding the ToString() Method in C#

String Operations

Sometimes it can be useful to override a method, be it your own or maybe even one of .NET’s methods. In this example I am going to create a simple class and then show you how to override its ToString() method.

In .NET, whenever you create a class, the ToString() method is automatically created for you internally. But most of the time it is not useful at all because all it will return is the class name. So to make it more useful we can override it and return our own value instead – for example a string representation of the object.

To start off let’s create a simple class as shown below:

using System;

namespace OverridingMethods
{
    public class Automobile
    {
        #region Private Members
        private string brand;
        private string name;
        private string model;
        private int year;
        private string colour;
        #endregion

        #region Public Properties
        public string Brand
        {
            get { return brand; }
            set { brand = value; }
        }

        public string Name
        {
            get { return name; }
            set { name = value; }
        }

        public string Model
        {
            get { return model; }
            set { model = value; }
        }

        public int Year
        {
            get { return year; }
            set { year = value; }
        }

        public string Colour
        {
            get { return colour; }
            set { colour = value; }
        }
        #endregion

        #region Constructor
        public Automobile(string brand, string name, string model, int year, string colour)
        {
            this.brand = brand;
            this.name = name;
            this.model = model;
            this.year = year;
            this.colour = colour;
        }
        #endregion
    }
}

[continue reading…]

0 comments

Create a Random Text and Sentence Generator

String Operations

As a developer I am sure you have come across the need to generate some random text – most likely for testing load or something similar. In this short article I am going to show you how you can generate random text and random sentences quite quickly.

To start off I am going to create a class called RandomText. I am going to add a variable of type Random to the class and initialise it in the constructor. The code for this is below:

using System;
using System.Text;

namespace RandomTextGenerator
{
    public class RandomText
    {
        // Random object to be used for generating random text
        private Random random;

        // Constructor
        public RandomText()
        {
            this.random = new Random();
        }
    }
}

Random Uppercase Text

Now I am going to add a method called GetRandomTextUpper to the class. This method accepts an integer parameter which will be used to indicate the size of the word to be generated. Capital letters start at ASCII code 65, and there are 26 letters in the English alphabet, so we need to generate a random number greater or equal to 64 and less or equal to 90. This random number will then be used to get the corresponding ASCII character, and this way we would only be generating random uppercase letters. The code is below:

public string GetRandomTextUpper(int size)
{
    StringBuilder builder = new StringBuilder();

    for (int i = 0; i < size; i++)
    {
        // Uppercase letters start at ASCII code 65 and there are 26 letters in the alphabet
        builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));
    }

    return builder.ToString();
}

[continue reading…]

4 comments

The Proper Way to Create a Login Screen for your ASP.NET Website

ASP.NET, Internet

In this article I am going to show you how to create a secure login screen for your ASP.NET website – the proper way. I have come across many examples which do not show the correct way of implementing this, so I decided to create my own example and clarify the facts a little.

The Web Pages

Let’s start off by creating our web pages. We need three for this example:

  • A Home Page (Home.aspx)
  • A Login Page (LogIn.aspx)
  • A Members-Only Page (Member.aspx)

So create an ASP.NET Web Application Project and add Home.aspx and LogIn.aspx to the project. Now in your project tree create a new folder and call it Members. Then create Member.aspx under the Members folder. Also under the Members folder, add a new Web Configuration File.

Your project tree should now look like this:

The Home Page

Now let’s go to the Home.aspx and add some code to the page. For the purpose of this example I’m going to keep it simple. Let’s just add a title, a welcome message and a link to the LogIn.aspx page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="MembershipSite._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <h2>Home Page</h2>
        <asp:Label ID="Label1" runat="server" Text="Welcome to my site!"></asp:Label>
        <br />
        <br />
        <asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/LogIn.aspx">Access Member's Area</asp:HyperLink>
    </div>
    </form>
</body>
</html>

[continue reading…]

52 comments

How to create your own C# Hashing Class Library

String Operations, Windows Forms

In this article I’m going to show you how to create your very own class library – also know as a dll file. We’ll be building a class containing a static text hashing method, which we’ll then call from a separate application. After reading this article you will know exactly how to create a dll file with your own methods and how to use it within other projects, and that is extremely important for any developer to know.

Creating the Class Library

First of all we must start off by creating a Class Library project from within Visual Studio – in this case we shall name it HashLibrary. Now the namespace for our dll will automatically be set to HashLibrary as well.

Next create a class and call it Hasher. We have the option of either creating a normal class or a static class. A static class is one which does not need to be instantiated. Therefore whoever consumes the class can do so by calling its methods directly, without having to create an instance of it. This is ideal for our situation because we do not need to store any data within the Hasher class – all we’ll have is a method which returns a hash value.

So make the class static by adding the static keyword before the class name as shown below:

using System;
using System.Text;

namespace HashLibrary
{
    public static class Hasher
    {
    }
}

Since the class is static, we don’t even need a constructor, as can be seen in the code. All we have is an empty class which does absolutely nothing at the moment.

So let’s make it do something. Let’s add a string hashing method as shown below.

[continue reading…]

8 comments

Create and Read Cookies in ASP.NET

ASP.NET

Cookies are small pieces of text which are created by websites and stored by the Internet browser in its cache for later use. Typically a cookie would contain information related to a surfer’s session in a particular website, such as the user name, items in a shopping cart, page layout preferences, etc.

When a surfer visits a website, a cookie would be created with his details, and when he returns to the site his details are loaded from the cookie and sent to the website. This can for example, allow the website to identify who the surfer is and load his last session back.

Cookies can be very useful but they are also easily accessible so it’s advisable to never store sensitive data, such as passwords or credit card numbers, in cookies.

In this short article I am going to show you how to create a cookie in ASP.NET, obviously using C#, and then I will also show you how to read your cookie’s value.

First you must create an ASP.NET Web Application, and once that’s done add two buttons and a label to your Default.aspx web form. The first button we will call “Save Cookie” and the second one “Load Cookie”. The label will be used to display the status on-screen.

In the event handler for the “Save Cookie” button we will create a cookie and add a string value to it. The code should look like this:

protected void btnSave_Click(object sender, EventArgs e)
{
    // Create a cookie object
    HttpCookie cookie = new HttpCookie("TestCookie");

    // Set the cookie's value
    cookie.Value = "David Azzopardi";

    // Set the cookie's expiration date
    cookie.Expires = DateTime.Now.AddDays(7);

    // Add the cookie to the cookie collection
    Response.Cookies.Add(cookie);

    // Display the status
    lblStatus.Text = "Cookie has been created.";
}

[continue reading…]

1 comment