Tuesday, May 22, 2012

ASP.NET - Efficiently Hide GridView Columns using Column names.

I've seen several places on the web that illustrate how to hide Columns of a GridView based on Column number rather than Column name. After poking around a bit and a fellow developer pushed me in the right direction, I found a cleaner approach using column names.

This blog post however assumes that the DataSource of the GridView is a DataTable. Which means that when Binding data to the GridView its DataSource Property is set to a DataTable object.

 For Example:


DataTable dt = /* Taken from already formatted Column Named Table */;
gridView.DataSource = dt;
gridView.DataBind();


It also assumes that the DataTable has already been formatted with appropriate Header/Column Names.

First,  before the DataTable is bound like in the code above, a Dictionary object should be created to store both Column Names and Column Indices.  This is done using the Ordinal member variable of the DataTable:


Dictionary<string,int> hideIndices = new Dictionary<string,int>();

hideIndices.Add("NAME", dt.Columns["NAME"].Ordinal);


hideIndices.Add("Description", dt.Columns["Description"].Ordinal);

The above Columns are then "NAME" and "Description" respectively.

Now the hideIndices object needs to be saved (due to the Postback behavior of asp.net) to a Session variable.


Session.Add("hideIndices", hideIndices);


Finally, These columns can be hidden in the RowCreated event handler assigned to the gridView.  The indices can be looped through in the dictionary in order to make each Cell that corresponds to all indices in the saved list invisible (Visible property = false).

protected void gridView_RowCreated(object sender, GridViewRowEventArgs e){
    if (Session["hideIndices"] != DBNull.Value)
    {
         Dictionary<string, int> hideIndices = 
         (Dictionary<string,  int>)Session["hideIndices"];
         
         foreach (int index in hideIndices.Values)
         {
               e.Row.Cells[index].Visible = false;
         }
     }
}
That should effectively hide all columns in a gridview based on column name.  Notice however that a List<int> object would have worked just as well for this example.  I however left it as a Dictionary object incase of further need of the Column name else where.

Wednesday, April 20, 2011

Guidelines for Coding Aesthetics

What makes code truly beautiful? Is there something more to it than just instructions executed by the machine? Is there an absolute reason for its beauty or is it merely biased opinion? Is it the underlining algorithms that make code beautiful or is it the organization of the code itself? Where do you draw the line and say that some code is ugly, some code is normal, and some is magnificent(Okay, more like lines - plural)?

I believe that these questions all have answers. Which is really the objective of this blog. To seek out new ideas and beautification...to boldly go where every software engineer should have gone before..that is to the depths of the coding practice and the ideas behind what can make software so solid it won't collapse even with the most treacherous hammering which true software testers provide.

I want to take a look at each question to truly define the guidelines behind coding aesthetics - in otherwords what makes code truly beautiful(Thus answering the first question). I first want to address the question about algorithms vs. code organization. This happens to be a deep subject for me and thus may take a couple of posts. Hopefully, I'll address how I feel about algorithms in this blog. The other questions I plan to cover in another post but remember that this is discovery. SO I'm glad to say I don't have all the answers yet :).


Efficient Algorithms vs Code Organization - Which one is beautiful?

At any university level Beginning Algorithms course it should be taught that every algorithm runs at a certain order of magnitude based on some sort of notation. The most common notation is the "Big-O" notation since it is used to determine the worst case scenario of a running algorithm and thus makes for an excellent candidate for measuring the overall efficiency of any given algorithm. While there are many details behind the use of other notations this is the only one I will consider here. However, my point being that efficiency is very important for the machine to run quickly and you might even call it beautifully...since it is beautiful to have a process finish in a short period of time. Unless of course you like your software to freeze while you make coffee or something...

Anyway, the "Big-O" notation has rules which can be placed on common coding mechanisms (assignment statements, loops, control structures, functions...etc). The point being that with these types of statements there is a cost on the system and it doesn't matter what the notation is...you must take into account the overall effect of the algorithm to understand how efficient your code is running. This means that the "Big-O" notation, regardless of all the system specifications - how fast it runs - how much space is available, measures the algorithm the same as to NOT take into account any details of the system.

This really measures efficiency in a way that is more geared toward any hypotetical system. Great huh? So what does this have to do with beauty in code - the efficient algorithms that are measured regardless of system details are in effect beautiful because they can be implemented on any system and work the same (Only vary in systems specific speed).

