Archive for September, 2008

Gridview ObjectDataSource binding with multiple tiers

Sunday, September 28th, 2008

Binding a DataSource control to a gridview is a understandable way of grabbing data from your database and presenting it to the end user. However when building enterprise style applications it is often best to use a multi layer approach, usually consisting of a user layer, business logic layer, and data layer. Having a datasource directly connected and pulling data from the database does not really make as much sense in this style application especially if there is some logic that needs to be performed in the business layer before hand. This is where the value of the ObjectDataSource comes in. It allows you to use objects as your data source, providing you with the task of coding the functionality for pulling down the data.

What I will demonstrate below will be a simple use of a ObjectDataSource for simply pulling data from the database using the “select method” attribute.

Here is what our user layer source will look like.


<asp:ObjectDataSource
    TypeName="UserLib.User"
    SelectMethod="GetAll"
    ID="odsUsers"
    runat="server"
/>

<asp:GridView ID="gvUsers" DataSourceID="odsUsers" runat="server"
    AutoGenerateColumns="False">
    <Columns>
        <asp:TemplateField HeaderText="Username">
            <ItemTemplate>
                <asp:Label ID="lblUsernameRow" runat="server" Text='<%# Bind("username") %>'/>
            </ItemTemplate>
            <EditItemTemplate>
                <asp:TextBox ID="lblUsernameRow" runat="server" Text='<%# Bind("username") %>'></asp:TextBox>
            </EditItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

So lets pull this apart. We define a object data source, specifying two important attributes “select method” and “typename”. The select method specifies the method which we want to call on our object to get our data. This method must return an object of IEnumerable or ICollection, so we can return a DataSet. The typename specifies the object that we will call the method on.

In the gridview we bind the datasource by specifying the “datasourceID” attribute and giving it the ID of our object datasource.


public DataSet GetAll()
{
    DataSet ds = null;
    try
    {
        UserData.User data = new UserData.User();
        ds = data.GetAll();
    }
    catch (Exception ex)
    {
        throw ex;
    }
    return ds;
}

Above is our business logic layer. Theres really no logic here, all we are doing is calling to our data layer to grab the data from the database and load it into a dataset for us. When we receive the dataset from the data layer we will then pass this dataset back to the user layer to be binded to the gridview.


        public DataSet GetAll()
        {
            SqlConnection conn  = null;
            SqlDataAdapter da   = null;
            SqlCommand cmd      = null;
            DataSet ds = null;

            try
            {
                conn = new SqlConnection(CONN_STRING);
                conn.Open();

                ds = new DataSet();

                cmd = new SqlCommand();
                cmd.Connection = conn;
                cmd.CommandText = "spGetAllUsers";
                cmd.CommandType = CommandType.StoredProcedure;

                da = new SqlDataAdapter(cmd);
                da.Fill(ds, "users");

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (conn != null && conn.State == ConnectionState.Open)
                {
                    conn.Close();
                    conn.Dispose();
                }

                if (cmd != null)
                    cmd.Dispose();
                if (da != null)
                    da.Dispose();
            }
            return ds;
        }

Here is our data layer method which does all of our database interactions.

Today I only demonstrated the select method, but updates, deletes and inserts can also be setup and performed by the ObjectDataSource making it a very powerful and customizable way of interacting with the database.

Setting up vi

Sunday, September 28th, 2008

As I return to programming in Linux again I have begun to regain my previously acquired tools and knowledge. Because of this, I have decided to write this post describing how to setup a basic configuration file for the vi editor. This file will prevent the headaches of having to reset all of your settings every time you load a vi session.

Make a new file in your home directory called .exrc. What will I use to edit this file…vi of course!
% cd /home/craig
% vi .exrc

Inside the file is where you write all of your set commands that you would normally write at the start of a vi session.
The following are settings that I find I use often.
# number - Displays line numbers
# autoindent - Indents the left margin of new lines by the indent of the previous line
# tabstop - Sets the number of spaces for each tab on the screen.
# wrapmargin - Starts a new line before reaching the right margin. This occurs when the last word is less then the set number of characters./

My configuration file looks like the following.
:set wrapmargin=15
:set number
:set autoindent
:set tabstop=5

Save and restart vi, your changes should now be visible in your editor. Enjoy.

Psychology of programming

Sunday, September 28th, 2008

While reading Joe Stump’s blog, I came across a link to this interesting article on the psychology of programmers. It talks about how programmers resemble that of artists more then scientists and explains how to gain the most out of your development team by understanding the psyche of the programmer and how we work. I found it a good read, check it out.

