This commit is contained in:
2024-02-23 00:41:24 -05:00
commit 1f1079a71c
16 changed files with 2457 additions and 0 deletions

330
.gitignore vendored Normal file
View File

@@ -0,0 +1,330 @@
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
bld/
[Bb]in/
[Oo]bj/
[Ll]og/
# Visual Studio 2015/2017 cache/options directory
.vs/
# Uncomment if you have tasks that create the project's static files in wwwroot
#wwwroot/
# Visual Studio 2017 auto generated files
Generated\ Files/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
# NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
# Benchmark Results
BenchmarkDotNet.Artifacts/
# .NET Core
project.lock.json
project.fragment.lock.json
artifacts/
**/Properties/launchSettings.json
# StyleCop
StyleCopReport.xml
# Files built by Visual Studio
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.iobj
*.pch
*.pdb
*.ipdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opendb
*.opensdf
*.sdf
*.cachefile
*.VC.db
*.VC.VC.opendb
# Visual Studio profiler
*.psess
*.vsp
*.vspx
*.sap
# Visual Studio Trace Files
*.e2e
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding add-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# AxoCover is a Code Coverage Tool
.axoCover/*
!.axoCover/settings.json
# Visual Studio code coverage results
*.coverage
*.coveragexml
# NCrunch
_NCrunch_*
.*crunch*.local.xml
nCrunchTemp_*
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
# Note: Comment the next line if you want to checkin your web deploy settings,
# but database connection strings (with potential passwords) will be unencrypted
*.pubxml
*.publishproj
# Microsoft Azure Web App publish settings. Comment the next line if you want to
# checkin your Azure Web App publish settings, but sensitive information contained
# in these scripts will be unencrypted
PublishScripts/
# NuGet Packages
*.nupkg
# The packages folder can be ignored because of Package Restore
**/[Pp]ackages/*
# except build/, which is used as an MSBuild target.
!**/[Pp]ackages/build/
# Uncomment if necessary however generally it will be regenerated when needed
#!**/[Pp]ackages/repositories.config
# NuGet v3's project.json files produces more ignorable files
*.nuget.props
*.nuget.targets
# Microsoft Azure Build Output
csx/
*.build.csdef
# Microsoft Azure Emulator
ecf/
rcf/
# Windows Store app package directories and files
AppPackages/
BundleArtifacts/
Package.StoreAssociation.xml
_pkginfo.txt
*.appx
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
# Others
ClientBin/
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.jfm
*.pfx
*.publishsettings
orleans.codegen.cs
# Including strong name files can present a security risk
# (https://github.com/github/gitignore/pull/2483#issue-259490424)
#*.snk
# Since there are multiple workflows, uncomment next line to ignore bower_components
# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
#bower_components/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
ServiceFabricBackup/
*.rptproj.bak
# SQL Server files
*.mdf
*.ldf
*.ndf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
*.rptproj.rsuser
# Microsoft Fakes
FakesAssemblies/
# GhostDoc plugin setting file
*.GhostDoc.xml
# Node.js Tools for Visual Studio
.ntvs_analysis.dat
node_modules/
# Visual Studio 6 build log
*.plg
# Visual Studio 6 workspace options file
*.opt
# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
*.vbw
# Visual Studio LightSwitch build output
**/*.HTMLClient/GeneratedArtifacts
**/*.DesktopClient/GeneratedArtifacts
**/*.DesktopClient/ModelManifest.xml
**/*.Server/GeneratedArtifacts
**/*.Server/ModelManifest.xml
_Pvt_Extensions
# Paket dependency manager
.paket/paket.exe
paket-files/
# FAKE - F# Make
.fake/
# JetBrains Rider
.idea/
*.sln.iml
# CodeRush
.cr/
# Python Tools for Visual Studio (PTVS)
__pycache__/
*.pyc
# Cake - Uncomment if you are using it
# tools/**
# !tools/packages.config
# Tabs Studio
*.tss
# Telerik's JustMock configuration file
*.jmconfig
# BizTalk build output
*.btp.cs
*.btm.cs
*.odx.cs
*.xsd.cs
# OpenCover UI analysis results
OpenCover/
# Azure Stream Analytics local run output
ASALocalRun/
# MSBuild Binary and Structured Log
*.binlog
# NVidia Nsight GPU debugger configuration file
*.nvuser
# MFractors (Xamarin productivity tool) working folder
.mfractor/

10
App.config Normal file
View File

@@ -0,0 +1,10 @@
<?xml version="1.0"?>
<configuration>
<appSettings>
<add key="market_data" value="Database=market_data;Datasource=localhost;Username=root;Password=dbas"/>
<add key="portfolio_data" value="Database=portfolio_data;Datasource=localhost;Username=root;Password=dbas"/>
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.2"/>
</startup>
</configuration>

BIN
Assemblies/MySql.Data.dll Normal file

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@@ -0,0 +1,200 @@
<?xml version="1.0" encoding="utf-8"?><doc>
<assembly>
<name>System.Runtime.CompilerServices.Unsafe</name>
</assembly>
<members>
<member name="T:System.Runtime.CompilerServices.Unsafe">
<summary>Contains generic, low-level functionality for manipulating pointers.</summary>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.Add``1(``0@,System.Int32)">
<summary>Adds an element offset to the given reference.</summary>
<param name="source">The reference to add the offset to.</param>
<param name="elementOffset">The offset to add.</param>
<typeparam name="T">The type of reference.</typeparam>
<returns>A new reference that reflects the addition of offset to pointer.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.Add``1(``0@,System.IntPtr)">
<summary>Adds an element offset to the given reference.</summary>
<param name="source">The reference to add the offset to.</param>
<param name="elementOffset">The offset to add.</param>
<typeparam name="T">The type of reference.</typeparam>
<returns>A new reference that reflects the addition of offset to pointer.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.AddByteOffset``1(``0@,System.IntPtr)">
<summary>Adds a byte offset to the given reference.</summary>
<param name="source">The reference to add the offset to.</param>
<param name="byteOffset">The offset to add.</param>
<typeparam name="T">The type of reference.</typeparam>
<returns>A new reference that reflects the addition of byte offset to pointer.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.AreSame``1(``0@,``0@)">
<summary>Determines whether the specified references point to the same location.</summary>
<param name="left">The first reference to compare.</param>
<param name="right">The second reference to compare.</param>
<typeparam name="T">The type of reference.</typeparam>
<returns>true if <paramref name="left">left</paramref> and <paramref name="right">right</paramref> point to the same location; otherwise, false.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.As``1(System.Object)">
<summary>Casts the given object to the specified type.</summary>
<param name="o">The object to cast.</param>
<typeparam name="T">The type which the object will be cast to.</typeparam>
<returns>The original object, casted to the given type.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.As``2(``0@)">
<summary>Reinterprets the given reference as a reference to a value of type <typeparamref name="TTo">TTo</typeparamref>.</summary>
<param name="source">The reference to reinterpret.</param>
<typeparam name="TFrom">The type of reference to reinterpret..</typeparam>
<typeparam name="TTo">The desired type of the reference.</typeparam>
<returns>A reference to a value of type <typeparamref name="TTo">TTo</typeparamref>.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.AsPointer``1(``0@)">
<summary>Returns a pointer to the given by-ref parameter.</summary>
<param name="value">The object whose pointer is obtained.</param>
<typeparam name="T">The type of object.</typeparam>
<returns>A pointer to the given value.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.AsRef``1(System.Void*)">
<summary>Reinterprets the given location as a reference to a value of type <typeparamref name="T">T</typeparamref>.</summary>
<param name="source">The location of the value to reference.</param>
<typeparam name="T">The type of the interpreted location.</typeparam>
<returns>A reference to a value of type <typeparamref name="T">T</typeparamref>.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.ByteOffset``1(``0@,``0@)">
<summary>Determines the byte offset from origin to target from the given references.</summary>
<param name="origin">The reference to origin.</param>
<param name="target">The reference to target.</param>
<typeparam name="T">The type of reference.</typeparam>
<returns>Byte offset from origin to target i.e. <paramref name="target">target</paramref> - <paramref name="origin">origin</paramref>.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.Copy``1(System.Void*,``0@)">
<summary>Copies a value of type <typeparamref name="T">T</typeparamref> to the given location.</summary>
<param name="destination">The location to copy to.</param>
<param name="source">A reference to the value to copy.</param>
<typeparam name="T">The type of value to copy.</typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.Copy``1(``0@,System.Void*)">
<summary>Copies a value of type <typeparamref name="T">T</typeparamref> to the given location.</summary>
<param name="destination">The location to copy to.</param>
<param name="source">A pointer to the value to copy.</param>
<typeparam name="T">The type of value to copy.</typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.CopyBlock(System.Byte@,System.Byte@,System.UInt32)">
<summary>Copies bytes from the source address to the destination address.</summary>
<param name="destination">The destination address to copy to.</param>
<param name="source">The source address to copy from.</param>
<param name="byteCount">The number of bytes to copy.</param>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.CopyBlock(System.Void*,System.Void*,System.UInt32)">
<summary>Copies bytes from the source address to the destination address.</summary>
<param name="destination">The destination address to copy to.</param>
<param name="source">The source address to copy from.</param>
<param name="byteCount">The number of bytes to copy.</param>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.CopyBlockUnaligned(System.Void*,System.Void*,System.UInt32)">
<summary>Copies bytes from the source address to the destination address
without assuming architecture dependent alignment of the addresses.</summary>
<param name="destination">The destination address to copy to.</param>
<param name="source">The source address to copy from.</param>
<param name="byteCount">The number of bytes to copy.</param>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.CopyBlockUnaligned(System.Byte@,System.Byte@,System.UInt32)">
<summary>Copies bytes from the source address to the destination address
without assuming architecture dependent alignment of the addresses.</summary>
<param name="destination">The destination address to copy to.</param>
<param name="source">The source address to copy from.</param>
<param name="byteCount">The number of bytes to copy.</param>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.InitBlock(System.Byte@,System.Byte,System.UInt32)">
<summary>Initializes a block of memory at the given location with a given initial value.</summary>
<param name="startAddress">The address of the start of the memory block to initialize.</param>
<param name="value">The value to initialize the block to.</param>
<param name="byteCount">The number of bytes to initialize.</param>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.InitBlock(System.Void*,System.Byte,System.UInt32)">
<summary>Initializes a block of memory at the given location with a given initial value.</summary>
<param name="startAddress">The address of the start of the memory block to initialize.</param>
<param name="value">The value to initialize the block to.</param>
<param name="byteCount">The number of bytes to initialize.</param>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(System.Byte@,System.Byte,System.UInt32)">
<summary>Initializes a block of memory at the given location with a given initial value
without assuming architecture dependent alignment of the address.</summary>
<param name="startAddress">The address of the start of the memory block to initialize.</param>
<param name="value">The value to initialize the block to.</param>
<param name="byteCount">The number of bytes to initialize.</param>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.InitBlockUnaligned(System.Void*,System.Byte,System.UInt32)">
<summary>Initializes a block of memory at the given location with a given initial value
without assuming architecture dependent alignment of the address.</summary>
<param name="startAddress">The address of the start of the memory block to initialize.</param>
<param name="value">The value to initialize the block to.</param>
<param name="byteCount">The number of bytes to initialize.</param>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.Read``1(System.Void*)">
<summary>Reads a value of type <typeparamref name="T">T</typeparamref> from the given location.</summary>
<param name="source">The location to read from.</param>
<typeparam name="T">The type to read.</typeparam>
<returns>An object of type <typeparamref name="T">T</typeparamref> read from the given location.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.ReadUnaligned``1(System.Byte@)">
<summary>Reads a value of type <typeparamref name="T">T</typeparamref> from the given location
without assuming architecture dependent alignment of the addresses.</summary>
<param name="source">The location to read from.</param>
<typeparam name="T">The type to read.</typeparam>
<returns>An object of type <typeparamref name="T">T</typeparamref> read from the given location.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.ReadUnaligned``1(System.Void*)">
<summary>Reads a value of type <typeparamref name="T">T</typeparamref> from the given location
without assuming architecture dependent alignment of the addresses.</summary>
<param name="source">The location to read from.</param>
<typeparam name="T">The type to read.</typeparam>
<returns>An object of type <typeparamref name="T">T</typeparamref> read from the given location.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.SizeOf``1">
<summary>Returns the size of an object of the given type parameter.</summary>
<typeparam name="T">The type of object whose size is retrieved.</typeparam>
<returns>The size of an object of type <typeparamref name="T">T</typeparamref>.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.Subtract``1(``0@,System.Int32)">
<summary>Subtracts an element offset from the given reference.</summary>
<param name="source">The reference to subtract the offset from.</param>
<param name="elementOffset">The offset to subtract.</param>
<typeparam name="T">The type of reference.</typeparam>
<returns>A new reference that reflects the subraction of offset from pointer.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.Subtract``1(``0@,System.IntPtr)">
<summary>Subtracts an element offset from the given reference.</summary>
<param name="source">The reference to subtract the offset from.</param>
<param name="elementOffset">The offset to subtract.</param>
<typeparam name="T">The type of reference.</typeparam>
<returns>A new reference that reflects the subraction of offset from pointer.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.SubtractByteOffset``1(``0@,System.IntPtr)">
<summary>Subtracts a byte offset from the given reference.</summary>
<param name="source">The reference to subtract the offset from.</param>
<param name="byteOffset"></param>
<typeparam name="T">The type of reference.</typeparam>
<returns>A new reference that reflects the subraction of byte offset from pointer.</returns>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.Write``1(System.Void*,``0)">
<summary>Writes a value of type <typeparamref name="T">T</typeparamref> to the given location.</summary>
<param name="destination">The location to write to.</param>
<param name="value">The value to write.</param>
<typeparam name="T">The type of value to write.</typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.WriteUnaligned``1(System.Byte@,``0)">
<summary>Writes a value of type <typeparamref name="T">T</typeparamref> to the given location
without assuming architecture dependent alignment of the addresses.</summary>
<param name="destination">The location to write to.</param>
<param name="value">The value to write.</param>
<typeparam name="T">The type of value to write.</typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.Unsafe.WriteUnaligned``1(System.Void*,``0)">
<summary>Writes a value of type <typeparamref name="T">T</typeparamref> to the given location
without assuming architecture dependent alignment of the addresses.</summary>
<param name="destination">The location to write to.</param>
<param name="value">The value to write.</param>
<typeparam name="T">The type of value to write.</typeparam>
</member>
</members>
</doc>

Binary file not shown.

View File

@@ -0,0 +1,166 @@
<?xml version="1.0" encoding="utf-8"?><doc>
<assembly>
<name>System.Threading.Tasks.Extensions</name>
</assembly>
<members>
<member name="T:System.Runtime.CompilerServices.ValueTaskAwaiter`1">
<typeparam name="TResult"></typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.ValueTaskAwaiter`1.GetResult">
<returns></returns>
</member>
<member name="P:System.Runtime.CompilerServices.ValueTaskAwaiter`1.IsCompleted">
<returns></returns>
</member>
<member name="M:System.Runtime.CompilerServices.ValueTaskAwaiter`1.OnCompleted(System.Action)">
<param name="continuation"></param>
</member>
<member name="M:System.Runtime.CompilerServices.ValueTaskAwaiter`1.UnsafeOnCompleted(System.Action)">
<param name="continuation"></param>
</member>
<member name="T:System.Threading.Tasks.ValueTask`1">
<summary>Provides a value type that wraps a <see cref="Task{TResult}"></see> and a <typeparamref name="TResult">TResult</typeparamref>, only one of which is used.</summary>
<typeparam name="TResult">The result.</typeparam>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.#ctor(System.Threading.Tasks.Task{`0})">
<summary>Initializes a new instance of the <see cref="ValueTask{TResult}"></see> class using the supplied task that represents the operation.</summary>
<param name="task">The task.</param>
<exception cref="T:System.ArgumentNullException">The <paramref name="task">task</paramref> argument is null.</exception>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.#ctor(`0)">
<summary>Initializes a new instance of the <see cref="ValueTask{TResult}"></see> class using the supplied result of a successful operation.</summary>
<param name="result">The result.</param>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.AsTask">
<summary>Retrieves a <see cref="Task{TResult}"></see> object that represents this <see cref="ValueTask{TResult}"></see>.</summary>
<returns>The <see cref="Task{TResult}"></see> object that is wrapped in this <see cref="ValueTask{TResult}"></see> if one exists, or a new <see cref="Task{TResult}"></see> object that represents the result.</returns>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.ConfigureAwait(System.Boolean)">
<summary>Configures an awaiter for this value.</summary>
<param name="continueOnCapturedContext">true to attempt to marshal the continuation back to the captured context; otherwise, false.</param>
<returns>The configured awaiter.</returns>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.CreateAsyncMethodBuilder">
<summary>Creates a method builder for use with an async method.</summary>
<returns>The created builder.</returns>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.Equals(System.Object)">
<summary>Determines whether the specified object is equal to the current object.</summary>
<param name="obj">The object to compare with the current object.</param>
<returns>true if the specified object is equal to the current object; otherwise, false.</returns>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.Equals(System.Threading.Tasks.ValueTask{`0})">
<summary>Determines whether the specified <see cref="ValueTask{TResult}"></see> object is equal to the current <see cref="ValueTask{TResult}"></see> object.</summary>
<param name="other">The object to compare with the current object.</param>
<returns>true if the specified object is equal to the current object; otherwise, false.</returns>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.GetAwaiter">
<summary>Creates an awaiter for this value.</summary>
<returns>The awaiter.</returns>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.GetHashCode">
<summary>Returns the hash code for this instance.</summary>
<returns>The hash code for the current object.</returns>
</member>
<member name="P:System.Threading.Tasks.ValueTask`1.IsCanceled">
<summary>Gets a value that indicates whether this object represents a canceled operation.</summary>
<returns>true if this object represents a canceled operation; otherwise, false.</returns>
</member>
<member name="P:System.Threading.Tasks.ValueTask`1.IsCompleted">
<summary>Gets a value that indicates whether this object represents a completed operation.</summary>
<returns>true if this object represents a completed operation; otherwise, false.</returns>
</member>
<member name="P:System.Threading.Tasks.ValueTask`1.IsCompletedSuccessfully">
<summary>Gets a value that indicates whether this object represents a successfully completed operation.</summary>
<returns>true if this object represents a successfully completed operation; otherwise, false.</returns>
</member>
<member name="P:System.Threading.Tasks.ValueTask`1.IsFaulted">
<summary>Gets a value that indicates whether this object represents a failed operation.</summary>
<returns>true if this object represents a failed operation; otherwise, false.</returns>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.op_Equality(System.Threading.Tasks.ValueTask{`0},System.Threading.Tasks.ValueTask{`0})">
<summary>Compares two values for equality.</summary>
<param name="left">The first value to compare.</param>
<param name="right">The second value to compare.</param>
<returns>true if the two <see cref="ValueTask{TResult}"></see> values are equal; otherwise, false.</returns>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.op_Inequality(System.Threading.Tasks.ValueTask{`0},System.Threading.Tasks.ValueTask{`0})">
<summary>Determines whether two <see cref="ValueTask{TResult}"></see> values are unequal.</summary>
<param name="left">The first value to compare.</param>
<param name="right">The seconed value to compare.</param>
<returns>true if the two <see cref="ValueTask{TResult}"></see> values are not equal; otherwise, false.</returns>
</member>
<member name="P:System.Threading.Tasks.ValueTask`1.Result">
<summary>Gets the result.</summary>
<returns>The result.</returns>
</member>
<member name="M:System.Threading.Tasks.ValueTask`1.ToString">
<summary>Returns a string that represents the current object.</summary>
<returns>A string that represents the current object.</returns>
</member>
<member name="T:System.Runtime.CompilerServices.AsyncMethodBuilderAttribute">
</member>
<member name="M:System.Runtime.CompilerServices.AsyncMethodBuilderAttribute.#ctor(System.Type)">
<param name="builderType"></param>
</member>
<member name="P:System.Runtime.CompilerServices.AsyncMethodBuilderAttribute.BuilderType">
<returns></returns>
</member>
<member name="T:System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1">
<typeparam name="TResult"></typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1.AwaitOnCompleted``2(``0@,``1@)">
<param name="awaiter"></param>
<param name="stateMachine"></param>
<typeparam name="TAwaiter"></typeparam>
<typeparam name="TStateMachine"></typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1.AwaitUnsafeOnCompleted``2(``0@,``1@)">
<param name="awaiter"></param>
<param name="stateMachine"></param>
<typeparam name="TAwaiter"></typeparam>
<typeparam name="TStateMachine"></typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1.Create">
<returns></returns>
</member>
<member name="M:System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1.SetException(System.Exception)">
<param name="exception"></param>
</member>
<member name="M:System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1.SetResult(`0)">
<param name="result"></param>
</member>
<member name="M:System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1.SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine)">
<param name="stateMachine"></param>
</member>
<member name="M:System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1.Start``1(``0@)">
<param name="stateMachine"></param>
<typeparam name="TStateMachine"></typeparam>
</member>
<member name="P:System.Runtime.CompilerServices.AsyncValueTaskMethodBuilder`1.Task">
<returns></returns>
</member>
<member name="T:System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1.ConfiguredValueTaskAwaiter">
<typeparam name="TResult"></typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1.ConfiguredValueTaskAwaiter.GetResult">
<returns></returns>
</member>
<member name="P:System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1.ConfiguredValueTaskAwaiter.IsCompleted">
<returns></returns>
</member>
<member name="M:System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1.ConfiguredValueTaskAwaiter.OnCompleted(System.Action)">
<param name="continuation"></param>
</member>
<member name="M:System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1.ConfiguredValueTaskAwaiter.UnsafeOnCompleted(System.Action)">
<param name="continuation"></param>
</member>
<member name="T:System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1">
<typeparam name="TResult"></typeparam>
</member>
<member name="M:System.Runtime.CompilerServices.ConfiguredValueTaskAwaitable`1.GetAwaiter">
<returns></returns>
</member>
</members>
</doc>

73
CommandArgs.cs Normal file
View File

@@ -0,0 +1,73 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace CopyDb
{
public class CommandArgs : Dictionary<String,NVP>
{
public CommandArgs(String[] args)
{
for(int index=0;index<args.Length;index++)
{
String command=args[index];
String[] nvp=null;
if(command.StartsWith("/"))
{
command=command.Substring(1);
nvp=command.Split(':');
if(nvp.Length>2)
{
StringBuilder sb=new StringBuilder();
for(int subIndex=1;subIndex<nvp.Length;subIndex++){sb.Append(nvp[subIndex]);if(subIndex<nvp.Length-1)sb.Append(":");}
nvp=new String[]{nvp[0],sb.ToString().Trim()};
}
}
else nvp=command.Split('=');
if(2!=nvp.Length)continue;
if(ContainsKey(nvp[0]))continue;
Add(nvp[0].ToUpper(),new NVP(nvp[0],nvp[1]));
}
}
public bool Contains(String name)
{
return ContainsKey(name);
}
public bool Has(String commandList)
{
commandList=commandList.ToUpper();
String[] commands=commandList.Split(',');
if(0==commands.Length)return false;
foreach(String command in commands)
{
if(!ContainsKey(command))return false;
}
return true;
}
public T Get<T>(String name)
{
T result=default(T);
try {result = (T)Convert.ChangeType(this[name].Value, typeof(T));}
catch {result = default(T);}
return result;
}
public T Coalesce<T>(String name,T coalesce)
{
T result=default(T);
try
{
if(!Contains(name))result=coalesce;
else result = (T)Convert.ChangeType(this[name].Value, typeof(T));
}
catch {result = default(T);}
return result;
}
public T Coalesce<T>(String name)
{
T result=default(T);
try {result = (T)Convert.ChangeType(this[name].Value, typeof(T));}
catch {result = default(T);}
return result;
}
}
}

22
CopyDB.sln Normal file
View File

@@ -0,0 +1,22 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
VisualStudioVersion = 12.0.21005.1
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CopyDb", "CopyDb.csproj", "{76844CDA-F2B2-416E-9F0F-AEC587176F33}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{76844CDA-F2B2-416E-9F0F-AEC587176F33}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{76844CDA-F2B2-416E-9F0F-AEC587176F33}.Debug|Any CPU.Build.0 = Debug|Any CPU
{76844CDA-F2B2-416E-9F0F-AEC587176F33}.Release|Any CPU.ActiveCfg = Release|Any CPU
{76844CDA-F2B2-416E-9F0F-AEC587176F33}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

75
CopyDb.csproj Normal file
View File

@@ -0,0 +1,75 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{76844CDA-F2B2-416E-9F0F-AEC587176F33}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>CopyDb</RootNamespace>
<AssemblyName>CopyDb</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x64</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="MySql.Data, Version=8.0.11.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d, processorArchitecture=MSIL">
<SpecificVersion>False</SpecificVersion>
<HintPath>Assemblies\MySql.Data.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Runtime.CompilerServices.Unsafe">
<HintPath>Assemblies\System.Runtime.CompilerServices.Unsafe.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Tasks.Extensions">
<HintPath>Assemblies\System.Threading.Tasks.Extensions.dll</HintPath>
</Reference>
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="CommandArgs.cs" />
<Compile Include="NVP.cs" />
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SQLUtils.cs" />
<Compile Include="Utility.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>

98
NVP.cs Normal file
View File

@@ -0,0 +1,98 @@
using System;
using System.Collections;
using System.Text;
using System.Collections.Generic;
namespace CopyDb
{
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;
}
public NVP(String nvpString)
{
if(null==nvpString)return;
String[] nvps=nvpString.Split('=');
if(2!=nvps.Length)return;
Name=nvps[0].Trim();
Value=nvps[1].Trim();
}
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();
}
}
}

586
Program.cs Normal file
View File

@@ -0,0 +1,586 @@
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using System.IO;
using MySql.Data.MySqlClient;
using System.Data;
namespace CopyDb
{
public class Constants
{
public static String IBD_EXTENSION=".ibd";
public static int COMMAND_TIMEOUT=0; // no timeout
public static string CHARACTER_SET="utf8mb4";
public static string COLLATION="utf8mb4_0900_ai_ci";
}
public class Schemas : List<Schema>
{
public void Display()
{
for(int index=0;index<Count;index++)
{
Console.WriteLine(String.Format("{0}){1}",index+1,this[index].TableName));
}
}
}
public class Schema
{
public Schema()
{
SchemaLines=new List<String>();
HasForeignKey=false;
}
public List<String> SchemaLines{get;set;}
public String TableName{get;set;}
public bool HasForeignKey{get;set;}
public String ForeignKeyTable{get;set;}
public String ForeignKeyConstraint{get;set;}
}
// ******************************************************************
public class Config
{
public String Server{get;set;}
public int Port{get;set;}
public String Database{get;set;}
public String User{get;set;}
public String Password{get;set;}
public String PathSchemaFileName{get;set;}
public String PathIbd{get;set;}
public String Mode{get;set;}
public String DatabaseDirectory{get;set;}
public String CharacterSet{get;set;}
public String Collation{get;set;}
public void Display()
{
Console.WriteLine(String.Format("SERVER:{0}",Server));
Console.WriteLine(String.Format("PORT:{0}",Port));
Console.WriteLine(String.Format("DATABASE:{0}",Database));
Console.WriteLine(String.Format("USER:{0}",User));
Console.WriteLine(String.Format("PASSWORD:{0}",Password));
Console.WriteLine(String.Format("PATHSCHEMAFILE:{0}",PathSchemaFileName));
Console.WriteLine(String.Format("PATHIBD:{0}",PathIbd));
Console.WriteLine(String.Format("MODE:{0}",Mode));
Console.WriteLine(String.Format("DATABASEDIRECTORY:{0}",DatabaseDirectory));
Console.WriteLine(String.Format("CHARACTERSET:{0}",CharacterSet));
Console.WriteLine(String.Format("COLLATION:{0}",Collation));
}
}
class Program
{
static void Main(string[] args)
{
if(1==args.Length)
{
Console.WriteLine(String.Format("USAGE: COPYDB /SERVER:{server} /PORT:{port} /ROWCOUNTSONLY:{true|false} /CONVERTCHARSETCOLLATION:{charset@collation} /DATABASE:{databasename} /USER:{username} /PASSWORD:{password} /PATHSCHEMAFILE:{pathschemafilename} /PATHIDB:{pathibdfiles} /MODE:{LIVE|TEST} /DATABASEDIRECTORY:{path}"));
return;
}
PerformImport(args);
}
public static void PerformImport(string[] args)
{
String strResult=null;
CommandArgs commandArgs=new CommandArgs(args);
Console.WriteLine("*********** C O N F I G ***********");
Config config=GetConfig(commandArgs);
config.Display();
if(!commandArgs.Has("SERVER,PORT,DATABASE,USER,PASSWORD,PATHSCHEMAFILE"))
{
Console.WriteLine(String.Format("One or more required parameters are missing. SERVER,PORT,DATABASE,USER,PASSWORD,PATHSCHEMAFILE"));
return;
}
// ************************************************************* S C H E M A *******************************************************
Schemas schemas=Program.GetSchemas(config);
if(null==schemas)
{
Console.WriteLine(String.Format("Unable to read schemas"));
return;
}
Console.WriteLine("*********** S C H E M A ***********");
schemas.Display();
// *********************************************************** D A T A B A S E ********************************************************
Console.WriteLine("*********** V E R I F Y I N G D A T A B A S E ***********");
MySqlConnection sqlConnection=null;
try{ sqlConnection=SqlUtils.CreateMySqlConnection(config.Server,config.Port.ToString(),config.Database,config.User,config.Password);}
catch(Exception exception)
{
Console.WriteLine(String.Format("Encountered Exception: {0}",exception.ToString()));
return;
}
ConnectionState connectionState=sqlConnection.State;
if(!connectionState.Equals(ConnectionState.Open))
{
Console.WriteLine(String.Format("Unable to connect to databse {0}",config.Database));
return;
}
Console.WriteLine("Database connection verified.");
// ***************************************************** T A B L E R O W C O U N T S***********************************************************
GetTableRowCounts(schemas, config, sqlConnection);
if(commandArgs.Has("ROWCOUNTSONLY") && commandArgs.Get<bool>("ROWCOUNTSONLY").Equals(true))
{
Console.WriteLine("Exiting because ROWCOUNTSONLY is set to True.");
return;
}
// *********************************************************************************************************************************************
// (i.e.) CONVERTCHARSETCOLLATION:utf8mb4@utf8mb4_0900_ai_ci
if(commandArgs.Has("CONVERTCHARSETCOLLATION"))
{
Console.WriteLine("**WARNING** This is a destructive event. This process will convert tables in {0}",config.Database);
Console.WriteLine("Please review settings. Proceed Y/N?");
strResult=Console.ReadLine();
if(null==strResult||(!strResult.ToUpper().Equals("Y") && !strResult.ToUpper().Equals("YES")))
{
Console.WriteLine("Cancelled");
return;
}
ConvertSchema(schemas ,config, sqlConnection);
GetTableRowCounts(schemas, config, sqlConnection);
Console.WriteLine("Done.");
Console.ReadLine();
return;
}
if(!commandArgs.Has("PATHIBD,MODE,DATABASEDIRECTORY"))
{
Console.WriteLine(String.Format("One or more required parameters are missing."));
return;
}
Console.WriteLine("*********** V E R I F Y I N G I D B F I L E S ***********");
if(!VerifyIdbFiles(schemas,config))
{
Console.WriteLine("Unable to verify IDBFiles");
return;
}
if(config.Mode.ToUpper().Equals("TEST"))
{
Console.WriteLine("Mode is TEST.");
sqlConnection.Close();
sqlConnection.Dispose();
return;
}
Console.WriteLine("**WARNING** This is a destructive event. This process will drop tables in {0}",config.Database);
Console.WriteLine("Please review settings. Proceed Y/N?");
strResult=Console.ReadLine();
if(null==strResult||(!strResult.ToUpper().Equals("Y") && !strResult.ToUpper().Equals("YES")))
{
Console.WriteLine("Cancelled");
return;
}
Console.WriteLine("*********** I M P O R T ***********");
foreach(Schema schema in schemas)
{
ImportTable(schema ,config, sqlConnection);
}
sqlConnection.Close();
sqlConnection.Dispose();
Console.WriteLine("Done.");
return;
}
// ********************************************************************************************************************************************************************************
// *************************************************************************** C O N V E R T C H A R A C T E R S E T ***********************************************************
// ********************************************************************************************************************************************************************************
private static void ConvertSchema(Schemas schemas, Config config, MySqlConnection sqlConnection)
{
MySqlCommand sqlCommand=null;
String strSetKeyChecksTrue="SET foreign_key_checks =1;";
String strSetKeyChecksFalse="SET foreign_key_checks =0;";
try
{
Console.WriteLine(String.Format("{0}",strSetKeyChecksFalse));
sqlCommand = new MySqlCommand(strSetKeyChecksFalse, sqlConnection);
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
sqlCommand.ExecuteNonQuery();
sqlCommand.Dispose();
foreach(Schema schema in schemas)
{
StringBuilder sb=new StringBuilder();
sb.Append("ALTER TABLE ").Append(schema.TableName).Append(" CONVERT TO CHARACTER SET ").Append(config.CharacterSet).Append(" COLLATE ").Append(config.Collation).Append(" ;");
String strQuery=sb.ToString();
Console.WriteLine(String.Format(strQuery));
sqlCommand = new MySqlCommand(strQuery, sqlConnection);
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
sqlCommand.ExecuteNonQuery();
sqlCommand.Dispose();
if(!VerifyCharSetCollation(schema.TableName, config, sqlConnection))
{
Console.WriteLine(String.Format("FAILED to change character set / collation on table {0}",schema.TableName));
}
else Console.WriteLine(String.Format("VERIFIED"));
}
Console.WriteLine(String.Format("{0}",strSetKeyChecksTrue));
Console.WriteLine("");
sqlCommand = new MySqlCommand(strSetKeyChecksTrue, sqlConnection);
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
sqlCommand.ExecuteNonQuery();
sqlCommand.Dispose();
}
catch(Exception exception)
{
if(null!=sqlCommand)
{
sqlCommand.Dispose();
sqlCommand=null;
}
Console.WriteLine("Exception converting character set :{0}",exception.ToString());
}
}
// ********************************************************************************************************************************************************************************
// *************************************************************************** V E R I F Y C H A R A C T E R S E T ***********************************************************
// ********************************************************************************************************************************************************************************
private static bool VerifyCharSetCollation(String tableName, Config config, MySqlConnection sqlConnection)
{
MySqlCommand sqlCommand=null;
MySqlDataReader sqlReader=null;
bool verified=true;
try
{
StringBuilder sb=new StringBuilder();
sb.Append("SHOW FULL COLUMNS FROM ").Append(tableName).Append(" ;");
sqlCommand=sqlConnection.CreateCommand();
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
String strQuery=sb.ToString();
Console.WriteLine(String.Format(strQuery));
sqlCommand = new MySqlCommand(strQuery, sqlConnection);
sqlReader=sqlCommand.ExecuteReader();
while(sqlReader.Read())
{
String field=sqlReader.IsDBNull(0)?null:sqlReader.GetString(0);
String type=sqlReader.IsDBNull(1)?null:sqlReader.GetString(1).ToLower();
String collation=sqlReader.IsDBNull(2)?null:sqlReader.GetString(2).ToLower();
if(!type.StartsWith("varchar"))continue;
if(!collation.Equals(config.Collation))verified=false;
}
sqlReader.Close();
sqlReader.Dispose();
sqlCommand.Dispose();
sqlCommand=null;
sqlReader=null;
return verified;
}
catch(Exception exception)
{
Console.WriteLine("Exception converting character set :{0}",exception.ToString());
if(null!=sqlReader)
{
sqlReader.Close();
sqlReader.Dispose();
}
if(null!=sqlCommand)
{
sqlCommand.Dispose();
sqlCommand=null;
}
return false;
}
}
// ********************************************************************************************************************************************************************************
// ******************************************************************************** T A B L E R O W C O U N T S ***********************************************************************
// ********************************************************************************************************************************************************************************
private static void GetTableRowCounts(Schemas schemas, Config config, MySqlConnection sqlConnection)
{
MySqlCommand sqlCommand=null;
MySqlDataReader sqlReader=null;
try
{
foreach(Schema schema in schemas)
{
StringBuilder sb=new StringBuilder();
sb.Append("SELECT COUNT(*) FROM ").Append(schema.TableName).Append(" ;");
sqlCommand=sqlConnection.CreateCommand();
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
String strQuery=sb.ToString();
sqlCommand = new MySqlCommand(strQuery, sqlConnection);
sqlReader=sqlCommand.ExecuteReader();
while(sqlReader.Read())
{
int rows=sqlReader.GetInt32(0);
Console.WriteLine(String.Format("{0},{1}",schema.TableName,Utility.FormatNumber(rows,0,false)));
}
sqlReader.Close();
sqlReader.Dispose();
sqlCommand.Dispose();
sqlCommand=null;
sqlReader=null;
}
}
catch(Exception exception)
{
Console.WriteLine("Exception:{0}",exception.ToString());
if(null!=sqlReader)
{
sqlReader.Close();
sqlReader.Dispose();
}
if(null!=sqlCommand)
{
sqlCommand.Dispose();
sqlCommand=null;
}
}
}
// *****************************************************************************************************************************************************
// *************************************************************** I M P O R T T A B L E **************************************************************
// *****************************************************************************************************************************************************
private static void ImportTable(Schema schema, Config config,MySqlConnection sqlConnection)
{
MySqlTransaction sqlTransaction=null;
String pathIdbFile=null;
String pathIdbFileDestination=null;
try
{
MySqlCommand sqlCommand=null;
String strQuery=null;
StringBuilder sb=null;
pathIdbFile=config.PathIbd+"\\"+schema.TableName+".ibd";
pathIdbFileDestination=config.DatabaseDirectory+"\\"+schema.TableName+".ibd";
sqlTransaction=sqlConnection.BeginTransaction(IsolationLevel.RepeatableRead);
sb=new StringBuilder();
sb.Append("DROP TABLE IF EXISTS ").Append(schema.TableName).Append(";");
sqlCommand=sqlConnection.CreateCommand();
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
strQuery=sb.ToString();
Console.WriteLine(String.Format(strQuery));
sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
sqlCommand.ExecuteNonQuery();
sqlCommand.Dispose();
sqlCommand=sqlConnection.CreateCommand();
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
strQuery=Utility.ListToString(schema.SchemaLines,' ');
Console.WriteLine(String.Format(schema.SchemaLines[0]));
sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
int result=sqlCommand.ExecuteNonQuery();
sqlCommand.Dispose();
sb=new StringBuilder();
sb.Append("ALTER TABLE ").Append(schema.TableName).Append(" DISCARD TABLESPACE;");
strQuery=sb.ToString();
Console.WriteLine(String.Format("{0}",strQuery));
sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
result=sqlCommand.ExecuteNonQuery();
sqlCommand.Dispose();
Console.WriteLine(String.Format("Copy file {0} -> {1}",pathIdbFile,pathIdbFileDestination));
File.Copy(pathIdbFile,pathIdbFileDestination,true);
sb=new StringBuilder();
sb.Append("ALTER TABLE ").Append(schema.TableName).Append(" IMPORT TABLESPACE;");
strQuery=sb.ToString();
Console.WriteLine(String.Format("{0}",strQuery));
sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
sqlCommand.ExecuteNonQuery();
sqlCommand.Dispose();
try
{
sb=new StringBuilder();
sb.Append("ALTER TABLE ").Append(schema.TableName).Append(" CONVERT TO CHARACTER SET ").Append(Constants.CHARACTER_SET).Append(" COLLATE ").Append(Constants.COLLATION).Append(";");
strQuery=sb.ToString();
Console.WriteLine(String.Format("{0}",strQuery));
sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
sqlCommand.ExecuteNonQuery();
sqlCommand.Dispose();
}
catch(Exception exception)
{
Console.WriteLine("Exception converting character set :{0}",exception.ToString());
}
if(schema.HasForeignKey)
{
sb=new StringBuilder();
sb.Append("ALTER TABLE ").Append(schema.TableName).Append(" ADD ").Append(schema.ForeignKeyConstraint).Append(";");
strQuery=sb.ToString();
Console.WriteLine(String.Format("{0}",strQuery));
sqlCommand = new MySqlCommand(strQuery, sqlConnection, sqlTransaction);
sqlCommand.CommandTimeout=Constants.COMMAND_TIMEOUT;
sqlCommand.ExecuteNonQuery();
sqlCommand.Dispose();
}
sqlTransaction.Commit();
Console.WriteLine("");
}
catch(Exception exception)
{
Console.WriteLine(String.Format("Exception:{0}",exception.ToString()));
try{sqlTransaction.Rollback();}
catch(Exception rollbackException)
{
Console.WriteLine(String.Format("Rollback exception:{0}",rollbackException.ToString()));
}
}
}
private static bool VerifyIdbFiles(Schemas schemas,Config config)
{
bool success=true;
foreach(Schema schema in schemas)
{
String pathIdbFile=config.PathIbd+"\\"+schema.TableName+Constants.IBD_EXTENSION;;
Console.Write(String.Format("{0}",pathIdbFile));
if(!File.Exists(pathIdbFile))
{
Console.WriteLine("...Not found.");
success=false;
}
Console.WriteLine("...Verified");
}
return success;
}
private static Schemas GetSchemas(Config config)
{
Schemas schemas=new Schemas();
try
{
FileStream inStream = new FileStream(config.PathSchemaFileName,FileMode.Open);
StreamReader streamReader=new StreamReader(inStream);
String strLine=null;
bool inCreate=false;
Schema schema=null;
while(null!=(strLine=streamReader.ReadLine()))
{
if(strLine.StartsWith("CREATE TABLE") && !inCreate)
{
schema=new Schema();
schema.TableName=Utility.BetweenString(strLine,"`","`");
schema.SchemaLines.Add(strLine);
inCreate=true;
}
else if(inCreate)
{
// schema.SchemaLines.Add(strLine);
if(strLine.Contains("FOREIGN KEY"))
{
// schema.SchemaLines.Add(strLine);
schema.ForeignKeyConstraint=strLine;
schema.HasForeignKey=true;
String[] elements=strLine.Split(' ');
schema.ForeignKeyTable=GetForeignKeyTable(elements);
}
else if(strLine.Trim().EndsWith(";"))
{
// schema.SchemaLines.Add(") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;");
if(schema.SchemaLines[schema.SchemaLines.Count-1].EndsWith(","))
{
String line=schema.SchemaLines[schema.SchemaLines.Count-1];
line=line.Substring(0,line.Length-1); // FUNNY
schema.SchemaLines[schema.SchemaLines.Count-1]=line;
}
schema.SchemaLines.Add(strLine);
inCreate=false;
schemas.Add(schema);
schema=null;
}
else
{
schema.SchemaLines.Add(strLine);
}
}
}
streamReader.Close();
streamReader.Dispose();
inStream.Close();
inStream.Dispose();
OrderSchemas(schemas);
return schemas;
}
catch(Exception exception)
{
Console.WriteLine(String.Format("Exception:{0}",exception.ToString()));
return null;
}
}
private static Schemas OrderSchemas(Schemas schemas)
{
for(int index=0;index<schemas.Count;index++)
{
Schema schema=schemas[index];
if(schema.HasForeignKey)
{
int foreignKeyIndex=FindSchemaLocation(schemas,schema.ForeignKeyTable);
if(-1==foreignKeyIndex)
{
Console.WriteLine(String.Format("Cannot locate schema {0}",schema.ForeignKeyTable));
return schemas;
}
if(index>foreignKeyIndex)continue;
SwapSchemaPositions(schemas,index,foreignKeyIndex);
index=-1;
continue;
}
}
return schemas;
}
private static void SwapSchemaPositions(Schemas schemas,int schemaIndex,int foreignKeySchemaIndex)
{
Schema tempSchema=schemas[schemaIndex];
schemas[schemaIndex]=schemas[foreignKeySchemaIndex];
schemas[foreignKeySchemaIndex]=tempSchema;
}
private static int FindSchemaLocation(Schemas schemas,String tableName)
{
for(int index=0;index<schemas.Count;index++)
{
if(schemas[index].TableName.Equals(tableName))
{
return index;
}
}
return -1;
}
private static String GetForeignKeyTable(String[] elements)
{
String tableName=Utility.GetElementAfter(elements,"REFERENCES");
tableName=Utility.BetweenString(tableName,"`","`");
return tableName;
}
private static Config GetConfig(CommandArgs commandArgs)
{
Config config=new Config();
config.Server=commandArgs.Get<String>("SERVER");
config.Port=commandArgs.Get<int>("PORT");
config.Database=commandArgs.Get<String>("DATABASE");
config.User=commandArgs.Get<String>("USER");
config.Password=commandArgs.Get<String>("PASSWORD");
config.PathSchemaFileName=commandArgs.Get<String>("PATHSCHEMAFILE");
config.PathIbd=commandArgs.Get<String>("PATHIBD");
config.Mode=commandArgs.Get<String>("MODE");
config.DatabaseDirectory=commandArgs.Get<String>("DATABASEDIRECTORY");
if(commandArgs.Has("CONVERTCHARSETCOLLATION"))
{
String[] charsetcollation=commandArgs.Get<String>("CONVERTCHARSETCOLLATION").Split('@');
config.CharacterSet=charsetcollation[0];
config.Collation=charsetcollation[1];
}
return config;
}
}
}

View File

@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TestHarness")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestHarness")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("54484c44-f1be-4113-95d7-eabd8d7c2f50")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

236
SQLUtils.cs Normal file
View File

@@ -0,0 +1,236 @@
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 CopyDb
{
/// <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=100;
/// <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)
{
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("allow user variables=").Append("true").Append("; ");
sb.Append("default command timeout=").Append("300").Append("; ");
sb.Append("connect timeout=").Append("300").Append(" ");
connectionString=sb.ToString();
MySqlConnection connection=new MySqlConnection(connectionString);
connection.Open();
return connection;
}
catch(SqlException exception)
{
throw 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)
//{
// 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(" ");
// connectionString=sb.ToString();
// MySqlConnection connection=new MySqlConnection(connectionString);
// connection.Open();
// return connection;
// }
// catch(SqlException 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)
//{
// if (Utility.IsEpoch(dateTime)) return null;
// return Utility.DateTimeToStringYYYYHMMHDD(dateTime);
//}
//public static String ToSqlDateTime(DateTime dateTime)
//{
// return Utility.DateTimeToStringYYYYHMMHDDHHMMSS(dateTime);
//}
//public static String ToSqlDateTimeTT(DateTime dateTime)
//{
// return Utility.DateTimeToStringYYYYHMMHDDHHMMSSTT(dateTime);
//}
/// <summary>SqlString - Return minimum sql date.</summary>
/// <returns>DateTime</returns>
public static String SqlString(String value)
{
StringBuilder sb=new StringBuilder();
foreach(char ch in value)
{
sb.Append(ch);
if(ch=='\'')sb.Append("'");
}
return sb.ToString();
}
public static String ToSqlString(String value)
{
StringBuilder sb=new StringBuilder();
return sb.Append("'").Append(SqlString(value)).Append("'").ToString();
}
}
}

625
Utility.cs Normal file
View File

@@ -0,0 +1,625 @@
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 System.Security.Principal;
using System.Threading;
using ThreadState=System.Threading.ThreadState;
namespace CopyDb
{
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";
}
}
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
{
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 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("&#x2018;","'");
strItem=strItem.Replace("&#x2019;","'");
strItem=strItem.Replace("&#x2014;","-");
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 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 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[] { "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, new System.Globalization.CultureInfo("en-US"), 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 String FormatCurrencyWithQuotes(double number)
{
return AddQuotes(FormatCurrency(number));
}
public static String GetElementAfter(String[] elements,String key,int skip=0)
{
for(int index=0;index<elements.Length;index++)
{
if(elements[index].Equals(key))
{
return elements[index+1+skip].Trim();
}
}
return null;
}
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 s in list select s.Trim()).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)
{
Console.WriteLine(String.Format("Exception:{0}",exception.ToString()));
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)
{
Console.WriteLine(String.Format("Exception:{0}",exception.ToString()));
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 void DeleteFile(String pathFileName)
{
if(!File.Exists(pathFileName))return;
try{File.Delete(pathFileName);}catch(Exception){;}
}
}
}