Click here to Skip to main content
11,636,985 members (69,151 online)
Click here to Skip to main content
Add your own
alternative version

The Super Pool Framework

, 31 Aug 2010 CPOL 52.6K 1.2K 170
The Super Pool is a framework for decoupled communication and management of components. The Super Pool introduces a natural asynchronous communication environment into your solution that can be fluently spread over different components, threads, processes, or even computers or networks.
Matrix_SuperPool_Standalone.zip
Lib
PowerCollections.dll
Matrix.Framework.SuperPool.Standalone
bin
Debug
Release
Common.Sockets
Common
Core
Matrix.Common.Core
Collections
Identification
Results
Serialization
Matrix.Common.Extended
FastSerialization
Operationals
ThreadPools
Matrix.Common.Sockets
Common
Core
Matrix.Framework.MessageBus
Client
Clients
ExecutionStrategies
Core
Net
Messages
Matrix.Framework.SuperPool
Call
Clients
Core
DynamicProxy
Subscription
Matrix.Framework.SuperPool.Standalone.csproj.user
Properties
Tests
Lib
log4net.dll
Matrix.Common.Core.dll
Matrix.Common.Diagnostics.dll
Matrix.Common.Diagnostics.FrontEnd.dll
Matrix.Common.Extended.dll
Matrix.Common.FrontEnd.dll
Matrix.Common.Sockets.dll
Matrix.Framework.TestFramework.dll
nunit.framework.dll
Matrix.Framework.SuperPool.Demonstration
bin
Debug
Release
FormServer.cs.bak
Properties
Matrix.Framework.SuperPool.Test
bin
Debug
Release
Matrix.Framework.SuperPool.Test.vshost.exe.manifest
MultiThreadTests
Properties
Settings.settings
SpeedTests
Matrix.Framework.SuperPool.UnitTest
bin
Debug
Release
Matrix.Framework.SuperPool.UnitTest.csproj.user
Properties
// -----
// Copyright 2010 Deyan Timnev
// This file is part of the Matrix Platform (www.matrixplatform.com).
// The Matrix Platform is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, 
// either version 3 of the License, or (at your option) any later version. The Matrix Platform is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
// without even the implied warranty of  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
// You should have received a copy of the GNU Lesser General Public License along with the Matrix Platform. If not, see http://www.gnu.org/licenses/lgpl.html
// -----
//********************************************************************************************
// This code based on public domain code by Sergey Stoyan.
//********************************************************************************************
using System;
using System.Text.RegularExpressions;

namespace Matrix.Common.Core
{
    /// <summary>
    /// Miscellaneous and parsing thread-safe methods for DateTime,
    /// class helps with parsing multiple date time formats.
    /// </summary>
    public static class DateTimeHelper
    {
        static object lock_variable = new object();

        #region miscellaneous methods

        public static uint GetSecondsSinceUnixEpoch(System.DateTime date_time)
        {
            lock (lock_variable)
            {
                TimeSpan t = date_time - new System.DateTime(1970, 1, 1);
                int ss = (int)t.TotalSeconds;
                if (ss < 0)
                    return 0;
                return (uint)ss;
            }
        }

        #endregion

        #region parsing definitions

        /// <summary>
        /// Defines a substring where date-time was found and result of conversion
        /// </summary>
        public class ParsedDateTime
        {
            readonly public int IndexOfDate = -1;
            readonly public int LengthOfDate = -1;
            readonly public int IndexOfTime = -1;
            readonly public int LengthOfTime = -1;
            readonly public System.DateTime DateTime;
            /// <summary>
            /// True if a date was found within string
            /// </summary>
            readonly public bool IsDateFound;
            /// <summary>
            /// True if a time was found within string
            /// </summary>
            readonly public bool IsTimeFound;

            internal ParsedDateTime(int index_of_date, int length_of_date, int index_of_time, int length_of_time, System.DateTime date_time)
            {
                IndexOfDate = index_of_date;
                LengthOfDate = length_of_date;
                IndexOfTime = index_of_time;
                LengthOfTime = length_of_time;
                DateTime = date_time;
                IsDateFound = index_of_date > -1;
                IsTimeFound = index_of_time > -1;
            }
        }