http://www.devx.com/devx/editorial/11659

I write code like a girl

Sunday, September 28th, 2008

After reading this article Men Write Code from Mars, Women Write More Helpful Code from Venus I find myself thinking I write code more like the description of code written by women. I tend to be a style junkie always concerned with writing very clean and smooth running code that can easily be read and understood later. Writing code with a hidden intent and in a cryptic way just doesn’t sit right with me. I find it to produce more buggy code, harder code to debug, and is not visually elegant. I am definitely not isolated to this issue however because I have worked and seen many people with this approach to coding. I think for most it is just an ego issue and is thought to bring job security to oneself.

Although commenting can benefit others understanding of your code, over use of commenting can also become a bad thing. To much commenting separates and spaces the code to the point where it becomes hard to understand its overall intent quickly. This is partially due to the fact that your scrolling up and down and loosing your placing constantly. I prefer to fit an entire section of code on my screen where I can walk through it and attain its flow and intent myself without leaping over comments. If I feel a routine needs heavy commenting then I will comment the routine at its beginning, and provide an overall summary of what is to come.

In conclusion I guess what I am trying to get across is that I feel it is better to write code that describes itself and its general purpose by its structure and style then to write sloppy code and comment the hell out of it. Steve Yegge writes a brilliant article on this subject appropriately named Portrait of a n00b.

If you are interested in reading more into writing style focused code, I highly recommend the book The Practice of Programming. Written by Brian Kernighan and Rob Pike you can be sure that there is a lot to gain from it and I personally have found it an excellent read.

Handling Multiple .NET Controls with a Single Event Handler

Sunday, September 28th, 2008

I recently needed a control to display a large amount of PictureBox controls in a grid like fashion. I obviously didn’t want a click event handler for each PictureBox, that would be ridiculous since they essentially all did the same thing. The following is the solution I came up with after looking at MSDN and some other sites.

First to organize the controls into a group I wrapped them all in a panel control. This allows me to grab all of the controls from the panel and loop through them like so. While looping through them I apply a new event to the click event property and specify my own custom event handler which is defined later in the class. This all occurs in the constructor of the form.


public Grid()
{
	InitializeComponent();

	foreach (Control c in GridPanel.Controls)
	{
		c.Click += new System.EventHandler(this.ClickEventHandler);
	}
}

Now I define the handler which I stated above as the click event handler to handle all events from any controls in the panel. Of course since one handler is being used for all controls we need some way to determine which control was clicked. I do this by grabbing the control reference from the sender parameter, and grabbing the ID of it.


private void ClickEventHandler(object sender, System.EventArgs e)
{
	if (GridClicked != null)
	{
		PictureBox p = (PictureBox)sender;
		mId = p.Name;

		//do something here
	}
}

Hope this helps simplify your code in the future by reducing repetitive events for similar controls.

C++ String Tokenizer

Sunday, September 28th, 2008

I’ve been using java’s StringTokenizer lately and recently needed to use the same functionality in c++ for one of my classes, so I wrote a c++ utility class to handle this. It is presented much like the java tokenizer class but obviously toned down a bit.


/* @class Tokenizes a string and generates elements
 */
class Tokenizer {

private: 

	vector _elements;
	string _data;
	char _delimiter;
	int _index;

public:

	Tokenizer(string value, const char delimiter = ‘ ‘)
	: _data(value)
	, _delimiter(delimiter)
	, _index(0)
	{
		//tokenize our input so its ready to be transversed
		tokenize();
	}

	/* @brief Provides the next element to the caller
	 * @param element The string to store the element (passed by reference)
	 * @return Whether or no we have reached the end
	 */
	bool next(string&amp; element) {

		if(_index >= _elements.size())
			return false; 

		element =  _elements[_index];
		++_index;
		return true;
	}

	/* @brief Resets the internal pointer to the beginning of the element
	 * list
	 */
	bool first() {
		_index = 0;
	}

private:

	/* @brief Seperates and stores each element in the string
	 */
	void tokenize() {

		int first = 0;
		int last = 0;

		do {
			//search for the first or next token
			last = _data.find_first_of(_delimiter, first);	

			if(last == -1) {
				if(first == _data.size())
				 	//there no tokens or characters left, exit
					break;
				else {
					//still one element left but no final token
					last = _data.size();
					_elements.push_back(_data.substr(first, last - first));
					break;
				}
			}
			else {
				//found token, store element
				_elements.push_back(_data.substr(first, last - first));
				first = last + 1;
			}

		} while(last != -1 );
	}

};

