The Self-Taught Programmer

Recipes from real-world experience with asp.net.

How to get the value from a GridView column on RowDeleting

leave a comment »

The Situation:

You need to get the value of one of the columns in the row you are deleting in a GridView to do some processing before the row is deleted.

A Solution:

When using the RowDeleting method, you cannot use e.Row.Cells[1].Controls[1] to get the control in that cell like you can in the RowCreated method. Instead, you can simply access the text of the desired cell and convert it to whatever datatype you need, like this:

protected void gridview1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
	// You get the Key (identity value) of the row like this...
	string userName = gridview1.DataKeys[e.RowIndex].Value.ToString();
	
	// And you can get the value of any other cell in the row like this... 
	// (this would get the value in the 4th cell)
	string cellval = gridview1.Rows[e.RowIndex].Cells[3].Text;
	
	// DO MORE PROCESSING HERE
}

Written by Jim McMullen

June 19, 2012 at 3:51 pm

Posted in How-To

Tagged with

How to Get the Name of the Current Folder from the URL

leave a comment »

The Situation:

You need to get the name of the current page request folder from the URL.

A Solution:

Use this method:

public string GetCurrentFolderName()
{
	//get current file path 
	string folder = System.Web.HttpContext.Current.Request.FilePath;

	//find the position of the last '/' 
	int intPos = folder.LastIndexOf("/");

	// if it is not the root folder...
	if ( intPos > 0 )
	{
		//cut off all characters after the last '/' 
		folder = folder.Substring(1, intPos - 1);

		//find the position of the last '/' in the new string 
		int intPos2 = folder.LastIndexOf("/");

		//get the length of the characters between the two '/' 
		int intLength = ( intPos - 1 ) - ( intPos2 + 1 );

		//get the characters between the 2 '/' 
		folder = folder.Substring(intPos2 + 1, intLength);
	}
	else
	{
		folder = "";
	}

	return folder;
}

Written by Jim McMullen

December 2, 2011 at 11:06 am

Posted in How-To

Tagged with ,

How to Find the Index of a String in a List

leave a comment »

The Situation

You are trying to find out if a string exists in a List object.

A Solution

You could use a Find with a predicate, or try the simple method below.

private int FindStringInList(List<string> list, string str)
{
    return list.FindIndex(s => s == str);
}

Written by Jim McMullen

October 17, 2011 at 3:54 pm

Posted in How-To

Tagged with ,

How to Troubleshoot Problems Upgrading an Existing App from EntitySpaces 2009

leave a comment »

I am a big fan of EntitySpaces, a .NET ORM framework that I find very easy to use. When the developers upgraded the framework in 2010, they “broke” some things I used in my code. Specifically, they changed the way instantiate a new ORM entity. Entities used to have a method that looked like this…

esEntity.AddNew()

According to the release notes:
This method has been removed. It was optional in 2009 and has finally been removed. If you have overloaded or overridden this virtual method in a Custom class, you should move that logic to the constructor in your Custom classes (see above) and remove the custom AddNew method.

In fact, there were a bunch of “breaking” changes in ES2010. Keep a copy of the release notes when you upgrade past 2010 so that you will have a way to troubleshoot old apps when you upgrade them. (This is a good idea for all developer tools and languages, in fact.)

Written by Jim McMullen

October 17, 2011 at 2:37 pm

Posted in How-To

Tagged with ,

How To Get Values from a DataTable without Crashing if a Column Doesn’t Exist

leave a comment »

The Situation

You have uploaded data into a DataTable (perhaps from a CSV file – see How To Parse a CSV File Into a DataTable for Use In Your Code) and now you need to retreive the data from the DataTable.

BUT because the data has come from an uploaded from a CSV file, it is possible that one or more of the required columns could be missing. How do you handle this problem without causing exceptions to be thrown?

The best solution in many cases would be to test the uploaded data to make sure all the columns are there, and if they aren’t, to notify the user to correct the file and reupload.

But what if you want to process the file even if a column is missing?

A Solution

In this situation, a good thing to do would be to process the data, but also notify the user that columns were missing. I do this by creating a private variable in the class:

private List<string> _missingcolumns;

Then create this function:

