SqlConnection, Close and deconstructor: Internal .Net Framework Data Provider error 1.

Today I experienced the following issue:

I had a class where I would open a SqlConnection, do some actions, and then in the deconstructor I closed the SqlConnection.

~Dumper()
{
    this._sqlConnection.Close();
}

Unfortunately every time my program ran it stopped with this error:

image

Internal .Net Framework Data Provider error 1.

(click to enlarge)

Well it seems that you cannot close a SqlConnection in a ~Deconstructor block.

So the solution is implementing the IDisposable interface

internal class Dumper : IDisposable
{
    private readonly SqlConnection _sqlConnection;

    public Dumper()
    {
        //build and open the connection
        this._sqlConnection = new SqlConnection(Settings.Default.ConnectionString);
        this._sqlConnection.Open();
    }

    /// <summary>
    /// Some function
    /// </summary>
    /// <param name="param">param</param>
    public void SomeFunction(SomeParameter param)
    {
    }

    public void Dispose()
    {
        this._sqlConnection.Close();
    }
}

And to use it you do this:

using (Dumper dumper = new Dumper())
{
    dumper.SomeFunction(myParam);
}

This will cause dumper to be Disposed after the } and it will no longer be available

.NET 3.5 pager, generate pages from List<T>

A friend of mine asked me to generate pages from a List<T>. This is my implementation:

using System;
using System.Collections.Generic;
using System.Linq;

namespace Pager
{
    static class Program
    {
        static void Main()
        {
            List<int> list = new List<int>();

            //add 26 items
            for (int x = 0; x < 26; x++)
            {
                list.Add(x);
            }

            //generate pages
            List<int>[] pagesList = Pager<int>(list, 4);

            Console.WriteLine("Please examine pagesList");
            System.Diagnostics.Debugger.Break();

        }

        /// <summary>
        /// Converts a collection of T to an array of pages
        /// </summary>
        /// <typeparam name="T">The type of items in the list, can be inferred most of the time</typeparam>
        /// <param name="list">The list to page</param>
        /// <param name="itemsPerPage">Items per page</param>
        /// <returns>An array of lists, pages if you will</returns>
        static List<T>[] Pager<T>(ICollection<T> list, int itemsPerPage)
        {
            int pages = (int)Math.Ceiling((double)list.Count / itemsPerPage);

            List<T>[] pagesList = new List<T>[pages];

            for (int currentPage = 0; currentPage < pages; currentPage++)
            {
                pagesList[currentPage] = list.Skip(currentPage * itemsPerPage).Take(itemsPerPage).ToList();
            }

            return pagesList;
        }
    }
}