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

Comments 1 Comment »

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;
        }
    }
}

Comments No Comments »

Some functions expect an array with a minimum size. While this is generally bad coding sometimes you can’t avoid it (e.g. with csv files).

That’s when this piece of code comes in handy: (it’s an extension method, so it only works on .NET 3.5)

public static class ArrayHelper
{
    /// <summary>
    /// Expands an array to the given <paramref name="size"/>
    /// </summary>
    /// <typeparam name="T">The type of the array (not neccesairy, can be infered).</typeparam>
    /// <param name="array">The array</param>
    /// <param name="size">The size it should become</param>
    /// <returns>The array expanded to the given size</returns>
    public static T[] Expand<T>(this T[] array, int size)
    {
        if (size < array.Length)
        {
            throw new ArgumentException("size < array.Length, this will cause data to be truncated, canceling", "size");
        }

        T[] list = new T[size];

        for (int index = 0; index < array.Length; index++)
        {
            list[index] = array[index];
        }

        return list;
    }
}

Usage:

class Program
{
    static void Main(string[] args)
    {
        string[] array = new string[] { "test1", "test2", "test3" };

        //array1 has a length of 3
        Console.WriteLine("array.Length = {0}", array.Length); 

        array = array.Expand<string>(10);

        //now array has a length of 10
        Console.WriteLine("array.Length = {0}", array.Length);

        Console.ReadLine();
    }
}

Enjoy :)

Comments No Comments »

This is something I’ve been thinking about a lot. When do I throw an exception? Do I program with exceptions? Do I catch those exceptions.

Consider this piece of code:

public Product GetProduct(int id)
{
    //get the product, or null if not found
    Product p = //...

    return p;
}

Now you can ask yourself the following question:

Is it ok to return null if the product is not found? After all, the calling layer assumes that we’ll be getting a Product, not a null.

So now the calling layer needs to check if the product != null.

It would be exceptional if no product was found.

So in my opinion you throw an exception if no product is found. And that get’s handled in the calling layer.

But on the other hand: if you would just return a null and test on that in the calling layer you would use less resources since exception throwing is expensive.

I’d still go with the first one since it goes better with my consume code thoughts.

But this is an agreement you need to make across your team, and across your API.

Comments 2 Comments »

So yesterday I reinstalled my laptop because some beta driver was acting up, no big deal. I had both of my partitions secured with Bitlocker (and a BIOS password set up) so that my laptop is secure.

After formatting I noticed that my C drive wasn’t encrypted anymore (which is obvious, it was formatted).

But my D drive looked like this:

locked

It was locked. Fortunately I printed my recovery key so I was able to unlock the drive.

Please print the keys, and keep them safe!

Comments No Comments »

Well not really my computer, but my girlfriend’s. It needed some updating (you know how people are, not updating & stuff).

Adobe Reader already sets 2 programs in startup. A speed launcher and another one which I am too lazy to identify. If your application is too slow then optimize it, don’t treat the symptoms.

Then our good slow friend Java. Always had their speed launcher (symptom treatment!!) in startup, but guess what also added a service.

naamloos

What the f*ck? I’m moving closer and closer to not install Java on new pcs, since it’s a burdon to manage and keep up to date!

Comments No Comments »

Something not many people know: when you need to compare 2 strings in C#.NET you can use the == operator overload:

if(firstString == secondString)
{
    //...
}

This is case sensitive. But when you need to ignore the case please don’t use this:

if(firstString.ToLower() == secondString.ToLower())
{
    //...
}

or this:

if(firstString.ToLower().Equals(secondString.ToLower()))
{
    //...
}

A Framework provides you with utilities, please use them. They are usually better than your implementation!

Use this:

if (firstString.Equals(secondString, StringComparison.OrdinalIgnoreCase))
{
    //...
}

StringComparison is an enum. So please look at the options :)

Comments 1 Comment »

Ever wanted a getJSON which does a post?

Here it is:

jQuery.extend({
    postJSON: function(url, data, callback)
    {
        $.post(url, data, callback, "json");
    }
});

Comments No Comments »

To connect to your SQL Server 2008 Express edition over network you need to enable the following options:

First: open SQL Configuration Manager (SQLServerManager10.msc):

image

Double click on ‘Named Pipes’ and enable them.

image

Then click ‘OK’ on the bottom. Now we have the access set up, now we need to start the service.

Now open Services (services.msc) and double click on ‘SQL Server Browser’:

image

Set the startup type to ‘Manual’ or ‘Auto’. That’s up to you. I have it on manual for security reasons. Then you can click start. But we have one more step to do. In the window copy the path to the executable (‘C:\Program Files (x86)\Microsoft SQL Server\90\Shared\sqlbrowser.exe’).

Then go to your firewall in your control panel and add the sqlbrowser path to allowed programs.

You’ll eventually see this:

image

You can also check the public, but that’s not necessary for me. If you set the sqlbrowser service to manual, you’ll need to start it each time you want it (just by making a shortcut to the path we copied above.) If not, it’ll start at startup :)

Good luck and post your questions below!

I’m going to try replication between 2 SQL Servers Express in one of these days and I’ll post the results on that too!

Comments No Comments »

Today I was trying to find out a way to use jQuery in one of my views. Since I include the jQuery in my master page I bumped into the problem that Visual Studio doesn’t recognize the jQuery in the child page.

So I tried some stuff, and I thought: I might share it as well here so you don’t spend time on looking up everything like I did.