Ensuring safe database resource cleanup even in failure cases

Sunday, September 28th, 2008

Often when I see database code on forums and newsgroups I notice resource management in a situation of failure is non-existent. Exceptions can be handled gracefully and allow the application to continue running, so why should we ignore the mess of open connections and resources in the background that are not cleaned up in most cases due to cleanup code being bypassed when an exception is thrown.

Allow me to give a typical example…

public DataSet Load(string username)
{
    DataSet ds = null;
    try
    {
        SqlConnection conn = new SqlConnection(CONN_STRING);
        SqlDataAdapter da = new SqlCommand();
        SqlCommand cmd = new SqlDataAdapter(cmd);

        cmd.CommandText = "GetUser";
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = username;

        conn.Open();
        da.Fill(ds, "user");

        conn.Close();

    }
    catch (System.Exception ex)
    {
        throw ex;
    }

    return ds;
}

If you look above you may think, “we are closing the connection so what is the problem?” By closing the connection within the try block, we risk that the call to close on the connection object may never be called if an exception is thrown from our data adapter after the connection is opened. We are also are relying on the garbage collector to dispose all of our current database resources which isn’t very efficient.

So lets clean this up a bit with the addition of a ‘finally’ to our try catch.

public DataSet Load(string username)
{
    DataSet ds = null;
    SqlConnection conn = null;
    SqlDataAdapter da = null;
    SqlCommand cmd = null;

    try
    {
        conn = new SqlConnection(CONN_STRING);
        cmd = new SqlCommand();
        da = new SqlDataAdapter(cmd);

        cmd.CommandText = "GetUser";
        cmd.CommandType = System.Data.CommandType.StoredProcedure;
        cmd.Connection = conn;

        cmd.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = username;

        conn.Open();
        da.Fill(ds, "user");

    }
    catch (System.Exception ex)
    {
    throw ex;
    }
    finally
    {
        if (conn != null)
        {
            if(conn.State == System.Data.ConnectionState.Open)
                conn.Close();
            conn.Dispose();
        }

        if(cmd != null)
            cmd.Dispose();
        if(da != null)
            da.Dispose();
    }

    return ds;
}

The advantage of using a finally block here is that whether or not an exception is thrown or is not thrown, the finally block will always be executed. This gives us the perfect place to put any final cleanup and connection code that we must guarantee will be executed, even in the event of an exception.

Note the ‘null’ checks on all objects before calling close and dispose methods on them. We do this because cannot guarantee that the objects have been initialized when they reach the finally block because the code could have thrown an exception very early within the try block before full initialization took place. We also need to place the object declarations outside of the try catch in order for them to be in proper scope for the finally block.

It is great to handle exceptions gracefully and continue application execution but you also need to be aware of what is going on behind the scenes with resources. Overtime with applications throwing many exceptions and many connections being left open, you are likely to see a slight performance hit in your applications, especially with a large user base.

Now this is all good, we now have successful closing of our connections, we have disposing even when exceptions are thrown, but personally I don’t like how long this code has become. Add a SqlDataReader to this code and it grows even more. So what can we do while still ensuring that clean up will happen?

C# offers a great solution called “using”. “Using” provides scope for your resources, and ensures that resources and even connections are both disposed and closed when they reach the end of their life. Underneath the hood a try finally is being wrapped around the objects, and providing the closing and disposing calls for you. Lets see what our example looks like with this new syntax.

public DataSet Load(string username)
{
    try
    {
        using(SqlConnection conn = new SqlConnection(CONN_STRING))
        {
            conn.Open();
            using(SqlCommand cmd = new SqlCommand("spGetUser", conn))
            {
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.Add("@username", SqlDbType.VarChar, 50).Value = username;

                using(SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(ds, "users");
                }
            }
        }
    }
    catch (System.Exception ex)
    {
        throw ex;
    }
    return ds;
}

So as you can see our finally clause is now gone. We have also removed the need to declare our Sql objects at the beginning of our function and have moved the stored procedure and connection into the command object’s constructor. To me this provides much nicer code and organizes everything into nice workable chunks.

So in the end its really up to you which method you choose, but if you prefer organized code the latter will be the most likely choice. Remember, the more code you have to write the larger the chance for a bug to occur or a missed closing call.