This application has failed to start because the application configuration is incorrect

C++ installations have never been easy and probably never will be. Having not done any C++ release work for a number of years I ran into a problem when releasing a C++ application that I built using Visual Studio 2005.

In the old days you had a nightmare working out which version of the C++ libraries to distribute and where to put them. Unless of course you statically link to the libraries which resolves the problem but makes the files rather larger.

But now with building the application using VS 2005, there is this new problem that arises which results in the obsure message

This application has failed to start because the application configuration is incorrect

After a bit of digging into all of this I found that there is a redistributable package from Microsoft that installs the necessary libraries for C++ that were used by VS2005 to build the application in the first place. Where it puts the libraries I don’t know, but to be honest I don’t really care as the installation was very simple and worked first time….so i’m happy for now.

Heres a link to the redistributable package from Microsoft. ┬áThis is the SP1 version of the package which is required if your VS2005 installation is all up-to-date. If it isn’t there is an older version of the package available from Microsoft, or your could do the right thing and get VS2005 up-to-date instead.

Tagged

A neater way of getting data out of a DbDataReader

Previously I have always done the following to iterate through a bDataReader

while(reader.Read())
{
int index = reader.GetOrdinal(“User_Description”);
list.Add(reader[index] as string);
}
But today I stumbled upon the following which is so much neater:

foreach (DbDataRecord dbDataRecord in reader)
{
int index = dbDataRecord.GetOrdinal(“User_Description”);
list.Add(dbDataRecord[index] as string);
}

I just think it’s a lot neater and clearer as to what’s going on.

Tagged

Reverse iterating through a List collection

Reversing through the object in a List is an operation that isn’t so uncommon, and there is a simple way of doing this using a for loop with a decrement on an index value. But it isn’t a particularly elegant way of acheiving this and the re-use of the for loop isn’t the most efficient in terms of code re-use. Thankfully with the use of the IEnumerable interface we can create a simple, clean and elegant solution to the problem.

By deriving from the IEnumerable interface we can create a new GetEnumerator method and do the meat of the work here. Below is a class that implements this interface to create a reversable enumerator dependant on a simple local property. The property is from a simple enumeration that is defined as Forwards or Reverse.

public sealed class Counts : List<long>, IEnumerable<long>
{
/// <summary>
/// The direction to iterate through our collection
/// </summary>
private IteratorDirection iteratorDirection = IteratorDirection.Forwards;

/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>
/// A <see cref=”T:System.Collections.Generic.IEnumerator`1″></see>
/// that can be used to iterate through the collection.
/// </returns>
public new IEnumerator<long> GetEnumerator()
{
if(iteratorDirection == IteratorDirection.Forwards)
{
for (int i = 0; i < Count; i++)
{
yield return this[i];
}
}
else
{
for (int i = Count – 1; i >= 0; i–)
{
yield return this[i];
}
}
}

/// <summary>
/// Sets the iterator direction.
/// </summary>
/// <value>The iterator direction.</value>
public IteratorDirection IteratorDirection
{
set { iteratorDirection = value; }
}
}
To use the class is simple… First set the direction that you want to iterate through the collection, then iterate through the collection using the ubiquitous foreach loop

OurCounts.IteratorDirection = IteratorDirection.Forwards;
foreach (long count in OurCounts)
{
}

OurCounts.IteratorDirection = IteratorDirection.Reverse;
foreach (long count in OurCounts)
{
}

Getting the application path using reflection and C#

Just recently I had a problem whereby there was a case which resulted in the current working directory changing before some of my code had run. As I hadn’t catered for this case it came up with a crash which was easily fixed by getting the current application path and then combining this with the filename which I wished to access. Heres the code that I used to acheive this in a nice clean fashion and create a path to a configuration file (configurationFilename):

Uri uri = new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase);
string fullConfigurationFilename = Path.Combine(Path.GetDirectoryName(uri.AbsolutePath), configurationFilename);
fullConfigurationFilename = HttpUtility.UrlDecode(fullConfigurationFilename);

By using reflection to get the location of the currently executing assembly I am not relying on the actual .exe location (or website location in fact), but instead using the actual dll’s location from which the current code is running. You might wish to use the actual application’s path or the website root path, but in the scenario that I am using this in, the assembly’s path is exactly what I wanted.

Tagged

Auto-generating a sitemap conforming to Sitemap Protocol 0.9

Having recently installed BlogEngine.NET, I was interested to see the auto-generated sitemap that Mads had created. Basically, he implemented a custom HttpHandler that when requested would respone with XML that conformed to the Sitemap Protocol 0.9 which is dictated by sitemaps.org. This is an XML schema that all of the major search engines have signed up to which include Google, Yahoo! and Microsoft.