        /// <summary>
        /// Date that is accepted in the following cases:
        /// - no date was parsed by TryParse();
        /// - no year was found by TryParseDate();
        /// It is ignored when DefaultDateIsCurrent = true
        /// </summary>
        public static System.DateTime DefaultDate
        {
            set
            {
                _DefaultDate = value;
            }
            get
            {
                if (DefaultDateIsNow)
                    return System.DateTime.Now;
                else
                    return _DefaultDate;
            }
        }
        static System.DateTime _DefaultDate = System.DateTime.Now;

        /// <summary>
        /// If true then DefaultDate property is ignored and DefaultDate is always DateTime.Now
        /// </summary>
        public static bool DefaultDateIsNow = true;

        /// <summary>
        /// Defines default date-time format.
        /// </summary>
        public enum DateTimeFormat
        {
            /// <summary>
            /// month number goes before day number
            /// </summary>
            USA_DATE,
            /// <summary>
            /// day number goes before month number
            /// </summary>
            UK_DATE,
            ///// <summary>
            ///// time is specifed through AM or PM
            ///// </summary>
            //USA_TIME,
        }

        #endregion

        #region parsing derived methods for DateTime output

        /// <summary>
        /// Tries to find date and time within the passed string and return it as DateTime structure. 
        /// </summary>
        /// <param name="str">string that contains date and(or) time</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="date_time">parsed date-time output</param>
        /// <returns>true if both date and time were found, else false</returns>
        static public bool TryParseDateTime(string str, DateTimeFormat default_format, out System.DateTime date_time)
        {
            lock (lock_variable)
            {
                ParsedDateTime parsed_date_time;
                if (!TryParseDateTime(str, default_format, out parsed_date_time))
                {
                    date_time = new System.DateTime(1, 1, 1);
                    return false;
                }
                date_time = parsed_date_time.DateTime;
                return true;
            }
        }

        /// <summary>
        /// Tries to find date and(or) time within the passed string and return it as DateTime structure. 
        /// If only date was found, time in the returned DateTime is always 0:0:0.
        /// If only time was found, date in the returned DateTime is DefaultDate.
        /// </summary>
        /// <param name="str">string that contains date and(or) time</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="date_time">parsed date-time output</param>
        /// <returns>true if date and(or) time was found, else false</returns>
        static public bool TryParse(string str, DateTimeFormat default_format, out System.DateTime date_time)
        {
            lock (lock_variable)
            {
                ParsedDateTime parsed_date_time;
                if (!TryParse(str, default_format, out parsed_date_time))
                {
                    date_time = new System.DateTime(1, 1, 1);
                    return false;
                }
                date_time = parsed_date_time.DateTime;
                return true;
            }
        }

        /// <summary>
        /// Tries to find time within the passed string and return it as DateTime structure. 
        /// It recognizes only time while ignoring date, so date in the returned DateTime is always 1/1/1.
        /// </summary>
        /// <param name="str">string that contains time</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="time">parsed time output</param>
        /// <returns>true if time was found, else false</returns>
        public static bool TryParseTime(string str, DateTimeFormat default_format, out System.DateTime time)
        {
            lock (lock_variable)
            {
                ParsedDateTime parsed_time;
                if (!TryParseTime(str, default_format, out parsed_time, null))
                {
                    time = new System.DateTime(1, 1, 1);
                    return false;
                }
                time = parsed_time.DateTime;
                return true;
            }
        }

        /// <summary>
        /// Tries to find date within the passed string and return it as DateTime structure. 
        /// It recognizes only date while ignoring time, so time in the returned DateTime is always 0:0:0.
        /// If year of the date was not found then it accepts the current year. 
        /// </summary>
        /// <param name="str">string that contains date</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="date">parsed date output</param>
        /// <returns>true if date was found, else false</returns>
        static public bool TryParseDate(string str, DateTimeFormat default_format, out System.DateTime date)
        {
            lock (lock_variable)
            {
                ParsedDateTime parsed_date;
                if (!TryParseDate(str, default_format, out parsed_date))
                {
                    date = new System.DateTime(1, 1, 1);
                    return false;
                }
                date = parsed_date.DateTime;
                return true;
            }
        }

