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


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


DateDiff – Subtract

In my VB.Net code I’ve always used the DateDiff function to determine the number of days between 2 dates. Today I was playing around working out which order to put dates in and discovered that the Date object as a method called Subtract. This returns a TimeSpan then its just a case of using the Days property

startDate.Subtract(now).Days

Note that if startDate is before todays date this will return a negative value

>? now.subtract(cdate("1 Jan 2009")).days
1
>? cdate("1 Jan 2009").subtract(now).days
-1
>? now.subtract(cdate("1 Jan 2008")).days
367


Forcing Data Types on literal constants

The following type characters can be used to force a literal value to be a certain data type


"a"c 'Char
#1/1/1900# 'Date
0D 'Decimal
0@ 'Decimal
0.0R 'Double
0.0# 'Double
0I 'Integer
0% 'Integer
0L 'Long
0& 'Long
0S 'Short
0.0F 'Single
0.0! 'Single

See MSDN for more details


PrintPreviewControl

If you are using the PrintPreviewControl and what the page displayed to be refreshed with a new document, you must call the PrintPreviewControl.InvalidatePreview method. In 1.1 this did it automatically everytime a document was set, but now you have to do it manually, thats progress for you!

StatementPrintPreviewControl.Document = aDocument
StatementPrintPreviewControl.InvalidatePreview()


Previous Entries Next Entries