Initial Commit

This commit is contained in:
2025-03-25 21:42:32 -04:00
parent c266eecfeb
commit 30c33d3cfd
247 changed files with 60107 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
using System;
using System.Text;
using System.Collections.Generic;
namespace MarketData.Utils
{
public class CSVLineHelper
{
public CSVLineHelper()
{
}
public static String[] ParseLine(String strLine)
{
try
{
List<String> items = new List<String>();
int length = strLine.Length;
for (int index = 0; index < length; index++)
{
char ch = strLine[index];
if (ch == '"') items.Add(GetQuotedItem(strLine, ref index, length));
else items.Add(GetItem(strLine, ref index, length));
}
return items.ToArray();
}
catch (Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,exception.ToString());
return null;
}
}
private static String GetQuotedItem(String strLine,ref int index,int length)
{
StringBuilder sb = new StringBuilder();
char ch = '\0';
while (index<length)
{
ch = strLine[++index];
if (ch == '"') { index++; break; }
if (ch != ',') sb.Append(ch);
}
return sb.ToString();
}
private static String GetItem(String strLine, ref int index, int length)
{
StringBuilder sb = new StringBuilder();
char ch='\0';
while (ch != ',' && index<length)
{
ch = strLine[index++];
if (ch != ',') sb.Append(ch);
}
index--;
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,456 @@
using System;
using System.Collections.Generic;
// Filename: DateGenerator.cs
// Author:Sean Kessler
namespace MarketData.Utils
{
/// <summary>DateGenerator - Generate Historical Dates</summary>
/// "BusinessDay" is analagous to "MarketDay". To qualify as a business day the date must not be a weekend or a market holiday
[Serializable]
public class DateGenerator
{
private static readonly TimeSpan TIMESPAN_INCREASE_ONE_DAY=new TimeSpan(1,0,0,0);
private static readonly TimeSpan TIMESPAN_DECREASE_ONE_DAY=new TimeSpan(-1,0,0,0);
public DateGenerator()
{
}
/// <summary>GetCurrMonthStart - Finds the first business day of the previous month</summary>
/// <returns>DateTime</returns>
public DateTime GetPrevMonthStart(DateTime dateTime)
{
DateTime startDate = new DateTime(dateTime.Year, dateTime.Month, 1);
startDate = startDate.AddMonths(-1);
startDate = GetNextBusinessDay(startDate);
return startDate;
}
/// <summary>GetCurrMonthStart - Finds the first business day of the current month</summary>
/// <returns>DateTime</returns>
public DateTime GetCurrMonthStart(DateTime dateTime)
{
DateTime startDate = new DateTime(dateTime.Year, dateTime.Month, 1);
startDate = GetNextBusinessDay(startDate);
return startDate;
}
public static int GetPrevMonth(int month)
{
if(1==month)return 12;
return month-1;
}
/// <summary>FindPrevBusinessDay - Finds previous business day</summary>
/// <returns>DateTime</returns>
public DateTime FindPrevBusinessDay(DateTime asOf)
{
TimeSpan oneDay=new TimeSpan(1,0,0,0);
asOf=asOf.Subtract(oneDay);
while(IsWeekend(asOf)||IsHoliday(asOf))asOf=asOf.Subtract(oneDay);
return asOf.Date;
}
/// <summary>FindForwardBusinessDay - Finds following business day going daysForward days</summary>
/// <returns>DateTime</returns>
public DateTime FindForwardBusinessDay(DateTime asOf,int daysForward)
{
for (int index = 0; index < daysForward; index++)
{
asOf = FindNextBusinessDay(asOf);
}
return asOf.Date;
}
/// <summary>FindPastBusinessDay - Finds previous business day going daysPast days</summary>
/// <returns>DateTime</returns>
public DateTime FindPastBusinessDay(DateTime asOf,int daysPast)
{
for (int index = 0; index < daysPast; index++)
{
asOf = FindPrevBusinessDay(asOf);
}
return asOf.Date;
}
/// <summary>FindNextBusinessDay - Finds following nth business day</summary>
/// <returns>DateTime</returns>
public DateTime FindNextBusinessDay(DateTime asOf,int days)
{
DateTime nextDate=asOf;
for(int index=0;index<days;index++)
{
nextDate=FindNextBusinessDay(nextDate);
}
return nextDate;
}
/// <summary>FindNextBusinessDay - Finds following business day</summary>
/// <returns>DateTime</returns>
public DateTime FindNextBusinessDay(DateTime asOf)
{
TimeSpan oneDay=new TimeSpan(1,0,0,0);
asOf=asOf.Add(oneDay);
while(IsWeekend(asOf)||IsHoliday(asOf))asOf=asOf.Add(oneDay);
return asOf.Date;
}
/// <summary>GetPrevBusinessDay - Gets previous business day</summary>
/// <note>If the given date is a business day then this method will return the given date</note>
/// <returns>None</returns>
public DateTime GetPrevBusinessDay(DateTime asOf)
{
TimeSpan oneDay=new TimeSpan(1,0,0,0);
while(IsWeekend(asOf)||IsHoliday(asOf))asOf=asOf.Subtract(oneDay);
return asOf.Date;
}
/// <summary>GetNextBusinessDay - Gets next business day</summary>
/// <note>If the given date is a business day then this method will return the given date</note>
/// <returns>None</returns>
public DateTime GetNextBusinessDay(DateTime asOf)
{
TimeSpan oneDay=new TimeSpan(1,0,0,0);
while(IsWeekend(asOf)||IsHoliday(asOf))asOf=asOf.Add(oneDay);
return asOf.Date;
}
/// <summary>GetNextDay - Gets next business day</summary>
/// <note>If the given date is a business day then this method will return the given date</note>
/// <returns>None</returns>
public DateTime GetNextDay(DateTime asOf)
{
return (asOf.Add(Utility.OneDay)).Date;
}
/// <summary>GetPrevFriday - Gets date of prior friday</summary>
/// <note>Get the date of the previous friday - if previous Friday is holiday will seek previous business day</note>
/// <returns>None</returns>
public DateTime GetPrevFriday(DateTime asOf)
{
TimeSpan oneDay=new TimeSpan(1,0,0,0);
List<DateTime> historicalDates=null;
int daysToFetch=7;
if(DayOfWeek.Friday==asOf.DayOfWeek)
{
asOf=asOf.Subtract(oneDay);
daysToFetch--;
}
historicalDates=GenerateHistoricalDates(asOf,daysToFetch);
for(int index=0;index<historicalDates.Count;index++)
{
DateTime date=(DateTime)historicalDates[index];
if(DayOfWeek.Friday==date.DayOfWeek)return GetPrevBusinessDay(date);
}
throw new Exception("The week no longer contains Friday?");
}
public DateTime GetPrevQuarterStartDate(DateTime asOf)
{
int month=asOf.Month;
if(asOf.Month>=1 && asOf.Month<=3)month=1;
else if(asOf.Month>=4 && asOf.Month<=6)month=4;
else if(asOf.Month>=7 && asOf.Month<=9)month=7;
else month=10;
DateTime quarterStartDate=new DateTime(asOf.Year,month,1);
quarterStartDate=GetNextBusinessDay(quarterStartDate);
return quarterStartDate;
}
public DateTime GetNextQuarterStartDate(DateTime asOf)
{
DateTime prevQuarterStartDate=GetPrevQuarterStartDate(asOf);
int month=prevQuarterStartDate.Month;
int year=prevQuarterStartDate.Year;
if(prevQuarterStartDate.Month.Equals(10)){year++;}
month+=3;
if(month>12)month=1;
DateTime nextQuarterStartDate=new DateTime(year,month,1);
nextQuarterStartDate=GetNextBusinessDay(nextQuarterStartDate);
return nextQuarterStartDate;
}
public DateTime GetCurrentMonthEnd(DateTime asOf)
{
TimeSpan oneDay=new TimeSpan(-1,0,0,0);
DateTime date=new DateTime(asOf.Year,asOf.Month,asOf.Day);
date=new DateTime(date.Year,date.Month,DateTime.DaysInMonth(asOf.Year,asOf.Month));
while(IsWeekend(date)||IsHoliday(date))date=date.Add(oneDay);
return date;
}
public DateTime GetNextMonthEnd(DateTime asOf)
{
TimeSpan oneDay=new TimeSpan(-1,0,0,0);
DateTime date=new DateTime(asOf.Year,asOf.Month,asOf.Day);
date=date.AddMonths(1);
date=new DateTime(date.Year,date.Month,DateTime.DaysInMonth(date.Year,date.Month));
while(IsWeekend(date)||IsHoliday(date))date=date.Add(oneDay);
return date;
}
public DateTime GetPrevMonthEnd(DateTime asOf)
{
TimeSpan oneDay=new TimeSpan(-1,0,0,0);
DateTime date=new DateTime(asOf.Year,asOf.Month,asOf.Day);
date=date.AddMonths(-1);
date=new DateTime(date.Year,date.Month,DateTime.DaysInMonth(date.Year,date.Month));
while(IsWeekend(date)||IsHoliday(date))date=date.Add(oneDay);
return date;
}
public DateTime GetPrevMonthEnd(DateTime asOf,int count)
{
for(int index=0;index<count;index++)
{
asOf=GetPrevMonthEnd(asOf);
}
return asOf;
}
public DateTime EnsureWeekday(DateTime asOf)
{
TimeSpan oneDay=new TimeSpan(1,0,0,0);
if(!IsWeekend(asOf))return asOf;
while(IsWeekend(asOf=asOf.Add(oneDay)));
return asOf;
}
public DateTime GenerateHistoricalDate(DateTime startDate,int dayCount)
{
DateTime histDate;
int datedDates=0;
TimeSpan singleDay;
startDate = startDate.Date;
histDate=startDate;
if(dayCount<0)singleDay=TIMESPAN_DECREASE_ONE_DAY;
else singleDay=TIMESPAN_INCREASE_ONE_DAY;
dayCount=dayCount<0?-dayCount:dayCount;
while(datedDates<dayCount)
{
if(!(DayOfWeek.Sunday==histDate.DayOfWeek||DayOfWeek.Saturday==histDate.DayOfWeek))
{
if(!IsHoliday(histDate.Date))datedDates++;
}
histDate=histDate.Subtract(singleDay);
}
return histDate.Add(singleDay);
}
// Does not account for weekends etc.,
public DateTime GenerateFutureDate(DateTime startDate,int dayCount)
{
DateTime futureDate;
int datedDates=0;
TimeSpan singleDay;
startDate = startDate.Date;
futureDate=startDate;
singleDay=new TimeSpan(1,0,0,0);
while(datedDates<dayCount)
{
futureDate=futureDate.Add(singleDay);
datedDates++;
}
return futureDate.Add(singleDay);
}
// Accounts for weekends
public DateTime GenerateFutureBusinessDate(DateTime startDate,int dayCount)
{
DateTime futureDate;
int datedDates=0;
TimeSpan singleDay;
startDate = startDate.Date;
futureDate=startDate;
singleDay=new TimeSpan(1,0,0,0);
while(datedDates<dayCount)
{
if(IsMarketOpen(futureDate))datedDates++;
futureDate=futureDate.Add(singleDay);
}
return futureDate.Add(singleDay);
}
public int DaysBetweenActual(DateTime historicalDate)
{
DateTime today = DateTime.Now;
TimeSpan timeSpan = historicalDate.Date - today;
return (int)timeSpan.TotalDays;
}
public int DaysBetweenActual(DateTime historicalDate,DateTime startingDate)
{
TimeSpan timeSpan = historicalDate.Date-startingDate;
int totalDays = (int)timeSpan.TotalDays;
if (historicalDate < startingDate) totalDays = (Math.Abs(totalDays) * -1);
else totalDays = Math.Abs(totalDays);
return totalDays;
}
public DateTime DaysAddActual(DateTime date, int daysActual)
{
TimeSpan days = new TimeSpan(daysActual, 0, 0, 0);
return date + days;
}
public int DaysBetween(DateTime startDate, DateTime endDate)
{
if (startDate > endDate)
{
TimeSpan timeSpan = startDate.Date - endDate.Date;
return (int)timeSpan.TotalDays;
}
else
{
TimeSpan timeSpan = endDate.Date - startDate.Date;
return (int)timeSpan.TotalDays;
}
}
public int MonthsBetween(DateTime startDate,DateTime endDate)
{
return DaysBetween(startDate,endDate)/30;
}
public static List<int> GenerateHistoricalYear(int startYear,int years)
{
List<int> yearsList = new List<int>();
for (int index = 0; index < years; index++)
{
yearsList.Add(startYear);
startYear--;
}
return yearsList;
}
public List<DateTime> GenerateHistoricalDates(DateTime startDate, int dayCount)
{
List<DateTime> histDates=new List<DateTime>();
DateTime histDate;
TimeSpan singleDay;
startDate = startDate.Date;
histDate=startDate;
if(dayCount<0)singleDay=new TimeSpan(-1,0,0,0);
else singleDay=new TimeSpan(1,0,0,0);
dayCount=dayCount<0?-dayCount:dayCount;
while(histDates.Count<dayCount)
{
if(IsMarketOpen(histDate))histDates.Add(histDate);
histDate=histDate.Subtract(singleDay);
}
return histDates;
}
/// <summary>
/// Generates dates into the future respecting weekens and market holidays
/// </summary>
/// <param name="startDate"></param>
/// <param name="dayCount"></param>
/// <returns></returns>
public List<DateTime> GenerateFutureDates(DateTime startDate, int dayCount)
{
List<DateTime> futureDates=new List<DateTime>();
DateTime futureDate;
TimeSpan singleDay;
startDate = startDate.Date;
futureDate=startDate;
if(dayCount<0)singleDay=new TimeSpan(1,0,0,0);
else singleDay=new TimeSpan(1,0,0,0);
dayCount=dayCount<0?-dayCount:dayCount;
while(futureDates.Count<dayCount)
{
if(IsMarketOpen(futureDate))futureDates.Add(futureDate);
futureDate=futureDate.Add(singleDay);
}
return futureDates;
}
public int TradingDaysBetween(DateTime startDate,DateTime endDate)
{
List<DateTime> historicalDates=GenerateHistoricalDates(startDate,endDate);
return historicalDates.Count;
}
// The function will figure out which date is the most recent and which one is the historical date.
// Generally, make startDate the most recent and endDate the historical date.
// The returned series will contain an ascending date series with the earliest (most distant) date in the lowest numbered index.
public List<DateTime> GenerateHistoricalDates(DateTime startDate,DateTime endDate)
{
if (Utility.Epoch.Equals(startDate)||Utility.Epoch.Equals(endDate)) return null;
startDate = startDate.Date;
endDate = endDate.Date;
List<DateTime> histDates = new List<DateTime>();
DateTime histDate;
TimeSpan singleDay;
bool reverse = false;
if (endDate > startDate)
{
reverse = true;
DateTime swap = endDate;
endDate = startDate;
startDate = swap;
}
histDate=startDate;
singleDay=new TimeSpan(1,0,0,0);
while(histDate>=endDate)
{
if(IsMarketOpen(histDate))histDates.Add(histDate);
histDate=histDate.Subtract(singleDay);
}
if (reverse) histDates.Reverse();
return histDates;
}
// The function will figure out which date is the most recent and which one is the historical date.
// Generally, make startDate the most recent and endDate the historical date.
public List<DateTime> GenerateHistoricalDatesActual(DateTime startDate, DateTime endDate)
{
if (Utility.Epoch.Equals(startDate) || Utility.Epoch.Equals(endDate)) return null;
startDate = startDate.Date;
endDate = endDate.Date;
List<DateTime> histDates = new List<DateTime>();
DateTime histDate;
TimeSpan singleDay;
bool reverse = false;
if (endDate > startDate)
{
reverse = true;
DateTime swap = endDate;
endDate = startDate;
startDate = swap;
}
histDate = startDate;
singleDay = new TimeSpan(1, 0, 0, 0);
while (histDate >= endDate)
{
histDates.Add(histDate);
histDate = histDate.Subtract(singleDay);
}
if (reverse) histDates.Reverse();
return histDates;
}
public bool IsMarketOpen(DateTime dateTime)
{
if(IsWeekend(dateTime)||IsHoliday(dateTime))return false;
return true;
}
public bool IsWeekend(DateTime dateTime)
{
if(DayOfWeek.Sunday==dateTime.DayOfWeek || DayOfWeek.Saturday==dateTime.DayOfWeek)return true;
return false;
}
// This uses a singleton cache of holidays.
public bool IsHoliday(DateTime dateTime)
{
return HolidayCache.GetInstance().IsHoliday(dateTime);
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace MarketData.Utils
{
public class DateRange : List<DateTime>
{
public DateRange(DateTime startDate,DateTime endDate)
{
startDate = startDate.Date;
endDate=endDate.Date;
DateGenerator dateGenerator=new DateGenerator();
List<DateTime> dates= dateGenerator.GenerateHistoricalDates(startDate, endDate);
foreach (DateTime date in dates) Add(date);
Sort(); // ensure that no matter how we set this up, the oldest date winds up being at the lowest index of the list
}
public DateTime StartDate
{
get { return this[0]; }
}
public DateTime EndDate
{
get { return this[Count-1]; }
}
}
}

View File

@@ -0,0 +1,25 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MarketData.Utils
{
public static class ExtensionMethods
{
public static bool IsNullOrEmpty<T>(this ICollection<T> list)
{
if(null==list || 0==list.Count())return true;
return false;
}
public static bool ContainsIgnoreCase(this List<String> list, string str)
{
foreach(String strString in list)
{
if(strString.Equals(str,StringComparison.InvariantCultureIgnoreCase))return true;
}
return false;
}
}
}

View File

@@ -0,0 +1,343 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MarketData;
using MarketData.MarketDataModel;
using MarketData.Utils;
namespace MarketData.Utils
{
public class FeedParser
{
private FeedParser()
{
}
public static TimeSeriesCollection ParseTimeSeries(String symbol, List<DateTime> reportDates, TimeSeriesElement.ElementType elementType,String strLine)
{
TimeSeriesCollection timeSeriesCollection = new TimeSeriesCollection();
Dictionary<DateTime,DateTime> dates = new Dictionary<DateTime,DateTime>();
try
{
if (null == reportDates || 0 == reportDates.Count) return null;
String[] lineItems = CSVLineHelper.ParseLine(strLine);
if (null == lineItems) return null;
for (int index = 0; index < reportDates.Count;index++)
{
TimeSeriesElement timeSeriesElement = new TimeSeriesElement();
timeSeriesElement.Type = elementType;
timeSeriesElement.Symbol = symbol;
timeSeriesElement.AsOf = reportDates[index];
if (lineItems.Length - 1 < index + 1) continue;
timeSeriesElement.Value = ParseValue(lineItems[index + 1]);
if (double.IsNaN(timeSeriesElement.Value)) continue;
if (strLine.Contains("USD Mil"))
{
timeSeriesElement.Value *= 1000000.00;
}
if (!dates.ContainsKey(timeSeriesElement.AsOf))
{
dates.Add(timeSeriesElement.AsOf, timeSeriesElement.AsOf);
timeSeriesCollection.Add(timeSeriesElement);
}
}
return timeSeriesCollection;
}
catch (Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,exception.ToString());
return null;
}
}
//"Book Value Per Share USD,3.31,3.22,2.64,2.58,2.28,2.10,1.39,2.64,3.88,3.94,3.94"
public static List<DateTime> ParsePeriodEndingDates(String periodEnding)
{
List<DateTime> periodEndingDates = new List<DateTime>();
if (null == periodEnding || !periodEnding.StartsWith("Period Ending")) return null;
periodEnding = periodEnding.Replace("Period Ending", "");
int length = periodEnding.Length;
int index = 0;
while (index<length)
{
String strMonth = periodEnding.Substring(index, 3);
char ch;
index += 3;
StringBuilder sb = new StringBuilder();
while ((ch = periodEnding[index++]) != ',') sb.Append(ch);
String strDay = sb.ToString().Trim();
sb = new StringBuilder();
for (int yIndex = 0; yIndex < 5; yIndex++) sb.Append(periodEnding[index++]);
String strYear = sb.ToString().Trim();
DateTime periodEndingDate=DateTime.ParseExact(strMonth+Utility.Pad(strDay,'0',2)+strYear, "MMMddyyyy", new System.Globalization.CultureInfo("en-US"));
periodEndingDates.Add(periodEndingDate);
}
return periodEndingDates;
}
public static DateTime ParseValueDateTime(String strText)
{
try
{
if(strText.Contains("Est"))
{
strText=Utility.RemoveAfter(strText,'-');
strText = strText.Trim();
strText = strText + " "+DateTime.Now.Year.ToString();
string[] items = strText.Split(' ');
strText = items[0] + "-" + Utility.Pad(items[1], '0', 2) + "-" + items[2];
return DateTime.ParseExact(strText, "MMM-dd-yyyy", new System.Globalization.CultureInfo("en-US"));
}
else
{
strText = strText.Replace(" ", "0");
return DateTime.ParseExact(strText, "dd-MMM-yy", new System.Globalization.CultureInfo("en-US"));
}
}
catch(Exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,"[ParseValueDateTime] Error parsing date '"+strText+"'");
return DateTime.Parse("01-01-0001");
}
}
// "Middleby Corp. Fri, Aug 2, 2013"
public static DateTime ParseValueDateTimeMonthFormatFromMarketWatch(String strItem)
{
strItem = Utility.RemoveControlChars(strItem.Trim());
String[] strItems = strItem.Split(' ');
if (strItems.Length < 3) return DateTime.Parse("01-01-0001"); ;
String strDate = strItems[strItems.Length - 3] + " " + strItems[strItems.Length - 2] + " " + strItems[strItems.Length - 1];
return ParseValueDateTimeMonthFormat(strDate);
}
public static double ParseValueFromMarketWatch(String identifier,String strItem)
{
try
{
strItem = Utility.RemoveControlChars(strItem.Trim());
identifier = identifier.ToLower();
strItem = strItem.ToLower();
if (!strItem.StartsWith(identifier)) return double.NaN;
String strValue = strItem.Substring(strItem.IndexOf(':') + 1).Trim();
return double.Parse(strValue);
}
catch (Exception)
{
return double.NaN;
}
}
public static long ParseLongValueFromMarketWatch(String identifier, String strItem)
{
try
{
strItem = Utility.RemoveControlChars(strItem.Trim());
identifier = identifier.ToLower();
strItem = strItem.ToLower();
if (!strItem.StartsWith(identifier)) return 0;
String strValue = strItem.Substring(strItem.IndexOf(':') + 1).Trim();
strValue = strValue.Replace(",", "");
return long.Parse(strValue);
}
catch (Exception)
{
return 0;
}
}
//"Aug 23, 2013"
public static DateTime ParseValueDateTimeMonthFormat(String strText)
{
try
{
if(null==strText)return Utility.Epoch;
String[] strArray = strText.Split(' ');
if (3 != strArray.Length) return DateTime.Parse("01-01-0001");
strArray[1] = strArray[1].Replace(",", "");
return ParseValueDateTime(Utility.Pad(strArray[1],'0',2)+"-"+strArray[0]+"-"+strArray[2].Substring(2,2));
}
catch (Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,"[ParseValueDateTimeMonthFormat] Error parsing date '" + strText + "', "+exception.ToString());
return DateTime.Parse("01-01-0001");
}
}
// "Apr. 04"
// "1:00pm"
public static DateTime ParseValueDateTimeMonth(String strText)
{
try
{
if(null==strText)return DateTime.Parse("01-01-0001");
if(strText.EndsWith("am") || strText.EndsWith("pm"))
{
return DateTime.Now;
}
else if(strText.Contains("."))
{
strText=strText.Replace(".",null);
String[] subItems=strText.Split(' ');
DateTime currentDate = DateTime.Now;
StringBuilder sb=new StringBuilder();
sb.Append(subItems[0]).Append(" ");
sb.Append(subItems[1]).Append(",").Append(" ");
sb.Append(currentDate.Year.ToString());
DateTime resultingDate = ParseValueDateTimeMonthFormat(sb.ToString());
if(resultingDate>currentDate)resultingDate = new DateTime(resultingDate.Year-1,resultingDate.Month, resultingDate.Day);
return resultingDate;
}
else
{
return Utility.ParseDate(strText);
}
}
catch (Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG, "[ParseValueDateTimeMonth] Error parsing date '" + strText + "', " + exception.ToString());
return DateTime.Parse("01-01-0001");
}
}
// Sep. 25, 2022 at 4:31 p.m. ET
public static DateTime ParseValueDateTimeMonthFormatTZ(String strText)
{
try
{
if(null==strText)return Utility.Epoch;
String[] strArray = strText.Split(' ');
if (3 > strArray.Length) return DateTime.Parse("01-01-0001");
strArray[1] = strArray[1].Replace(",", null);
strArray[0] = strArray[0].Replace(".", null);
return ParseValueDateTime(Utility.Pad(strArray[1],'0',2)+"-"+strArray[0]+"-"+strArray[2].Substring(2,2));
}
catch (Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,"[ParseValueDateTimeMonthFormat] Error parsing date '" + strText + "', "+exception.ToString());
return DateTime.Parse("01-01-0001");
}
}
public static DateTime? ParseRelativeDate(String strDate)
{
try
{
DateTime today=DateTime.Now;
if(strDate.Contains("day"))
{
DateGenerator dateGenerator=new DateGenerator();
String[] items=strDate.Split(' ');
DateTime relativeDate=dateGenerator.GenerateHistoricalDate(today,int.Parse(items[0])+1);
return relativeDate;
}
else if(strDate.Contains("hour"))
{
String[] items=strDate.Split(' ');
TimeSpan timeSpan=new TimeSpan(int.Parse(items[0]),0,0);
DateTime relativeDate=today.Subtract(timeSpan);
return relativeDate;
}
else if(strDate.Contains("minute"))
{
String[] items=strDate.Split(' ');
TimeSpan timeSpan=new TimeSpan(0,int.Parse(items[0]),0);
DateTime relativeDate=today.Subtract(timeSpan);
return relativeDate;
}
return ParseValueDateTimeMonthFormat(strDate);
}
catch(Exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Unable to parse date '{0}'",strDate));
return null;
}
}
public static double ParseValue(String strText)
{
double value = double.NaN;
double multiplier = 1.00;
try
{
if (null == strText || 0 == strText.Length) return double.NaN;
strText=strText.Trim();
if(strText.StartsWith("--"))return double.NaN;
if(strText.Equals("N/A"))return double.NaN;
strText=strText.Replace("%", "");
strText = strText.Replace("$", "");
if (strText.Contains("("))
{
strText=strText.Replace("(", "");
strText=strText.Replace(")", "");
multiplier = -1.00;
}
if (strText.Equals("-")) return double.NaN;
if (strText[strText.Length - 1].Equals('T'))
{
strText = strText.Replace("T", "");
value = double.Parse(strText);
value *= 1000000000000;
}
if (strText[strText.Length - 1].Equals('B'))
{
strText = strText.Replace("B", "");
value = double.Parse(strText);
value *= 1000000000;
}
else if (strText[strText.Length - 1].Equals('M'))
{
strText = strText.Replace("M", "");
value = double.Parse(strText);
value *= 1000000;
}
else if (strText[strText.Length - 1].Equals('K')||strText[strText.Length - 1].Equals('k'))
{
strText = strText.Replace("K", "");
strText = strText.Replace("k", "");
value = double.Parse(strText);
value *= 1000;
}
else value = double.Parse(strText);
value *= multiplier;
return value;
}
catch (Exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,"[ParseValue] Error parsing '"+strText+"'");
return double.NaN;
}
}
public static long ParseValueLong(String strText)
{
long value;
try
{
if(null==strText)return 0;
strText=strText.Replace("%","");
strText = strText.Replace(",", "");
if (strText.Equals("-")) return 0;
if (strText[strText.Length - 1].Equals('B'))
{
strText = strText.Replace("B", "");
value = Int64.Parse(strText);
value *= 1000000000;
}
else if (strText[strText.Length - 1].Equals('M'))
{
strText = strText.Replace("M", "");
value = Int64.Parse(strText);
value *= 1000000;
}
else if (strText[strText.Length - 1].Equals('K'))
{
strText = strText.Replace("K", "");
value = Int64.Parse(strText);
value *= 1000;
}
else value = Int64.Parse(strText);
return value;
}
catch (Exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,"[ParseValueLong] Error parsing '" + strText + "'");
return 0;
}
}
}
}

