Blog

Categorised by 'C#'.

  • I had around 2000 webpage URL’s listed in a text file that needed to be generated into a simple Google sitemap.

    I decided to create a quick Google Sitemap generator console application fit for purpose. The program iterates through each line of a text file and parses it to a XmlTextWriter to create the required XML format.

    Feel free to copy and make modifications to the code below.

    Code:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    using System.Xml;
    
    namespace GoogleSitemapGenerator
    {
        class Program
        {
            static void Main(string[] args)
            {
                string textFileLocation = String.Empty;
    
                if (args != null && args.Length > 0)
                {
                    textFileLocation = args[0];
                }
    
                if (!String.IsNullOrEmpty(textFileLocation))
                {
                    string fullSitemapPath = String.Format("{0}sitemap.xml", GetCurrentFileDirectory(textFileLocation));
    
                    //Read text file
                    StreamReader sr = File.OpenText(textFileLocation);
    
                    using (XmlTextWriter xmlWriter = new XmlTextWriter(fullSitemapPath, Encoding.UTF8))
                    {
                        xmlWriter.WriteStartDocument();
                        xmlWriter.WriteStartElement("urlset");
                        xmlWriter.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
    
                        while (!sr.EndOfStream)
                        {
                            string currentLine = sr.ReadLine();
    
                            if (!String.IsNullOrEmpty(currentLine))
                            {
                                xmlWriter.WriteStartElement("url");
                                xmlWriter.WriteElementString("loc", currentLine);
                                xmlWriter.WriteElementString("lastmod", DateTime.Now.ToString("yyyy-MM-dd"));
                                //xmlWriter.WriteElementString("changefreq", "weekly");
                                //xmlWriter.WriteElementString("priority", "1.0");
    
                                xmlWriter.WriteEndElement();
                            }
                        }
    
                        xmlWriter.WriteEndElement();
                        xmlWriter.WriteEndDocument();
                        xmlWriter.Flush();
    
                        if (File.Exists(fullSitemapPath))
                            Console.Write("Sitemap successfully created at: {0}", fullSitemapPath);
                        else
                            Console.Write("Sitemap has not been generated. Please check your text file for any problems.");
    
                    }
                }
                else
                {
                    Console.Write("Please enter the full path to where the text file is situated.");
                }
            }
    
            static string GetCurrentFileDirectory(string path)
            {
                string[] pathArr = path.Split('\\');
    
                string newPath = String.Empty;
    
                for (int i = 0; i < pathArr.Length - 1; i++)
                {
                    newPath += pathArr[i] + "\\";
                }
    
                return newPath;
            }
        }
    }
    

    I will be uploading a the console application project including the executable shortly.

  • I always found writing code to read an RSS feed within my .NET application very time-consuming and long-winded. My RSS code was always a combination of using WebRequest, WebResponse, Stream, XmlDocument, XmlNodeList and XmlNode. That’s a lot of classes just to read an RSS feed.

    Yesterday, I stumbled on an interesting piece of code on my favourite programming site StackOverflow.com, where someone asked how to parse an RSS feed in ASP.NET. The answer was surprisingly simple. RSS feeds can now be consumed using the System.ServiceModel.Syndication namespace in .NET 3.5 SP1. All you need is two lines of code:

    var reader = XmlReader.Create("http://mysite.com/feeds/serializedFeed.xml");
    var feed = SyndicationFeed.Load(reader);
    

    Here’s a full example on how we can iterate through through the SyndicationFeed class:

    public static List<BlogPost> Get(string rssFeedUrl)
    {
        var reader = XmlReader.Create(rssFeedUrl);
        var feed = SyndicationFeed.Load(reader);
    
        List<BlogPost> postList = new List<BlogPost>();
    
        //Loop through all items in the SyndicationFeed
        foreach (var i in feed.Items)
        {
            BlogPost bp = new BlogPost();
            bp.Title = i.Title.Text;
            bp.Body = i.Summary.Text;
            bp.Url = i.Links[0].Uri.OriginalString;
            postList.Add(bp);
        }
    
        return postList;
    }
    

    That’s too simple, especially when compared to the 70 lines of code I normally use to do the exact same thing.

  • Debugging a page that uses many methods from other classes can become a right pain in the neck. I find myself accidentally stepping into a method that I don’t need to debug or wanting to output specific values from my methods straight away. Being the cowboy (correction, agile) developer that I am, one of my code boffins at work showed me a two cool ways to meet my debugging needs:

    1) DubuggerHidden Attribute

    Using the DubuggerHidden attribute tells the Visual Studio debugger that the method is hidden from the debugging process. The simple example below, shows the DebuggerHidden attribute in use:

    protected void btnDoSomething_Click(object sender, EventArgs e)
    {    
        //Output random number to Textbox
        txtOutput.Text = GetNumber(1, 10).ToString();
    } 
     
    [DebuggerHidden]
    int GetNumber(int min, int max)
    {    
        System.Random random = new Random();
        return random.Next(min, max);
    }
    

    2) DebuggerDisplay Attrubute

    The DebuggerDisplay attribute allows us to output variable values from a class or method to be displayed in our Visual Studio debugger. The attribute includes a single argument that is supplied as a string. The string can contain references to fields, properties and methods in the class so that the actual values from an object may be included in its description.

    [DebuggerDisplay("a={a}, b={b}, ValueTotal={CalculateValues()}")]
    public class AddValues
    {    
        public int a { get; set; }
        public int b { get; set; }
        
        public int CalculateValues()
        {
            return a + b;
        }
    }
    

    You also have the ability to include simple expressions, like so:

    [DebuggerDisplay("a={a}, b={b}, ValueTotal={CalculateValues() * 2}")]
    

    In addition to the “DebuggerHidden” and DebuggerDisplay attributes, .NET contains some very useful attributes that modify the behaviour of a debugger. For me, they weren’t as interesting as the two debugger attributes I listed above. :-)

  • A little while back I needed to create a comma-delimited string to parse into my SQL Query. My first attempt in creating my comma-delimited string involved using a StringBuilder class and appending a comma at the end of each of my values via a loop. However, I found that my application would error when parsing my comma-delimited string into my SQL query due to the fact a comma was added to the end of my string.

    After some research on the MSDN website to solve my problem I found a solution and it was simpler than I thought. The .NET Framework already has a class called CommaDelimitedStringCollection and it is pretty simple to use as the following example shows:

    using System.Configuration;
    public partial class CommaPage : System.Web.UI.Page 
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Create a collection to parse to CommaDelimitedStringCollection class
            List<string> cars = new List<string>();
            cars.Add("Volvo");
            cars.Add("VW");
            cars.Add("BMW");
            cars.Add("Ford");
            
            //Create instance of CommaDelimitedStringCollection
            CommaDelimitedStringCollection commaCollection 
            = new CommaDelimitedStringCollection() ;
            
            //Iterate through cars collection and add to commaCollection
            foreach (string item in cars)
            {
                commaCollection.Add(item);
            }
            
            //Read out list of values
            Response.Write(commaCollection.ToString());     
        }
    }
    

    The output of the example above would be: "Volvo, VW, BMW, Ford".

    So pretty much the .NET Framework's CommaDelimitedStringCollection class did all the work for me.

    Nice one!

  • Published on
    -
    1 min read

    Is an Arraylist still in use?

    When I first started using ASP.NET 1.1, I always used an Arraylist to iterate through most of my collections. However, when I started using ASP.NET 2.0 I was introduced to Generic Lists. The List<T> class is the generic equivalent of the ArrayList class. It implements the IList<T> generic interface using an array whose size is dynamically increased as required. This means the List class performs much better in most cases and more importantly it is "type" safe.

    So I am not too sure why you would ever need to use an Arraylist since a Generic List class is able to do exactly the same thing with the added benefit of extra perfomance. So is the Arraylist still widely used in todays standards? I guess it still must be in use if Microsoft has not omitted it from their Framework. Maybe Microsoft has something in store for the Arraylist in their grand plan.

    Here are a few useful links:

    C# Corner - C# Generics Josh Williams MSDN Blog - Arraylist vs. Generic List MSDN Network - List (T) Generic Class

  • Published on
    -
    1 min read

    Inline If Statement

    Standard IF statements are great. But I found that when I am using very simple conditions within my IF Statement I waste a lot of space in my code.

    Example 1:

    public int IfExample(bool bolFlag)
    {
    int result = 0;
    if (bolFlag)
    {
    result = 1;
    }
    else
    {
    result = 2;
    }
    return result;
    } 
    

    There is no problem using Example 1. But there is a much quicker and less tedius way of using a simple conditional IF statement.

    Example 2:

    public int IfExample(bool bolFlag)
    {
    return (bolFlag) ? 1 : 2;
    }
    

    This example is basically saying: "return if (bolFlag) 1 else 2". So you are in theory assigning the IF condition to the variable.

    I know it takes a little while to understand the syntax. But it is really good for those less complex IF conditions.

  • Published on
    -
    1 min read

    C# NULL Coalescing Operator

    Here is a really neat trick that a mate showed me at work. It is a way to assign one variable to another, but only if the variable is not null. If it is null, you want to populate the target variable with perhaps another value.

    For example, lets assume we have an integer variable "intCounter". We could check if the integer contents was null, and if not return another value:

    int intCounter = 5;
    int intResult = intCounter ?? 0;
    // Output: intResult == 5 
    

    We got the following output because intCounter did not contain a null.

    The C# NULL coalescing operator also works with string variables as well:

    string strMessage = "Hello World";
    string strResult = strMessage ?? "No message";
    // Output: strResult == "Hello World" 
    


    So we can see from the two examples above that this NULL Coalescing operator is quite useful. Here is an example of what would have happened if a variable was null:

    string strMessage = null;
    string strResult = strMessage ?? "No message";
    // Output: strResult == "No message" 
    

    Scott Guthrie talks more about this in his own blog and how to use this feature in LINQ: http://weblogs.asp.net/scottgu/archive/2007/09/20/the-new-c-null-coalescing-operator-and-using-it-with-linq.aspx