Monday, 26 December 2011

My wife's book

Today my wife released her first Kindle book on Amazon http://www.amazon.com/dp/B006Q5R4MK.
So we will see how it works.
This children books is about wise dog and it's thoughts. I hope it could be interesting for English-speaking readers.

Thursday, 15 December 2011

MS SQL Server 2008 Database Developer

I've just passed MS Exam 70-433 and now I'm a Certified SQL Server 2008 Database Developer.

It was not too difficult, especially if currently I'm spending 80% of my work time doing something with SQL Server :)

Tuesday, 13 September 2011

True Permanent Residency

Now I'm a real Permanent Resident of New Zealand.

What does it mean?

Now my visa has no expiration date and I can live in New Zealand, travel outside, return to New Zealand any time. So now I glad that I (and my family) have a safe and nice place to live.

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