View File

@@ -0,0 +1,35 @@
using System;
using System.Collections;
using System.Collections.Generic;
using MarketData.Utils;
using MarketData.DataAccess;
namespace MarketData.Utils
{
public class HolidayCache
{
private static HolidayCache instance=null;
private Dictionary<DateTime,DateTime> holidays=null;
private HolidayCache()
{
holidays=HolidayDA.GetHolidays();
}
public static HolidayCache GetInstance()
{
lock(typeof(HolidayCache))
{
if(null==instance) instance=new HolidayCache();
return instance;
}
}
public bool IsHoliday(DateTime dateTime)
{
lock(instance)
{
if(null==holidays) return false;
return holidays.ContainsKey(dateTime.Date);
}
}
}
}

View File

@@ -0,0 +1,110 @@
using System;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text;
using System.Collections.Generic;
namespace MarketData.Utils
{
public class NVPDictionary : Dictionary<String,NVP>
{
public NVPDictionary()
{
}
}
public class NVPCollections : List<NVPCollection>
{
public NVPCollections()
{
}
public NVPCollections(List<String> nvpCollections)
{
foreach(String nvpCollectionString in nvpCollections)Add(new NVPCollection(nvpCollectionString));
}
public List<String> ToList()
{
List<String> nvpCollections=new List<String>();
foreach(NVPCollection nvpCollection in this)nvpCollections.Add(nvpCollection.ToString());
return nvpCollections;
}
}
public class NVPCollection : List<NVP>
{
public NVPCollection()
{
}
public NVPCollection(String nvpCollectionString)
{
if(null==nvpCollectionString)return;
String[] nvpItems=nvpCollectionString.Split('|');
if(null==nvpItems)return;
for(int index=0;index<nvpItems.Length;index++)
{
Add(new NVP(nvpItems[index]));
}
}
public NVPDictionary ToDictionary()
{
NVPDictionary dict=new NVPDictionary();
foreach(NVP nvp in this)dict.Add(nvp.Name,nvp);
return dict;
}
public static NVPCollection FromString(String strNVPCollection)
{
return new NVPCollection(strNVPCollection);
}
public override String ToString()
{
StringBuilder sb=new StringBuilder();
for(int index=0;index<Count;index++)
{
NVP nvp=this[index];
sb.Append(nvp.ToString());
if(index<Count-1)sb.Append("|");
}
return sb.ToString();
}
}
public class NVP
{
public NVP(String name,String value)
{
Name=name;
Value=value;
}
// This needs to work with nvpString assignment that contains embedded '=' signs. For example Expression=a=1;b=2. Name="Expression", Value="a=1;b=2"
public NVP(String nvpString)
{
if(null==nvpString)return;
String[] nvps=nvpString.Split('=');
if(nvps.Length<2)return;
Name=nvps[0].Trim();
if(2==nvps.Length)Value=nvps[1].Trim();
else
{
StringBuilder sb=new StringBuilder();
for(int itemIndex=1;itemIndex<nvps.Length;itemIndex++)
{
sb.Append(nvps[itemIndex]);
if(itemIndex<nvps.Length-1)sb.Append("=");
}
Value=sb.ToString();
}
}
public T Get<T>()
{
T result=default(T);
try {result = (T)Convert.ChangeType(Value, typeof(T));}
catch {result = default(T);}
return result;
}
public String Name{get;set;}
public String Value{get;set;}
public override String ToString()
{
StringBuilder sb=new StringBuilder();
sb.Append(Name).Append("=").Append(Value);
return sb.ToString();
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Diagnostics;
// Filename: Profiler.cs
// Author:Sean Kessler
namespace MarketData.Utils
{
/// <summary>Profiler - Profiler utility class</summary>
public class Profiler
{
private Stopwatch watch = default;
public Profiler()
{
watch = System.Diagnostics.Stopwatch.StartNew();
}
public void Reset()
{
watch = System.Diagnostics.Stopwatch.StartNew();
}
public void Start()
{
watch = System.Diagnostics.Stopwatch.StartNew();
}
public long Stop()
{
return End();
}
public long End()
{
watch.Stop();
return watch.ElapsedMilliseconds;
}
}
}

View File

@@ -0,0 +1,263 @@
using System;
using System.Data.SqlClient;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlTypes;
using System.Text;
using MySql.Data.MySqlClient;
using MarketData.DataAccess;
namespace MarketData.Utils
{
/// <summary>SQlUtils - SQL utility class</summary>
public class SqlUtils
{
public static int COMMAND_TIMEOUT=300;
public static int MIN_POOL_SIZE=10;
public static int MAX_POOL_SIZE=50;
public static string COLLATION="utf8mb4_unicode_ci";
/// <summary>CreateMySqlConnection - Creates an SQL connection.</summary>
/// <param name="datasource">datasource.</param>
/// <param name="database">database.</param>
/// <param name="username">username.</param>
/// <param name="password">users password.</param>
/// <returns>SqlConnection or null on error.</returns>
public static MySqlConnection CreateMySqlConnection(string datasource,string port,string database,string username,string password)
{
lock(typeof(SqlUtils))
{
try
{
String connectionString=null;
StringBuilder sb=new StringBuilder();
sb.Append("server=").Append(datasource).Append("; ");
sb.Append("user id=").Append(username).Append("; ");
sb.Append("password=").Append(password).Append("; ");
sb.Append("database=").Append(database).Append("; ");
sb.Append("SslMode=").Append("None").Append("; ");
sb.Append("pooling=").Append("true").Append(";");
sb.Append("MinimumPoolSize=").Append(MIN_POOL_SIZE).Append(";");
sb.Append("MaximumPoolSize=").Append(MAX_POOL_SIZE).Append(";");
sb.Append("allow user variables=").Append("true").Append("; ");
sb.Append("default command timeout=").Append("300").Append("; ");
sb.Append("connect timeout=").Append("300").Append(";");
sb.Append("charset=").Append("utf8mb4").Append(" ");
connectionString=sb.ToString();
MySqlConnection connection=new MySqlConnection(connectionString);
connection.Open();
//SetConnectionCollation(connection);
return connection;
}
catch(Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,exception.ToString());
return null;
}
}
}
/// <summary>CreateSqlConnection - Creates an SQL connection.</summary>
/// <param name="datasource">the datasource.</param>
/// <returns>SqlConnection or null on error.</returns>
public static MySqlConnection CreateMySqlConnection(DataSourceEx datasource)
{
lock(typeof(SqlUtils))
{
try
{
String connectionString=null;
StringBuilder sb=new StringBuilder();
sb.Append("server=").Append(datasource.Datasource).Append("; ");
sb.Append("user id=").Append(datasource.Username).Append("; ");
sb.Append("password=").Append(datasource.Password).Append("; ");
sb.Append("database=").Append(datasource.Database).Append("; ");
sb.Append("SslMode=").Append("None").Append("; ");
sb.Append("pooling=").Append("true").Append(";");
sb.Append("allow user variables=").Append("true").Append("; ");
sb.Append("default command timeout=").Append("300").Append("; ");
sb.Append("connect timeout=").Append("300").Append(";");
sb.Append("MinimumPoolSize=").Append(MIN_POOL_SIZE).Append(";");
sb.Append("MaximumPoolSize=").Append(MAX_POOL_SIZE).Append(";");
sb.Append("charset=").Append("utf8mb4").Append(" ");
connectionString=sb.ToString();
MySqlConnection connection=new MySqlConnection(connectionString);
connection.Open();
return connection;
}
catch(Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,exception.ToString());
return null;
}
}
}
public static String FormatDate(DateTime dateTime)
{
return Utility.DateTimeToStringYYYYHMMHDD(dateTime);
}
/// <summary>CreateInClause - Creates an In Clause.</summary>
/// <param name="list">ArrayList of items.</param>
/// <returns>String.</returns>
public static String CreateInClause(ArrayList list)
{
StringBuilder sb=new StringBuilder();
Hashtable hashtable=new Hashtable();
foreach(string item in list)if(!hashtable.ContainsKey(item))hashtable.Add(item,item);
list=new ArrayList(hashtable.Keys);
sb.Append("(");
for(int index=0;index<list.Count;index++)
{
sb.Append("'").Append((string)list[index]).Append("'");
if(index<list.Count-1)sb.Append(",");
}
sb.Append(")");
return sb.ToString();
}
/// <summary>CreateInClause - Creates an In Clause.</summary>
/// <param name="list">List<String></String> of items.</param>
/// <returns>String.</returns>
public static String CreateInClause(List<String> list)
{
StringBuilder sb = new StringBuilder();
Hashtable hashtable = new Hashtable();
foreach (string item in list) if (!hashtable.ContainsKey(item)) hashtable.Add(item, item);
ArrayList uniqueKeys = new ArrayList(hashtable.Keys);
sb.Append("(");
for (int index = 0; index < uniqueKeys.Count; index++)
{
sb.Append("'").Append((string)uniqueKeys[index]).Append("'");
if (index < uniqueKeys.Count - 1) sb.Append(",");
}
sb.Append(")");
return sb.ToString();
}
/// <summary>CreateInClause - Creates an In Clause.</summary>
/// <param name="list">ArrayList of items.</param>
/// <returns>String.</returns>
public static String CreateInClauseInt(List<String> list)
{
ArrayList uniqueList=new ArrayList();
StringBuilder sb=new StringBuilder();
Hashtable hashtable=new Hashtable();
foreach(string item in list)if(!hashtable.ContainsKey(item))hashtable.Add(item,item);
uniqueList=new ArrayList(hashtable.Keys);
sb.Append("(");
for(int index=0;index<uniqueList.Count;index++)
{
sb.Append((string)uniqueList[index]);
if(index<uniqueList.Count-1)sb.Append(",");
}
sb.Append(")");
return sb.ToString();
}
/// <summary>CreateInClause - Creates an In Clause.</summary>
/// <param name="list">ArrayList of items.</param>
/// <returns>String.</returns>
public static String CreateInClauseInt(List<int> list)
{
ArrayList uniqueList=new ArrayList();
StringBuilder sb=new StringBuilder();
Hashtable hashtable=new Hashtable();
foreach(int item in list)if(!hashtable.ContainsKey(item))hashtable.Add(item,item);
uniqueList=new ArrayList(hashtable.Keys);
sb.Append("(");
for(int index=0;index<uniqueList.Count;index++)
{
sb.Append((int)uniqueList[index]);
if(index<uniqueList.Count-1)sb.Append(",");
}
sb.Append(")");
return sb.ToString();
}
/// <summary>CreateInClause - Creates an In Clause.</summary>
/// <param name="list">ArrayList of items.</param>
/// <returns>String.</returns>
public static String CreateInClauseYear(List<DateTime> list)
{
ArrayList uniqueList = new ArrayList();
StringBuilder sb = new StringBuilder();
Hashtable hashtable = new Hashtable();
foreach (DateTime item in list)
{
String strRep = Utility.DateTimeToStringYYYYHMMHDD(item);
if (!hashtable.ContainsKey(strRep)) hashtable.Add(strRep, strRep);
}
uniqueList = new ArrayList(hashtable.Keys);
sb.Append("(");
for (int index = 0; index < uniqueList.Count; index++)
{
sb.Append(Utility.AddQuotes((string)uniqueList[index]));
if (index < uniqueList.Count - 1) sb.Append(",");
}
sb.Append(")");
return sb.ToString();
}
//
public static String CreateInClause(List<int> list)
{
StringBuilder sb = new StringBuilder();
sb.Append("(");
for (int index = 0; index < list.Count; index++)
{
sb.Append(list[index].ToString());
if (index < list.Count - 1) sb.Append(",");
}
sb.Append(")");
return sb.ToString();
}
/// <summary>MinDate - Return minimum sql date.</summary>
/// <returns>DateTime</returns>
public static DateTime MinSqlDate()
{
return SqlDateTime.MinValue.Value;
}
public static String AddQuotes(String item)
{
return "'" + item + "'";
}
public static String SqlDate(DateTime dateTime, bool addQuotes=false)
{
if (Utility.IsEpoch(dateTime)) return null;
return addQuotes?AddQuotes(Utility.DateTimeToStringYYYYHMMHDD(dateTime)):Utility.DateTimeToStringYYYYHMMHDD(dateTime);
}
public static String ToSqlDateTime(DateTime dateTime, bool addQuotes=false)
{
return addQuotes?AddQuotes(Utility.DateTimeToStringYYYYHMMHDDHHMMSS(dateTime)):Utility.DateTimeToStringYYYYHMMHDDHHMMSS(dateTime);
}
public static String ToSqlDateTimeTT(DateTime dateTime, bool addQuotes=false)
{
return addQuotes?AddQuotes(Utility.DateTimeToStringYYYYHMMHDDHHMMSSTT(dateTime)):Utility.DateTimeToStringYYYYHMMHDDHHMMSSTT(dateTime);
}
public static String SqlString(String value,bool addQuotes=false)
{
StringBuilder sb=new StringBuilder();
foreach(char ch in value)
{
sb.Append(ch);
if(ch=='\'')sb.Append("'");
}
return addQuotes?AddQuotes(sb.ToString()):sb.ToString();
}
public static String ToSqlString(String value)
{
return SqlString(value,true);
}
public static string Set(string name,string value)
{
StringBuilder sb=new StringBuilder();
sb.Append("SET ").Append(name).Append("=").Append(AddQuotes(value)).Append(" ").Append(Collation()).Append(";");
return sb.ToString();
}
public static string Set(string name,DateTime date)
{
StringBuilder sb=new StringBuilder();
sb.Append("SET ").Append(name).Append("=").Append(SqlDate(date,true)).Append(" ").Append(Collation()).Append(";");
return sb.ToString();
}
private static string Collation()
{
return "COLLATE "+COLLATION;
}
}
}

View File

@@ -0,0 +1,497 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MarketDataLib.Utility
{
public class Sections
{
private Sections()
{
}
// returns the length of string containing the section.
// Given: "kaskHSkahsKAHSLDFDLFG<article>......</article>ALaks;LKSA;ks;a;SKL;ks;aKS;"
// will return <article>.....</article>
public static String GetItemsInSection(String strInput,String sectionName,ref int searchIndex)
{
String startSection="<"+sectionName;
String endSection="</"+sectionName;
int startIndex=strInput.IndexOf(startSection,searchIndex);
if(-1==startIndex){searchIndex=-1;return null;}
int endIndex=strInput.IndexOf(endSection,startIndex);
if(-1==endIndex){searchIndex=-1;return null;}
searchIndex=endIndex+endSection.Length;
String strContainingString=strInput.Substring(startIndex,(endIndex-startIndex)+endSection.Length+1);
if(String.IsNullOrEmpty(strContainingString))return null;
return strContainingString;
}
public static List<String> GetAllItemsInSections(String strInput, String sectionName)
{
int searchIndex = 0;
List<String> sectionItems = new List<string>();
while (true)
{
String itemsInSection = GetItemsInSection(strInput, sectionName, ref searchIndex);
if(null==itemsInSection)break;
sectionItems.Add(itemsInSection);
searchIndex++;
}
return sectionItems;
}
public static List<String> GetSections(String strInput)
{
try
{
List<String> sections=new List<String>();
int index=0;
String strLiteral=null;
if(null==strInput)return null;
while(index<strInput.Length)
{
char ch=strInput[index];
if(ch=='>')
{
strLiteral=ScanSection(strInput,ref index);
if(null!=strLiteral&&!":??".Equals(strLiteral))
{
if (strLiteral.Contains("&amp;")) strLiteral = strLiteral.Replace("&amp;", "&");
if(strLiteral.Contains("&quot;")) strLiteral=strLiteral.Replace("&quot;","'");
if(strLiteral.Contains("&#039;")) strLiteral=strLiteral.Replace("&#039;","'");
if(strLiteral.Contains("&mdash;")) strLiteral=strLiteral.Replace("&mdash;","-");
if(strLiteral.Contains("&nbsp;")) strLiteral=strLiteral.Replace("&nbsp;"," ");
sections.Add(strLiteral);
}
}
index++;
}
return sections;
}
catch(Exception)
{
return null;
}
}
public static List<String> FlattenSection(List<String> section)
{
List<String> flattened = new List<String>();
foreach(String item in section)
{
if("".Equals(item))continue;
flattened.Add(item);
}
return flattened;
}
public static bool FindInSections(List<String> sections,String startsWith,int startingIndex,ref int indexOfItem,bool findExact=true)
{
for(int index=startingIndex;index<sections.Count;index++)
{
if(!findExact &&sections[index].StartsWith(startsWith))
{
indexOfItem=index;
return true;
}
else if(sections[index].Equals(startsWith))
{
indexOfItem=index;
return true;
}
}
return false;
}
public static bool FindInSectionsReverse(List<String> sections,String startsWith,int startingIndex,ref int indexOfItem,bool findExact=true)
{
for(int index=startingIndex;index>=0;index--)
{
if(!findExact &&sections[index].StartsWith(startsWith))
{
indexOfItem=index;
return true;
}
else if(sections[index].Equals(startsWith))
{
indexOfItem=index;
return true;
}
}
return false;
}
public static String ScanSectionsFindStartWithReturnIndexAfter(List<String> sections, String startsWith, int indexAfter)
{
if (null == sections || 0 == sections.Count) return null;
for (int index = 0; index < sections.Count; index++)
{
String sectionItem = sections[index];
if (null == sectionItem || "".Equals(sectionItem)||!sectionItem.StartsWith(startsWith)) continue;
return sections[index + indexAfter];
}
return null;
}
public static List<String> LocateItems(String strInput,String item,int startIndex,int iterator)
{
List<String> items=new List<String>();
try
{
if(null==item||null==strInput)return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos)return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
if(0==sections.Count||sections.Count<=startIndex)return null;
if(!item.Contains(sections[0])||"".Equals(sections[0]))return null;
for(;startIndex<sections.Count;startIndex+=iterator)
{
String strItem=sections[startIndex];
if("".Equals(strItem)||"-".Equals(strItem))return items;
items.Add(strItem);
}
return items;
}
catch(Exception)
{
return null;
}
}
public static List<String> GetItemSections(String strInput,String item)
{
int startIndex=0;
List<String> items=new List<String>();
try
{
if(null==item||null==strInput)return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos)return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
if(0==sections.Count||sections.Count<=startIndex)return null;
return sections;
}
catch(Exception)
{
return null;
}
}
public static List<String> LocateItems(String strInput,String item)
{
int startIndex=0;
List<String> items=new List<String>();
try
{
if(null==item||null==strInput)return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos)return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
if(0==sections.Count||sections.Count<=startIndex)return null;
if(!item.Contains(sections[0])||"".Equals(sections[0]))return null;
for(;startIndex<sections.Count;startIndex++)
{
String strItem=sections[startIndex];
if(item.Contains(strItem))continue;
if("".Equals(strItem)||"-".Equals(strItem))continue;
if(strItem.All(Char.IsLetter)||strItem.Contains(" "))break;
items.Add(strItem);
}
return items;
}
catch(Exception)
{
return null;
}
}
public static List<int> LocateAllOccurrences(List<String> sections, String item)
{
List<int> itemIndices = new List<int>();
try
{
if(null==item)return null;
if(null==sections||0==sections.Count)return null;
for(int startIndex=0;startIndex<sections.Count;startIndex++)
{
String sectionItem=sections[startIndex];
if(sectionItem.Contains(item))
{
itemIndices.Add(startIndex);
continue;
}
}
return itemIndices;
}
catch(Exception)
{
return null;
}
}
public static List<int> LocateAllOccurrences(String strInput,String item)
{
try
{
List<String> sections=Sections.GetSections(strInput);
return LocateAllOccurrences(sections, item);
}
catch(Exception)
{
return null;
}
}
public static String LocateItem(String strInput,String item,int maxDepth)
{
int startIndex=0;
String strItem=null;
try
{
int depth=0;
if(null==item||null==strInput)return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos)return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
if(null==sections||0==sections.Count)return null;
if(!item.Contains(sections[0])||"".Equals(sections[0]))return null;
startIndex++;
for(;startIndex<sections.Count;startIndex++)
{
String sectionItem=sections[startIndex];
if("".Equals(sectionItem)||"-".Equals(sectionItem)||sectionItem.StartsWith("("))
{
depth++;
if(depth>maxDepth)return null;
continue;
}
strItem=sectionItem;
break;
}
return strItem;
}
catch(Exception)
{
return null;
}
}
public static String LocateItem(String strInput,String item)
{
int startIndex=0;
String strItem=null;
try
{
if(null==item||null==strInput)return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos)return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
if(null==sections||0==sections.Count)return null;
if(!item.Contains(sections[0])||"".Equals(sections[0]))return null;
for(;startIndex<sections.Count;startIndex++)
{
String sectionItem=sections[startIndex];
if(item.Contains(sectionItem))continue;
if("".Equals(sectionItem)||"-".Equals(sectionItem)||"--".Equals(sectionItem)||sectionItem.StartsWith("("))continue;
if((sectionItem.All(Char.IsLetter)||sectionItem.Contains(" ")))break;
strItem=sectionItem;
break;
}
return strItem;
}
catch(Exception)
{
return null;
}
}
public static String LocateItemAcceptAnyText(String strInput,String item)
{
int startIndex=0;
String strItem=null;
try
{
if(null==item||null==strInput)return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos)return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
if(null==sections||0==sections.Count)return null;
if(!item.Contains(sections[0])||"".Equals(sections[0]))return null;
for(;startIndex<sections.Count;startIndex++)
{
String sectionItem=sections[startIndex];
if(item.Contains(sectionItem))continue;
if("".Equals(sectionItem)||"-".Equals(sectionItem)||sectionItem.StartsWith("("))continue;
strItem=sectionItem;
break;
}
return strItem;
}
catch(Exception)
{
return null;
}
}
public static String LocateItemAcceptAnyTextMinDepth(String strInput,String item,int minIndex)
{
int startIndex=0;
String strItem=null;
try
{
if(null==item||null==strInput)return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos)return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
if(null==sections||0==sections.Count)return null;
if(!item.Contains(sections[0])||"".Equals(sections[0]))return null;
for(;startIndex<sections.Count;startIndex++)
{
String sectionItem=sections[startIndex];
if(item.Contains(sectionItem))continue;
if("".Equals(sectionItem)||"-".Equals(sectionItem)||sectionItem.StartsWith("("))continue;
if(startIndex<minIndex)continue;
strItem=sectionItem;
break;
}
if(strItem.Equals("-"))strItem=null;
return strItem;
}
catch(Exception)
{
return null;
}
}
public static String LocateItemMinDepth(String strInput,String item,int minIndex)
{
int startIndex=0;
String strItem=null;
try
{
if(null==item||null==strInput)return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos)return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
if(null==sections||0==sections.Count)return null;
if(!item.Contains(sections[0])||"".Equals(sections[0]))return null;
for(;startIndex<sections.Count;startIndex++)
{
String sectionItem=sections[startIndex];
if(item.Contains(sectionItem))continue;
if("".Equals(sectionItem)||"-".Equals(sectionItem)||sectionItem.StartsWith("("))continue;
if(startIndex<minIndex)continue;
if((sectionItem.All(Char.IsLetter)||sectionItem.Contains(" ")))break;
strItem=sectionItem;
break;
}
return strItem;
}
catch(Exception)
{
return null;
}
}
public static String LocateItemAtDepth(String strInput,String item,int depth)
{
String strItem=null;
try
{
if(null==item||null==strInput) return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos) return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
strItem=Sections.ScanSectionsFindStartWithReturnIndexAfter(sections,item,depth);
if(null==strItem||strItem.Equals("-"))return null;
return strItem;
}
catch(Exception)
{
return null;
}
}
public static String LocateFirstItem(String strInput,String item)
{
int startIndex=0;
String strItem=null;
try
{
if(null==item||null==strInput)return null;
int startPos=strInput.IndexOf(item);
if(-1==startPos)return null;
strInput=strInput.Substring(startPos-1);
List<String> sections=Sections.GetSections(strInput);
if(null==sections||0==sections.Count)return null;
if(!item.Contains(sections[0])||"".Equals(sections[0]))return null;
for(;startIndex<sections.Count;startIndex++)
{
String sectionItem=sections[startIndex];
if(item.Contains(sectionItem))continue;
if("".Equals(sectionItem))continue;
strItem=sectionItem;
break;
}
return strItem;
}
catch(Exception)
{
return null;
}
}
private static String GetItem(String strInput, String item)
{
if (null == strInput) return null;
int startIndex = strInput.IndexOf(item);
if (-1 == startIndex) return null;
strInput = strInput.Substring(startIndex);
String strItem = MarketData.Utils.Utility.BetweenString(strInput, ">", "<");
return strItem;
}
public static String GetFirstNonEmptyItemInSection(List<String> sections, int startingIndex)
{
if(startingIndex>=sections.Count)return null;
for(int index=startingIndex;index < sections.Count;index++)
{
String sectionItem = sections[index].Trim();
if(String.IsNullOrEmpty(sectionItem))continue;
return sectionItem;
}
return null;
}
private static String ScanSection(String strInput, ref int index)
{
try
{
StringBuilder sb=new StringBuilder();
index++;
while(index<strInput.Length)
{
char ch=strInput[index++];
if('<'.Equals(ch))
return sb.ToString().Trim();
sb.Append(ch);
}
return null;
}
catch(Exception)
{
return null;
}
}
}
}