There is however a drawback to the idea behind efficient algorithms! They sometimes contain some of the most incomprehensible code which requires several days of labor in understanding as well as planning. The problem isn't that they are hard to understand but can create truly unorganized messes that can only be read by the original author...no matter how efficient it could seem to run..the maintainers hate the software and hope to never venture into the land of algorithmic chaos. Yep..that really does happen in the field.

So, there is an obvious beauty to organization. Which I believe is based on coding standards and styles. More of this is to come in the next post..but just to recap - Efficient Algorithms are beautiful in the since that they can run beautifully and have ingenious components that make them worth while to understand but the can cause an overwhelming difficulty in organization. My point is that beauty isn't in the algorithm itself - or the idea ALONE! Beauty is found in more than one place. Of course, you could say its in the eye of the beholder..but then you would just be irrational. :)

Friday, April 15, 2011

Is there Beauty in Events?

There is a question that comes to mind - Is there beauty in events? In using events, do you feel like they are just a giant mess? This tends to happen to me anyway. Event driven software is much of what I find myself doing with C# nowadays. Somehow, I am able to code rapidly with events but the overall feel of the code is more like a monster that just keeps growing and growing. This is probably from a lack of understanding of how to implement them beautifully or efficiently. I would love to consider this more...How to develop event driven software that doesn't feel like I'm just creating events all over the place.

With the help of Visual Studio, it appears that you can now auto create an event handler just by typing in the name of an event somewhere in a xaml tag or somewhere in the code-behind and then by simply pressing the tab button. This auto-generates your event handler with a generic name. Talk about creating easy to read code (sarcasm) ;). Thanks Microsoft...okay so it could be a bad tool if you don't take into account how visual studio creates these event handlers. It appears to take the name of the calling object/class followed by an underscore and then the name of the event. This is pretty slick but can also make for some unfortunate misunderstanding in code.

What if you could use one event handler for several objects?? This seems to be the biggest problem for me when using this tool! If you have a single event handler for objects such as a Border and a Grid then when you use the auto-generate tool for the first object it will come with the name of the Border or Grid class which you selected.

For example, suppose you had the following Border defined in xaml:

<Border BorderThickness="1" Margin="0,42,2,-69" Width="146" HorizontalAlignment="Right" RenderTransformOrigin="0.396,0.59" MouseEnter="Border_MouseEnter" MouseLeave="Border_MouseLeave" Grid.Column="5" Grid.ColumnSpan="2">

and the following Grid also definded:

<Grid Height="150" Width="150" MouseEnter="Border_MouseEnter" MouseLeave="Border_MouseLeave" Margin="-1,7,7,7">

Do you see the problem? Both the Border and the Grid are using the same event handler but the name of the event handler leaves you with a feeling of discomfort. The Grid isn't a Border and therefore makes you wonder why should a Grid have a Border event handler. This is an ambiguity that for truly beautiful code shouldn't be ignored. While the Microsoft tool is great..the point is to use it with the dignity to make your code clear. Be careful in the way that you use it in order to create a more healthy clean environment :). Or something like that...


Thursday, April 14, 2011

First post - for a future of code

This is my first post on this blog. It will follow my adventures in trying to identify what truly is beautiful about coding. I'am beginning a job in software engineering at Schneider-Electric(Square-d) at the end of August 2011 and have been coding since I can remember. My quest is to find what is truly beautiful in code and find a more beautiful way to write solid, clean, and manageable code.

It appears that writing beautiful code hasn't always been my goal but rather "getting the job done" has been something I've done in the past. (As any fellow college student should admit too.) This however shouldn't be any software engineers goal when it comes to writing truly solid code.

After spending a year interning with Schneider-Electric before finishing my last semester in college I found that much of the software I worked on to be riddled with indwelling problems(like any software) and even contest to several frustrating days behind a keyboard. It wasn't that the software was all bad but that there was such a mess of code that it often left me feeling of unrest. Often times I could just feel the sheer instability and fickleness of a system that truly marks a non-solid system by just using the software itself. This leads me to believe that there must be patterns in software and principles that must allow for truly beautiful code and create solid applications. This is the purpose of the blog and for the search to better the products by defining what is truly beautiful and what just isn't.