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";
}
}
///
/// poses a question to the console and receives a confirmation response
///
/// The message to ask the user.
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();
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 void RemoveLogFilesExcept(String exceptFile,String strFolder=null)
{
if(null==strFolder)strFolder=Directory.GetCurrentDirectory();
String[] logFiles=Directory.GetFiles(strFolder,"*.log");
if(null==logFiles || 0==logFiles.Length)return;
logFiles=logFiles
.Where(x => x.EndsWith(".log",StringComparison.InvariantCultureIgnoreCase) &&
!x.EndsWith(exceptFile,StringComparison.InvariantCultureIgnoreCase)).ToArray();
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 = { "'","»" };
if(null==strItem)return strItem;
foreach (String code in codes)
{
strItem = strItem.Replace(code,"'");
}
strItem=strItem.Replace("&","&");
strItem=strItem.Replace(@"\\u0026","&");
strItem=strItem.Replace("‘","'");
strItem=strItem.Replace("’","'");
strItem=strItem.Replace("—","-");
strItem=strItem.Replace("“",@"""");
strItem=strItem.Replace("“",@"""");
strItem=strItem.Replace("”",@"""");
strItem=strItem.Replace("”",@"""");
strItem=strItem.Replace("–","-");
strItem=strItem.Replace("'","'");
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'))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=1000.00) formatString.Append("{0:0,0.");
else formatString.Append("{0:0.");
for(int index=0;index list,char separator=',')
{
StringBuilder sb=new StringBuilder();
if (null == list || 0 == list.Count) return null;
for(int index=0;index ToList(String items,char separator=',')
{
List list = items.Split(separator).ToList();
list=(from String str in list where !String.IsNullOrEmpty(str) select str.Trim()).ToList();
return list;
}
public static String FromList(List items,String postFix=",")
{
StringBuilder sb=new StringBuilder();
for(int index=0;index 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();
}
}
}
}