private static string GetColumnValue(DataRow row, string column)
{
	string result = "";
	if (row.Table.Columns.Contains(column))
	{
		if (CommonBase.HasValue(row[column].ToString()))
		{
			result = row[column].ToString();
		}
	}
	else
	{
		// Add to the list of missing columns if it isn't already in there
		if ( _missingcolumns.FindIndex(s => s == column) == -1 )
		{
			_missingcolumns.Add(column);
		}
	}

	return result;
}

Note that this function calls my common function library method ‘HasValue’, which can be found here.

Then call the function like this:

foreach ( DataRow r in dtable.Rows )
{
	string somevar = GetColumnValue(r, "Company Name");
}

(The variable ‘dtable’ is of type DataTable.)

So if the column exists and it has a value, you get the value (as a string). If the column exists but is null, you get back an empty string. If the column doesn’t exist, you get back an empty string. (You can of course alter this to suit your needs.)

Notify the User

If the column doesn’t exist, the name of the column is added to the _missingcolumns list, which you can use to notify the user that their data was processed but was incomplete.

Written by Jim McMullen

October 10, 2011 at 3:25 pm

Posted in How-To

Tagged with ,

How To Parse a CSV File Into a DataTable for Use In Your Code

with one comment

The situation:

You have uploaded a CSV file, and you now need to do something with the data in your programming.

A Solution:

using System.Data;
using System.Data.OleDb;
using System.IO;

public static DataTable ParseCSV(string path, bool headerinfile)
{
	if ( !File.Exists(path) )
		return null;

	string headertext = "No";
	if ( headerinfile )
	{
		headertext = "Yes";
	}

	string full = Path.GetFullPath(path);
	string file = Path.GetFileName(full);
	string dir = Path.GetDirectoryName(full);

	//create the "database" connection string 
	string connString = "Provider=Microsoft.Jet.OLEDB.4.0;"
	  + "Data Source=\"" + dir + "\\\";"
	  + "Extended Properties=\"text;HDR=" + headertext + ";FMT=Delimited\"";

	//create the database query
	string query = "SELECT * FROM " + file;

	//create a DataTable to hold the query results
	DataTable dTable = new DataTable();

	//create an OleDbDataAdapter to execute the query
	OleDbDataAdapter dAdapter = new OleDbDataAdapter(query, connString);

	try
	{
		//fill the DataTable
		dAdapter.Fill(dTable);
	}
	catch ( InvalidOperationException /*e*/)
	{ throw; }

	dAdapter.Dispose();

	return dTable;
}

Written by Jim McMullen

October 10, 2011 at 1:33 pm

Posted in How-To

Tagged with

Common Function Library – HasValue()

with one comment

Like many programmers, I have a Common Function Library containing generic methods I use over and over again. Here is one of them.

/// <summary>
/// Checks a variable to make sure it has value (isn't null or a zero-length string once trimmed).
/// </summary>
/// <param name="o">variable to test.</param>
/// <returns>true if the variable has a value.</returns>
public static bool HasValue(object o)
{
	if ( o == null )
	{
		return false;
	}

	if ( o == System.DBNull.Value )
	{
		return false;
	}

	if ( o is String )
	{
		if ( ( (String)o ).Trim() == String.Empty )
		{
			return false;
		}
	}

	return true;
}

I use this often to test if a variable or object exists and if it has any value. This is an easy way to avoid NullReferenceExceptions or other errors that would crop up if an object is null — BEFORE the exception is thrown.

Written by Jim McMullen

May 12, 2011 at 1:24 am

My Love-Hate Relationship with DotNetNuke

leave a comment »

I am an ASP.NET programmer, so when I needed to implement a Content Management System (CMS), I looked around for an ASP.NET-based system that would let me create add-ons or modules if the base package didn’t do everything I want. I just knew that my clients would insist on implementing some feature or another in a custom way, and that I’d be forced to delve into the depths of the CMS and change it as I had already done with ecommerce packages.

After much research, DotNetNuke (DNN) seemed the obvious choice. I have been using it for several years now and for several different web sites, and I have purchased several off-the-shelf modules from snowcovered.com. I loved it right from the start, but have, over time, become disappointed with it.

