C# – IsNumeric

Use the TryParse method to determine if a value is numeric

int retNum;
if (Int32.TryParse(BookId, System.Globalization.NumberStyles.Any, System.Globalization.NumberFormatInfo.InvariantInfo, out retNum))
{
    //Is numeric
}

PasswordRecovery – Gotcha

Using the default style for the register and password recovery controls, the register expects a user name and email address. The passowrd recovery template asks for your email address, but what it actually looks up in the background is based on the user name and will therefore never find a match for the email address entered. A quick way round this is to change the default text to say User name instead of Email Address!

Singleton Class – Basic Example

Below is an example of a Singleton implementation C# class.

public sealed class StaticData
{
    private  StaticData() {}
    public static readonly StaticData Instance = new StaticData();
    string connectionString = "";
    public string ConnectionToUse
    {
        get
        {
            if (connectionString.Length == 0)
            {
                connectionString = System.Configuration.ConfigurationManager.AppSettings.Get("DBConnection").ToString();
            }
            return connectionString;
        }
    }
}

Output Parameters with returned value

When using output parameter values you need to check that the value is not DBNull before using it…

using (SqlConnection conn = new SqlConnection())
{
    conn.ConnectionString = System.Configuration.ConfigurationManager.AppSettings.Get("DBConnection").ToString();
    conn.Open();
    using (SqlCommand cmd = new SqlCommand())
    {
        cmd.Connection = conn;
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add(new SqlParameter("@ChapterId", _ChapterId));
        cmd.Parameters.Add(new SqlParameter("@Sequence", _Sequence));
        cmd.CommandText = "Get_ContentPrevNext";
        SqlParameter parameterPreviousId = new SqlParameter("@PreviousId", System.Data.SqlDbType.Int)
        {
            Direction = System.Data.ParameterDirection.Output
        };
        cmd.Parameters.Add(parameterPreviousId);
        SqlParameter parameterNextId = new SqlParameter("@NextId", System.Data.SqlDbType.Int)
        {
            Direction = System.Data.ParameterDirection.Output
        };
        cmd.Parameters.Add(parameterNextId);
        cmd.ExecuteNonQuery();
        if (parameterPreviousId.Value != DBNull.Value)
        {
            _PreviousId = Convert.ToInt32(parameterPreviousId.Value);
        }
        if (parameterNextId.Value != DBNull.Value)
        {
            _NextId = Convert.ToInt32(parameterNextId.Value);
        }
    }
}

Image from Byte Array

To render an image to a picturebox using the data stored in a byte array use the following code

using (MemoryStream ms = new MemoryStream(ImageDetails.ThumbnailImage))
{
    ThumbnailImage.Image = Image.FromStream(ms);
}

Render Image using Generic Handler ASP.Net

The following code uses a property from an object that returns a byte array that contains an image.

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "image/jpg";
    if (context.Request.Params["Id"] != null)
    {
        Content selectedImage = new Content(Convert.ToInt32(context.Request.Params["Id"].ToString()));
        if (context.Request.Params["t"] == "D")
        {
            context.Response.OutputStream.Write(selectedImage.ImageDetails.FullImage, 0, selectedImage.ImageDetails.FullImage.Length);
        }
        else
        {
            context.Response.OutputStream.Write(selectedImage.ImageDetails.ThumbnailImage, 0, selectedImage.ImageDetails.ThumbnailImage.Length);
        }
    }
}

Loading Image/BLOB from SQL Server

If you have an image column in your SQL table you can load the bytes using the following code.

int bufferSize = Convert.ToInt32(reader.GetBytes(7,0,null,0,int.MaxValue));
_ThumbnailImage = new Byte[bufferSize];
reader.GetBytes(7, 0, _ThumbnailImage, 0, bufferSize);


The first parameter is the column number, in this case 7, call GetBytes with a null buffer first to get the number of bytes needed.

Remember that an image column, holds bytes and therefore can contain any sort of document, not necessarily an image, could be a PDF

C# 3.5 – Code Snippets

In the intellisense list certain options will appear that state they are code snippets, e.g. foreach. To get the snippet to actually insert press TAB twice.

See MSDN for more details

TRUNCATE TABLE – execute permissions

In SQL 2005 you can now use WITH EXECUTE AS to allow a normal user to truncate tables. It basically means they run the specificed procedure with higher rights than they have.

CREATE PROCEDURE TruncateMyTable
WITH EXECUTE AS OWNER
AS TRUNCATE TABLE MyDB..MyTable;

See MSDN for more details.

VB.Net – ControlChars

If you need special characters in your VB.Net use the ControlChars class, it has definitions for Lf, Crlf, etc.

See MSDN for more details

Previous Entries