ASP.net directory on hosting

It is quite a common case to have a website on a remote hosting when, for whatever reason, you can’t afford a full-fledged server onto your fridge or in a remote location. One of the issue you might come across on a hosting server running ASP.net is finding the path of a folder you want to work on. Usually you have a local copy of your website where you work using Visual Studio and then you publish it to the remote location: this is the typical example where the folder structure will not match to the root: you might have a c:\documents\websites\mysite\ that on the hosting server maps as d:\webs\789547\customers\jhondoe\jhondoe.com\. To find the right path both locally, on a hosting location or wherever else there is a simple strategy. Review the following code:

For Each CurrFile As FileInfo In New DirectoryInfo(Hosting.HostingEnvironment.MapPath("\test")).EnumerateFiles
    […
    work on each file
    …]
Next

This piece of code is enumerating all the files in a subfolder called “test” under the root of your website no matter where it is actually located in the absolute directory tree. Review this article on the MSDN library for more information.

Advertisements

Doing it elegantly

There are plenty of programming languages out there and they all allow endless possibility in how to write a piece of code.
Very often things can be done in two ways: the blunt way and the elegant way.

Consider for instance this piece of code:

    […]
    For Each SingleFeed As XElement In XMLDoc.Descendants(XName.Get(CurrentFeed.RootElement))
        Dim SyndFeed As SyndicationFeed = SyndicationFeed.Load(System.Xml.XmlReader.Create(SingleFeed.Descendants(XName.Get("feed")).Value.ToString))
        Dim TempItems As New List(Of SyndicationItem)

        If SyndFeed.Items.Count >= CurrentFeed.TotalElements Then
            TempItems.AddRange(SyndFeed.Items.ToList.GetRange(0, CurrentFeed.TotalElements))
        Else
            TempItems.AddRange(SyndFeed.Items.ToList)
        End If

        […]

        FeedItems.AddRange(TempItems)
    Next
    […]

It has to do with the creation of an object to store items from an ATOM feed.
The important point I want to show is the one about the If … else … End If cycle. What you are looking here is the first implementation of the code: it’s the easy way and, as i discovered later, the longest and stupidest way to write it.

Yes, it was stupid: the compact, most logical and briefly the elegant way to wrote it turned out to be:

        TempItems.AddRange(SyndFeed.Items.ToList.GetRange(0, Math.Min(CurrentFeed.TotalElements, SyndFeed.Items.Count)))

Probably any coding language nowadays includes some kind of Minimum function to return the smallest of two numbers.
Very often is just a matters of knowing what you are doing.