Saturday, 27 August 2011

Online code formatter

I know that a lot of online code formatters are available. I just found this one usuful for me:
http://www.manoli.net/csharpformat/

Number to text



I had to convert number to text and haven't found any nice implemenation in 30 minutes of googling, so I created my own:

using System;
using System.Text.RegularExpressions;

class NumberToText
{
    private static string[] _numbers = { string.Empty, "one", "two", "three",
            "four", "five", "six", "seven", "eight", "nine" };
    private const string _hundred = " hundred";
    private static string[] _numbersT = { "", "ten", "twenty", "thirty",
            "fourty", "fifty", "sixty", "seventy", "eighty", "ninety" };
    private static string[] _numbers11_19 = { "", "eleven", "twelve",
            "thirteen", "fourteen", "fifteen", "sixteen", "seventeen",
            "eightteen", "nineteen" };
    private static string _thousand = " thousand ";
    private static string _million = "one million and more";

    private static string _ConvertNumber(uint inputNumber)
    {
        string unitStr, tenStr, tenString;
        uint hundreds = inputNumber / 100;
        uint hundredReminder = inputNumber % 100;
        uint tens = hundredReminder / 10;
        uint units = hundredReminder % 10;

        tenString = _numbers[hundreds < 10 ? hundreds : 0]
                + (hundreds > 0 ? _hundred : string.Empty);
        if (tens == 1 && units != 0)
        {
            tenStr = _numbers11_19[units];
            unitStr = string.Empty;
        }
        else
        {
            tenStr = _numbersT[tens];
            unitStr = _numbers[units];
        }

        return string.Format("{0} {1} {2}", tenString, tenStr, unitStr);
    }

    public static string ConvertNumber(uint inputNumber)
    {
        if (inputNumber < 1000)
            return _ConvertNumber(inputNumber);
        else if (inputNumber < 1000000)
            return _ConvertNumber(inputNumber / 1000) + _thousand
                    + _ConvertNumber(inputNumber % 1000);
        else
            return _million;
    }

    public static string RemoveExtraSpaces(string input)
    {
        return Regex.Replace(input, "\\W+", " ").Trim();
    }

    public static void Main(string[] args)
    {
        for (uint i = 1; i < 2000; i++)
        {
            Console.WriteLine(RemoveExtraSpaces(ConvertNumber(i)));
        }
    }
}

RSS for your ASP.NET web site



Some time ago I found how easily RSS Feed can be implemented on ASP.NET web-site using System.ServiceModel.Syndication namespace and classes SyndicationFeed and SyndicationItem

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web.UI;
using System.Xml;
using CompanyName.BusinessLayer.Components;
using CompanyName.BusinessLayer.Entities;
using CompanyName.Utilities;

namespace CompanyName.Presentation
{
    public partial class Rss : Page
    {
        string _webSite;

        const string rssTitle = "Test RSS Feed";
        const string rssDescription = "Provides news for Test items";
        const string rssID = "TestRSS";

        /// <summary>
        /// Creates a link to Document
        /// </summary>
        /// <param name="docID">Document version ID</param>
        /// <returns>the URL</returns>
        private string BuildDocumentLink(string docID)
        {
            return string.IsNullOrEmpty(_webSite) ? string.Empty :
                string.Format(CultureInfo.InvariantCulture, "{0}/ContentView.aspx?ID={1}",
                    _webSite, docID);
        }

        /// <summary>
        /// Creates a link to RSS Feed
        /// </summary>
        /// <returns>the URL</returns>
        private string BuildRssLink()
        {
            return string.IsNullOrEmpty(_webSite) ? string.Empty :
                string.Format(CultureInfo.InvariantCulture, "{0}/{1}.aspx",
                    _webSite, WebpageName.Rss.ToString());
        }
        
        /// <summary>
        /// Page load event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            _webSite = Config.GetValue("WebsiteUrl");

            Response.Clear();
            Response.ClearHeaders();
            Response.ContentType = "application/rss+xml";
            EnableViewState = false;

            SyndicationFeed feed =
                new SyndicationFeed(rssTitle,
                                    rssDescription,
                                    new Uri(BuildRssLink()),
                                    rssID,
                                    DateTime.Now);

            WebSession ws = null;
            try
            {
                string client = Request["client"];
                string processId = Request["processId"];

                ws = Authentication.AnonimousLogOn(Config.ConnectionString, client);
                feed.Items = BuildRssFeedList(processId, ws);
            }
            catch (Exception ex)
            {
                feed.Items = ReportError(ex);
            }

            WriteRssContent(feed);

            Response.End();
        }

        /// <summary>
        /// Writes RSS content
        /// </summary>
        /// <param name="feed">the syndication feed object</param>
        private void WriteRssContent(SyndicationFeed feed)
        {
            Rss20FeedFormatter rssFormatter = new Rss20FeedFormatter(feed);
            using (var sw = new StringWriter())
            {
                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Encoding = Encoding.UTF8;
                settings.Indent = true;

                using (XmlWriter writer = XmlWriter.Create(sw, settings))
                {
                    rssFormatter.WriteTo(writer);
                }
                // TODO: investigate why default content is utf-16
                Response.Write(sw.ToString().Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>",
                        "<?xml version=\"1.0\" encoding=\"utf-8\"?>"));
                Response.Flush();
            }
        }

        /// <summary>
        /// Reports errors
        /// </summary>
        /// <param name="ex">exception</param>
        /// <returns>the list of syndication items with error description</returns>
        private List<SyndicationItem> ReportError(Exception ex)
        {
            List<SyndicationItem> items = new List<SyndicationItem>();

            SyndicationItem item =
            new SyndicationItem("Error occured on data retrival",
                                ex.Message,
                                new Uri(BuildRssLink()),
                                Guid.NewGuid().ToString(),
                                DateTime.Now);
            items.Add(item);

            return items;
        }

        /// <summary>
        /// Retrieves the list of syndication items
        /// </summary>
        /// <param name="processId">Process ID</param>
        /// <param name="ws">web wession</param>
        /// <returns>the list of syndication items</returns>
        private List<SyndicationItem> BuildRssFeedList(string processId, WebSession ws)
        {
            Guid processGuid = new Guid(processId);
            List<SyndicationItem> items = new List<SyndicationItem>();

            // Some data retrieval procedure is here...
            var ctx = ws.TableHelper.DataContext;
            var docVersions = ctx.DocVersions.Where(
                    dv => dv.RecordState == RecordState.Active
                    && ctx.Categories.Any(
                        c => c.CategoryID == dv.CategoryID
                        && c.ProcessID == processGuid
                    )
                ).Select(dv => dv);

            foreach (var dv in docVersions.ToList())
            {
                SyndicationItem item =
                new SyndicationItem(dv.Title,
                                    dv.Title + " - Version: " + dv.Version,
                                    new Uri(BuildDocumentLink(dv.DocVersionID.ToString())),
                                    dv.DocVersionID.ToString(),
                                    dv.PublishedDate);
                items.Add(item);
            }
            return items;
        }
    }
}