What I wanted to do is to implement this for my own site, but the custom handlers of Mads was tailored to BlogEngine.NET, so it required a bit of tweaking. Now, I have a Web.sitemap for my website, so in the scheme of wanting to do things from a generic point of view, I decided to implement the HttpHandler to utilise the Web.sitemap file to generate the sitemap response. To do this, first we have to load up the sitemap file…

XmlSiteMapProvider xmlSiteMap = new XmlSiteMapProvider();
NameValueCollection myCollection = new NameValueCollection(1);
myCollection.Add(“siteMapFile”, “Web.sitemap”);
xmlSiteMap.Initialize(“provider”, myCollection);
xmlSiteMap.BuildSiteMap();

Then we have to navigate through the tree structure identifying the nodes that we are interested in…

private static void ProcessNode(XmlWriter writer, SiteMapNode node, string attribute)
{
foreach (SiteMapNode siteMapNode in node.ChildNodes)
{
string actualUrl;
if (siteMapNode.HasChildNodes)
{
ProcessNode(writer, siteMapNode, attribute);
}
actualUrl = siteMapNode[attribute];
if (string.IsNullOrEmpty(actualUrl))
{
actualUrl = siteMapNode.Url;
if (string.IsNullOrEmpty(actualUrl))
{
continue;
}
}
WriteUrl(actualUrl, writer);
}
}

And lastly building up the XML response…

if(Uri.IsWellFormedUriString(actualUrl, UriKind.Relative))
{
FileInfo fileInfo = new FileInfo(HostingEnvironment.MapPath(actualUrl));
writer.WriteStartElement(“url”);
writer.WriteElementString(“loc”, HttpContext.Current.Request.Url.AbsoluteUri.Replace(HttpContext.Current.Request.Url.AbsolutePath, “”) + actualUrl);
writer.WriteElementString(“lastmod”, fileInfo.LastWriteTime.ToString(“yyyy-MM-dd”));
writer.WriteElementString(“changefreq”, “monthly”);
writer.WriteEndElement();
}

I have implemented this HttpHandler in a seperate component, simply to allow me to reference this utility from other websites that I have written, but you may decide to simply plug in the HttpHandler to your main project….the decision is yours.

Now, hopefully you’ve also realised that you’ll need to reference the HttpHandler in the website’s web.config……like so…

<httpHandlers>
<add verb=”*” path=”sitemap.axd” type=”CodeConsults.HttpHandlers.Generic.Sitemap” validate=”false”/>
</httpHandlers>

Now you can run your website, point your favoured browser to http://website/sitemap.axd and voila, your sitemap is available for all to see. But the last stage should be to update your robots.txt file to tell the search engines that you have a nice sitemap for them to use. To do this simply open your robots.txt file and enter the following…

sitemap: http://www.codeconsults.com/sitemap.axd

Alternative to Server.MapPath…use HostingEnvironment.MapPath

A call to the following context sensitive MapPath function does exactly what the documentation says it does.

System.Web.HttpContext.Current.Server.MapPath(“\filename.txt”);

It returns the physical file path that corresponds to the specified virtual path on the Web server. But this isn’t always what you want as it works on the current context which may be a web form running in a sub-directory of the main website.

In this case the solution is simple. Use the following code to map the path to a physical path on the server

System.Web.Hosting.HostingEnvironment.MapPath(“\filename.txt”);

Getting the Calling method through Reflection

Having recently created a simple framework for other developers to use, I needed to create a custom Exception class to use when throwing exceptions.

When throwing an exception in a WinForms application I always generate my own Exception class, which adds some other useful information that I can package along with the actual exception that was originally thrown. Although the Call Stack is included in the actual exception, one thing that I like to do is tell the developer the method in which the exception was originally thrown. This removes the need for the developer to navigate through the exception as all they are initially after is where the Exception occured.

In the past I would have normally simply passed in the method name like so:

throw new Exception(connSettings, MethodBase.GetCurrentMethod().Name, “Argument is Null”, ex);

But I decided to spend some time making this transparent. In the end I was able to put this in the actual Exception class using the following method which is called as a part of the constructor of the Exception class:

private void SetCallingMethod()

{
method = new StackFrame(2, false).GetMethod().Name;
}

In this we open up a new stack trace and navigate to the second frame in the trace (remembering that frame 1 of the stack will result in the constructor method). Now the code to create the new exception is simpler:

throw new Exception(connSettings, “Argument is Null”, ex);

Tagged