From 4c52b2b1d1165cca5cbeaf1317bff32c478cd0ca Mon Sep 17 00:00:00 2001 From: Ryddag <27833747+Ryddag@users.noreply.github.com> Date: Mon, 27 Jan 2020 15:21:52 +0100 Subject: [PATCH] initial source commit --- .gitattributes | 17 + .gitignore | 330 ++++++++++++ LICENSE | 674 ++++++++++++++++++++++++ ProjectCeleste.Misc.Utils.sln | 25 + README.md | 16 +- VersionManifest.md | 1 + appveyor.yml | 312 +++++++++++ src/Crc32.cs | 125 +++++ src/Directory.cs | 147 ++++++ src/Extension/Bytes.cs | 174 ++++++ src/Extension/Class.cs | 54 ++ src/Extension/Comparable.cs | 94 ++++ src/Extension/Convertible.cs | 49 ++ src/Extension/DateTime.cs | 53 ++ src/Extension/Dictionary.cs | 81 +++ src/Extension/Enumerable.cs | 103 ++++ src/Extension/FileInfo.cs | 15 + src/Extension/Object.cs | 28 + src/Extension/Random.cs | 45 ++ src/Extension/SecureString.cs | 29 + src/Extension/String.cs | 138 +++++ src/Extension/Task.cs | 26 + src/Extension/TimeSpan.cs | 40 ++ src/Extension/Type.cs | 126 +++++ src/File.cs | 119 +++++ src/FingerPrint.cs | 230 ++++++++ src/IsValidString.cs | 180 +++++++ src/Json.cs | 73 +++ src/Network.cs | 117 ++++ src/OSVersion.cs | 145 +++++ src/ProjectCeleste.Misc.Utils.csproj | 56 ++ src/Random.cs | 106 ++++ src/RandomGenerator/CryptoRandom.cs | 150 ++++++ src/RandomGenerator/StaticRandom.cs | 160 ++++++ src/RandomGenerator/UniqueRandomInt.cs | 65 +++ src/RandomGenerator/UniqueRandomLong.cs | 66 +++ src/StringWriterWithEncoding.cs | 63 +++ src/SymLink.cs | 113 ++++ src/Xml.cs | 135 +++++ src/ZipFile.cs | 175 ++++++ src/icon.png | Bin 0 -> 4543 bytes 41 files changed, 4654 insertions(+), 1 deletion(-) create mode 100644 .gitattributes create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 ProjectCeleste.Misc.Utils.sln create mode 100644 VersionManifest.md create mode 100644 appveyor.yml create mode 100644 src/Crc32.cs create mode 100644 src/Directory.cs create mode 100644 src/Extension/Bytes.cs create mode 100644 src/Extension/Class.cs create mode 100644 src/Extension/Comparable.cs create mode 100644 src/Extension/Convertible.cs create mode 100644 src/Extension/DateTime.cs create mode 100644 src/Extension/Dictionary.cs create mode 100644 src/Extension/Enumerable.cs create mode 100644 src/Extension/FileInfo.cs create mode 100644 src/Extension/Object.cs create mode 100644 src/Extension/Random.cs create mode 100644 src/Extension/SecureString.cs create mode 100644 src/Extension/String.cs create mode 100644 src/Extension/Task.cs create mode 100644 src/Extension/TimeSpan.cs create mode 100644 src/Extension/Type.cs create mode 100644 src/File.cs create mode 100644 src/FingerPrint.cs create mode 100644 src/IsValidString.cs create mode 100644 src/Json.cs create mode 100644 src/Network.cs create mode 100644 src/OSVersion.cs create mode 100644 src/ProjectCeleste.Misc.Utils.csproj create mode 100644 src/Random.cs create mode 100644 src/RandomGenerator/CryptoRandom.cs create mode 100644 src/RandomGenerator/StaticRandom.cs create mode 100644 src/RandomGenerator/UniqueRandomInt.cs create mode 100644 src/RandomGenerator/UniqueRandomLong.cs create mode 100644 src/StringWriterWithEncoding.cs create mode 100644 src/SymLink.cs create mode 100644 src/Xml.cs create mode 100644 src/ZipFile.cs create mode 100644 src/icon.png diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..bdb0cab --- /dev/null +++ b/.gitattributes @@ -0,0 +1,17 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..3e759b7 --- /dev/null +++ b/.gitignore @@ -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/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/ProjectCeleste.Misc.Utils.sln b/ProjectCeleste.Misc.Utils.sln new file mode 100644 index 0000000..22d206e --- /dev/null +++ b/ProjectCeleste.Misc.Utils.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29613.14 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ProjectCeleste.Misc.Utils", "src\ProjectCeleste.Misc.Utils.csproj", "{DBE9A458-8CBB-4324-AE91-87D3515F29B4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DBE9A458-8CBB-4324-AE91-87D3515F29B4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DBE9A458-8CBB-4324-AE91-87D3515F29B4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DBE9A458-8CBB-4324-AE91-87D3515F29B4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DBE9A458-8CBB-4324-AE91-87D3515F29B4}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {CBA33469-6326-47B9-9856-4AA8D0704C92} + EndGlobalSection +EndGlobal diff --git a/README.md b/README.md index d92105e..9dd8462 100644 --- a/README.md +++ b/README.md @@ -1 +1,15 @@ -# ProjectCeleste.Misc.Utils \ No newline at end of file +# ProjectCeleste.Misc.Utils + +ProjectCeleste.Misc.Utils For Age Of Empires Online Celeste Fan Project + +Visit Us: https://www.projectceleste.com/ + +------------------------------------------------------------------------------- + +Nuget Package: https://www.nuget.org/packages/ProjectCeleste.Misc.Utils/ + +Nigthly Build Nuget Feed: https://ci.appveyor.com/nuget/projectceleste-misc-utils-obe9hen2whsc + +------------------------------------------------------------------------------- + +Age of Empires Online © Microsoft Corporation. Celeste Fan Project was created under Microsoft's Game Content Usage Rules using assets from Age of Empires Online, and it is not endorsed by or affiliated with Microsoft (See: https://www.xbox.com/en-us/developers/rules). \ No newline at end of file diff --git a/VersionManifest.md b/VersionManifest.md new file mode 100644 index 0000000..1f2c8da --- /dev/null +++ b/VersionManifest.md @@ -0,0 +1 @@ +0.0.0.0 \ No newline at end of file diff --git a/appveyor.yml b/appveyor.yml new file mode 100644 index 0000000..46f72ba --- /dev/null +++ b/appveyor.yml @@ -0,0 +1,312 @@ +#---------------------------------# +# general configuration # +#---------------------------------# + +# version format +version: 0.0.0.{build} + +# Do not build on tags +skip_tags: false + +# Start builds on tags only +skip_non_tags: false + +# Skipping commits with specific message +skip_commits: + message: /\[ci deploy\]/ + +# +pull_requests: + do_not_increment_build_number: true + +#---------------------------------# +# environment configuration # +#---------------------------------# + +# Build worker image (VM template) +image: Visual Studio 2019 + +# scripts that are called at very beginning, before repo cloning +init: +- ps: | + $env:Celeste_IsTagAndRelease = "false" + $env:Celeste_IsDeploy = "false" + if ($env:APPVEYOR_REPO_TAG -eq "true") + { + $env:Celeste_IVersion = "$env:APPVEYOR_REPO_TAG_NAME" + if ($env:CONFIGURATION -eq "Release") + { + if ($env:APPVEYOR_REPO_COMMIT_MESSAGE.Contains("[ci deploy]")) + { + $env:Celeste_IsDeploy = "true" + $env:Celeste_IsTagAndRelease = "false" + } + else + { + $env:Celeste_IsDeploy = "false" + $env:Celeste_IsTagAndRelease = "true" + } + } + if ($env:APPVEYOR_REPO_TAG_NAME.StartsWith("v")) + { + $env:Celeste_Version = $env:APPVEYOR_REPO_TAG_NAME.Substring(1) + } + else + { + $env:Celeste_Version = "$env:APPVEYOR_REPO_TAG_NAME" + } + if ($env:APPVEYOR_REPO_TAG_NAME.Contains("-rc") -or $env:APPVEYOR_REPO_TAG_NAME.Contains("-beta") -or $env:APPVEYOR_REPO_TAG_NAME.Contains("-alpha")) + { + $env:Celeste_Version = $env:Celeste_Version.Replace("-rc", "") + $env:Celeste_Version = $env:Celeste_Version.Replace("-beta", "") + $env:Celeste_Version = $env:Celeste_Version.Replace("-alpha", "") + $env:Celeste_PreRelease = "true" + } + else + { + $env:Celeste_PreRelease = "false" + } + if ((($env:Celeste_Version.Split('.')).Count - 1) -eq 0) + { + $env:Celeste_AVersion = "$env:Celeste_Version.0.0.0" + } + elseif ((($env:Celeste_Version.Split('.')).Count - 1) -eq 1) + { + $env:Celeste_AVersion = "$env:Celeste_Version.0.0" + } + elseif ((($env:Celeste_Version.Split('.')).Count - 1) -eq 2) + { + $env:Celeste_AVersion = "$env:Celeste_Version.0" + } + else + { + $env:Celeste_AVersion = "$env:Celeste_Version" + } + } + else + { + $env:Celeste_Version = "$env:APPVEYOR_BUILD_VERSION" + $env:Celeste_AVersion = "$env:APPVEYOR_BUILD_VERSION" + $env:Celeste_IVersion = "v$env:APPVEYOR_BUILD_VERSION" + $env:Celeste_PreRelease = "false" + } + git config --global core.autocrlf true + +# clone directory +clone_folder: c:\projects\ProjectCeleste.Misc.Utils + +# fetch repository as zip archive +shallow_clone: false + +# nuget +nuget: + account_feed: true + project_feed: true + disable_publish_on_pr: true + +# set clone depth +#clone_depth: 5 # clone entire repository history if not defined + +# environment variables +environment: + APPVEYOR_IGNORE_COMMIT_FILTERING_ON_TAG: true + access_token: + secure: FCfA6NOUpYu23Acwkb5xfB0fI9iOtw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x5e//f574gHSYrrVgQEUkUzcdbDfAxesmZHhCk064qZSKnxfwIbmWeC8lI32f0IGWE/qFpGvyYmTIqn1JFxbG80H5Q== + +# build cache to preserve files/folders between builds +cache: + - '%USERPROFILE%\.nuget\packages -> **\ProjectCeleste.Misc.Utils.csproj' # preserve packages directory but will reset it if ProjectCeleste.Misc.Utils.csproj is modified + +# scripts that run after cloning repository +install: + # Git submodule init +- cmd: git submodule update --init --recursive + # Update AppVeyor Build Version +- ps: | + if ($env:APPVEYOR_REPO_TAG -eq "true") + { + # Update VersionManifest + $VersionManifestPath = Join-Path -Path $ENV:APPVEYOR_BUILD_FOLDER -ChildPath 'VersionManifest.md' + Set-Content -NoNewline -Path $VersionManifestPath -Value $env:Celeste_AVersion + # Update AppVeyor build + Update-AppveyorBuild -Version "$env:Celeste_AVersion-$env:APPVEYOR_BUILD_NUMBER" + } + else + { + # Update AppVeyor Build Version + $VersionManifestPath = Join-Path -Path $ENV:APPVEYOR_BUILD_FOLDER -ChildPath 'VersionManifest.md' + $ManifestContent = Get-Content -Path $VersionManifestPath -Raw + # Set Version number + $env:Celeste_Version = "$ManifestContent" + $env:Celeste_AVersion = "$ManifestContent" + $env:Celeste_IVersion = "v$ManifestContent-$env:APPVEYOR_BUILD_NUMBER" + # update AppVeyor build + if ($env:APPVEYOR_PULL_REQUEST_NUMBER) + { + $ShortSHA = $env:APPVEYOR_PULL_REQUEST_HEAD_COMMIT.Substring(0,7) + Update-AppveyorBuild -Version "$ManifestContent-$env:APPVEYOR_BUILD_NUMBER--PR$env:APPVEYOR_PULL_REQUEST_NUMBER-$ShortSHA" + $env:Celeste_IVersion = "v$ManifestContent-$env:APPVEYOR_BUILD_NUMBER--PR$env:APPVEYOR_PULL_REQUEST_NUMBER-$ShortSHA" + } + else + { + Update-AppveyorBuild -Version "$ManifestContent-$env:APPVEYOR_BUILD_NUMBER" + $env:Celeste_IVersion = "v$ManifestContent-$env:APPVEYOR_BUILD_NUMBER" + } + } + +# enable patching of AssemblyInfo.* files +dotnet_csproj: + patch: true + file: '**\*.csproj' + version: '$(Celeste_AVersion)' + package_version: '$(Celeste_AVersion)' + assembly_version: '$(Celeste_AVersion)' + file_version: '$(Celeste_AVersion)' + informational_version: '$(Celeste_IVersion)' + +#---------------------------------# +# build configuration # +#---------------------------------# + +# build platform, i.e. x86, x64, Any CPU. This setting is optional. +platform: Any CPU + +# to add several platforms to build matrix: +#platform: +# - x86 +# - Any CPU + +# build Configuration, i.e. Debug, Release, etc. +configuration: + - Debug + - Release + +build: + parallel: true + # MSBuild verbosity level + verbosity: minimal + +# scripts to run before build +before_build: + # Display .NET Core version + - cmd: dotnet --version + # Display minimal restore text + - cmd: dotnet restore ./src/ProjectCeleste.Misc.Utils.csproj --verbosity m + +# scripts to run *after* solution is built and *before* automatic packaging occurs (web apps, NuGet packages, Azure Cloud Services) +before_package: + +# scripts to run after build +after_build: + +# to run your custom scripts instead of automatic MSBuild +build_script: + +#---------------------------------# +# tests configuration # +#---------------------------------# + +# to disable automatic tests +test: off + +#---------------------------------# +# artifacts configuration # +#---------------------------------# + +artifacts: + - path: 'src\bin\$(CONFIGURATION)' + name: ProjectCeleste.Misc.Utils + type: zip + - path: 'src\bin\Release\ProjectCeleste.Misc.Utils.*.*nupkg' + name: NuGet_Package + +#---------------------------------# +# deployment configuration # +#---------------------------------# + +# providers: Local, FTP, WebDeploy, AzureCS, AzureBlob, S3, NuGet, Environment +# provider names are case-sensitive! +deploy: + + # Deploy to GitHub Releases + - provider: GitHub + tag: $(APPVEYOR_REPO_TAG_NAME) + description: '[View CHANGELOG.md](https://github.com/ProjectCeleste/ProjectCeleste.Misc.Utils/blob/master/CHANGELOG.md)' + release: ProjectCeleste.Misc.Utils $(Celeste_IVersion) + auth_token: $(access_token) + artifact: ProjectCeleste.Misc.Utils + draft: false + prerelease: $(Celeste_PreRelease) + force_update: true + on: + Celeste_IsDeploy: true + + # Deploy to NuGet + - provider: NuGet + server: # remove to push to NuGet.org + api_key: + secure: JurVq4I9wOP95B7ZAerkZlt/+f5MOQahoOCk9ScEA4bF6PIWe6iwEIMjhyUnnWgX + skip_symbols: false + symbol_server: # remove to push symbols to SymbolSource.org + artifact: NuGet_Package + on: + Celeste_IsDeploy: true + + # Deploy to GitHub Packages + - provider: NuGet + server: https://nuget.pkg.github.com/ProjectCeleste/index.json + api_key: '$(access_token)' + username: '$(github_user)' + artifact: /.nupkg/ + on: + Celeste_IsDeploy: true + +# scripts to run before deployment +before_deploy: + +# scripts to run after deployment +after_deploy: + +#---------------------------------# +# global handlers # +#---------------------------------# + +# on successful build +on_success: +- ps: | + if ($env:Celeste_IsTagAndRelease -eq "true") + { + $env:GIT_REDIRECT_STDERR = '2>&1' + $fileContent = "-----BEGIN RSA PRIVATE KEY-----`n" + $fileContent += $env:priv_key.Replace(' ', "`n") + $fileContent += "`n-----END RSA PRIVATE KEY-----`n" + Set-Content "$env:USERPROFILE\.ssh\id_rsa" "$fileContent" + Set-Content "$env:USERPROFILE\.git-credentials" "https://$($env:access_token):x-oauth-basic@github.com`n" + git config --global credential.helper store + git config --global user.email "$env:github_email" + git config --global user.name "$env:github_user" + git checkout -b Appveyor "$env:APPVEYOR_REPO_COMMIT" + git add . + git commit -m "$env:APPVEYOR_REPO_TAG_NAME [ci deploy]" + git checkout "$env:APPVEYOR_REPO_BRANCH" + git merge --squash Appveyor + git add . + git commit -m "$env:APPVEYOR_REPO_TAG_NAME [ci deploy]" + git branch -d Appveyor + git pull "origin" "$env:APPVEYOR_REPO_BRANCH" + git push "origin" "$env:APPVEYOR_REPO_BRANCH" + git tag -f "$env:APPVEYOR_REPO_TAG_NAME" + git push --tags --force + } + +# on build failure +on_failure: + +# after build failure or success +on_finish: diff --git a/src/Crc32.cs b/src/Crc32.cs new file mode 100644 index 0000000..1c635af --- /dev/null +++ b/src/Crc32.cs @@ -0,0 +1,125 @@ +using System; +using System.IO; +using System.Threading; +using System.Threading.Tasks; +using Force.Crc32; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + public static class Crc32Utils + { + private const int BufferSize = 64 * FileUtils.Kb; + + [UsedImplicitly] + [Pure] + public static uint GetCrc32([NotNull] byte[] data) + { + data.ThrowIfNull(nameof(data)); + + using var fs = new MemoryStream(data); + return GetCrc32FromStream(fs); + } + + [UsedImplicitly] + [Pure] + public static uint GetCrc32FromFile([NotNull] string fileName) + { + fileName.ThrowIfNullOrWhiteSpace(nameof(fileName)); + + if (!File.Exists(fileName)) + throw new FileNotFoundException($"File '{fileName}' not found!", fileName); + + using var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, + FileOptions.SequentialScan); + return GetCrc32FromStream(fs); + } + + [UsedImplicitly] + [Pure] + public static uint GetCrc32FromStream([NotNull] Stream stream) + { + stream.ThrowIfNull(nameof(stream)); + + var result = 0u; + var buffer = new byte[BufferSize]; + int read; + while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) + { + result = Crc32Algorithm.Append(result, buffer, 0, read); + } + + return result; + } + + [UsedImplicitly] + [Pure] + public static async Task GetCrc32Async([NotNull] byte[] data, + [CanBeNull] IProgress progress = null, + CancellationToken ct = default) + { + data.ThrowIfNull(nameof(data)); + + using var fs = new MemoryStream(data); + return await GetCrc32FromStreamAsync(fs, progress, ct); + } + + [UsedImplicitly] + [Pure] + public static async Task GetCrc32FromFileAsync([NotNull] string fileName, + [CanBeNull] IProgress progress = null, + CancellationToken ct = default) + { + fileName.ThrowIfNullOrWhiteSpace(nameof(fileName)); + + if (!File.Exists(fileName)) + throw new FileNotFoundException($"File '{fileName}' not found!", fileName); + + using var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read, BufferSize, + FileOptions.Asynchronous | FileOptions.SequentialScan); + return await GetCrc32FromStreamAsync(fs, progress, ct); + } + + [UsedImplicitly] + [Pure] + public static async Task GetCrc32FromStreamAsync([NotNull] Stream stream, + [CanBeNull] IProgress progress = null, + CancellationToken ct = default) + { + stream.ThrowIfNull(nameof(stream)); + + var result = 0u; + var buffer = new byte[BufferSize]; + int read; + var totalRead = 0L; + var length = stream.Length; + var lastProgress = 0d; + while ((read = await stream.ReadAsync(buffer, 0, buffer.Length, ct)) > 0) + { + // + ct.ThrowIfCancellationRequested(); + + totalRead += read; + + result = Crc32Algorithm.Append(result, buffer, 0, read); + + if (progress != null) + { + var newProgress = (double) totalRead / length * 100; + + if (newProgress - lastProgress > 1) + { + progress.Report(newProgress); + lastProgress = newProgress; + } + } + + if (totalRead >= length) + break; + } + + return result; + } + } +} \ No newline at end of file diff --git a/src/Directory.cs b/src/Directory.cs new file mode 100644 index 0000000..ed49fad --- /dev/null +++ b/src/Directory.cs @@ -0,0 +1,147 @@ +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + public static class DirectoryUtils + { + [UsedImplicitly] + public static async Task CopyDirectoryAsync([NotNull] string sourceDirectory, + [NotNull] string destinationDirectory, + CancellationToken cancellationToken = default) + { + sourceDirectory.ThrowIfNullOrWhiteSpace(nameof(sourceDirectory)); + destinationDirectory.ThrowIfNullOrWhiteSpace(nameof(destinationDirectory)); + + if (!Directory.Exists(destinationDirectory)) + Directory.CreateDirectory(destinationDirectory); + + foreach (var folder in Directory.EnumerateDirectories(sourceDirectory)) + { + var name = Path.GetFileName(folder); + if (string.IsNullOrWhiteSpace(name)) + continue; + + var destFolder = Path.Combine(destinationDirectory, name); + await CopyDirectoryAsync(folder, destFolder, cancellationToken); + } + + Directory.EnumerateFiles(sourceDirectory).AsParallel().ForAll(async file => + { + var name = Path.GetFileName(file); + if (string.IsNullOrWhiteSpace(name)) + return; + + var destFile = Path.Combine(destinationDirectory, name); + await FileUtils.CopyFileAsync(file, destFile, cancellationToken); + }); + } + + [UsedImplicitly] + public static void CopyDirectory([NotNull] string sourceDirectory, [NotNull] string destinationDirectory) + { + sourceDirectory.ThrowIfNullOrWhiteSpace(nameof(sourceDirectory)); + destinationDirectory.ThrowIfNullOrWhiteSpace(nameof(destinationDirectory)); + + if (!Directory.Exists(destinationDirectory)) + Directory.CreateDirectory(destinationDirectory); + + foreach (var folder in Directory.EnumerateDirectories(sourceDirectory)) + { + var name = Path.GetFileName(folder); + if (string.IsNullOrWhiteSpace(name)) + continue; + + var destFolder = Path.Combine(destinationDirectory, name); + CopyDirectory(folder, destFolder); + } + + Directory.EnumerateFiles(sourceDirectory).AsParallel().ForAll(file => + { + var name = Path.GetFileName(file); + if (string.IsNullOrWhiteSpace(name)) + return; + + var destFile = Path.Combine(destinationDirectory, name); + File.Copy(file, destFile, true); + }); + } + + [UsedImplicitly] + public static void CleanUpDirectory([NotNull] string sourceDirectory, [NotNull] string pattern = "*", + SearchOption searchOption = SearchOption.AllDirectories) + { + sourceDirectory.ThrowIfNullOrWhiteSpace(nameof(sourceDirectory)); + pattern.ThrowIfNullOrWhiteSpace(nameof(pattern)); + + Directory.EnumerateFiles(sourceDirectory, pattern, searchOption).AsParallel().ForAll(file => + { + try + { + File.Delete(file); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch + { + // + } +#pragma warning restore CA1031 // Do not catch general exception types + }); + } + + [UsedImplicitly] + public static void MoveDirectory([NotNull] string sourceDirectory, [NotNull] string destinationDirectory, + bool keepOldFile = true, + [NotNull] string oldFileExt = ".old") + { + sourceDirectory.ThrowIfNullOrWhiteSpace(nameof(sourceDirectory)); + destinationDirectory.ThrowIfNullOrWhiteSpace(nameof(destinationDirectory)); + oldFileExt.ThrowIfNullOrWhiteSpace(nameof(oldFileExt)); + + if (!Directory.Exists(destinationDirectory)) + Directory.CreateDirectory(destinationDirectory); + + foreach (var folder in Directory.EnumerateDirectories(sourceDirectory)) + { + var name = Path.GetFileName(folder); + if (string.IsNullOrWhiteSpace(name)) + continue; + var destFolder = Path.Combine(destinationDirectory, name); + MoveDirectory(folder, destFolder, keepOldFile, oldFileExt); + } + + Directory.EnumerateFiles(sourceDirectory).AsParallel().ForAll(file => + { + var name = Path.GetFileName(file); + if (string.IsNullOrWhiteSpace(name)) + return; + + var destFile = Path.Combine(destinationDirectory, name); + + FileUtils.MoveFile(file, destFile, keepOldFile, oldFileExt); + }); + } + + [UsedImplicitly] + [Pure] + public static bool IsDirectory([NotNull] string path) + { + path.ThrowIfNullOrWhiteSpace(nameof(path)); + + path = path.Trim(); + + if (Directory.Exists(path)) + return true; + + if (File.Exists(path)) + return false; + + return new[] {Path.DirectorySeparatorChar.ToString(), Path.AltDirectorySeparatorChar.ToString()} + .Any(x => path.EndsWith(x)) || string.IsNullOrWhiteSpace(Path.GetExtension(path)); + } + } +} \ No newline at end of file diff --git a/src/Extension/Bytes.cs b/src/Extension/Bytes.cs new file mode 100644 index 0000000..ea3a0ea --- /dev/null +++ b/src/Extension/Bytes.cs @@ -0,0 +1,174 @@ +using System; +using System.IO; +using System.IO.Compression; +using System.Threading; +using System.Threading.Tasks; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class BytesExtensions + { + [UsedImplicitly] + [Pure] + public static uint GetCrc32([NotNull] this byte[] data) + { + return Crc32Utils.GetCrc32(data); + } + + [UsedImplicitly] + [Pure] + public static async Task GetCrc32Async([NotNull] this byte[] data, + [CanBeNull] IProgress progress = null, + CancellationToken ct = default) + { + return await Crc32Utils.GetCrc32Async(data, progress, ct); + } + + #region Compression + + private const int CompressBufferSize = 64 * FileUtils.Kb; + + [UsedImplicitly] + [NotNull] + [Pure] + public static byte[] Compress([NotNull] this byte[] input, + CompressionLevel compressionLevel = CompressionLevel.Optimal) + { + input.ThrowIfNull(nameof(input)); + + byte[] output; + using (var inputStream = new MemoryStream(input)) + { + using var final = new MemoryStream(); + { + using (var a = new DeflateStream(final, compressionLevel)) + { + var buffer = new byte[CompressBufferSize]; + int read; + var totalRead = 0L; + var length = inputStream.Length; + + while ((read = inputStream.Read(buffer, 0, buffer.Length)) > 0) + { + totalRead += read; + + a.Write(buffer, 0, read); + + if (totalRead >= length) + break; + } + } + + output = final.ToArray(); + } + } + + return output; + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static async Task CompressAsync([NotNull] this byte[] input, + CompressionLevel compressionLevel = CompressionLevel.Optimal, [CanBeNull] IProgress progress = null, + CancellationToken ct = default) + { + input.ThrowIfNull(nameof(input)); + + byte[] output; + using (var inputStream = new MemoryStream(input)) + { + using var final = new MemoryStream(); + { + using (var a = new DeflateStream(final, compressionLevel)) + { + var buffer = new byte[CompressBufferSize]; + int read; + var totalRead = 0L; + var length = inputStream.Length; + var lastProgress = 0d; + while ((read = await inputStream.ReadAsync(buffer, 0, buffer.Length, ct)) > 0) + { + ct.ThrowIfCancellationRequested(); + + totalRead += read; + + await a.WriteAsync(buffer, 0, read, ct); + + if (progress != null) + { + var newProgress = (double) totalRead / length * 100; + + if (newProgress - lastProgress > 1) + { + progress.Report(newProgress); + lastProgress = newProgress; + } + } + + if (totalRead >= length) + break; + } + } + + output = final.ToArray(); + } + } + + return output; + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static byte[] Decompress([NotNull] this byte[] input) + { + input.ThrowIfNull(nameof(input)); + + byte[] output; + using (var f = new MemoryStream(input)) + { + using var a = new DeflateStream(f, CompressionMode.Decompress); + using var final = new MemoryStream(); + var buffer = new byte[CompressBufferSize]; + int read; + while ((read = a.Read(buffer, 0, buffer.Length)) > 0) + { + final.Write(buffer, 0, read); + } + + output = final.ToArray(); + } + + return output; + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static async Task DecompressAsync([NotNull] this byte[] input, CancellationToken ct = default) + { + input.ThrowIfNull(nameof(input)); + + byte[] output; + using (var f = new MemoryStream(input)) + { + using var a = new DeflateStream(f, CompressionMode.Decompress); + using var final = new MemoryStream(); + var buffer = new byte[CompressBufferSize]; + int read; + while ((read = await a.ReadAsync(buffer, 0, buffer.Length, ct)) > 0) + { + await final.WriteAsync(buffer, 0, read, ct); + } + + output = final.ToArray(); + } + + return output; + } + + #endregion + } +} \ No newline at end of file diff --git a/src/Extension/Class.cs b/src/Extension/Class.cs new file mode 100644 index 0000000..8439797 --- /dev/null +++ b/src/Extension/Class.cs @@ -0,0 +1,54 @@ +using System.Text; +using JetBrains.Annotations; +using Newtonsoft.Json; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class ClassExtensions + { + #region Xml + + [UsedImplicitly] + [NotNull] + [Pure] + public static T DeepCopyUsingXml([NotNull] this T value) where T : class + { + var xml = XmlUtils.SerializeToXml(value, Encoding.UTF8); + return XmlUtils.DeserializeFromXml(xml, Encoding.UTF8); + } + + [UsedImplicitly] + public static void SerializeToXmlFile([NotNull] this T serializableObject, [NotNull] string xmlFilePath, + [NotNull] Encoding encoding, + bool backup = true, [NotNull] string backupExt = ".bak") where T : class + { + XmlUtils.SerializeToXmlFile(serializableObject, xmlFilePath, encoding, backup, backupExt); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static string SerializeToXml([NotNull] this T serializableObject, [NotNull] Encoding encoding) + where T : class + { + return XmlUtils.SerializeToXml(serializableObject, encoding); + } + + #endregion + + #region Json + + [UsedImplicitly] + [NotNull] + [Pure] + public static T DeepCopyUsingJson([NotNull] this T value) where T : class + { + value.ThrowIfNull(nameof(value)); + + var json = JsonConvert.SerializeObject(value); + return JsonConvert.DeserializeObject(json); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/Extension/Comparable.cs b/src/Extension/Comparable.cs new file mode 100644 index 0000000..8b25966 --- /dev/null +++ b/src/Extension/Comparable.cs @@ -0,0 +1,94 @@ +using System; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class ComparableExtensions + { + [UsedImplicitly] + [Pure] + public static bool IsWithinInclusive(this T value, T minimum, T maximum) where T : IComparable + { + return value.CompareTo(minimum) >= 0 && value.CompareTo(maximum) <= 0; + } + + [UsedImplicitly] + [Pure] + public static bool IsWithinExclusive(this T value, T minimum, T maximum) where T : IComparable + { + return value.CompareTo(minimum) >= 0 && value.CompareTo(maximum) <= 0; + } + + #region ThrowIf + + [UsedImplicitly] + public static void ThrowIfNotWithinInclusive(this T value, T minimum, T maximum, string name = null) + where T : IComparable + { + if (!value.IsWithinInclusive(minimum, maximum)) + { + throw name == null + ? new ArgumentOutOfRangeException() + : new ArgumentOutOfRangeException(name, value, null); + } + } + + [UsedImplicitly] + public static void ThrowIfNotWithinExclusive(this T value, T minimum, T maximum, string name = null) + where T : IComparable + { + if (!value.IsWithinExclusive(minimum, maximum)) + { + throw name == null + ? new ArgumentOutOfRangeException() + : new ArgumentOutOfRangeException(name, value, null); + } + } + + [UsedImplicitly] + public static void ThrowIfNotEquals([CanBeNull] this T value, [CanBeNull] T compareValue, string name = null) + where T : IComparable + { + switch (value) + { + case null when compareValue == null: + return; + case null: + throw name == null + ? new ArgumentException() + : new ArgumentException(string.Empty, name); + } + + if (value.Equals(compareValue)) + { + throw name == null + ? new ArgumentException() + : new ArgumentException(string.Empty, name); + } + } + + [UsedImplicitly] + public static void ThrowIfEquals([CanBeNull] this T value, [CanBeNull] T compareValue, string name = null) + where T : IComparable + { + switch (value) + { + case null when compareValue == null: + throw name == null + ? new ArgumentException() + : new ArgumentException(string.Empty, name); + case null: + return; + } + + if (value.Equals(compareValue)) + { + throw name == null + ? new ArgumentException() + : new ArgumentException(string.Empty, name); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/src/Extension/Convertible.cs b/src/Extension/Convertible.cs new file mode 100644 index 0000000..edf965a --- /dev/null +++ b/src/Extension/Convertible.cs @@ -0,0 +1,49 @@ +using System; +using System.Globalization; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class ConvertibleExtensions + { + [UsedImplicitly] + [NotNull] + [Pure] + public static string ToBytesSize([NotNull] this T value2, bool useThreeNonZeroDigits = true) + where T : IConvertible + { + var value = value2.ToDecimal(new NumberFormatInfo()); + if (!useThreeNonZeroDigits) + { + if (value < FileUtils.Kb) + return $"{value} bytes"; + if (value < FileUtils.Mb) + return $"{value / FileUtils.Kb:f2} KB"; + return value < FileUtils.Gb ? $"{value / FileUtils.Mb:f2} MB" : $"{value / FileUtils.Gb:f2} GB"; + } + + string[] suffixes = + { + "bytes", "KB", "MB", "GB", + "TB", "PB", "EB", "ZB", "YB" + }; + + for (var i = 0; i < suffixes.Length; i++) + { + if (value <= (decimal) Math.Pow(FileUtils.Kb, i + 1)) + return ThreeNonZeroDigits(value / (decimal) Math.Pow(FileUtils.Kb, i)) + " " + suffixes[i]; + } + + return ThreeNonZeroDigits(value / (decimal) Math.Pow(FileUtils.Kb, suffixes.Length - 1)) + " " + + suffixes[suffixes.Length - 1]; + } + + [NotNull] + [Pure] + private static string ThreeNonZeroDigits([NotNull] T value2) where T : IConvertible + { + var value = value2.ToDecimal(new NumberFormatInfo()); + return value >= 100 ? value.ToString("0,0") : value.ToString(value >= 10 ? "0.0" : "0.00"); + } + } +} \ No newline at end of file diff --git a/src/Extension/DateTime.cs b/src/Extension/DateTime.cs new file mode 100644 index 0000000..cc6e6da --- /dev/null +++ b/src/Extension/DateTime.cs @@ -0,0 +1,53 @@ +using System; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class DateTimeExtensions + { + /// + /// Offsets to move the day of the year on a week, allowing + /// for the current year Jan 1st day of week, and the Sun/Mon + /// week start difference between ISO 8601 and Microsoft + /// + private static readonly int[] MoveByDays = {6, 7, 8, 9, 10, 4, 5}; + + /// + /// Get the Week number of the year + /// (In the range 1..53) + /// This conforms to ISO 8601 specification for week number. + /// + /// + /// Week of year + [UsedImplicitly] + [Pure] + public static int WeekOfYear(this DateTime date) + { + var startOfYear = new DateTime(date.Year, 1, 1); + var endOfYear = new DateTime(date.Year, 12, 31); + + // ISO 8601 weeks start with Monday + // The first week of a year includes the first Thursday + // This means that Jan 1st could be in week 51, 52, or 53 of the previous year... + var numberDays = date.Subtract(startOfYear).Days + + MoveByDays[(int) startOfYear.DayOfWeek]; + + var weekNumber = numberDays / 7; + if (weekNumber != 0) + { + if (weekNumber != 53) + return weekNumber; + + // In first week of next year. + if (endOfYear.DayOfWeek < DayOfWeek.Thursday) + weekNumber = 1; + } + else + { + weekNumber = WeekOfYear(startOfYear.AddDays(-1)); + } + + return weekNumber; + } + } +} \ No newline at end of file diff --git a/src/Extension/Dictionary.cs b/src/Extension/Dictionary.cs new file mode 100644 index 0000000..5cababb --- /dev/null +++ b/src/Extension/Dictionary.cs @@ -0,0 +1,81 @@ +using System; +using System.Collections.Generic; +using System.Data; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class DictionaryExtensions + { + [UsedImplicitly] + public static TValue GetOrAdd([NotNull] this IDictionary dictionary, + [NotNull] TKey key, + [NotNull] Func valueProvider) + { + dictionary.ThrowIfNull(nameof(dictionary)); + key.ThrowIfNull(nameof(key)); + valueProvider.ThrowIfNull(nameof(valueProvider)); + + if (dictionary.TryGetValue(key, out var ret)) + return ret; + ret = valueProvider(); + dictionary[key] = ret; + return ret; + } + + [UsedImplicitly] + public static TValue GetOrAdd([NotNull] this IDictionary dictionary, + [NotNull] TKey key, + [NotNull] TValue value) + { + dictionary.ThrowIfNull(nameof(dictionary)); + key.ThrowIfNull(nameof(key)); + value.ThrowIfNull(nameof(value)); + + if (dictionary.TryGetValue(key, out var ret)) + return ret; + ret = value; + dictionary[key] = ret; + return ret; + } + + [UsedImplicitly] + public static bool ChangeKey([NotNull] this IDictionary dictionary, + [NotNull] TKey oldKey, [NotNull] TKey newKey, out Exception exception) + { + dictionary.ThrowIfNull(nameof(dictionary)); + oldKey.ThrowIfNull(nameof(oldKey)); + newKey.ThrowIfNull(nameof(newKey)); + + if (dictionary.IsReadOnly) + { + exception = new ReadOnlyException(); + return false; + } + + if (!dictionary.TryGetValue(oldKey, out var value)) + throw new KeyNotFoundException($"Key '{oldKey} not found'"); + + if (dictionary.ContainsKey(newKey)) + throw new ArgumentException($"Key '{newKey}' already used", nameof(newKey)); + + dictionary.Remove(oldKey); + + try + { + dictionary.Add(newKey, value); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception e) + { + exception = e; + dictionary.Add(oldKey, value); + return false; + } +#pragma warning restore CA1031 // Do not catch general exception types + + exception = null; + return true; + } + } +} \ No newline at end of file diff --git a/src/Extension/Enumerable.cs b/src/Extension/Enumerable.cs new file mode 100644 index 0000000..bfe1608 --- /dev/null +++ b/src/Extension/Enumerable.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using System.Linq; +using System.Text; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class EnumerableExtensions + { + [UsedImplicitly] + [NotNull] + [Pure] + public static IEnumerable EmptyIfNull([NoEnumeration] [ItemNotNull] this IEnumerable source) + { + return source ?? Enumerable.Empty(); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static string ToStringList([NotNull] [ItemNotNull] this IEnumerable source, + [NotNull] string separator = ",") + { + separator.ThrowIfNullOrEmpty(nameof(separator)); + + var enumerable = source as string[] ?? source.ToArray(); + if (enumerable.Length == 0) + { + return string.Empty; + } + + var list = enumerable.Aggregate(string.Empty, (current, str) => current + str + separator); + if (list.EndsWith(separator)) + { + list = list.Substring(0, list.Length - 1); + } + + return list; + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static string ToStringFormat([NotNull] [ItemNotNull] this IEnumerable source) + { + var enumerable = source as T[] ?? source.ToArray(); + if (enumerable.Length == 0) + { + return $"new {typeof(T)}[0] " + "{}"; + } + + var sb = new StringBuilder($"new {typeof(T)}[" + enumerable.Length + "] { "); + for (var i = 0; i < enumerable.Length; i++) + { + var type = typeof(T); + if (type == typeof(string)) + { + sb.Append(i + 1 < enumerable.Length ? $"{enumerable[i]}, " : $"{enumerable[i]}"); + } + else if (type == typeof(byte)) + { + sb.Append(i + 1 < enumerable.Length ? $"0x{enumerable[i]:X2}, " : $"0x{enumerable[i]:X2}"); + } + else if (type == typeof(short)) + { + sb.Append(i + 1 < enumerable.Length ? $"0x{enumerable[i]:X4}, " : $"0x{enumerable[i]:X4}"); + } + else if (type == typeof(ushort)) + { + sb.Append(i + 1 < enumerable.Length ? $"0x{enumerable[i]:X4}, " : $"0x{enumerable[i]:X4}"); + } + else if (type == typeof(int)) + { + sb.Append(i + 1 < enumerable.Length ? $"0x{enumerable[i]:X4}, " : $"0x{enumerable[i]:X4}"); + } + else if (type == typeof(uint)) + { + sb.Append(i + 1 < enumerable.Length ? $"0x{enumerable[i]:X4}, " : $"0x{enumerable[i]:X4}"); + } + else if (type == typeof(long)) + { + sb.Append(i + 1 < enumerable.Length ? $"0x{enumerable[i]:X8}, " : $"0x{enumerable[i]:X8}"); + } + else if (type == typeof(ulong)) + { + sb.Append(i + 1 < enumerable.Length ? $"0x{enumerable[i]:X8}, " : $"0x{enumerable[i]:X8}"); + } + else if (type == typeof(decimal)) + { + sb.Append(i + 1 < enumerable.Length ? $"0x{enumerable[i]:X16}, " : $"0x{enumerable[i]:X16}"); + } + else + { + sb.Append(i + 1 < enumerable.Length ? $"{enumerable[i]}, " : $"{enumerable[i]}"); + } + } + + sb.Append(" }"); + + return sb.ToString(); + } + } +} \ No newline at end of file diff --git a/src/Extension/FileInfo.cs b/src/Extension/FileInfo.cs new file mode 100644 index 0000000..fd30620 --- /dev/null +++ b/src/Extension/FileInfo.cs @@ -0,0 +1,15 @@ +using System.IO; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class FileInfoExtensions + { + [UsedImplicitly] + [Pure] + public static bool IsFileLocked([NotNull] this FileInfo file) + { + return FileUtils.IsFileLocked(file); + } + } +} \ No newline at end of file diff --git a/src/Extension/Object.cs b/src/Extension/Object.cs new file mode 100644 index 0000000..cc71265 --- /dev/null +++ b/src/Extension/Object.cs @@ -0,0 +1,28 @@ +using System; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class ObjectExtensions + { + #region ThrowIf + + /// + /// Throws an ArgumentNullException if the given data item is null. + /// + /// The item to check for nullity. + /// The name to use when throwing an exception, if necessary + /// is null. + [UsedImplicitly] + [ContractAnnotation("data:null => halt")] + public static void ThrowIfNull([CanBeNull] this object data, string name = null) + { + if (data == null) + { + throw name == null ? new ArgumentNullException() : new ArgumentNullException(name); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/src/Extension/Random.cs b/src/Extension/Random.cs new file mode 100644 index 0000000..6ec94b8 --- /dev/null +++ b/src/Extension/Random.cs @@ -0,0 +1,45 @@ +using System; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + [UsedImplicitly] + public static class RandomExtension + { + /// + /// Returns a random number within a specified range. + /// + /// The random generator + /// The inclusive lower bound of the random number returned. + /// + /// The exclusive upper bound of the random number returned. + /// maxValue must be greater than or equal to minValue. + /// + /// + /// A 64-bit signed integer greater than or equal to minValue and less than maxValue; + /// that is, the range of return values includes minValue but not maxValue. + /// If minValue equals maxValue, minValue is returned. + /// + /// minValue is greater than maxValue. + [UsedImplicitly] + [Pure] + public static long NextLong([NotNull] this Random random, long minValue, long maxValue) + { + random.ThrowIfNull(nameof(random)); + + if (minValue > maxValue) + throw new ArgumentOutOfRangeException(nameof(minValue), minValue, "minValue is greater than maxValue"); + + var uRange = (ulong) (maxValue - minValue); + ulong ulongRand; + do + { + var buf = new byte[8]; + random.NextBytes(buf); + ulongRand = (ulong) BitConverter.ToInt64(buf, 0); + } while (ulongRand > ulong.MaxValue - (((ulong.MaxValue % uRange) + 1) % uRange)); + + return (long) (ulongRand % uRange) + minValue; + } + } +} \ No newline at end of file diff --git a/src/Extension/SecureString.cs b/src/Extension/SecureString.cs new file mode 100644 index 0000000..d8bd6e4 --- /dev/null +++ b/src/Extension/SecureString.cs @@ -0,0 +1,29 @@ +using System; +using System.Runtime.InteropServices; +using System.Security; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class SecureStringExtensions + { + [UsedImplicitly] + [NotNull] + [Pure] + public static string GetValue([NotNull] this SecureString secureString) + { + secureString.ThrowIfNull(nameof(secureString)); + + var unmanagedString = IntPtr.Zero; + try + { + unmanagedString = Marshal.SecureStringToGlobalAllocUnicode(secureString); + return Marshal.PtrToStringUni(unmanagedString) ?? throw new InvalidOperationException(); + } + finally + { + Marshal.ZeroFreeGlobalAllocUnicode(unmanagedString); + } + } + } +} \ No newline at end of file diff --git a/src/Extension/String.cs b/src/Extension/String.cs new file mode 100644 index 0000000..06a6ddc --- /dev/null +++ b/src/Extension/String.cs @@ -0,0 +1,138 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using System.Security; +using System.Text.RegularExpressions; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class StringExtensions + { + [UsedImplicitly] + [NotNull] + [Pure] + public static string WrapIfLengthIsLongerThan([NotNull] this string value, + [Range(0, int.MaxValue)] int maxLength, + [NotNull] string prefix = "") + { + if (string.IsNullOrWhiteSpace(value)) + return string.Empty; + + if (value.Length <= maxLength) + { + return value; + } + + var cutIndex = value.Length - maxLength; + return prefix + value.Substring(cutIndex); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static SecureString ToSecureString([NotNull] this string value) + { + value.ThrowIfNullOrWhiteSpace(nameof(value)); + + var secureString = new SecureString(); + foreach (var t in value) + secureString.AppendChar(t); + + return secureString; + } + + [UsedImplicitly] + [Pure] + public static T StringToEnum([CanBeNull] this string input, T defaultValue = default, + bool isNullable = false) + { + if (string.IsNullOrWhiteSpace(input) && isNullable && + Nullable.GetUnderlyingType(typeof(T))?.GetElementType() == null) + { + return default; + } + + return (input ?? throw new ArgumentNullException(nameof(input))).EnumTryParse(out T outType) + ? outType + : defaultValue; + } + + [UsedImplicitly] + [Pure] + public static bool EnumTryParse([NotNull] this string input, out T theEnum) + { + input.ThrowIfNullOrWhiteSpace(nameof(input)); + + var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T); + + if (Enum.GetNames(type).Any(en => en.Equals(input, StringComparison.OrdinalIgnoreCase))) + { + theEnum = (T) Enum.Parse(type, input, true); + return true; + } + + theEnum = default; + + return false; + } + + #region ThrowIf + + /// + /// Throws an ArgumentNullException if the given string item is null or empty. + /// + /// The item to check for nullity. + /// The name to use when throwing an exception, if necessary + /// + [UsedImplicitly] + [ContractAnnotation("data:null => halt")] + public static void ThrowIfNullOrEmpty([CanBeNull] this string data, string name = null) + { + if (string.IsNullOrEmpty(data)) + { + throw name == null ? new ArgumentNullException() : new ArgumentNullException(name); + } + } + + /// + /// Throws an ArgumentNullException if the given string item is null or empty or white space. + /// + /// The item to check for nullity. + /// The name to use when throwing an exception, if necessary + /// + [UsedImplicitly] + [ContractAnnotation("data:null => halt")] + public static void ThrowIfNullOrWhiteSpace([CanBeNull] this string data, string name = null) + { + if (string.IsNullOrWhiteSpace(data)) + { + throw name == null ? new ArgumentNullException() : new ArgumentNullException(name); + } + } + + /// + /// Throws an ArgumentException if the given string not match. + /// + /// The item to check for nullity. + /// + /// The name to use when throwing an exception, if necessary + /// + /// + /// + /// + [UsedImplicitly] + [ContractAnnotation("data:null => halt")] + [ContractAnnotation("pattern:null => halt")] + public static void ThrowIfNotMatchRegEx([NotNull] this string data, [NotNull] [RegexPattern] string pattern, + string name = null, RegexOptions regexOptions = RegexOptions.None) + { + if (Regex.IsMatch(data, pattern, regexOptions)) + { + throw name == null ? new ArgumentException() : new ArgumentException(name); + } + } + + #endregion + } +} \ No newline at end of file diff --git a/src/Extension/Task.cs b/src/Extension/Task.cs new file mode 100644 index 0000000..beca7a0 --- /dev/null +++ b/src/Extension/Task.cs @@ -0,0 +1,26 @@ +using System; +using System.Threading; +using System.Threading.Tasks; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class TaskExtensions + { + [UsedImplicitly] + public static async Task IgnoringCancellation([NotNull] this Task task, CancellationToken token) + { + task.ThrowIfNull(nameof(task)); + + try + { + await task; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (OperationCanceledException) when (token.IsCancellationRequested) + { + } +#pragma warning restore CA1031 // Do not catch general exception types + } + } +} \ No newline at end of file diff --git a/src/Extension/TimeSpan.cs b/src/Extension/TimeSpan.cs new file mode 100644 index 0000000..cc6a9bd --- /dev/null +++ b/src/Extension/TimeSpan.cs @@ -0,0 +1,40 @@ +using System; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class TimeSpanExtensions + { + [UsedImplicitly] + [NotNull] + [Pure] + public static string ToStringReadable(this TimeSpan span) + { + var formatted = + (span.Duration().Days > 0 + ? $"{span.Days:0} day{(span.Days == 1 ? string.Empty : "s")}, " + : string.Empty) + + (span.Duration().Hours > 0 + ? $"{span.Hours:0} hour{(span.Hours == 1 ? string.Empty : "s")}, " + : string.Empty) + + (span.Duration().Minutes > 0 + ? $"{span.Minutes:0} minute{(span.Minutes == 1 ? string.Empty : "s")}, " + : string.Empty) + + (span.Duration().Seconds > 0 + ? $"{span.Seconds:0} second{(span.Seconds == 1 ? string.Empty : "s")}" + : string.Empty); + + if (formatted.EndsWith(", ")) + { + formatted = formatted.Substring(0, formatted.Length - 2); + } + + if (string.IsNullOrWhiteSpace(formatted)) + { + formatted = "0 second"; + } + + return formatted; + } + } +} \ No newline at end of file diff --git a/src/Extension/Type.cs b/src/Extension/Type.cs new file mode 100644 index 0000000..e05c415 --- /dev/null +++ b/src/Extension/Type.cs @@ -0,0 +1,126 @@ +using System; +using System.Linq.Expressions; +using System.Reflection; +using System.Text; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.Extension +{ + public static class TypeExtensions + { + [Pure] + private static ConstructorInfo GetConstructor([NotNull] this Type type, + [NotNull] [ItemNotNull] params Type[] argumentTypes) + { + type.ThrowIfNull(nameof(type)); + argumentTypes.ThrowIfNull(nameof(argumentTypes)); + + var ci = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, null, + argumentTypes, null); + if (ci != null) + return ci; + + var sb = new StringBuilder(); + sb.Append(type.Name).Append(" has no ctor("); + for (var i = 0; i < argumentTypes.Length; i++) + { + if (i > 0) + { + sb.Append(','); + } + + sb.Append(argumentTypes[i].Name); + } + + sb.Append(')'); + throw new InvalidOperationException(sb.ToString()); + } + + [UsedImplicitly] + [Pure] + public static Func Ctor([NotNull] this Type type) + { + var ci = GetConstructor(type, Type.EmptyTypes); + return Expression.Lambda>( + Expression.New(ci)).Compile(); + } + + [UsedImplicitly] + [Pure] + public static Func + Ctor([NotNull] this Type type) + { + var ci = GetConstructor(type, typeof(TArg1)); + var + param1 = Expression.Parameter(typeof(TArg1), "arg1"); + + return Expression.Lambda>( + Expression.New(ci, param1), param1).Compile(); + } + + [UsedImplicitly] + [Pure] + public static Func + Ctor([NotNull] this Type type) + { + var ci = GetConstructor(type, typeof(TArg1), typeof(TArg2)); + ParameterExpression + param1 = Expression.Parameter(typeof(TArg1), "arg1"), + param2 = Expression.Parameter(typeof(TArg2), "arg2"); + + return Expression.Lambda>( + Expression.New(ci, param1, param2), param1, param2).Compile(); + } + + [UsedImplicitly] + [Pure] + public static Func + Ctor([NotNull] this Type type) + { + var ci = GetConstructor(type, typeof(TArg1), typeof(TArg2), typeof(TArg3)); + ParameterExpression + param1 = Expression.Parameter(typeof(TArg1), "arg1"), + param2 = Expression.Parameter(typeof(TArg2), "arg2"), + param3 = Expression.Parameter(typeof(TArg3), "arg3"); + + return Expression.Lambda>( + Expression.New(ci, param1, param2, param3), + param1, param2, param3).Compile(); + } + + [UsedImplicitly] + [Pure] + public static Func + Ctor([NotNull] this Type type) + { + var ci = GetConstructor(type, typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4)); + ParameterExpression + param1 = Expression.Parameter(typeof(TArg1), "arg1"), + param2 = Expression.Parameter(typeof(TArg2), "arg2"), + param3 = Expression.Parameter(typeof(TArg3), "arg3"), + param4 = Expression.Parameter(typeof(TArg4), "arg4"); + + return Expression.Lambda>( + Expression.New(ci, param1, param2, param3, param4), + param1, param2, param3, param4).Compile(); + } + + [UsedImplicitly] + [Pure] + public static Func + Ctor([NotNull] this Type type) + { + var ci = GetConstructor(type, typeof(TArg1), typeof(TArg2), typeof(TArg3), typeof(TArg4), typeof(TArg5)); + ParameterExpression + param1 = Expression.Parameter(typeof(TArg1), "arg1"), + param2 = Expression.Parameter(typeof(TArg2), "arg2"), + param3 = Expression.Parameter(typeof(TArg3), "arg3"), + param4 = Expression.Parameter(typeof(TArg4), "arg4"), + param5 = Expression.Parameter(typeof(TArg5), "arg5"); + + return Expression.Lambda>( + Expression.New(ci, param1, param2, param3, param4, param5), + param1, param2, param3, param4, param5).Compile(); + } + } +} \ No newline at end of file diff --git a/src/File.cs b/src/File.cs new file mode 100644 index 0000000..fb11909 --- /dev/null +++ b/src/File.cs @@ -0,0 +1,119 @@ +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + public static class FileUtils + { + public const int Kb = 1024; + + public const int Mb = Kb * Kb; + + public const int Gb = Kb * Mb; + + [UsedImplicitly] + public static async Task CopyFileAsync([NotNull] string sourceFile, [NotNull] string destinationFile, + CancellationToken cancellationToken = default) + { + sourceFile.ThrowIfNullOrWhiteSpace(nameof(sourceFile)); + destinationFile.ThrowIfNullOrWhiteSpace(nameof(destinationFile)); + + const FileOptions fileOptions = FileOptions.Asynchronous | FileOptions.SequentialScan; + const int bufferSize = 64 * Kb; + using var sourceStream = + new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize, fileOptions); + using var destinationStream = + new FileStream(destinationFile, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize, + fileOptions); + await sourceStream.CopyToAsync(destinationStream, bufferSize, cancellationToken); + } + + [UsedImplicitly] + public static void MoveFile([NotNull] string sourceFile, [NotNull] string destinationFile, + bool keepOld = true, + [NotNull] string oldExt = ".old") + { + sourceFile.ThrowIfNullOrWhiteSpace(nameof(sourceFile)); + destinationFile.ThrowIfNullOrWhiteSpace(nameof(destinationFile)); + oldExt.ThrowIfNullOrWhiteSpace(nameof(oldExt)); + + if (!File.Exists(sourceFile)) + throw new FileNotFoundException(string.Empty, sourceFile); + + if (File.Exists(destinationFile)) + { + if (keepOld) + { + if (File.Exists(destinationFile + oldExt)) + File.Delete(destinationFile + oldExt); + + File.Move(destinationFile, destinationFile + oldExt); + } + else + { + File.Delete(destinationFile); + } + } + + File.Move(sourceFile, destinationFile); + } + + [UsedImplicitly] + [Pure] + public static bool IsFileLocked([NotNull] string filename) + { + filename.ThrowIfNullOrWhiteSpace(nameof(filename)); + + return IsFileLocked(new FileInfo(filename)); + } + + [UsedImplicitly] + [Pure] + public static bool IsFileLocked([NotNull] FileInfo fileInfo) + { + fileInfo.ThrowIfNull(nameof(fileInfo)); + + try + { + using (fileInfo.Open(FileMode.Open, + FileAccess.ReadWrite, FileShare.None)) + { + } + } + catch (FileNotFoundException) + { + throw; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (IOException) + { + return true; + } +#pragma warning restore CA1031 // Do not catch general exception types + + return false; + } + + [UsedImplicitly] + [Pure] + public static bool IsFile([NotNull] string path) + { + path.ThrowIfNullOrWhiteSpace(nameof(path)); + + path = path.Trim(); + + if (Directory.Exists(path)) + return false; + + if (File.Exists(path)) + return true; + + return new[] {Path.DirectorySeparatorChar.ToString(), Path.AltDirectorySeparatorChar.ToString()} + .Any(x => !path.EndsWith(x)) && !string.IsNullOrWhiteSpace(Path.GetExtension(path)); + } + } +} \ No newline at end of file diff --git a/src/FingerPrint.cs b/src/FingerPrint.cs new file mode 100644 index 0000000..668fd11 --- /dev/null +++ b/src/FingerPrint.cs @@ -0,0 +1,230 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Management; +using System.Security.Cryptography; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + /// + /// Generates a 16 byte Unique Identification code of a computer + /// Example: 4876-8DB5-EE85-69D3-FE52-8CF7-395D-2EA9 + /// https://www.codeproject.com/Articles/28678/Generating-Unique-Key-Finger-Print-for-a-Computer + /// + public static class FingerPrintProvider + { + [CanBeNull] private static string _fingerPrint; + + [UsedImplicitly] + [NotNull] + public static string GetValue() + { + if (_fingerPrint != null) + return _fingerPrint; + + try + { + var listId = new[] + { + CpuId(), + BiosId(), + BaseId(), + VideoId(), + MacId() + //diskId() + }; + + if (listId.All(string.IsNullOrWhiteSpace)) + throw new Exception(); + + _fingerPrint = GetHash("CPU >> " + listId[0] + + "\nBIOS >> " + listId[1] + + "\nBASE >> " + listId[2] + + "\nVIDEO >> " + listId[3] + + "\nMAC >> " + listId[4] + //"\nDISK >> " + listId[5] + ); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch //AV Block? + { + _fingerPrint = string.Empty; + } +#pragma warning restore CA1031 // Do not catch general exception types + + return _fingerPrint; + } + + [UsedImplicitly] + [NotNull] + public static async Task GetValueAsync(CancellationToken ct = default) + { + return _fingerPrint ?? await Task.Factory.StartNew(GetValue, ct); + } + + [NotNull] + private static string GetHash([NotNull] string s) + { + s.ThrowIfNull(nameof(s)); + + MD5 sec = new MD5CryptoServiceProvider(); + var enc = new ASCIIEncoding(); + var bt = enc.GetBytes(s); + return GetHexString(sec.ComputeHash(bt)); + } + + [NotNull] + private static string GetHexString([NotNull] IReadOnlyList bt) + { + bt.ThrowIfNull(nameof(bt)); + + var s = string.Empty; + for (var i = 0; i < bt.Count; i++) + { + int n = bt[i]; + var n1 = n & 15; + var n2 = (n >> 4) & 15; + if (n2 > 9) + s += ((char) (n2 - 10 + 'A')).ToString(); + else + s += n2.ToString(); + if (n1 > 9) + s += ((char) (n1 - 10 + 'A')).ToString(); + else + s += n1.ToString(); + if (i + 1 != bt.Count && (i + 1) % 2 == 0) s += "-"; + } + + return s; + } + + #region Original Device ID Getting Code + + //Return a hardware identifier + private static string Identifier(string wmiClass, string wmiProperty, string wmiMustBeTrue) + { + var result = string.Empty; + var mc = new ManagementClass(wmiClass); + foreach (var o in mc.GetInstances()) + { + var mo = (ManagementObject) o; + if (mo[wmiMustBeTrue].ToString() != "True") + continue; + if (!string.IsNullOrWhiteSpace(result)) + continue; + try + { + result = mo[wmiProperty].ToString(); + break; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch + { + // ignored + } +#pragma warning restore CA1031 // Do not catch general exception types + } + + return result; + } + + //Return a hardware identifier + private static string Identifier(string wmiClass, string wmiProperty) + { + var result = string.Empty; + var mc = new ManagementClass(wmiClass); + foreach (var o in mc.GetInstances()) + //Only get the first one + { + var mo = (ManagementObject) o; + if (!string.IsNullOrWhiteSpace(result)) + continue; + try + { + result = mo[wmiProperty].ToString(); + break; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch + { + // ignored + } +#pragma warning restore CA1031 // Do not catch general exception types + } + + return result; + } + + private static string CpuId() + { + //Uses first CPU identifier available in order of preference + //Don't get all identifiers, as it is very time consuming + var retVal = Identifier("Win32_Processor", "UniqueId"); + + if (!string.IsNullOrWhiteSpace(retVal)) + return retVal; + + retVal = Identifier("Win32_Processor", "ProcessorId"); + + if (!string.IsNullOrWhiteSpace(retVal)) + return retVal; + + retVal = Identifier("Win32_Processor", "Name"); + if (string.IsNullOrWhiteSpace(retVal)) //If no Name, use Manufacturer + retVal = Identifier("Win32_Processor", "Manufacturer"); + //Add clock speed for extra security + retVal += Identifier("Win32_Processor", "MaxClockSpeed"); + return retVal; + } + + //BIOS Identifier + private static string BiosId() + { + return Identifier("Win32_BIOS", "Manufacturer") + + Identifier("Win32_BIOS", "SMBIOSBIOSVersion") + + Identifier("Win32_BIOS", "IdentificationCode") + + Identifier("Win32_BIOS", "SerialNumber") + + Identifier("Win32_BIOS", "ReleaseDate") + + Identifier("Win32_BIOS", "Version"); + } + + //Main physical hard drive ID + //private static string DiskId() + //{ + // return identifier("Win32_DiskDrive", "Model") + // + identifier("Win32_DiskDrive", "Manufacturer") + // + identifier("Win32_DiskDrive", "Signature") + // + identifier("Win32_DiskDrive", "TotalHeads"); + //} + + //Motherboard ID + private static string BaseId() + { + return Identifier("Win32_BaseBoard", "Model") + + Identifier("Win32_BaseBoard", "Manufacturer") + + Identifier("Win32_BaseBoard", "Name") + + Identifier("Win32_BaseBoard", "SerialNumber"); + } + + //Primary video controller ID + private static string VideoId() + { + return Identifier("Win32_VideoController", "DriverVersion") + + Identifier("Win32_VideoController", "Name"); + } + + //First enabled network card ID + private static string MacId() + { + return Identifier("Win32_NetworkAdapterConfiguration", + "MACAddress", "IPEnabled"); + } + + #endregion Original Device ID Getting Code + } +} \ No newline at end of file diff --git a/src/IsValidString.cs b/src/IsValidString.cs new file mode 100644 index 0000000..0f22cc9 --- /dev/null +++ b/src/IsValidString.cs @@ -0,0 +1,180 @@ +using System; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + public static class IsValidStringUtils + { + #region Email + + public const int EmailMinLength = 5; + public const int EmailMaxLength = 64; + + private const string MatchEmailPattern = + @"^(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]? + [0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]? + [0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|([a-zA-Z0-9]+[\w-]+\.)+[a-zA-Z]{1}[a-zA-Z0-9-]{1,23})$"; + + /// + /// Is Valid Email Address + /// + /// + /// + /// Is null or empty or white space + /// Invalid length + /// Invalid pattern + [UsedImplicitly] + [ContractAnnotation("emailAddress:null => false")] + [ContractAnnotation("=> false, exception:notnull")] + [ContractAnnotation("=> true, exception:null")] + [Pure] + public static bool IsValidEmailAddress([CanBeNull] string emailAddress, out Exception exception) + { + try + { + emailAddress.ThrowIfNullOrWhiteSpace(nameof(emailAddress)); + emailAddress.Length.ThrowIfNotWithinInclusive(EmailMinLength, EmailMaxLength, nameof(emailAddress)); + emailAddress.ThrowIfNotMatchRegEx(MatchEmailPattern, nameof(emailAddress)); + + exception = null; + return true; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception e) + { + exception = e; + return false; + } +#pragma warning restore CA1031 // Do not catch general exception types + } + + #endregion + + #region UserName + + public const int UserNameMinLength = 3; + public const int UserNameMaxLength = 15; + + private const string MatchUserNamePattern = + "^[A-Za-z0-9]{3,15}$"; + + private const string MatchUserNameClanPattern = + "^[A-Za-z0-9_]{3,15}$"; + + /// + /// Is Valid User Name + /// + /// + /// + /// + /// Is null or empty or white space + /// Invalid length + /// Invalid pattern + [UsedImplicitly] + [ContractAnnotation("userName:null => false")] + [ContractAnnotation("=> false, exception:notnull")] + [ContractAnnotation("=> true, exception:null")] + [Pure] + public static bool IsValidUserName([CanBeNull] string userName, out Exception exception, + bool allowClanTag = false) + { + try + { + userName.ThrowIfNullOrWhiteSpace(nameof(userName)); + userName.Length.ThrowIfNotWithinInclusive(UserNameMinLength, UserNameMaxLength, nameof(userName)); + userName.ThrowIfNotMatchRegEx(allowClanTag ? MatchUserNameClanPattern : MatchUserNamePattern, + nameof(userName)); + + exception = null; + return true; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception e) + { + exception = e; + return false; + } +#pragma warning restore CA1031 // Do not catch general exception types + } + + #endregion + + #region Password + + public const int PasswordMinLength = 3; + public const int PasswordMaxLength = 15; + + /// + /// Is Valid Password + /// + /// + /// + /// Is null or empty or white space + /// Invalid length + /// Invalid pattern + [UsedImplicitly] + [ContractAnnotation("password:null => false")] + [ContractAnnotation("=> false, exception:notnull")] + [ContractAnnotation("=> true, exception:null")] + [Pure] + public static bool IsValidPassword([CanBeNull] string password, out Exception exception) + { + try + { + password.ThrowIfNullOrWhiteSpace(nameof(password)); + password.Length.ThrowIfNotWithinInclusive(PasswordMinLength, PasswordMaxLength, nameof(password)); + if (password.Contains("'") || password.Contains("\"")) + throw new ArgumentException(string.Empty, nameof(password)); + exception = null; + return true; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception e) + { + exception = e; + return false; + } +#pragma warning restore CA1031 // Do not catch general exception types + } + + #endregion + + #region VerifyKey + + public const int VerifyKeyLength = 32; + + /// + /// Is Valid Password + /// + /// + /// + /// Is null or empty or white space + /// Invalid length + /// Invalid pattern + [UsedImplicitly] + [ContractAnnotation("verifyKey:null => false")] + [ContractAnnotation("=> false, exception:notnull")] + [ContractAnnotation("=> true, exception:null")] + [Pure] + public static bool IsValidVerifyKey([CanBeNull] string verifyKey, out Exception exception) + { + try + { + verifyKey.ThrowIfNullOrWhiteSpace(nameof(verifyKey)); + verifyKey.Length.ThrowIfNotEquals(VerifyKeyLength, nameof(verifyKey)); + exception = null; + return true; + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception e) + { + exception = e; + return false; + } +#pragma warning restore CA1031 // Do not catch general exception types + } + + #endregion + } +} \ No newline at end of file diff --git a/src/Json.cs b/src/Json.cs new file mode 100644 index 0000000..fac8716 --- /dev/null +++ b/src/Json.cs @@ -0,0 +1,73 @@ +using System.IO; +using System.Text; +using JetBrains.Annotations; +using Newtonsoft.Json; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + public static class JsonUtils + { + [UsedImplicitly] + public static void SerializeToJsonFile([NotNull] this object serializableObject, [NotNull] string filePath, + Encoding encoding, bool backup = true, [NotNull] string backupExt = ".bak") + { + serializableObject.ThrowIfNull(nameof(serializableObject)); + filePath.ThrowIfNullOrWhiteSpace(nameof(filePath)); + backupExt.ThrowIfNullOrWhiteSpace(nameof(backupExt)); + encoding.ThrowIfNull(nameof(encoding)); + + var xml = serializableObject.SerializeToJson(encoding); + + if (File.Exists(filePath)) + { + if (backup) + { + var backupFile = filePath + backupExt; + + if (File.Exists(backupFile)) + File.Delete(backupFile); + + File.Move(filePath, backupFile); + } + + File.Delete(filePath); + } + + File.WriteAllText(filePath, xml, Encoding.UTF8); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static string SerializeToJson([NotNull] this T value, Encoding encoding) where T : class + { + value.ThrowIfNull(nameof(value)); + encoding.ThrowIfNull(nameof(encoding)); + + return JsonConvert.SerializeObject(value, Formatting.Indented); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static T DeserializeFromJson([NotNull] string json, Encoding encoding) where T : class + { + json.ThrowIfNullOrWhiteSpace(nameof(json)); + encoding.ThrowIfNull(nameof(encoding)); + + return JsonConvert.DeserializeObject(json); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static T DeserializeFromJsonFile([NotNull] string filePath, Encoding encoding) where T : class + { + filePath.ThrowIfNullOrWhiteSpace(nameof(filePath)); + encoding.ThrowIfNull(nameof(encoding)); + + return DeserializeFromJson(File.ReadAllText(filePath, encoding), encoding); + } + } +} \ No newline at end of file diff --git a/src/Network.cs b/src/Network.cs new file mode 100644 index 0000000..385d7b7 --- /dev/null +++ b/src/Network.cs @@ -0,0 +1,117 @@ +#nullable enable +using System; +using System.Net; +using System.Net.Sockets; +using System.Runtime.InteropServices; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + public static class NetworkUtils + { + [UsedImplicitly] + [NotNull] + [Pure] + public static IPAddress GetLocalIp([NotNull] Socket activeSocket) + { + activeSocket.ThrowIfNull(nameof(activeSocket)); + + if (!(activeSocket.LocalEndPoint is IPEndPoint ipEndPoint) || Equals(ipEndPoint.Address, IPAddress.Any)) + throw new InvalidOperationException("Socket not connected"); + + return ipEndPoint.Address; + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static IPAddress GetIpAddress(uint ipAddress) + { + var addressBytes = BitConverter.GetBytes(ipAddress); + Array.Reverse(addressBytes); + + return new IPAddress(addressBytes); + } + + [UsedImplicitly] + [Pure] + public static uint GetIpAddress([NotNull] IPAddress ipAddress) + { + ipAddress.ThrowIfNull(nameof(ipAddress)); + + var addressBytes = ipAddress.GetAddressBytes(); + Array.Reverse(addressBytes); + + return BitConverter.ToUInt32(addressBytes, 0); + } + + [UsedImplicitly] + [Pure] + public static uint NetworkToHostOrder(uint input) + { + return (uint) IPAddress.NetworkToHostOrder((int) input); + } + + [UsedImplicitly] + [Pure] + public static ulong NetworkToHostOrder(ulong input) + { + return (ulong) IPAddress.NetworkToHostOrder((long) input); + } + + [UsedImplicitly] + [Pure] + public static ushort NetworkToHostOrder(ushort input) + { + return (ushort) IPAddress.NetworkToHostOrder((short) input); + } + + [UsedImplicitly] + public static bool TryParseIpEndPoint([NotNull] string stringValue, [CanBeNull] out IPEndPoint? endPoint) + { + stringValue.ThrowIfNullOrWhiteSpace(nameof(stringValue)); + + var endpointParts = stringValue.Split(':'); + if (endpointParts.Length != 2) + { + endPoint = null; + return false; + } + + if (!IPAddress.TryParse(endpointParts[0], out var address)) + { + endPoint = null; + return false; + } + + if (!ushort.TryParse(endpointParts[1], out var port)) + { + endPoint = null; + return false; + } + + endPoint = new IPEndPoint(address, port); + return true; + } + + [DllImport("wininet.dll")] + private static extern bool InternetGetConnectedState(out int description, int reservedValue); + + [UsedImplicitly] + [Pure] + public static bool IsConnectedToInternet() + { + try + { + return InternetGetConnectedState(out _, 0); + } +#pragma warning disable CA1031 // Do not catch general exception types + catch (Exception) + { + return true; + } +#pragma warning restore CA1031 // Do not catch general exception types + } + } +} \ No newline at end of file diff --git a/src/OSVersion.cs b/src/OSVersion.cs new file mode 100644 index 0000000..7f37e08 --- /dev/null +++ b/src/OSVersion.cs @@ -0,0 +1,145 @@ +#region Using directives + +using System; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +#endregion + +namespace ProjectCeleste.Misc.Utils +{ + public sealed class OsVersionInfo + { + internal OsVersionInfo([NotNull] string name, [NotNull] Version version) + { + name.ThrowIfNullOrWhiteSpace(nameof(name)); + version.ThrowIfNull(nameof(version)); + + Name = name; + Minor = version.Minor; + Major = version.Major; + Build = version.Build; + FullName = "Microsoft " + Name + " [Version " + Major + "." + Minor + "." + Build + "]"; + } + + [UsedImplicitly] [NotNull] public string Name { get; } + + [UsedImplicitly] [NotNull] public string FullName { get; } + + [UsedImplicitly] public int Minor { get; } + + [UsedImplicitly] public int Major { get; } + + [UsedImplicitly] public int Build { get; } + } + + public static class OsVersionUtils + { + private static OsVersionInfo _osVersionInfo; + + /// + /// Init OSVersionInfo object by current windows environment + /// + /// + /// + [UsedImplicitly] + [NotNull] + [Pure] + public static OsVersionInfo GetOsVersionInfo() + { + if (_osVersionInfo != null) + return _osVersionInfo; + + var osVersionObj = Environment.OSVersion; + _osVersionInfo = new OsVersionInfo(GetOsName(osVersionObj), osVersionObj.Version); + return _osVersionInfo; + } + + /// + /// Get current windows name + /// + /// + /// + /// + [NotNull] + private static string GetOsName([NotNull] OperatingSystem osInfo) + { + return osInfo.Platform switch + { + //for old windows kernel + PlatformID.Win32Windows => ForWin32Windows(osInfo), + //fow NT kernel + PlatformID.Win32NT => ForWin32Nt(osInfo), + PlatformID.MacOSX => throw new NotSupportedException(), + PlatformID.Unix => throw new NotSupportedException(), + PlatformID.Win32S => throw new NotSupportedException(), + PlatformID.WinCE => throw new NotSupportedException(), + PlatformID.Xbox => throw new NotSupportedException(), + _ => throw new ArgumentOutOfRangeException(nameof(osInfo.Platform), osInfo.Platform, string.Empty) + }; + } + + /// + /// for old windows kernel + /// this function is the child function for method GetOSName + /// + /// + /// + [NotNull] + private static string ForWin32Windows([NotNull] OperatingSystem osInfo) + { + //Code to determine specific version of Windows 95, + //Windows 98, Windows 98 Second Edition, or Windows Me. + return osInfo.Version.Minor switch + { + 0 => "Windows 95", + 10 => osInfo.Version.Revision.ToString() switch + { + "2222A" => "Windows 98 Second Edition", + _ => "Windows 98" + }, + 90 => "Windows Me", + _ => throw new ArgumentOutOfRangeException(nameof(osInfo.Version.Minor), osInfo.Version.Minor, + string.Empty) + }; + } + + /// + /// fow NT kernel + /// this function is the child function for method GetOSName + /// + /// + /// + [NotNull] + private static string ForWin32Nt([NotNull] OperatingSystem osInfo) + { + //Code to determine specific version of Windows NT 3.51, + //Windows NT 4.0, Windows 2000, or Windows XP. + return osInfo.Version.Major switch + { + 3 => "Windows NT 3.51", + 4 => "Windows NT 4.0", + 5 => osInfo.Version.Minor switch + { + 0 => "Windows 2000", + 1 => "Windows XP", + 2 => "Windows 2003", + _ => throw new ArgumentOutOfRangeException(nameof(osInfo.Version.Minor), osInfo.Version.Minor, + string.Empty) + }, + 6 => osInfo.Version.Minor switch + { + 0 => "Windows Vista", + 1 => "Windows 7", + 2 => "Windows 8", + 3 => "Windows 8.1", + _ => throw new ArgumentOutOfRangeException(nameof(osInfo.Version.Minor), osInfo.Version.Minor, + string.Empty) + }, + 10 => "Windows 10", + _ => throw new ArgumentOutOfRangeException(nameof(osInfo.Version.Major), osInfo.Version.Major, + string.Empty) + }; + } + } +} \ No newline at end of file diff --git a/src/ProjectCeleste.Misc.Utils.csproj b/src/ProjectCeleste.Misc.Utils.csproj new file mode 100644 index 0000000..cbfe290 --- /dev/null +++ b/src/ProjectCeleste.Misc.Utils.csproj @@ -0,0 +1,56 @@ + + + + netstandard2.0 + true + true + ProjectCeleste.Misc.Utils + https://github.com/ProjectCeleste/ProjectCeleste.Misc.Utils/blob/master/LICENSE + https://www.projectceleste.com + icon.png + https://github.com/ProjectCeleste/ProjectCeleste.Misc.Utils + git + + ProjectCeleste.Misc.Utils For Age Of Empires Online Celeste Fan Project + + Visit Us: https://www.projectceleste.com/ + + Age of Empires Online © Microsoft Corporation. Celeste Fan Project was created under Microsoft's Game Content Usage Rules using assets from Age of Empires Online, and it is not endorsed by or affiliated with Microsoft (See: https://www.xbox.com/en-us/developers/rules). + + projectceleste aoeo ageofempires + ProjectCeleste + + ProjectCeleste.Misc.Utils + 0.0.0.0 + 0.0.0.0 + 0.0.0.0 + v0.0 + true + true + snupkg + latest + + true + + + DEBUG;TRACE + + + TRACE + + + + + + + all + runtime; build; native; contentfiles; analyzers + + + + + + + + + \ No newline at end of file diff --git a/src/Random.cs b/src/Random.cs new file mode 100644 index 0000000..9da6038 --- /dev/null +++ b/src/Random.cs @@ -0,0 +1,106 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; +using ProjectCeleste.Misc.Utils.RandomGenerator; + +namespace ProjectCeleste.Misc.Utils +{ + public static class RandomUtils + { + [UsedImplicitly] + [NotNull] + [Pure] + public static string RandomString(int length, bool allowDigit = true, bool allowLowerCase = false, + bool allowSpecialChar = false) + { + int seed; + using (var r = new CryptoRandomGenerator()) + { + seed = r.Next(int.MinValue, int.MaxValue); + } + + return RandomString(length, seed, allowDigit, allowLowerCase, allowSpecialChar); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static string RandomString(int length, int seed, bool allowDigit = true, bool allowLowerCase = false, + bool allowSpecialChar = false) + { + var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; + + if (allowLowerCase) + chars += chars.ToLower(); + + if (allowDigit) + chars += "0123456789"; + + if (allowSpecialChar) + chars += @"$%-_#@&*-+=!?.,:;<>[]{}()/\|"; + + var random = new Random(seed); + + return new string(Enumerable.Repeat(chars, length) + .OrderBy(_ => random.Next()).Select(s => s[random.Next(s.Length - 1)]).ToArray()); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static T RandomWithChance([NotNull] params KeyValuePair[] args) + { + args.ThrowIfNull(nameof(args)); + + Random random; + using (var r = new CryptoRandomGenerator()) + { + random = new Random(r.Next(int.MinValue, int.MaxValue)); + } + + var rndList = args.OrderBy(_ => random.Next()).ToArray(); + var rndNumber = random.NextDouble(); + var cumulative = 0.0; + + foreach (var arg in rndList) + { + cumulative += arg.Value; + if (rndNumber <= cumulative) + return arg.Key; + } + + return rndList[0].Key; + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static T RandomWithWeight([NotNull] params KeyValuePair[] args) + { + args.ThrowIfNull(nameof(args)); + + if (args.Any(key => key.Value < 0)) + return args.Where(key => key.Value < 0).OrderByDescending(key => key).First().Key; + + args = args.Where(key => key.Value >= 0).ToArray(); + var sum = args.Sum(key => Convert.ToInt64(key.Value)); + return RandomWithChance((from value in args + let chance = (double) value.Value / sum + select new KeyValuePair(value.Key, chance)).ToArray()); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static T RandomWithoutChance([NotNull] params T[] args) + { + args.ThrowIfNull(nameof(args)); + + return RandomWithChance((from value in args + let chance = 1.00 / args.Length + select new KeyValuePair(value, chance)).ToArray()); + } + } +} \ No newline at end of file diff --git a/src/RandomGenerator/CryptoRandom.cs b/src/RandomGenerator/CryptoRandom.cs new file mode 100644 index 0000000..ac8feb7 --- /dev/null +++ b/src/RandomGenerator/CryptoRandom.cs @@ -0,0 +1,150 @@ +using System; +using System.Security.Cryptography; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.RandomGenerator +{ + public class CryptoRandomGenerator : IDisposable + { + private RandomNumberGenerator _r; + + /// + /// Creates an instance of the default implementation of a cryptographic random number generator that can be used to + /// generate random data. + /// + [UsedImplicitly] + public CryptoRandomGenerator() + { + _r = RandomNumberGenerator.Create(); + } + + /// + /// Fills the elements of a specified array of bytes with random numbers. + /// + /// An array of bytes to contain random numbers. + /// buffer is a null reference (Nothing in Visual Basic). + [UsedImplicitly] + public void NextBytes([NotNull] byte[] buffer) + { + _r.GetBytes(buffer); + } + + /// + /// Returns a random number between 0.0 and 1.0. + /// + [UsedImplicitly] + [Pure] + public double NextDouble() + { + var b = new byte[4]; + _r.GetBytes(b); + return BitConverter.ToUInt32(b, 0) / ((double) uint.MaxValue + 1); + } + + /// + /// Returns a random number within the specified range. + /// + /// The inclusive lower bound of the random number returned. + /// + /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal + /// to minValue. + /// + [UsedImplicitly] + [Pure] + public long NextLong(long minValue, long maxValue) + { + var range = maxValue - minValue; + return (long) Math.Floor(NextDouble() * range) + minValue; + } + + /// + /// Returns a nonnegative random number. + /// + [UsedImplicitly] + [Pure] + public long NextLong() + { + return NextLong(0, long.MaxValue); + } + + /// + /// Returns a nonnegative random number less than the specified maximum + /// + /// + /// The inclusive upper bound of the random number returned. maxValue must be greater than or equal + /// 0 + /// + [UsedImplicitly] + [Pure] + public long NextLong(long maxValue) + { + return NextLong(0, maxValue); + } + + /// + /// Returns a random number within the specified range. + /// + /// The inclusive lower bound of the random number returned. + /// + /// The exclusive upper bound of the random number returned. maxValue must be greater than or equal + /// to minValue. + /// + [UsedImplicitly] + [Pure] + public int Next(int minValue, int maxValue) + { + var range = (long) maxValue - minValue; + return (int) ((long) Math.Floor(NextDouble() * range) + minValue); + } + + /// + /// Returns a nonnegative random number. + /// + [UsedImplicitly] + [Pure] + public int Next() + { + return Next(0, int.MaxValue); + } + + /// + /// Returns a nonnegative random number less than the specified maximum + /// + /// + /// The inclusive upper bound of the random number returned. maxValue must be greater than or equal + /// 0 + /// + [UsedImplicitly] + [Pure] + public int Next(int maxValue) + { + return Next(0, maxValue); + } + + #region IDisposable Support + + private bool _disposedValue; + + protected virtual void Dispose(bool disposing) + { + if (_disposedValue) + return; + + if (disposing) + { + _r.Dispose(); + _r = null; + } + + _disposedValue = true; + } + + [UsedImplicitly] + public void Dispose() + { + Dispose(true); + } + + #endregion + } +} \ No newline at end of file diff --git a/src/RandomGenerator/StaticRandom.cs b/src/RandomGenerator/StaticRandom.cs new file mode 100644 index 0000000..01fad9c --- /dev/null +++ b/src/RandomGenerator/StaticRandom.cs @@ -0,0 +1,160 @@ +using System; +using System.ComponentModel.DataAnnotations; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils.RandomGenerator +{ + /// + /// Thread-safe equivalent of System.Random using static methods. + /// + public static class StaticRandom + { + private static readonly Random Random = new Random(); + private static readonly object SyncLock = new object(); + + /// + /// Returns a nonnegative random number. + /// + /// A 32-bit signed integer greater than or equal to zero and less than Int32.MaxValue. + [UsedImplicitly] + [Pure] + public static int Next() + { + lock (SyncLock) + { + return Random.Next(); + } + } + + /// + /// Returns a nonnegative random number less than the specified maximum. + /// + /// + /// A 32-bit signed integer greater than or equal to zero, and less than maxValue; + /// that is, the range of return values includes zero but not maxValue. + /// + /// maxValue is less than zero. + [UsedImplicitly] + [Pure] + public static int Next([Range(1, int.MaxValue)] int max) + { + lock (SyncLock) + { + return Random.Next(max); + } + } + + /// + /// Returns a random number within a specified range. + /// + /// The inclusive lower bound of the random number returned. + /// + /// The exclusive upper bound of the random number returned. + /// maxValue must be greater than or equal to minValue. + /// + /// + /// A 32-bit signed integer greater than or equal to minValue and less than maxValue; + /// that is, the range of return values includes minValue but not maxValue. + /// If minValue equals maxValue, minValue is returned. + /// + /// minValue is greater than maxValue. + [UsedImplicitly] + [Pure] + public static int Next([Range(int.MinValue, int.MaxValue - 1)] + int min, [Range(int.MinValue + 1, int.MaxValue)] + int max) + { + lock (SyncLock) + { + return Random.Next(min, max); + } + } + + /// + /// Returns a random number between 0.0 and 1.0. + /// + /// A double-precision floating point number greater than or equal to 0.0, and less than 1.0. + [UsedImplicitly] + [Pure] + public static double NextDouble() + { + lock (SyncLock) + { + return Random.NextDouble(); + } + } + + /// + /// Fills the elements of a specified array of bytes with random numbers. + /// + /// An array of bytes to contain random numbers. + /// buffer is a null reference (Nothing in Visual Basic). + [UsedImplicitly] + public static void NextBytes([NotNull] byte[] buffer) + { + lock (SyncLock) + { + Random.NextBytes(buffer); + } + } + + /// + /// Returns a nonnegative random number. + /// + /// A 64-bit signed integer greater than or equal to zero and less than Int32.MaxValue. + [UsedImplicitly] + [Pure] + public static long NextLong() + { + lock (SyncLock) + { + return Random.NextLong(long.MinValue, long.MaxValue); + } + } + + /// + /// Returns a nonnegative random number less than the specified maximum. + /// + /// + /// A 64-bit signed integer greater than or equal to zero, and less than maxValue; + /// that is, the range of return values includes zero but not maxValue. + /// + /// maxValue is less than zero. + [UsedImplicitly] + [Pure] + public static long NextLong([Range(1, long.MaxValue)] long max) + { + lock (SyncLock) + { + return Random.NextLong(0, max); + } + } + + /// + /// Returns a random number within a specified range. + /// + /// The inclusive lower bound of the random number returned. + /// + /// The exclusive upper bound of the random number returned. + /// maxValue must be greater than or equal to minValue. + /// + /// + /// A 64-bit signed integer greater than or equal to minValue and less than maxValue; + /// that is, the range of return values includes minValue but not maxValue. + /// If minValue equals maxValue, minValue is returned. + /// + /// minValue is greater than maxValue. + [UsedImplicitly] + [Pure] + public static long NextLong([Range(long.MinValue, long.MaxValue - 1)] + long min, [Range(long.MinValue + 1, long.MaxValue)] + long max) + { + lock (SyncLock) + { + return Random.NextLong(min, max); + } + } + } +} \ No newline at end of file diff --git a/src/RandomGenerator/UniqueRandomInt.cs b/src/RandomGenerator/UniqueRandomInt.cs new file mode 100644 index 0000000..672f6dd --- /dev/null +++ b/src/RandomGenerator/UniqueRandomInt.cs @@ -0,0 +1,65 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using JetBrains.Annotations; + +namespace ProjectCeleste.Misc.Utils.RandomGenerator +{ + [UsedImplicitly] + public class UniqueRandomIntGenerator + { + private readonly int _randomMaxReTry = 25000 * Environment.ProcessorCount; + private readonly object _syncLock = new object(); + private readonly IList _excludeNumbers; + private readonly int _minValue; + private readonly int _maxValue; + private Random _random; + + public UniqueRandomIntGenerator([Range(int.MinValue, int.MaxValue - 1)] + int min = int.MinValue, [Range(int.MinValue + 1, int.MaxValue)] + int max = int.MaxValue, + [CanBeNull] IEnumerable excludeNumbers = null) + { + if (min > max) + throw new ArgumentOutOfRangeException(nameof(min), min, "minValue is greater than maxValue"); + + _minValue = min; + _maxValue = max; + _excludeNumbers = excludeNumbers as List ?? excludeNumbers.ToList(); + + ReNewSeed(); + } + + private void ReNewSeed() + { + using var r = new CryptoRandomGenerator(); + _random = new Random(r.Next(int.MinValue, int.MaxValue)); + } + + [UsedImplicitly] + [Pure] + public int Next() + { + lock (_syncLock) + { + var countReTry = 0L; + var number = _random.Next(_minValue, _maxValue); + while (_excludeNumbers.Contains(number) && countReTry <= _randomMaxReTry) + { + countReTry++; + number = _random.Next(_minValue, _maxValue); + } + + if (_excludeNumbers.Contains(number)) + { + ReNewSeed(); + throw new IndexOutOfRangeException("Out of number, seed has been renewed"); + } + + _excludeNumbers.Add(number); + return number; + } + } + } +} \ No newline at end of file diff --git a/src/RandomGenerator/UniqueRandomLong.cs b/src/RandomGenerator/UniqueRandomLong.cs new file mode 100644 index 0000000..eed2ce9 --- /dev/null +++ b/src/RandomGenerator/UniqueRandomLong.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils.RandomGenerator +{ + [UsedImplicitly] + public class UniqueRandomLongGenerator + { + private readonly long _randomMaxReTry = 25000 * Environment.ProcessorCount; + private readonly object _syncLock = new object(); + private readonly IList _excludeNumbers; + private readonly long _minValue; + private readonly long _maxValue; + private Random _random; + + public UniqueRandomLongGenerator([Range(long.MinValue, long.MaxValue - 1)] + long min = long.MinValue, [Range(long.MinValue + 1, long.MaxValue)] + long max = long.MaxValue, + [CanBeNull] IEnumerable excludeNumbers = null) + { + if (min > max) + throw new ArgumentOutOfRangeException(nameof(min), min, "minValue is greater than maxValue"); + + _minValue = min; + _maxValue = max; + _excludeNumbers = excludeNumbers as List ?? excludeNumbers.ToList(); + + ReNewSeed(); + } + + private void ReNewSeed() + { + using var r = new CryptoRandomGenerator(); + _random = new Random(r.Next(int.MinValue, int.MaxValue)); + } + + [UsedImplicitly] + [Pure] + public long Next() + { + lock (_syncLock) + { + var countReTry = 0L; + var number = _random.NextLong(_minValue, _maxValue); + while (_excludeNumbers.Contains(number) && countReTry <= _randomMaxReTry) + { + countReTry++; + number = _random.NextLong(_minValue, _maxValue); + } + + if (_excludeNumbers.Contains(number)) + { + ReNewSeed(); + throw new IndexOutOfRangeException("Out of number, seed has been renewed"); + } + + _excludeNumbers.Add(number); + return number; + } + } + } +} \ No newline at end of file diff --git a/src/StringWriterWithEncoding.cs b/src/StringWriterWithEncoding.cs new file mode 100644 index 0000000..f0955ac --- /dev/null +++ b/src/StringWriterWithEncoding.cs @@ -0,0 +1,63 @@ +using System; +using System.IO; +using System.Text; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + public class StringWriterWithEncoding : StringWriter + { + [UsedImplicitly] + public StringWriterWithEncoding([NotNull] Encoding encoding) + { + encoding.ThrowIfNull(nameof(encoding)); + Encoding = encoding; + } + + /// Initializes a new instance of the class with the specified format control. + /// An object that controls formatting. + /// The encoding to report. + [UsedImplicitly] + public StringWriterWithEncoding([NotNull] IFormatProvider formatProvider, [NotNull] Encoding encoding) + : base(formatProvider) + { + encoding.ThrowIfNull(nameof(encoding)); + Encoding = encoding; + } + + /// + /// Initializes a new instance of the class that writes to the specified + /// . + /// + /// The object to write to. + /// sb is null. + /// The encoding to report. + [UsedImplicitly] + public StringWriterWithEncoding([NotNull] StringBuilder sb, [NotNull] Encoding encoding) + : base(sb) + { + encoding.ThrowIfNull(nameof(encoding)); + Encoding = encoding; + } + + /// + /// Initializes a new instance of the class that writes to the specified + /// and has the specified format provider. + /// + /// The object to write to. + /// An object that controls formatting. + /// sb is null. + /// The encoding to report. + [UsedImplicitly] + public StringWriterWithEncoding([NotNull] StringBuilder sb, [NotNull] IFormatProvider formatProvider, + [NotNull] Encoding encoding) + : base(sb, formatProvider) + { + encoding.ThrowIfNull(nameof(encoding)); + Encoding = encoding; + } + + [UsedImplicitly] public override Encoding Encoding { get; } + } +} \ No newline at end of file diff --git a/src/SymLink.cs b/src/SymLink.cs new file mode 100644 index 0000000..43e3480 --- /dev/null +++ b/src/SymLink.cs @@ -0,0 +1,113 @@ +using System; +using System.ComponentModel; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; +using JetBrains.Annotations; +using Microsoft.Win32.SafeHandles; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + public static class SymbolicLinkUtils + { + public enum SymbolicLinkFlag + { + File = 0, + Directory = 1 + } + + private const int CREATION_DISPOSITION_OPEN_EXISTING = 3; + private const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000; + + [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + [return: MarshalAs(UnmanagedType.I1)] + private static extern bool CreateSymbolicLink(string lpSymlinkFileName, string lpTargetFileName, + SymbolicLinkFlag dwFlags); + + [UsedImplicitly] + public static bool CreateSymLink([NotNull] string lpSymlinkFileName, [NotNull] string lpTargetFileName) + { + lpSymlinkFileName.ThrowIfNullOrWhiteSpace(nameof(lpSymlinkFileName)); + lpTargetFileName.ThrowIfNullOrWhiteSpace(nameof(lpTargetFileName)); + + return CreateSymbolicLink(lpSymlinkFileName, lpTargetFileName, + DirectoryUtils.IsDirectory(lpTargetFileName) ? SymbolicLinkFlag.Directory : SymbolicLinkFlag.File); + } + + [UsedImplicitly] + public static bool CreateSymLink([NotNull] string lpSymlinkFileName, [NotNull] string lpTargetFileName, + SymbolicLinkFlag dwFlags) + { + lpSymlinkFileName.ThrowIfNullOrWhiteSpace(nameof(lpSymlinkFileName)); + lpTargetFileName.ThrowIfNullOrWhiteSpace(nameof(lpTargetFileName)); + + return CreateSymbolicLink(lpSymlinkFileName, lpTargetFileName, dwFlags); + } + + [UsedImplicitly] + [Pure] + public static bool IsSymLinkPath([NotNull] string path) + { + path.ThrowIfNullOrWhiteSpace(nameof(path)); + + return IsSymLinkPath(path, + DirectoryUtils.IsDirectory(path) ? SymbolicLinkFlag.Directory : SymbolicLinkFlag.File); + } + + [UsedImplicitly] + [Pure] + public static bool IsSymLinkPath([NotNull] string path, SymbolicLinkFlag dwFlags) + { + path.ThrowIfNullOrWhiteSpace(nameof(path)); + + return dwFlags switch + { + SymbolicLinkFlag.File => ((new FileInfo(path).Attributes & FileAttributes.ReparsePoint) != 0), + SymbolicLinkFlag.Directory => ((new DirectoryInfo(path).Attributes & FileAttributes.ReparsePoint) != 0), + _ => throw new ArgumentOutOfRangeException(nameof(dwFlags), dwFlags, null) + }; + } + + [DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)] + private static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, + IntPtr securityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile); + + [DllImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, + SetLastError = true)] + private static extern int GetFinalPathNameByHandle([In] IntPtr hFile, [Out] StringBuilder lpszFilePath, + [In] int cchFilePath, [In] int dwFlags); + + [UsedImplicitly] + [NotNull] + [Pure] + public static string GetSymLinkRealPath([NotNull] string path) + { + path.ThrowIfNullOrWhiteSpace(nameof(path)); + + if (!IsSymLinkPath(path)) + throw new Exception("Path is not an symlink"); + + if (!Directory.Exists(path) && !File.Exists(path)) + throw new FileNotFoundException("Path not found", path); + + var symlink = new DirectoryInfo(path); // No matter if it's a file or folder + var directoryHandle = CreateFile(symlink.FullName, 0, 2, IntPtr.Zero, CREATION_DISPOSITION_OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero); //Handle file / folder + + if (directoryHandle.IsInvalid) + throw new Win32Exception(Marshal.GetLastWin32Error()); + + var result = new StringBuilder(512); + var mResult = GetFinalPathNameByHandle(directoryHandle.DangerousGetHandle(), result, result.Capacity, 0); + + if (mResult < 0) + throw new Win32Exception(Marshal.GetLastWin32Error()); + + if (result.Length >= 4 && result[0] == '\\' && result[1] == '\\' && result[2] == '?' && result[3] == '\\') + return result.ToString().Substring(4); // "\\?\" remove + + return result.ToString(); + } + } +} \ No newline at end of file diff --git a/src/Xml.cs b/src/Xml.cs new file mode 100644 index 0000000..253ec4f --- /dev/null +++ b/src/Xml.cs @@ -0,0 +1,135 @@ +using System.IO; +using System.Text; +using System.Xml; +using System.Xml.Linq; +using System.Xml.Serialization; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; + +namespace ProjectCeleste.Misc.Utils +{ + public static class XmlUtils + { + [UsedImplicitly] + public static void SerializeToXmlFile([NotNull] T serializableObject, [NotNull] string filePath, + [NotNull] Encoding encoding, + bool backup = true, [NotNull] string backupExt = ".bak") where T : class + { + serializableObject.ThrowIfNull(nameof(serializableObject)); + filePath.ThrowIfNullOrWhiteSpace(nameof(filePath)); + backupExt.ThrowIfNullOrWhiteSpace(nameof(backupExt)); + encoding.ThrowIfNull(nameof(encoding)); + + var xml = SerializeToXml(serializableObject, encoding); + + if (File.Exists(filePath)) + { + if (backup) + { + var backupFile = $"{filePath}.bak"; + + if (File.Exists(backupFile)) + File.Delete(backupFile); + + File.Move(filePath, backupFile); + } + + File.Delete(filePath); + } + + File.WriteAllText(filePath, xml, encoding); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static string SerializeToXml([NotNull] T serializableObject, [NotNull] Encoding encoding) + where T : class + { + serializableObject.ThrowIfNull(nameof(serializableObject)); + encoding.ThrowIfNull(nameof(encoding)); + + string output; + var serializer = new XmlSerializer(serializableObject.GetType()); + var settings = new XmlWriterSettings + { + Encoding = Encoding.UTF8, + Indent = true, + OmitXmlDeclaration = true, + NewLineHandling = NewLineHandling.None + }; + var ns = new XmlSerializerNamespaces(); + ns.Add(string.Empty, string.Empty); + using (var stringWriter = new StringWriterWithEncoding(encoding)) + { + using (var xmlWriter = XmlWriter.Create(stringWriter, settings)) + { + serializer.Serialize(xmlWriter, serializableObject, ns); + } + + output = stringWriter.ToString(); + } + + return output; + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static T DeserializeFromXmlFile([NotNull] string filePath, [NotNull] Encoding encoding) + where T : class + { + filePath.ThrowIfNullOrWhiteSpace(nameof(filePath)); + encoding.ThrowIfNull(nameof(encoding)); + + return DeserializeFromXml(File.ReadAllText(filePath, encoding), encoding); + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static T DeserializeFromXml([NotNull] string xml, [NotNull] Encoding encoding) where T : class + { + xml.ThrowIfNullOrWhiteSpace(nameof(xml)); + encoding.ThrowIfNull(nameof(encoding)); + + T output; + var serializer = new XmlSerializer(typeof(T)); + using (var ms = new MemoryStream(encoding.GetBytes(xml))) + { + output = (T) serializer.Deserialize(ms); + } + + return output; + } + + [UsedImplicitly] + [NotNull] + [Pure] + public static string PrettyXml([NotNull] string xml, [NotNull] Encoding encoding) + { + xml.ThrowIfNullOrWhiteSpace(nameof(xml)); + encoding.ThrowIfNull(nameof(encoding)); + + string output; + var xmlDoc = XDocument.Parse(xml); + using (var stringWriter = new StringWriterWithEncoding(encoding)) + { + using (var xmlWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings + { + Encoding = Encoding.UTF8, + Indent = true, + OmitXmlDeclaration = false, + NewLineHandling = NewLineHandling.None + })) + { + xmlDoc.Save(xmlWriter); + } + + output = stringWriter.ToString(); + } + + return output; + } + } +} \ No newline at end of file diff --git a/src/ZipFile.cs b/src/ZipFile.cs new file mode 100644 index 0000000..06d27a6 --- /dev/null +++ b/src/ZipFile.cs @@ -0,0 +1,175 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Threading; +using System.Threading.Tasks; +using Ionic.Zip; +using JetBrains.Annotations; +using ProjectCeleste.Misc.Utils.Extension; +using CompressionLevel = Ionic.Zlib.CompressionLevel; +using ZipFile = System.IO.Compression.ZipFile; + +namespace ProjectCeleste.Misc.Utils +{ + public static class ZipFileUtils + { + private const int BufferSize = 64 * FileUtils.Kb; + + [UsedImplicitly] + [Obsolete("Use System.IO.Compression.ZipFile.ExtractToDirectory() instead")] + public static void ExtractZipFile([NotNull] string archiveFileName, [NotNull] string outFolder) + { + archiveFileName.ThrowIfNullOrWhiteSpace(nameof(archiveFileName)); + outFolder.ThrowIfNullOrWhiteSpace(nameof(outFolder)); + + using var zipFile = ZipFile.OpenRead(archiveFileName); + foreach (var zipEntry in zipFile.Entries) + { + var filePath = Path.Combine(outFolder, zipEntry.Name); + var directoryName = Path.GetDirectoryName(filePath); + + if (!string.IsNullOrWhiteSpace(directoryName)) + Directory.CreateDirectory(directoryName); + + using var a = zipEntry.Open(); + using var fileStreamFinal = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, + FileShare.None, BufferSize, FileOptions.SequentialScan); + using var final = new BinaryWriter(fileStreamFinal); + var buffer = new byte[BufferSize]; + int read; + while ((read = a.Read(buffer, 0, buffer.Length)) > 0) + { + final.Write(buffer, 0, read); + } + } + } + + [UsedImplicitly] + public static async Task ExtractZipFileAsync([NotNull] string archiveFileName, [NotNull] string outFolder, + [CanBeNull] IProgress progress = null, CancellationToken ct = default) + { + archiveFileName.ThrowIfNullOrWhiteSpace(nameof(archiveFileName)); + outFolder.ThrowIfNullOrWhiteSpace(nameof(outFolder)); + + using var zipFile = ZipFile.OpenRead(archiveFileName); + foreach (var zipEntry in zipFile.Entries) + { + var length = zipEntry.Length; + + var filePath = Path.Combine(outFolder, zipEntry.Name); + var directoryName = Path.GetDirectoryName(filePath); + + if (!string.IsNullOrWhiteSpace(directoryName)) + Directory.CreateDirectory(directoryName); + + using var a = zipEntry.Open(); + using var fileStreamFinal = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write, + FileShare.None, BufferSize, FileOptions.Asynchronous | FileOptions.SequentialScan); + var buffer = new byte[BufferSize]; + int read; + var totalRead = 0L; + var lastProgress = 0d; + while ((read = await a.ReadAsync(buffer, 0, buffer.Length, ct)) > 0) + { + ct.ThrowIfCancellationRequested(); + + totalRead += read; + + await fileStreamFinal.WriteAsync(buffer, 0, read, ct); + + if (progress != null) + { + var newProgress = (double) totalRead / length * 100; + + if (newProgress - lastProgress > 1) + { + progress.Report(newProgress); + lastProgress = newProgress; + } + } + + if (totalRead >= length) + break; + } + } + } + + [UsedImplicitly] + public static void CompressDirectory([NotNull] string directory, [NotNull] string outFileName, + CompressionLevel compressionLevel = CompressionLevel.BestCompression) + { + directory.ThrowIfNullOrWhiteSpace(nameof(directory)); + outFileName.ThrowIfNullOrWhiteSpace(nameof(outFileName)); + + if (directory.EndsWith($"{Path.DirectorySeparatorChar}") || + directory.EndsWith($"{Path.AltDirectorySeparatorChar}")) + { + directory = directory.Substring(0, directory.Length - 1); + } + + using var zip = new Ionic.Zip.ZipFile + { + CompressionLevel = compressionLevel, + UseZip64WhenSaving = Zip64Option.AsNecessary + }; + foreach (var f in Directory.GetFiles(directory, "*", + SearchOption.AllDirectories).ToArray()) + { + var directoryName = Path.GetDirectoryName(f); + if (directoryName == null) continue; + zip.AddFile(f, directoryName.Replace(directory, string.Empty)); + } + + zip.Save(outFileName); + } + + [UsedImplicitly] + public static void CompressFiles([NotNull] string baseDirectory, [NotNull] string outFileName, + [NotNull] IEnumerable fileInfos, + CompressionLevel compressionLevel = CompressionLevel.BestCompression) + { + baseDirectory.ThrowIfNullOrWhiteSpace(nameof(baseDirectory)); + fileInfos.ThrowIfNull(nameof(fileInfos)); + outFileName.ThrowIfNullOrWhiteSpace(nameof(outFileName)); + + if (baseDirectory.EndsWith($"{Path.DirectorySeparatorChar}") || + baseDirectory.EndsWith($"{Path.AltDirectorySeparatorChar}")) + { + baseDirectory = baseDirectory.Substring(0, baseDirectory.Length - 1); + } + + using var zip = new Ionic.Zip.ZipFile + { + CompressionLevel = compressionLevel, + UseZip64WhenSaving = Zip64Option.AsNecessary + }; + foreach (var f in fileInfos) + { + var directoryName = Path.GetDirectoryName(f.FullName); + zip.AddFile(f.FullName, directoryName?.Replace(baseDirectory, string.Empty)); + } + + zip.Save(outFileName); + } + + [UsedImplicitly] + public static void CompressFiles([NotNull] IEnumerable> mappedPathsToContents, + [NotNull] string outFileName, + CompressionLevel compressionLevel = CompressionLevel.BestCompression) + { + mappedPathsToContents.ThrowIfNull(nameof(mappedPathsToContents)); + outFileName.ThrowIfNullOrWhiteSpace(nameof(outFileName)); + + using var zip = new Ionic.Zip.ZipFile + { + CompressionLevel = compressionLevel, + UseZip64WhenSaving = Zip64Option.AsNecessary + }; + foreach (var entry in mappedPathsToContents) + zip.AddEntry(entry.Key, entry.Value); + + zip.Save(outFileName); + } + } +} \ No newline at end of file diff --git a/src/icon.png b/src/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..32d1cfe2d0f337440c906f60ba1c4e28d4ed777d GIT binary patch literal 4543 zcmV;w5kT&VP)Px#1ZP1_K>z@;j|==^1poj532;bRa{vGi!vFvd!vV){sAK>D5mZS;K~!i%#hP2J zT<2BC*Uaq8+~-_o&hha%j_ufOE_QCku|rVW#+9Ie1WgMsNIX?RAR$zE=>tzlfP_$y zs6c|IAR$peEg}znh`6W}gc?F_#8r|evE#(?IX=hdHusr5Gkb>L|C`zNA$3FA23Ybs z-?zX0UDkcAZ;w;1Ti=SBX9tYW@8iZhk_r50j(9mIdDD*f|Xn@ zcO;w5uF+r4WHOa>IxR*lj^k)F8a2SJe!qXU+wHzH91gGXY9H)@V(15A<_BRwYb50b zh&{Qmuy7`y&!6*s|89t0VZ4+|rFityw3;sl)QrL5csync9Q}*D z+XJPY?~9S|mjMyJSSpq7tJP{hSuU5)BkdDNIwv9_&P_tnuJwGZXfom7O`0@EjIqWb zyoW|EqLF`wk*7MH&Pz<$1;xnwg7?cn8Z3rkc-P^>haa1tpMQ-02?)s~#Obg4!dMJI zC@Qe=Y;2;w<}i+?Yz)I17c(%$lF=oYcyecF=Sj@#Ri?JVsYKob-VXz^^BSh|D8xTr zC=?z>dci@$Q}n&Tz`{<)iv7Oj)rUYY(FjBiAi5I-)&SdJpXU@>5R(TOiO|N=+uPeu zG@H$DuyjYu-6r1y{wD?$Nsg?puKxVe($X(uF2|A0^i121a3)G76p`=TzcT%N5OtsO@ChZ$x zXcx<6Yru@mOdxGwQhUIcH?Lj$GxoX6@GY50;`F;gXWe%6=+VcK{I6iMbIxSg*vCAM zZf)6_-CaA4#Fvp=QN)4CW(S!_j941cdyPrfS)Lccl~HWfZpW~DtK;;sOpEuNnZwWS zOJ_0@qSfmRwZQN4iCZzC{g>9()_!4mdHL4}hjWT5{V1|*yKVPwZrT~lW(~sg;6Y-w z(6uw0nfCSfre@N!j;5#|@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