        #endregion

        #region parsing derived methods for ParsedDateTime output

        /// <summary>
        /// Tries to find date and time within the passed string and return it as ParsedDateTime object. 
        /// </summary>
        /// <param name="str">string that contains date-time</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="parsed_date_time">parsed date-time output</param>
        /// <returns>true if both date and time were found, else false</returns>
        static public bool TryParseDateTime(string str, DateTimeFormat default_format, out ParsedDateTime parsed_date_time)
        {
            lock (lock_variable)
            {
                if (DateTimeHelper.TryParse(str, DateTimeHelper.DateTimeFormat.USA_DATE, out parsed_date_time)
                    && parsed_date_time.IsDateFound
                    && parsed_date_time.IsTimeFound
                    )
                    return true;

                parsed_date_time = null;
                return false;
            }
        }

        /// <summary>
        /// Tries to find time within the passed string and return it as ParsedDateTime object. 
        /// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
        /// </summary>
        /// <param name="str">string that contains date-time</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="parsed_time">parsed date-time output</param>
        /// <returns>true if time was found, else false</returns>
        static public bool TryParseTime(string str, DateTimeFormat default_format, out ParsedDateTime parsed_time)
        {
            lock (lock_variable)
            {
                return TryParseTime(str, default_format, out parsed_time, null);
            }
        }

        /// <summary>
        /// Tries to find date and(or) time within the passed string and return it as ParsedDateTime object. 
        /// If only date was found, time in the returned ParsedDateTime is always 0:0:0.
        /// If only time was found, date in the returned ParsedDateTime is DefaultDate.
        /// </summary>
        /// <param name="str">string that contains date-time</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="parsed_date_time">parsed date-time output</param>
        /// <returns>true if date or time was found, else false</returns>
        static public bool TryParse(string str, DateTimeFormat default_format, out ParsedDateTime parsed_date_time)
        {
            lock (lock_variable)
            {
                parsed_date_time = null;

                ParsedDateTime parsed_date;
                ParsedDateTime parsed_time;
                if (!TryParseDate(str, default_format, out parsed_date))
                {
                    if (!TryParseTime(str, default_format, out parsed_time, null))
                        return false;

                    System.DateTime date_time = new System.DateTime(DefaultDate.Year, DefaultDate.Month, DefaultDate.Day, parsed_time.DateTime.Hour, parsed_time.DateTime.Minute, parsed_time.DateTime.Second);
                    parsed_date_time = new ParsedDateTime(-1, -1, parsed_time.IndexOfTime, parsed_time.LengthOfTime, date_time);
                }
                else
                {
                    if (!TryParseTime(str, default_format, out parsed_time, parsed_date))
                    {
                        System.DateTime date_time = new System.DateTime(parsed_date.DateTime.Year, parsed_date.DateTime.Month, parsed_date.DateTime.Day, 0, 0, 0);
                        parsed_date_time = new ParsedDateTime(parsed_date.IndexOfDate, parsed_date.LengthOfDate, -1, -1, date_time);
                    }
                    else
                    {
                        System.DateTime date_time = new System.DateTime(parsed_date.DateTime.Year, parsed_date.DateTime.Month, parsed_date.DateTime.Day, parsed_time.DateTime.Hour, parsed_time.DateTime.Minute, parsed_time.DateTime.Second);
                        parsed_date_time = new ParsedDateTime(parsed_date.IndexOfDate, parsed_date.LengthOfDate, parsed_time.IndexOfTime, parsed_time.LengthOfTime, date_time);
                    }
                }

                return true;
            }
        }

        #endregion

        #region parsing base methods