View File

@@ -0,0 +1,97 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace MarketData.Utils
{
public class UpdateManager
{
private StreamWriter streamWriter=null;
private FileStream fileStream=null;
private Dictionary<String,String> entries=new Dictionary<String,String>();
public UpdateManager()
{
}
public bool Prepare(String strPathFileName, int maxAgeDays=5)
{
try
{
String currentWorkingDirectory=Directory.GetCurrentDirectory();
if(!File.Exists(strPathFileName)||IsExpired(strPathFileName, maxAgeDays))
{
if(File.Exists(strPathFileName))File.Delete(strPathFileName);
fileStream=new FileStream(strPathFileName,FileMode.Create);
streamWriter=new StreamWriter(fileStream);
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Creating session file:{0}",strPathFileName));
}
else
{
FileStream fileStream=new FileStream(strPathFileName,FileMode.Open,FileAccess.ReadWrite,FileShare.Read);
StreamReader streamReader=new StreamReader(fileStream);
String strLine=null;
while(null!=(strLine=streamReader.ReadLine()))
{
if(!entries.ContainsKey(strLine))entries.Add(strLine,strLine);
}
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Loaded {0} entries from session file:{1}",entries.Count,strPathFileName));
streamReader.Close();
streamReader.Dispose();
fileStream.Close();
fileStream.Dispose();
fileStream=new FileStream(strPathFileName,FileMode.Append);
streamWriter=new StreamWriter(fileStream);
}
return true;
}
catch(Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Exception:{0}",exception));
return false;
}
}
private bool IsExpired(String strPathFileName, int maxAgeDays)
{
try
{
DateGenerator dateGenerator=new DateGenerator();
DateTime creationTime=File.GetCreationTime(strPathFileName);
int daysElapsed=Math.Abs(dateGenerator.DaysBetweenActual(creationTime,DateTime.Now));
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Ok. {0} is {1} days(s) old. MaxAge:{2} days",strPathFileName,daysElapsed,maxAgeDays));
if(daysElapsed>maxAgeDays)
{
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("{0} is expired. {1} days old. MaxAge:{2} days",strPathFileName,daysElapsed,maxAgeDays));
return true;
}
return false;
}
catch(Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Exception:{0}",exception));
return true;
}
}
public List<String> Entries
{
get{return new List<String>(entries.Keys);}
}
public void Add(String entry)
{
lock(this)
{
if(null==streamWriter)return;
streamWriter.WriteLine(entry);
streamWriter.Flush();
}
}
public void Dispose()
{
if(null!=streamWriter){streamWriter.Close();streamWriter.Dispose();}
if(null!=fileStream){fileStream.Close();fileStream.Dispose();}
}
}
}

