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;
        }
    }
}

Wednesday, 12 January 2011

Sequence Diagram Editor

Yesterday I found very interesting sequence diagram editor: http://sdedit.sourceforge.net/
It's free, it's small and easy to use (it has quite specific interface, but for me, it's easy to use!)


It has own language for diagram definition and provides very nice pictures (actually it draws diagrams on given definition).


For example, it uses this script:


bfs:BFS[a]
/queue:FIFO
someNode:Node
node:Node
adjList:List
adj:Node

bfs:queue.new
bfs:someNode.setLevel(0)
bfs:queue.insert(someNode)
[c:loop while queue != ()]
  bfs:node=queue.remove()
  bfs:level=node.getLevel()
  bfs:adjList=node.getAdjacentNodes()
  [c:loop 0 <= i < #adjList]
    bfs:adj=adjList.get(i)
    bfs:nodeLevel=adj.getLevel()
    [c:alt nodeLevel IS NOT defined]
      bfs:adj.setLevel(level+1)
      bfs:queue.insert(adj)
      --[else]
      bfs:nothing to do
    [/c]
  [/c]
[/c]
bfs:queue.destroy() 
and generates this diagram:

In my opinion it looks perfect!

Monday, 3 January 2011

Back home

Now I'm home. Yesterday I got back home.
Here is my itinerary:

View Larger Map

Saturday, 16 October 2010

Poetry

I was walking down the seashore this night and remembered a poetry from an old Russian book (this book was released in the middle of 20th century). I decided to translate this to English, so here is my humble attempt (I spent only about half an hour):



Swift sword's blow,
The arrow's prick, the shine of axe -
And world has disappeared in your eyes:
There is no sea, there are no friends,
You are alone.

But you are alone just for a while:
Valhalla's beam runs down to you.
The road to heaven:
It is strong, it is true,
Like Viking's arm, like solid sword.

And mighty steed flies by this road:
It is white as snow, it is pure as light.
Valkyrie rides this steed
With Wotan's wills and greetings:
He waits, he waits for you.

And you have got the place in heroes hall.
Then you take off like weightless smoke,
Like light steam, like pure clouds -
You and the messenger of heaven.

Monday, 4 October 2010

Autographed CD + t-shirt

About one month ago I had pre-ordered and recently received a new album of Fran Healy (http://www.franhealy.com/). He is the lead singer and main songwriter of Travis band (I like their music very much). A couple of months ago I found some information about his upcoming solo album "Wreckorder" and decided to buy it.


So last week I found a small box on the doorstep of my flat. This box contained autographed CD and a t-shirt (see the photo below).




I listened to this album and may say only "Amazing!". Good half of these songs can pull my strings, like these songs were written about me (in my past).

In my opinion these songs are just stunning:
1) Anything
2) Buttercups
3) Holiday



Saturday, 7 August 2010

Ebook reader

I had read many cheerful reviews of new Amazon Kindle Reading Device (see sidebar image, description is available on Amazon web site) and ordered it.
So, now I'm looking forward to playing with it.
P.S. It will be shipped after 27th of August...

Listening and understanding

Last week my Aikido teacher told me very interesting phrase: "If you are listening to someone carefully you will understand this person even if you don't know the language".
That time we were discussing a question of why I understand him better than my Russian teacher. And he told me that he is able to understand his japanese teacher even if my teacher don't have sufficient experince in Japanese.
So, to sum up: it is enought to listen carefully to understand anyone you want to understand.

Thursday, 17 June 2010

Another exam passed

I've just passed another MS Exam: 70-561 - ADO.NET Application Development
I passed it with score 895 out of 1000, which is good (in my opinion), because I haven't had even one REAL project with Entity Framework (only a couple of testing ones), and there were many Entity Framework questions.