First thing I tried is using the ///<reference path … /> syntax.

But this doesn’t work in <script …></script> tags. It only works in real (.js) javascript files.

I then used this ‘hack’ to make the intellisense work (and I don’t like hacks).

    <% if (false)
    { %>
    <script type="text/javascript" src="~/Scripts/jquery-1.3.2-vsdoc.js"></script>
    <% } %>

Stuff like this really makes my code look like a hack. I’ll test tonight if I have different behavior in Visual Studio 2010.

Comments No Comments »

And shepherds we shall be, for thee my Lord for thee, power hath descended forth from thy hand, that our feet may swiftly carry out thy command. We shall flow a river forth to thee, and teeming with souls shall it ever be. In nomine Patris, et Filii, et Spiritus Sancti.

headless horseman worksheets

letters requesting endorsements

multiplication printable worksheets

form letters template

hope center for youth texas

mass ufo sightings

letter holder decorative

sample acceptance job letter

examples of written warning letters

ufo news sceptical enquierer

words used for letters of alphabet

old missing goverment plane ufo

mission statement worksheet

four seasons maui day of hope

astronaught aliens

memorial letter sent after death

scooby doo worksheets for children

payson utah ufo wierd happenings

reading worksheets grade 1

stop forclosure hardship letter

fraction worksheets grade5

berkley wellness letter

fasfa worksheets

beginning worksheets for high school readers

language arts worksheet

without hope

ertes letter a print

beef o brady's hope mills nc

letter g sign

vowel print letter practice sheets

letter de scrambler

sample letter to credit reporting agencies

hope cestrone

fables arnold lobel worksheet

ghetto bubble letters

hope dream wish

paranoid personality disorder hopes

annual lease value worksheet

fourth of july independence day worksheets

physics themed movies worksheet

ufo contact from pleiades

alphabet soup wall letters

legal resident aliens

scale drawings worksheets furniture

dressage movements ten letters

cognitive behavioral depression worksheet

funny letter from boy scout

city of hope uae

september hope

ufo clode encounters diamond

phoenics printables

atom printable

printable brackets 2009 basketball

stand-ins printable

printable marriage certificates

free printable travel games for kids

printable english garden

free printable coupons for cesar canine

reading printables for halloween

printable divine office bookmarks

printable applebees coupon

printable english skill sheets

printable taget

printable map pacific islands

star printable

geoboard printable

printable volleyball line up sheets

free printable coloring pages sport

printable diego button

free printable online maths crossword puzzles

printable humorous fiction stories eighth grade

printable blank bracket forms

new years printable

printable novelitys

printable computer monitor calendars

thomas printable

asia printables

printable gothic stationary

printable summer memory game

digital audio cd-r injet printable hub

free printable last will and testament

clip art printable business check

printable timeline

printable millimeter scales

free printable christmas letterheads

free printable quizes

caterpillar printables

tornado photos printable

printable question mark sign

estimation printables

printable offer

printable pet vaccine record

earthweek printable

printable frame

tj maxx printable coupon

free printable dollhouse miniatures

autozone printable

kenken printable

third grade printable worksheets

printable daytime sequencing worksheet

printable callanders

printable elevation maps

winnie the pooh printables page

picasso printable

anime printable

barn printables

printable calenda

hpc mmal card printable version

olympia sports store printable coupons

printables money for kids

printable teen devotional

kinder printable

kids math problems printables

punctuation printables

free printable worksheets for books

employment printables

printable ohio state buckeye logo

free printable activities about chi

printable coloring pages of fish

free printable colorful calenders

printable julian date calendar

printable walmart application

printable country songs

printable cardboard

printable picture of car racing flags

printable story groundhogs day

free printable dragon pictures to color

proctor gamble printable coupons

printable frames for scrapbooking

target 10 off printable in-store coupon

free printable first then

free printable 5-day planner

soup and hand printable coupon

printable facts mardi gras

printable radiation signs

printable map pikeville ky

chinese new year printables for kids

printable manuscript writing sheets for abcs

printable coupon for atkins morning bar

printable pattern of a rose

a printable redneck diploma

kindgergarten printables

naming objects printables

printable alphabet dot to dot

printable tanglewords

lowes printable coupon wow

printable coloring mandalas pages

printable picture of niagara falls

starbucks frappuccino 4 pk printable coupon

printable soduku

michael jacksons printable photos

domino printables

printable ant activities

conservation printables

kohler printable coupons

printables art

printable ncaa

brown bear brown bear printables

pharmacy coupons retail printable

disney printable pumpkin patterns

printable cooking border writing paper

printable invitations

printable t-shirt

printable fruit

printable fantasy football draft sheet

printable ab workout

nebraska printables

free printable graduation cards

printable advanced english grammar exercises

printable list sms and text lingo

printable good manners pictures for kids

bible character word search printable

printable address albels

printable golf gift certificate template

print custom printable coupons

free printable pre-algebra worksheets

printable label

printable coloring pages of water

religious easter printables for kids

printable preschool biting activities

printable piano worksheets

printable do not enter signs

printable coupons gander mountain

printable superbowl square pool grids

jonathan mccoy n-word printable

party city printable coupon april

printable notepaper

fchristian printables

free printable business card templates

taco johns printable coupons

colorwheel printables

hidden picture printables

printable layouts

printable travel checklist

printable coloring pages of spongebob

printable brain

ups printable logo

printable camo

printable sign in sheet

pentominoes printables