View File

@@ -0,0 +1,726 @@
using System;
using System.Text;
using System.IO.Compression;
using System.IO;
using System.Globalization;
using System.Linq;
using System.Collections.Generic;
using Microsoft.Win32;
using System.Diagnostics;
using MarketData.MarketDataModel;
using System.Security.Principal;
using System.Threading;
using ThreadState=System.Threading.ThreadState;
using System.Net;
namespace MarketData.Utils
{
public class Utility
{
private static DateTime epoch = DateTime.Parse("01-01-0001");
private static TimeSpan oneDay=new TimeSpan(1,0,0,0);
public static String ThreadStateToString(Thread thread)
{
switch(thread.ThreadState)
{
case ThreadState.Running :
return "Running";
case ThreadState.StopRequested :
return "StopRequested";
case ThreadState.SuspendRequested :
return "SuspendRequested";
case ThreadState.Background :
return "Background";
case ThreadState.Unstarted :
return "Unstarted";
case ThreadState.Stopped :
return "Stopped";
case ThreadState.WaitSleepJoin :
return "WaitSleepJoin";
case ThreadState.Suspended :
return "Suspended";
case ThreadState.AbortRequested :
return "AbortRequested";
case ThreadState.Aborted :
return "Aborted";
default :
return "Unknown";
}
}
/// <summary>
/// poses a question to the console and receives a confirmation response
/// </summary>
/// <param name="message">The message to ask the user.</param>
public static bool GetVerificationToProceed(String message)
{
Console.Write(String.Format("{0} Y/N? ",message));
String answer = Console.ReadLine();
answer=answer.ToUpper();
if(!"Y".Equals(answer))return false;
return true;
}
public static long DateToUnixDate(DateTime dateTime)
{
DateTime javascriptEpoch=DateTime.Parse("01-01-1970 00:00:00");
DateTime eod=new DateTime(dateTime.Year,dateTime.Month,dateTime.Day,23,0,0); // request end of day
TimeSpan ts=eod-javascriptEpoch;
long longDate=(long)ts.TotalSeconds;
return longDate;
}
public static DateTime UnixDateToDate(long yahooDate)
{
DateTime javascriptEpoch=DateTime.Parse("01-01-1970 00:00:00");
TimeSpan timespan=TimeSpan.FromSeconds((double)yahooDate);
DateTime date=javascriptEpoch+timespan;
return date;
}
public static void RemoveLogFiles(String strFolder=null)
{
if(null==strFolder)strFolder=Directory.GetCurrentDirectory();
String[] logFiles=Directory.GetFiles(strFolder);
if(null==logFiles || 0==logFiles.Length)return;
logFiles=logFiles.Where(x => x.EndsWith(".log",StringComparison.InvariantCultureIgnoreCase)).ToArray<String>();
if(null==logFiles || 0==logFiles.Length)return;
foreach(String logFile in logFiles)
{
try
{
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("Removing {0}",logFile));
File.Delete(logFile);
}
catch(Exception){;}
}
}
public static String Pad(string str, char filler, int length)
{
int stringLength = str.Length;
if (stringLength >= length) return str;
StringBuilder sb = new StringBuilder();
while (stringLength < length)
{
sb.Append(filler);
stringLength++;
}
return sb.ToString() + str;
}
public static bool Is64Bit()
{
if(IntPtr.Size.Equals(8))return true;
return false;
}
public static bool IsAdministrator()
{
return (new WindowsPrincipal(WindowsIdentity.GetCurrent())).IsInRole(WindowsBuiltInRole.Administrator);
}
public static String ToUTF8(String str)
{
if(null==str)return str;
return Encoding.UTF8.GetString(Encoding.Default.GetBytes(str));
}
public static String RemoveHtml(String strItem)
{
if(null==strItem)return null;
String[] codes = { "&#x27;","&#187;" };
if(null==strItem)return strItem;
foreach (String code in codes)
{
strItem = strItem.Replace(code,"'");
}
strItem=strItem.Replace("&amp;","&");
strItem=strItem.Replace(@"\\u0026","&");
strItem=strItem.Replace("&#x2018;","'");
strItem=strItem.Replace("&#x2019;","'");
strItem=strItem.Replace("&#x2014;","-");
strItem=strItem.Replace("&#x201C;",@"""");
strItem=strItem.Replace("&#x201c;",@"""");
strItem=strItem.Replace("&#x201D;",@"""");
strItem=strItem.Replace("&#x201d;",@"""");
strItem=strItem.Replace("&#x2013;","-");
strItem=strItem.Replace("&#39;","'");
return strItem;
}
public static String RemoveDivs(String strItem)
{
StringBuilder sb=new StringBuilder();
bool inDiv=false;
if(null==strItem)return strItem;
for(int index=0;index<strItem.Length;index++)
{
char ch=strItem[index];
if(ch.Equals('<'))inDiv=true;
else if(ch.Equals('>'))inDiv=false;
else if(!inDiv)sb.Append(ch);
}
return sb.ToString();
}
public static int CharToNum(char ch)
{
return (int)ch-48;
}
public static String RemoveCC(String item)
{
StringBuilder sb=new StringBuilder();
foreach(char ch in item)
{
if(!Char.IsControl(ch)) sb.Append(ch);
}
return sb.ToString();
}
public static Stream StreamFromString(string s)
{
var stream=new MemoryStream();
var writer=new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position=0;
return stream;
}
public static String RemoveQuotes(String strItem)
{
if (String.IsNullOrEmpty(strItem)) return null;
if(strItem.StartsWith("\""))strItem=strItem.Substring(1);
if(strItem.EndsWith("\""))strItem=strItem.Substring(0,strItem.Length-1);
return strItem;
}
public static String BetweenString(String strItem, String strBegin, String strEnd)
{
if (null == strItem) return null;
int index=-1;
if(null==strBegin)index=0;
else index = strItem.IndexOf(strBegin);
if (-1 == index) return null;
String str = null;
if(null!=strBegin)str=strItem.Substring(index + strBegin.Length);
else str=strItem;
if(null==strEnd)return str;
index = str.IndexOf(strEnd);
if (-1 == index) return null;
StringBuilder sb = new StringBuilder();
for (int strIndex = 0; strIndex < str.Length; strIndex++)
{
if (index == strIndex) break;
sb.Append(str[strIndex]);
}
return sb.ToString();
}
public static String RemoveAfter(String strItem, char charItem)
{
StringBuilder sb = new StringBuilder();
for (int index = 0; index < strItem.Length; index++)
{
char ch = strItem[index];
if (ch.Equals(charItem)) break;
sb.Append(ch);
}
return sb.ToString();
}
public static bool OutOfRange(double value)
{
return value > 100000000000000000000.00 || value< -99999999999999999999.99;
}
public static String RemoveControlChars(String strItem)
{
StringBuilder sb=new StringBuilder();
for(int index=0;index<strItem.Length;index++)
{
char ch=strItem[index];
if(!char.IsControl(ch))sb.Append(ch);
}
return sb.ToString();
}
public static String GetPath(String strPathFileName)
{
int index=strPathFileName.LastIndexOf('\\');
if (-1 == index) return null;
String strPath = strPathFileName.Substring(0, index);
return strPath;
}
public static String GetFileNameNoExtension(String pathFileName)
{
if(null==pathFileName)return null;
pathFileName = Path.GetFileName(pathFileName);
pathFileName=Utility.BetweenString(pathFileName,null,".");
return pathFileName;
}
public static String KeepBefore(String strItem,String strKeepBefore)
{
int startPos=strItem.IndexOf(strKeepBefore);
if(-1==startPos)return null;
return strItem.Substring(0,startPos);
}
public static String KeepAfter(String strItem,String strKeepAfter)
{
int startPos=strItem.IndexOf(strKeepAfter);
if(-1==startPos)return null;
return strItem.Substring(startPos+strKeepAfter.Length);
}
public static String KeepAfterLast(String strItem,String strKeepAfter)
{
if(null==strItem)return null;
int startPos=strItem.LastIndexOf(strKeepAfter);
if(-1==startPos)return null;
return strItem.Substring(startPos+strKeepAfter.Length);
}
public static String Find(String strItem,String search,char delimeter)
{
if(null==strItem)return null;
bool foundDelimeter=false;
StringBuilder sb=new StringBuilder();
int startPos=strItem.LastIndexOf(search);
if(-1==startPos)return null;
startPos+=search.Length;
for(;startPos<strItem.Length;startPos++)
{
char ch=strItem[startPos];
if(ch.Equals(delimeter))
{
foundDelimeter=true;
break;
}
sb.Append(ch);
}
if(!foundDelimeter)return null;
return sb.ToString();
}
public static String FindFirst(String strItem,String search,char delimeter)
{
if(null==strItem)return null;
bool foundDelimeter=false;
StringBuilder sb=new StringBuilder();
int startPos=strItem.IndexOf(search);
if(-1==startPos)return null;
startPos+=search.Length;
for(;startPos<strItem.Length;startPos++)
{
char ch=strItem[startPos];
if(ch.Equals(delimeter))
{
foundDelimeter=true;
break;
}
sb.Append(ch);
}
if(!foundDelimeter)return null;
return sb.ToString();
}
public static String AddQuotes(String item)
{
return "\"" + item + "\"";
}
public static long DateToLong(DateTime date)
{
int year = date.Year;
int month = date.Month;
int day = date.Day;
return (year * 10000) + (month * 100) + day;
}
public static DateTime LongToDate(long longDate)
{
int year = (int)(longDate / 10000);
int month = ((int)longDate / 100) - year * 100;
int day = (int)(longDate - ((int)(longDate / 100)) * 100);
return new DateTime(year, month, day);
}
public static String DayOfWeekToString(DayOfWeek dayOfWeek)
{
switch(dayOfWeek)
{
case System.DayOfWeek.Monday: return "Monday";
case System.DayOfWeek.Tuesday: return "Tuesday";
case System.DayOfWeek.Wednesday: return "Wednesday";
case System.DayOfWeek.Thursday: return "Thursday";
case System.DayOfWeek.Friday: return "Friday";
case System.DayOfWeek.Saturday: return "Saturday";
case System.DayOfWeek.Sunday: return "Sunday";
default: return "";
}
}
public static String DateTimeToStringMMMM(DateTime dateTime)
{
if (Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("MMMM");
}
public static String DateTimeToStringMMM(DateTime dateTime)
{
if (Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("MMM");
}
public static String DateTimeToStringHHMMSS(DateTime dateTime)
{
if (Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("HH:mm:ss");
}
public static String DateTimeToStringMMSDDSYYYY(DateTime dateTime)
{
if (Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("MM/dd/yyyy");
}
public static String DateTimeToStringMMSDDSYYYYHHMMSS(DateTime dateTime)
{
if (Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("MM/dd/yyyy hh:mm:ss");
}
public static String DateTimeToStringMMHDDHYYYY(DateTime dateTime)
{
if (Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("MM-dd-yyyy");
}
public static String DateTimeToStringYYYYHMMHDD(DateTime dateTime)
{
if (Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("yyyy-MM-dd");
}
public static String DateTimeToStringYYYYHMMHDDHHMMSS(DateTime dateTime)
{
if (Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("yyyy-MM-dd hh:mm:ss");
}
public static String DateTimeToStringYYYYHMMHDDHHMMSSTT(DateTime dateTime)
{
if(Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("yyyy-MM-dd hh:mm:ss tt");
}
public static String DateTimeToStringYYYYMMDDMMSSTT(DateTime dateTime)
{
if(Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("yyyyMMddhhmmsstt");
}
public static String DateTimeToStringYYYYMMDD(DateTime dateTime)
{
if (Utility.IsEpoch(dateTime)) return "";
return dateTime.ToString("yyyyMMdd");
}
public static String AsteriskForString(String str)
{
StringBuilder sb = new StringBuilder();
int length = str.Length;
for (int index = 0; index < length; index++) sb.Append("*");
return sb.ToString();
}
public static String FormatNumber(double number)
{
StringBuilder sb=new StringBuilder();
if (double.NaN.Equals(number))sb.Append("N/A");
else sb.Append(String.Format("{0:0.000}", number));
return sb.ToString();
}
public static String FormatNumber(double number,int places,bool commas=false)
{
StringBuilder sb = new StringBuilder();
StringBuilder formatString=new StringBuilder();
if (commas&&Math.Abs(number)>=1000.00) formatString.Append("{0:0,0.");
else formatString.Append("{0:0.");
for(int index=0;index<places;index++)formatString.Append("0");
formatString.Append("}");
if (double.NaN.Equals(number)) sb.Append("N/A");
else sb.Append(String.Format(formatString.ToString(), number));
return sb.ToString();
}
public static String FormatCurrency(double number)
{
StringBuilder sb=new StringBuilder();
if (double.NaN.Equals(number))sb.Append("N/A");
else sb.Append(String.Format("{0:C}", number));
return sb.ToString();
}
public static String FormatPrice(double price)
{
return FormatCurrency(price, 3);
}
public static String FormatCurrency(double number,int decimals)
{
StringBuilder sb=new StringBuilder();
String currencyFormat="{0:C"+decimals+"}";
if (double.NaN.Equals(number))sb.Append("N/A");
else sb.Append(String.Format(currencyFormat, number));
return sb.ToString();
}
public static String FormatPercent(double number)
{
StringBuilder sb = new StringBuilder();
if (double.NaN.Equals(number)) sb.Append("N/A");
else sb.Append(String.Format("{0:P}", number));
return sb.ToString();
}
public static String FormatPercent(double number,int places)
{
StringBuilder sb=new StringBuilder();
String formatString="{0:P"+places+"}";
if(double.NaN.Equals(number)) sb.Append("N/A");
else sb.Append(String.Format(formatString,number));
return sb.ToString();
}
public static String ConformDate(String strDate)
{
String[] elements=strDate.Split(' ');
if(elements.Length<3)return strDate;
return elements[0]+" "+elements[1]+" "+elements[2];
}
public static DateTime ParseDate(String strDate)
{
System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("en-US");
String[] formats=new[] { "MM/dd/yyyy HH:MM tt", "yyyy-MM-dd","yy-MM-dd","yyyy-MM-dd hh:mm:ss tt","dddd, MMMM dd","MMM dd yyyy","yyyy-MM","ddd, MMM. d","ddd, MMM. dd","yyyy/MM/dd","M-d-yyyy","dd-MM-yyyy","MM-dd-yyyy","M.d.yyyy","dd.MM.yyyy","MM.dd.yyyy","yyyyMMdd" }.Union(cultureInfo.DateTimeFormat.GetAllDateTimePatterns()).ToArray();
strDate = strDate.Trim();
DateTime dateTime=DateTime.ParseExact(strDate, formats, cultureInfo, DateTimeStyles.AssumeLocal);
return dateTime;
}
public static double ParsePercent(String strPercent)
{
if (null == strPercent) return double.NaN;
strPercent = strPercent.Replace("%", null);
try { return double.Parse(strPercent)/100.00; }
catch (Exception) { return double.NaN; }
}
public static double ParseCurrency(String strNumber)
{
if (null == strNumber) return double.NaN;
if(Constants.CONST_DASHES.Equals(strNumber))return double.NaN;
strNumber = strNumber.Replace("$", null);
strNumber = strNumber.Replace(",", null);
strNumber = strNumber.Replace("(", "-");
strNumber = strNumber.Replace(")", null);
if (strNumber.Equals("")) return double.NaN;
try { return double.Parse(strNumber); }
catch (Exception) { return double.NaN; }
}
public static String FormatCurrencyWithQuotes(double number)
{
return AddQuotes(FormatCurrency(number));
}
public static String FormatDates(DateTime d1, DateTime d2)
{
StringBuilder sb=new StringBuilder();
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(d1)).Append("-");
sb.Append(Utility.DateTimeToStringMMSDDSYYYY(d2));
return sb.ToString();
}
public static String TrimToSpace(String strString)
{
if (null == strString) return strString;
StringBuilder sb = new StringBuilder();
for (int index = 0; index < strString.Length; index++)
{
char ch=strString[index];
if (' '.Equals(ch)) break;
sb.Append(ch);
}
return sb.ToString();
}
public static String BooleanToYesNoString(bool booleanValue)
{
return booleanValue ? "Yes" : "No";
}
public static bool IsEpoch(DateTime dateTime)
{
return dateTime.Equals(epoch);
}
public static DateTime Epoch
{
get { return epoch; }
}
public static TimeSpan OneDay
{
get{return oneDay;}
}
public static String ListToString(List<String> list,char separator=',')
{
StringBuilder sb=new StringBuilder();
if (null == list || 0 == list.Count) return null;
for(int index=0;index<list.Count;index++)
{
sb.Append(list[index]);
if(index<list.Count-1)sb.Append(separator);
}
return sb.ToString();
}
public static List<String> ToList(String items,char separator=',')
{
List<String> list = items.Split(separator).ToList<String>();
list=(from String str in list where !String.IsNullOrEmpty(str) select str.Trim()).ToList<String>();
return list;
}
public static String FromList(List<String> items,String postFix=",")
{
StringBuilder sb=new StringBuilder();
for(int index=0;index<items.Count;index++)
{
sb.Append(items[index]);
if(index<items.Count-1)sb.Append(postFix);
}
return sb.ToString();
}
public static byte[] Compress(String strString)
{
MemoryStream outputStream = null;
GZipStream compressionStream = null;
try
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strString);
outputStream = new MemoryStream();
compressionStream = new GZipStream(outputStream, CompressionMode.Compress, true);
compressionStream.Write(bytes, 0, bytes.Length);
compressionStream.Close();
compressionStream = null;
byte[] outputBytes = outputStream.ToArray();
outputStream.Close();
outputStream = null;
return outputBytes;
}
catch (Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,exception);
return null;
}
finally
{
if (null != compressionStream)
{
compressionStream.Close();
compressionStream = null;
}
if (null != outputStream)
{
outputStream.Close();
outputStream = null;
}
}
}
public static String Decompress(byte[] compressedBytes)
{
MemoryStream compressedStream = new MemoryStream(compressedBytes);
GZipStream decompressionStream = new GZipStream(compressedStream, CompressionMode.Decompress,true);
MemoryStream outputStream=new MemoryStream();
try
{
byte[] decompressedBytesBuffer = new byte[4096];
int count = 0;
while (true)
{
count = decompressionStream.Read(decompressedBytesBuffer, 0, decompressedBytesBuffer.Length);
if (count > 0) outputStream.Write(decompressedBytesBuffer, 0, count);
else break;
}
decompressionStream.Close();
compressedStream.Close();
String strDecompressed = System.Text.Encoding.UTF8.GetString(outputStream.ToArray());
outputStream.Close();
outputStream = null;
compressedStream = null;
decompressionStream = null;
return strDecompressed;
}
catch (Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,exception);
return null;
}
finally
{
if (null != outputStream)
{
outputStream.Close();
outputStream = null;
}
if (null != decompressionStream)
{
decompressionStream.Close();
decompressionStream = null;
}
if (null != compressedStream)
{
compressedStream.Close();
compressedStream = null;
}
}
}
public static void LaunchBrowserSearch(String searchTerm)
{
Process.Start("https://www.google.com/search?q="+Uri.EscapeDataString(searchTerm)+"/");
}
public static bool IsZeroOrNaN(double value)
{
return IsNaN(value)||IsZero(value);
}
private static bool IsZero(double value)
{
if(value==0.00)return true;
return false;
}
private static bool IsNaN(double value)
{
return double.IsNaN(value);
}
public static bool DeleteFile(String pathFileName)
{
if(!File.Exists(pathFileName))return false;
try{File.Delete(pathFileName);}catch(Exception){return false;}
return true;
}
public static bool CopyFile(String pathSrcFileName,String pathDstFileName)
{
if(!File.Exists(pathSrcFileName))return false;
try{File.Copy(pathSrcFileName,pathDstFileName);}catch(Exception){return false;}
return true;
}
private static DateTime GetRunDate(String strPathFileName)
{
DateTime runDate=DateTime.Now.Date;
DateGenerator dateGenerator=new DateGenerator();
StreamWriter streamWriter=null;
StreamReader streamReader=null;
try
{
if(!File.Exists(strPathFileName))
{
streamWriter=File.CreateText(strPathFileName);
streamWriter.WriteLine(Utility.DateTimeToStringMMHDDHYYYY(runDate));
streamWriter.Flush();
streamWriter.Close();
streamWriter=null;
return runDate;
}
streamReader=File.OpenText(strPathFileName);
String strLine=streamReader.ReadLine();
streamReader.Close();
streamReader=null;
runDate=Utility.ParseDate(strLine);
if(dateGenerator.DaysBetweenActual(runDate,DateTime.Now)>5)
{
File.Delete(strPathFileName);
runDate=DateTime.Now.Date;
streamWriter=File.CreateText(strPathFileName);
streamWriter.WriteLine(Utility.DateTimeToStringMMHDDHYYYY(runDate));
streamWriter.Flush();
streamWriter.Close();
streamWriter=null;
return runDate;
}
return runDate;
}
catch(Exception exception)
{
MDTrace.WriteLine(LogLevel.DEBUG,String.Format("GetRunDate:{0}",exception.ToString()));
return runDate;
}
finally
{
if(null!=streamWriter)streamWriter.Close();
if(null!=streamReader)streamReader.Close();
}
}
}
}