First, the good stuff…

  • It is free.
  • It is open source, so the source code is easily available if you need to customize it.
  • There is a huge number of 3rd-party modules available to make DNN do whatever you want.
  • If you can’t find a module, there is a relatively standardized way of creating your own module within the DNN framework.
  • There are also a huge number of 3rd-party skins to change the way your site looks.
  • Visitor tracking and Google analytics build in.

But hold on, some of those “pros”, which drew me to DNN in the first place, turned out to be double-edged swords, and here’s why…

Free: Yes the base code is free, and it will run a basic site if you don’t want it to do anything cutting-edge and way cool — most of the sites I have seen built with the base code only tend to look like sites of ten years ago. I have spent enough on 3rd-party modules that I could have easily purchased a commercial CMS.

Open source: In theory, this means that you can fire up Visual Studio and look at/customize the base code whenever you “need” to. But if you do, you can’t automatically upgrade to the newest versions when they are released. In fact, upgrading becomes a real pain. If you don’t think this is a big deal, then take a look at the number of versions released since 5.0 made it out of beta. And some of those were critical security updates. (Oh and if you want to do automatic upgrades, you have to plunk down more than $100 for a 3rd-party module to do it for you – or program your own module.)

3rd-Party modules: There are hundreds of modules available. This is mostly good, but unfortunately, they aren’t all written to the same standard. In just looking at the “admin” screens of various modules, you’ll find a wide variety of looks and ways the information is organized. So if you are training content editors, you have to specifically train them in the ins-and-outs of every module because they are all different. Even worse, I have had instances in which modules conflict with each other and crash my site – especially after the DNN core is updated.

Module development: I needed to create some custom modules for several clients. The online documentation on how to do this from the DotNetNuke organization is nearly non-existent. There is full documentation of all the DNN classes online, and these are helpful but take a lot of time to pore through.

Fortunately, there are some users who have published some helpful information, and I even purchased Mitchell Sellers book, but there are plenty of holes in that information. For example, I found that I needed to access and change user profile information in one module. Hours of research and trial-and-error were required to get that working. I think that should be simpler. And I think that the DNN folks should publish a best-practices manual for module development.

Skins: 3rd-party skins are great, but they are a bit generic looking. If you want something unique, you CAN do it yourself. DotNetNuke seems to pre-date the ASP.NET themes engine, so you can’t simply use themes you already have on hand and you must learn a whole new way of doing it. Not a huge thing, but again, it costs time.

Visitor tracking: this is one thing I find very odd. Visitor and link tracking are built in, but there is no built-in “dashboard” for viewing the stats. You have to build that page yourself! And the built-in Google Analyitics visitor tracking doesn’t track downloads of PDFs, word documents, and other non-web files.

So why am I still using it?

Well, I have a significant investment in it now, in both time and money. And there are some things I really do like about it. The feature I love over other solutions I’ve seen is the “in place editing” of content. You don’t have to go to some “content” or list page to find the content you want to edit. You do it right on the page you are editing. This simplifies content editor training. And I do love the vast selection of modules for purchase.

And in the ASP.NET space it is the 800-pound gorilla of CMS.

Written by Jim McMullen

May 11, 2011 at 1:58 pm

Posted in Reviews

Tagged with ,

Elmah Signaling – How To Log Exceptions with Elmah but Continue Processing

leave a comment »

Elmah is an excellent tool for web programmers. It is an extremely easy to install exception handler that logs application exceptions and sends the user to an “oops” page. It can also send an email to the developer or webmaster.

But what if you want to log an error but NOT send the user to an “oops” page. This can be especially useful in debugging code that already handles exceptions so that the user doesn’t see them.

Here is how it works:

Add a reference to Elmah to the page:

using Elmah;

Then, in your try/catch block, use this code:

try
{
    //some code}
catch (Exception ex)
{
    // handle your exception here
    ErrorSignal.FromCurrentContext().Raise(ex); //ELMAH Signaling  (logs error but processing continues)
    return false;  //assuming the method returns a boolean value.
}

Written by Jim McMullen

May 5, 2011 at 3:18 pm

Posted in How-To

Tagged with , ,