        /// <summary>
        /// Tries to find time within the passed string (relatively to the passed parsed_date if any) and return it as ParsedDateTime object.
        /// It recognizes only time while ignoring date, so date in the returned ParsedDateTime is always 1/1/1
        /// </summary>
        /// <param name="str">string that contains date</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="parsed_time">parsed date-time output</param>
        /// <param name="parsed_date">ParsedDateTime object if the date was found within this string, else NULL</param>
        /// <returns>true if time was found, else false</returns>
        public static bool TryParseTime(string str, DateTimeFormat default_format, out ParsedDateTime parsed_time, ParsedDateTime parsed_date)
        {
            lock (lock_variable)
            {
                parsed_time = null;

                Match m;
                if (parsed_date != null && parsed_date.IndexOfDate > -1)
                {//look around the found date
                    //look for <date> [h]h:mm[:ss] [PM/AM]
                    m = Regex.Match(str.Substring(parsed_date.IndexOfDate + parsed_date.LengthOfDate), @"(?<=^\s*,?\s+|^\s*at\s*|^\s*[T\-]\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                    if (!m.Success)
                        //look for [h]h:mm:ss <date>
                        m = Regex.Match(str.Substring(0, parsed_date.IndexOfDate), @"(?<=^|[^\d])(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[\s,]+)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }
                else//look anywere within string
                    //look for [h]h:mm[:ss] [PM/AM]
                    m = Regex.Match(str, @"(?<=^|\s+|\s*T\s*)(?'hour'\d{1,2})\s*:\s*(?'minute'\d{2})\s*(?::\s*(?'second'\d{2}))?(?:\s*([AP]M))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);

                if (m.Success)
                {
                    try
                    {
                        int hour = int.Parse(m.Groups["hour"].Value);
                        if (hour < 0 || hour > 23)
                            return false;

                        int minute = int.Parse(m.Groups["minute"].Value);
                        if (minute < 0 || minute > 59)
                            return false;

                        int second = 0;
                        if (!string.IsNullOrEmpty(m.Groups["second"].Value))
                        {
                            second = int.Parse(m.Groups["second"].Value);
                            if (second < 0 || second > 59)
                                return false;
                        }

                        if (string.Compare(m.Groups[4].Value, "PM", true) > -1)
                            hour += 12;

                        System.DateTime date_time = new System.DateTime(1, 1, 1, hour, minute, second);
                        parsed_time = new ParsedDateTime(-1, -1, m.Index, m.Length, date_time);
                    }
                    catch
                    {
                        return false;
                    }
                    return true;
                }

                return false;
            }
        }

        /// <summary>
        /// Tries to find date within the passed string and return it as ParsedDateTime object. 
        /// It recognizes only date while ignoring time, so time in the returned ParsedDateTime is always 0:0:0.
        /// If year of the date was not found then it accepts the current year. 
        /// </summary>
        /// <param name="str">string that contains date</param>
        /// <param name="default_format">format that must be used preferably in ambivalent instances</param>
        /// <param name="parsed_date">parsed date output</param>
        /// <returns>true if date was found, else false</returns>
        static public bool TryParseDate(string str, DateTimeFormat default_format, out ParsedDateTime parsed_date)
        {
            lock (lock_variable)
            {
                parsed_date = null;

                if (string.IsNullOrEmpty(str))
                    return false;

                //look for dd/mm/yy
                Match m = Regex.Match(str, @"(?<=^|[^\d])(?'day'\d{1,2})\s*(?'separator'[\\/\.])+\s*(?'month'\d{1,2})\s*\'separator'+\s*(?'year'\d{2,4})(?=$|[^\d])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (m.Success && m.Groups["year"].Value.Length != 3)
                {
                    System.DateTime date;
                    if ((default_format ^ DateTimeFormat.USA_DATE) == DateTimeFormat.USA_DATE)
                    {
                        if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["day"].Value), int.Parse(m.Groups["month"].Value), out date))
                            return false;
                    }
                    else
                    {
                        if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))
                            return false;
                    }
                    parsed_date = new ParsedDateTime(m.Index, m.Length, -1, -1, date);
                    return true;
                }

                //look for yy-mm-dd
                m = Regex.Match(str, @"(?<=^|[^\d])(?'year'\d{2,4})\s*(?'separator'[\-])\s*(?'month'\d{1,2})\s*\'separator'+\s*(?'day'\d{1,2})(?=$|[^\d])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (m.Success && m.Groups["year"].Value.Length != 3)
                {
                    System.DateTime date;
                    if (!convert_to_date(int.Parse(m.Groups["year"].Value), int.Parse(m.Groups["month"].Value), int.Parse(m.Groups["day"].Value), out date))
                        return false;
                    parsed_date = new ParsedDateTime(m.Index, m.Length, -1, -1, date);
                    return true;
                }

                //look for month dd yyyy
                m = Regex.Match(str, @"(?:^|[^\d\w])(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th)?\s*,?\s*(?'year'\d{4})(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (!m.Success)
                    //look for dd month [yy]yy
                    m = Regex.Match(str, @"(?:^|[^\d\w:])(?'day'\d{1,2})(?:-?st|-?th)?\s+(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*(?:\s*,?\s*(?:'?(?'year'\d{2})|(?'year'\d{4})))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (!m.Success)
                    //look for yyyy month dd
                    m = Regex.Match(str, @"(?:^|[^\d\w])(?'year'\d{4})\s+(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th)?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (!m.Success)
                    //look for  month dd [yyyy]
                    m = Regex.Match(str, @"(?:^|[^\d\w])(?'month'Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[uarychilestmbro]*\s+(?'day'\d{1,2})(?:-?st|-?th)?(?:\s*,?\s*(?'year'\d{4}))?(?=$|[^\d\w])", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                if (m.Success)
                {
                    int month = -1;
                    int index_of_date = m.Index;
                    int length_of_date = m.Length;

                    switch (m.Groups["month"].Value)
                    {
                        case "Jan":
                            month = 1;
                            break;
                        case "Feb":
                            month = 2;
                            break;
                        case "Mar":
                            month = 3;
                            break;
                        case "Apr":
                            month = 4;
                            break;
                        case "May":
                            month = 5;
                            break;
                        case "Jun":
                            month = 6;
                            break;
                        case "Jul":
                            month = 7;
                            break;
                        case "Aug":
                            month = 8;
                            break;
                        case "Sep":
                            month = 9;
                            break;
                        case "Oct":
                            month = 10;
                            break;
                        case "Nov":
                            month = 11;
                            break;
                        case "Dec":
                            month = 12;
                            break;
                    }

                    int year;
                    if (!string.IsNullOrEmpty(m.Groups["year"].Value))
                        year = int.Parse(m.Groups["year"].Value);
                    else
                        year = DefaultDate.Year;

                    System.DateTime date;
                    if (!convert_to_date(year, month, int.Parse(m.Groups["day"].Value), out date))
                        return false;
                    parsed_date = new ParsedDateTime(index_of_date, length_of_date, -1, -1, date);
                    return true;
                }

                return false;
            }
        }

        static bool convert_to_date(int year, int month, int day, out System.DateTime date)
        {
            if (year >= 100)
            {
                if (year < 1000)
                {
                    date = new System.DateTime(1, 1, 1);
                    return false;
                }
            }
            else
                if (year > 30)
                    year += 1900;
                else
                    year += 2000;

            try
            {
                date = new System.DateTime(year, month, day);
            }
            catch
            {
                date = new System.DateTime(1, 1, 1);
                return false;
            }
            return true;
        }

        #endregion
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Deyan Timnev
Product Manager Ingenious Ltd, Bulgaria
Bulgaria Bulgaria
I worked for a few years as a C++/Win32 developer and software architect, and then moved on to the .NET environment where I was able to discover the beauty of managed programming.

I am currently involved in the development and management of Open Forex Platform (www.openforexplatform.com) and the Matrix Platform (www.matrixplatform.com).

You may also be interested in...

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150728.1 | Last Updated 31 Aug 2010
Article Copyright 2010 by Deyan Timnev
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid