From 1a8e1c8eaff4b12b95b4c383a356cd4fe72854ae Mon Sep 17 00:00:00 2001 From: Oliver Booth Date: Sun, 7 Jul 2019 12:23:48 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=8E=89=20Initial=20commit?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .gitignore | 349 +++++++++++++++++++++++ README.md | 29 ++ X10D.Drawing/ImageExtensions.cs | 174 +++++++++++ X10D.Drawing/Properties/AssemblyInfo.cs | 36 +++ X10D.Drawing/X10D.Drawing.csproj | 49 ++++ X10D.Unity/MaterialExtensions.cs | 82 ++++++ X10D.Unity/Properties/AssemblyInfo.cs | 36 +++ X10D.Unity/Vector3Extensions.cs | 62 ++++ X10D.Unity/X10D.Unity.csproj | 61 ++++ X10D.WinForms/ControlExtensions.cs | 32 +++ X10D.WinForms/Properties/AssemblyInfo.cs | 36 +++ X10D.WinForms/X10D.WinForms.csproj | 49 ++++ X10D.sln | 43 +++ X10D/ByteExtensions.cs | 94 ++++++ X10D/CharExtensions.cs | 24 ++ X10D/ComparableExtensions.cs | 34 +++ X10D/ConvertibleExtensions.cs | 142 +++++++++ X10D/DateTimeExtensions.cs | 162 +++++++++++ X10D/DoubleExtensions.cs | 60 ++++ X10D/Int16Extensions.cs | 92 ++++++ X10D/Int32Extensions.cs | 91 ++++++ X10D/Int64Extensions.cs | 114 ++++++++ X10D/ListExtensions.cs | 54 ++++ X10D/Properties/AssemblyInfo.cs | 35 +++ X10D/RandomExtensions.cs | 35 +++ X10D/SingleExtensions.cs | 58 ++++ X10D/StringExtensions.cs | 141 +++++++++ X10D/StructExtensions.cs | 38 +++ X10D/TimeSpanExtensions.cs | 24 ++ X10D/X10D.csproj | 64 +++++ 30 files changed, 2300 insertions(+) create mode 100644 .gitignore create mode 100644 README.md create mode 100644 X10D.Drawing/ImageExtensions.cs create mode 100644 X10D.Drawing/Properties/AssemblyInfo.cs create mode 100644 X10D.Drawing/X10D.Drawing.csproj create mode 100644 X10D.Unity/MaterialExtensions.cs create mode 100644 X10D.Unity/Properties/AssemblyInfo.cs create mode 100644 X10D.Unity/Vector3Extensions.cs create mode 100644 X10D.Unity/X10D.Unity.csproj create mode 100644 X10D.WinForms/ControlExtensions.cs create mode 100644 X10D.WinForms/Properties/AssemblyInfo.cs create mode 100644 X10D.WinForms/X10D.WinForms.csproj create mode 100644 X10D.sln create mode 100644 X10D/ByteExtensions.cs create mode 100644 X10D/CharExtensions.cs create mode 100644 X10D/ComparableExtensions.cs create mode 100644 X10D/ConvertibleExtensions.cs create mode 100644 X10D/DateTimeExtensions.cs create mode 100644 X10D/DoubleExtensions.cs create mode 100644 X10D/Int16Extensions.cs create mode 100644 X10D/Int32Extensions.cs create mode 100644 X10D/Int64Extensions.cs create mode 100644 X10D/ListExtensions.cs create mode 100644 X10D/Properties/AssemblyInfo.cs create mode 100644 X10D/RandomExtensions.cs create mode 100644 X10D/SingleExtensions.cs create mode 100644 X10D/StringExtensions.cs create mode 100644 X10D/StructExtensions.cs create mode 100644 X10D/TimeSpanExtensions.cs create mode 100644 X10D/X10D.csproj diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..846c8c0 --- /dev/null +++ b/.gitignore @@ -0,0 +1,349 @@ +## 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 +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +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 +nunit-*.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/ + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.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 +# NuGet Symbol Packages +*.snupkg +# 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 +*.appxbundle +*.appxupload + +# 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 +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# 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/ + +# CodeRush personal settings +.cr/personal + +# 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/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..a8412c5 --- /dev/null +++ b/README.md @@ -0,0 +1,29 @@ +# X10D +Extension methods on crack + +## About +X10D (pronounced *extend*), is a collection of class libraries that provide various .NET extension methods, including extension methods for Unity, Windows Forms and System.Drawing. + +## Extended Classes +Below is a list of the number of extension methods written for a given type. Overloaded methods are not counted. +|Type|Library|Method count| +|- |- |- | +|`byte` / `byte[]`|`X10D`|8| +|`char`|`X10D`|1| +|`IComparable`|`X10D`|2| +|`IConvertible`|`X10D`|4| +|`DateTime`|`X10D`|12| +|`double`|`X10D`|5| +|`enum`|`X10D`|2| +|`float`|`X10D`|5| +|`short` / `ushort`|`X10D`|15| +|`int` / `uint`|`X10D`|15| +|`long` / `ulong`|`X10D`|15| +|`IList`|`X10D`|1| +|`Random`|`X10D`|1| +|`SecureString`|`X10D`|1| +|`string`|`X10D`|6| +|`TimeSpan`|`X10D`|1| +|`System.Drawing.Image`|`X10D.Drawing`|2 (+ async)| +|`UnityEngine.Material`|`X10D.Unity`|1| +|`System.Windows.Forms.Control`|`X10D.WinForms`|1| diff --git a/X10D.Drawing/ImageExtensions.cs b/X10D.Drawing/ImageExtensions.cs new file mode 100644 index 0000000..6a7fceb --- /dev/null +++ b/X10D.Drawing/ImageExtensions.cs @@ -0,0 +1,174 @@ +namespace X10D.Drawing +{ + #region Using Directives + + using System; + using System.Drawing; + using System.Drawing.Drawing2D; + using System.Drawing.Imaging; + using System.Threading.Tasks; + + #endregion + + /// + /// Extension methods for . + /// + public static class ImageExtensions + { + /// + /// Asynchronously converts the image so that its aspect ratio is 1:1, surrounding any new area with + /// transparency. + /// + /// The image to convert. + /// Returns an . + public static async Task ToSquareAsync(this Image image) => + await Task.Run(image.ToSquare); + + /// + /// Asynchronously converts the image so that its aspect ratio is 1:1, surrounding any new area with + /// transparency. + /// + /// The image to convert. + /// The new size of the image, i.e. the value of both the width and height. + /// Returns an . + public static async Task ToSquareAsync(this Image image, int size) => + await Task.Run(() => image.ToSquare(size)); + + /// + /// Asynchronously converts the image so that its aspect ratio is 1:1, surrounding any new area with a + /// specified background color. + /// + /// The image to convert. + /// The new size of the image, i.e. the value of both the width and height. + /// The background color to fill. + /// Returns an . + public static async Task ToSquareAsync(this Image image, int size, Color background) => + await Task.Run(() => image.ToSquare(size, background)); + + /// + /// Asynchronously converts the image so that its aspect ratio is 1:1, surrounding any new area with a + /// specified background color. + /// + /// The image to convert. + /// The background color to fill. + /// Returns an . + public static async Task ToSquareAsync(this Image image, Color background) => + await Task.Run(() => image.ToSquare(background)); + + /// + /// Converts the image so that its aspect ratio is 1:1, surrounding any new area with transparency. + /// + /// The image to convert. + /// Returns an . + public static Image ToSquare(this Image image) => + image.ToSquare(Color.Transparent); + + /// + /// Converts the image so that its aspect ratio is 1:1, surrounding any new area with transparency. + /// + /// The image to convert. + /// The new size of the image, i.e. the value of both the width and height. + /// Returns an . + public static Image ToSquare(this Image image, int size) => + image.ToSquare(size, Color.Transparent); + + /// + /// Converts the image so that its aspect ratio is 1:1, surrounding any new area with a specified background + /// color. + /// + /// The image to convert. + /// The background color to fill. + /// Returns an . + public static Image ToSquare(this Image image, Color background) + { + int resolution = Math.Max(image.Width, image.Height); + return image.ToSquare(resolution, background); + } + + /// + /// Converts the image so that its aspect ratio is 1:1, surrounding any new area with a specified background + /// color. + /// + /// The image to convert. + /// The new size of the image, i.e. the value of both the width and height. + /// The background color to fill. + /// Returns an . + public static Image ToSquare(this Image image, int size, Color background) + { + int resolution = Math.Max(image.Width, image.Height); + Bitmap newImage = new Bitmap(resolution, resolution); + + using (Graphics graphics = Graphics.FromImage(newImage)) + { + graphics.FillRectangle(new SolidBrush(background), new Rectangle(0, 0, + resolution, resolution)); + + graphics.DrawImageUnscaled(image, resolution / 2 - image.Width / 2, + resolution / 2 - image.Height / 2); + } + + return newImage.Scale(size, size); + } + + /// + /// Asynchronously scales the image. + /// + /// The image to scale. + /// The new width. + /// The new height. + /// Returns a new . + public static async Task ScaleAsync(this Image image, int width, int height) => + await Task.Run(() => image.Scale(width, height)); + + /// + /// Asynchronously scales the image. + /// + /// The image to scale. + /// The scale factor. + /// Returns a new . + public static async Task ScaleAsync(this Image image, float factor) => + await Task.Run(() => image.Scale(factor)); + + /// + /// Scales the image. + /// + /// The image to scale. + /// The scale factor. + /// Returns a new . + public static Bitmap Scale(this Image image, float factor) => + image.Scale((int)(image.Width * factor), (int)(image.Height * factor)); + + /// + /// Scales the image. + /// + /// The image to scale. + /// The new width. + /// The new height. + /// Returns a new . + public static Bitmap Scale(this Image image, int width, int height) + { + Rectangle destRect = new Rectangle(0, 0, width, height); + Bitmap destImage = new Bitmap(width, height); + + destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); + + using (Graphics graphics = Graphics.FromImage(destImage)) + { + graphics.CompositingMode = CompositingMode.SourceCopy; + graphics.CompositingQuality = CompositingQuality.HighQuality; + graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; + graphics.SmoothingMode = SmoothingMode.HighQuality; + graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; + + using (ImageAttributes wrapMode = new ImageAttributes()) + { + wrapMode.SetWrapMode(WrapMode.TileFlipXY); + graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, + wrapMode); + } + } + + return destImage; + } + } +} diff --git a/X10D.Drawing/Properties/AssemblyInfo.cs b/X10D.Drawing/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..8dd4268 --- /dev/null +++ b/X10D.Drawing/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Extensions.Drawing")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Extensions.Drawing")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("9e27fb65-4182-443c-8abe-71292f892b59")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/X10D.Drawing/X10D.Drawing.csproj b/X10D.Drawing/X10D.Drawing.csproj new file mode 100644 index 0000000..4a38a32 --- /dev/null +++ b/X10D.Drawing/X10D.Drawing.csproj @@ -0,0 +1,49 @@ + + + + + Debug + AnyCPU + {9E27FB65-4182-443C-8ABE-71292F892B59} + Library + Properties + X10D.Drawing + X10D.Drawing + v4.6 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/X10D.Unity/MaterialExtensions.cs b/X10D.Unity/MaterialExtensions.cs new file mode 100644 index 0000000..3f9d7ad --- /dev/null +++ b/X10D.Unity/MaterialExtensions.cs @@ -0,0 +1,82 @@ +namespace X10D.Unity +{ + #region Using Directives + + using System.Diagnostics.CodeAnalysis; + using UnityEngine; + + #endregion + + /// + /// A set of extension methods for . + /// + public static class MaterialExtensions + { + private static readonly int srcBlend = Shader.PropertyToID("_SrcBlend"); + private static readonly int dstBlend = Shader.PropertyToID("_DstBlend"); + private static readonly int zWrite = Shader.PropertyToID("_ZWrite"); + + /// + /// An enumeration of blend modes. + /// + public enum BlendMode + { + Opaque, + Cutout, + Fade, + Transparent + } + + /// + /// Changes the material's blend mode. + /// + /// The material. + /// The blend mode. + [SuppressMessage("ReSharper", "StringLiteralTypo")] + public static void ChangeRenderMode(this Material material, BlendMode blendMode) + { + switch (blendMode) + { + case BlendMode.Opaque: + material.SetInt(srcBlend, (int)UnityEngine.Rendering.BlendMode.One); + material.SetInt(dstBlend, (int)UnityEngine.Rendering.BlendMode.Zero); + material.SetInt(zWrite, 1); + material.DisableKeyword("_ALPHATEST_ON"); + material.DisableKeyword("_ALPHABLEND_ON"); + material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); + material.renderQueue = -1; + break; + + case BlendMode.Cutout: + material.SetInt(srcBlend, (int)UnityEngine.Rendering.BlendMode.One); + material.SetInt(dstBlend, (int)UnityEngine.Rendering.BlendMode.Zero); + material.SetInt(zWrite, 1); + material.EnableKeyword("_ALPHATEST_ON"); + material.DisableKeyword("_ALPHABLEND_ON"); + material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); + material.renderQueue = 2450; + break; + + case BlendMode.Fade: + material.SetInt(srcBlend, (int)UnityEngine.Rendering.BlendMode.SrcAlpha); + material.SetInt(dstBlend, (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); + material.SetInt(zWrite, 0); + material.DisableKeyword("_ALPHATEST_ON"); + material.EnableKeyword("_ALPHABLEND_ON"); + material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); + material.renderQueue = 3000; + break; + + case BlendMode.Transparent: + material.SetInt(srcBlend, (int)UnityEngine.Rendering.BlendMode.One); + material.SetInt(dstBlend, (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); + material.SetInt(zWrite, 0); + material.DisableKeyword("_ALPHATEST_ON"); + material.DisableKeyword("_ALPHABLEND_ON"); + material.EnableKeyword("_ALPHAPREMULTIPLY_ON"); + material.renderQueue = 3000; + break; + } + } + } +} diff --git a/X10D.Unity/Properties/AssemblyInfo.cs b/X10D.Unity/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..0cb6fa5 --- /dev/null +++ b/X10D.Unity/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Extensions.Unity")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Extensions.Unity")] +[assembly: AssemblyCopyright("Copyright © 2019")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("2657ef66-0334-4a5a-8c24-6c949224a989")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/X10D.Unity/Vector3Extensions.cs b/X10D.Unity/Vector3Extensions.cs new file mode 100644 index 0000000..66a4c6a --- /dev/null +++ b/X10D.Unity/Vector3Extensions.cs @@ -0,0 +1,62 @@ +namespace X10D.Unity +{ + #region Using Directives + + using UnityEngine; + + #endregion + + /// + /// A set of extension methods for . + /// + public static class Vector3Extensions + { + /// + /// Converts a vector normal to an Euler rotation. + /// + /// The vector normal. + /// Returns a representing the Euler rotation. + public static Vector3 NormalToEulerAngles(this Vector3 v) + { + float x = v.x; + v.x = v.z; + v.z = x; + v.z *= 2.0f * v.y; + v.y = 0.0f; + return v * 90.0f; + } + + /// + /// Rounds a vector to the nearest value. + /// + /// The vector to round. + /// The nearest value. + /// Returns a containing the rounded values. + public static Vector3 Round(this Vector3 v, int nearest = 1) => + new Vector3(v.x.Round(nearest), v.y.Round(nearest), v.z.Round(nearest)); + + /// + /// Inverts the X component of a vector. + /// + /// The vector to evaluate. + /// Returns a whose values are (-X, Y, Z). + public static Vector3 InvertX(this Vector3 v) => + new Vector3(-v.x, v.y, v.z); + + /// + /// Inverts the Y component of a vector. + /// + /// The vector to evaluate. + /// Returns a whose values are (X, -Y, Z). + public static Vector3 InvertY(this Vector3 v) => + new Vector3(v.x, -v.y, v.z); + + /// + /// Inverts the Z component of a vector. + /// + /// The vector to evaluate. + /// Returns a whose values are (X, Y, -Z). + public static Vector3 InvertZ(this Vector3 v) => + new Vector3(v.x, v.y, -v.z); + } +} diff --git a/X10D.Unity/X10D.Unity.csproj b/X10D.Unity/X10D.Unity.csproj new file mode 100644 index 0000000..f195701 --- /dev/null +++ b/X10D.Unity/X10D.Unity.csproj @@ -0,0 +1,61 @@ + + + + + Debug + AnyCPU + {2657EF66-0334-4A5A-8C24-6C949224A989} + Library + Properties + X10D.Unity + X10D.Unity + v4.6 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + F:\Program Files\Unity\2019.1.0f2\Editor\Data\Managed\UnityEngine\UnityEngine.dll + + + F:\Program Files\Unity\2019.1.0f2\Editor\Data\Managed\UnityEngine\UnityEngine.CoreModule.dll + + + + + + + + + + {de210f83-fc9a-4c23-ac2c-7a060960f716} + X10D + + + + \ No newline at end of file diff --git a/X10D.WinForms/ControlExtensions.cs b/X10D.WinForms/ControlExtensions.cs new file mode 100644 index 0000000..7155cc9 --- /dev/null +++ b/X10D.WinForms/ControlExtensions.cs @@ -0,0 +1,32 @@ +namespace X10D.WinForms +{ + #region Using Directives + + using System.Windows.Forms; + + #endregion + + /// + /// Extension methods for . + /// + public static class ControlExtensions + { + /// + /// Thread-safe method invocation. Calls if + /// returns . + /// + /// The control from which to invoke. + /// The action to invoke. + public static void InvokeIfRequired(this Control control, MethodInvoker action) + { + if (control?.InvokeRequired ?? false) + { + control.Invoke(action); + } + else + { + action(); + } + } + } +} diff --git a/X10D.WinForms/Properties/AssemblyInfo.cs b/X10D.WinForms/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..7878f12 --- /dev/null +++ b/X10D.WinForms/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Extensions.WinForms")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Extensions.WinForms")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("8bc9ef95-dc0f-4866-a01e-f07bbc675829")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/X10D.WinForms/X10D.WinForms.csproj b/X10D.WinForms/X10D.WinForms.csproj new file mode 100644 index 0000000..9fe7bc2 --- /dev/null +++ b/X10D.WinForms/X10D.WinForms.csproj @@ -0,0 +1,49 @@ + + + + + Debug + AnyCPU + {8BC9EF95-DC0F-4866-A01E-F07BBC675829} + Library + Properties + X10D.WinForms + X10D.WinForms + v4.6 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/X10D.sln b/X10D.sln new file mode 100644 index 0000000..c3042e7 --- /dev/null +++ b/X10D.sln @@ -0,0 +1,43 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.28902.138 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D", "X10D\X10D.csproj", "{DE210F83-FC9A-4C23-AC2C-7A060960F716}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.WinForms", "X10D.WinForms\X10D.WinForms.csproj", "{8BC9EF95-DC0F-4866-A01E-F07BBC675829}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.Drawing", "X10D.Drawing\X10D.Drawing.csproj", "{9E27FB65-4182-443C-8ABE-71292F892B59}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "X10D.Unity", "X10D.Unity\X10D.Unity.csproj", "{2657EF66-0334-4A5A-8C24-6C949224A989}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {DE210F83-FC9A-4C23-AC2C-7A060960F716}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DE210F83-FC9A-4C23-AC2C-7A060960F716}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DE210F83-FC9A-4C23-AC2C-7A060960F716}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DE210F83-FC9A-4C23-AC2C-7A060960F716}.Release|Any CPU.Build.0 = Release|Any CPU + {8BC9EF95-DC0F-4866-A01E-F07BBC675829}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8BC9EF95-DC0F-4866-A01E-F07BBC675829}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8BC9EF95-DC0F-4866-A01E-F07BBC675829}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8BC9EF95-DC0F-4866-A01E-F07BBC675829}.Release|Any CPU.Build.0 = Release|Any CPU + {9E27FB65-4182-443C-8ABE-71292F892B59}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {9E27FB65-4182-443C-8ABE-71292F892B59}.Debug|Any CPU.Build.0 = Debug|Any CPU + {9E27FB65-4182-443C-8ABE-71292F892B59}.Release|Any CPU.ActiveCfg = Release|Any CPU + {9E27FB65-4182-443C-8ABE-71292F892B59}.Release|Any CPU.Build.0 = Release|Any CPU + {2657EF66-0334-4A5A-8C24-6C949224A989}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2657EF66-0334-4A5A-8C24-6C949224A989}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2657EF66-0334-4A5A-8C24-6C949224A989}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2657EF66-0334-4A5A-8C24-6C949224A989}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {6F733785-8837-410C-BD91-C4AD1F0A6914} + EndGlobalSection +EndGlobal diff --git a/X10D/ByteExtensions.cs b/X10D/ByteExtensions.cs new file mode 100644 index 0000000..46e112d --- /dev/null +++ b/X10D/ByteExtensions.cs @@ -0,0 +1,94 @@ +namespace X10D +{ + #region Using Directives + + using System; + using System.Collections.Generic; + using System.Linq; + using System.Text; + + #endregion + + /// + /// Extension methods for . + /// + public static class ByteExtensions + { + /// + /// Gets a literally representing the raw values in the []. + /// + /// The bytes to get. + /// Returns a . + public static string AsString(this IEnumerable bytes) => + BitConverter.ToString(bytes.ToArray()); + + /// + /// Converts the [] to an . + /// + /// The bytes to convert. + /// Returns an . + public static short GetInt16(this IEnumerable bytes) => + BitConverter.ToInt16(bytes.ToArray(), 0); + + /// + /// Converts the [] to an . + /// + /// The bytes to convert. + /// Returns an . + public static int GetInt32(this IEnumerable bytes) => + BitConverter.ToInt32(bytes.ToArray(), 0); + + /// + /// Converts the [] to an . + /// + /// The bytes to convert. + /// Returns an . + public static long GetInt64(this IEnumerable bytes) => + BitConverter.ToInt64(bytes.ToArray(), 0); + + /// + /// Converts the [] to a . + /// + /// The bytes to convert. + /// Returns an . + public static ushort GetUInt16(this IEnumerable bytes) => + BitConverter.ToUInt16(bytes.ToArray(), 0); + + /// + /// Converts the [] to an . + /// + /// The bytes to convert. + /// Returns an . + public static uint GetUInt32(this IEnumerable bytes) => + BitConverter.ToUInt32(bytes.ToArray(), 0); + + /// + /// Converts the [] to an . + /// + /// The bytes to convert. + /// Returns an . + public static ulong GetUInt64(this IEnumerable bytes) => + BitConverter.ToUInt64(bytes.ToArray(), 0); + + /// + /// Gets a representing the value the [] with + /// encoding. + /// + /// The bytes to convert. + /// Returns a . + public static string GetString(this IEnumerable bytes) => + bytes.GetString(Encoding.UTF8); + + /// + /// Gets a representing the value the [] with the provided encoding. + /// + /// The bytes to convert. + /// The encoding to use. + /// Returns a . + public static string GetString(this IEnumerable bytes, Encoding encoding) + { + IEnumerable enumerable = bytes as byte[] ?? bytes.ToArray(); + return encoding.GetString(enumerable.ToArray(), 0, enumerable.Count()); + } + } +} diff --git a/X10D/CharExtensions.cs b/X10D/CharExtensions.cs new file mode 100644 index 0000000..249244b --- /dev/null +++ b/X10D/CharExtensions.cs @@ -0,0 +1,24 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class CharExtensions + { + /// + /// Repeats a character a specified number of times. + /// + /// The character to repeat. + /// The repeat count. + /// Returns a whose value is repeated + /// times. + public static string Repeat(this char c, int count) => + new string(c, count); + } +} diff --git a/X10D/ComparableExtensions.cs b/X10D/ComparableExtensions.cs new file mode 100644 index 0000000..eac0906 --- /dev/null +++ b/X10D/ComparableExtensions.cs @@ -0,0 +1,34 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class ComparableExtensions + { + /// + /// Determines if is between and . + /// + /// The comparable type. + /// The value to compare. + /// The inclusive lower bound. + /// The exclusive upper bound. + /// Returns if the value is between the bounds, + /// otherwise. + public static bool Between(this T actual, T lower, T upper) where T : IComparable => + actual.CompareTo(lower) > 0 && actual.CompareTo(upper) < 0; + + /// + /// Gets the value + /// + /// + /// + public static TimeSpan Days(this IComparable value) => + TimeSpan.FromDays((double)value); + } +} diff --git a/X10D/ConvertibleExtensions.cs b/X10D/ConvertibleExtensions.cs new file mode 100644 index 0000000..15e126b --- /dev/null +++ b/X10D/ConvertibleExtensions.cs @@ -0,0 +1,142 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class ConvertibleExtensions + { + /// + /// Converts the object to another type. + /// + /// The type to convert to. + /// The object to convert. + /// Returns the value converted to . + public static T To(this IConvertible obj) => + (T) Convert.ChangeType(obj, typeof(T)); + + /// + /// Converts the object to another type, returning the default value on failure. + /// + /// The type to convert to. + /// The object to convert. + /// Returns the value converted to . + public static T ToOrDefault(this IConvertible obj) + { + try + { + return To(obj); + } + catch + { + return default; + } + } + + /// + /// Converts the object to another type, returning the default value on failure. + /// + /// The type to convert to. + /// The object to convert. + /// The parameter where the result should be sent. + /// Returns on success, on failure. + public static bool ToOrDefault(this IConvertible obj, out T newObj) + { + try + { + newObj = To(obj); + return true; + } + catch + { + newObj = default; + return false; + } + } + + /// + /// Converts the object to another type, returning a different value on failure. + /// + /// The type to convert to. + /// The object to convert. + /// The backup value. + /// Returns the value converted to . + public static T ToOrOther(this IConvertible obj, T other) + { + try + { + return To(obj); + } + catch + { + return other; + } + } + + /// + /// Converts the object to another type, returning a different value on failure. + /// + /// The type to convert to. + /// The object to convert. + /// The parameter where the result should be sent. + /// The backup value. + /// Returns on success, on failure. + public static bool ToOrOther(this IConvertible obj, out T newObj, T other) + { + try + { + newObj = To(obj); + return true; + } + catch + { + newObj = other; + return false; + } + } + + /// + /// Converts the object to another type, returning on failure. + /// + /// The type to convert to. + /// The object to convert. + /// Returns a or . + public static T ToOrNull(this IConvertible obj) where T : class + { + try + { + return To(obj); + } + catch + { + return null; + } + } + + /// + /// Converts the object to another type, returning on failure. + /// + /// The type to convert to. + /// The object to convert. + /// The parameter where the result should be sent. + /// Returns a or . + public static bool ToOrNull(this IConvertible obj, out T newObj) where T : class + { + try + { + newObj = To(obj); + return true; + } + catch + { + newObj = null; + return false; + } + } + } +} diff --git a/X10D/DateTimeExtensions.cs b/X10D/DateTimeExtensions.cs new file mode 100644 index 0000000..6f1803b --- /dev/null +++ b/X10D/DateTimeExtensions.cs @@ -0,0 +1,162 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class DateTimeExtensions + { + /// + /// Represents the Unix epoch - midnight on January 1, 1970. + /// + public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0); + + /// + /// Calculates someone's age based on a date of birth. + /// + /// The date of birth. + public static int Age(this DateTime dateOfBirth) => + (int) (((DateTime.Today - TimeSpan.FromDays(1) - dateOfBirth.Date).TotalDays + 1) / 365.2425); + + /// + /// Gets a DateTime representing the first specified day in the current month + /// + /// The current day + /// The current day of week + /// + public static DateTime First(this DateTime current, DayOfWeek dayOfWeek) + { + DateTime first = current.FirstDayOfMonth(); + + if (first.DayOfWeek != dayOfWeek) + { + first = first.Next(dayOfWeek); + } + + return first; + } + + /// + /// Gets a representing the first day in the current month. + /// + /// The current date. + public static DateTime FirstDayOfMonth(this DateTime current) => + current.AddDays(1 - current.Day); + + /// + /// Gets a representing the last day in the current month. + /// + /// The current date. + public static DateTime LastDayOfMonth(this DateTime current) + { + int daysInMonth = DateTime.DaysInMonth(current.Year, current.Month); + + DateTime last = current.FirstDayOfMonth().AddDays(daysInMonth - 1); + return last; + } + + /// + /// Gets a representing the last specified day in the current month. + /// + /// The current date. + /// The current day of week. + public static DateTime Last(this DateTime current, DayOfWeek dayOfWeek) + { + DateTime last = current.LastDayOfMonth(); + + last = last.AddDays(Math.Abs(dayOfWeek - last.DayOfWeek) * -1); + return last; + } + + /// + /// Gets a representing midnight on the current date. + /// + /// The current date. + public static DateTime Midnight(this DateTime current) => + new DateTime(current.Year, current.Month, current.Day); + + /// + /// Gets a representing the first date following the current date which falls on the + /// given day of the week. + /// + /// The current date. + /// The day of week for the next date to get. + public static DateTime Next(this DateTime current, DayOfWeek dayOfWeek) + { + int offsetDays = dayOfWeek - current.DayOfWeek; + + if (offsetDays <= 0) + { + offsetDays += 7; + } + + DateTime result = current.AddDays(offsetDays); + return result; + } + + /// + /// Gets a representing noon on the current date. + /// + /// The current date. + public static DateTime Noon(this DateTime current) => + new DateTime(current.Year, current.Month, current.Day, 12, 0, 0); + + /// + /// Sets the time of the current date with minute precision. + /// + /// The current date. + /// The hour. + /// The minute. + public static DateTime SetTime(this DateTime current, int hour, int minute) => + current.SetTime(hour, minute, 0, 0); + + /// + /// Sets the time of the current date with second precision. + /// + /// The current date + /// The hour. + /// The minute. + /// The second. + /// + public static DateTime SetTime(this DateTime current, int hour, int minute, int second) => + current.SetTime(hour, minute, second, 0); + + /// + /// Sets the time of the current date with millisecond precision. + /// + /// The current date. + /// The hour. + /// The minute. + /// The second. + /// The millisecond. + public static DateTime SetTime(this DateTime current, int hour, int minute, int second, int millisecond) => + new DateTime(current.Year, current.Month, current.Day, hour, minute, second, millisecond); + + /// + /// Converts the to a Unix timestamp. + /// + /// The instance. + /// Optional. Whether or not the return value should be represented as milliseconds. + /// Defaults to . + /// Returns a Unix timestamp representing the provided . + public static long ToUnixTimeStamp(this DateTime time, bool useMillis = false) + { + TimeSpan difference = time - UnixEpoch; + return (long) (useMillis ? difference.TotalMilliseconds : difference.TotalSeconds); + } + + /// + /// Returns the with the year set to the provided value. + /// + /// The to copy. + /// The year to set. + /// Returns a . + public static DateTime WithYear(this DateTime date, int year) => + new DateTime(year, date.Month, date.Day, date.Hour, date.Minute, date.Second, date.Millisecond); + } +} diff --git a/X10D/DoubleExtensions.cs b/X10D/DoubleExtensions.cs new file mode 100644 index 0000000..5b24f1c --- /dev/null +++ b/X10D/DoubleExtensions.cs @@ -0,0 +1,60 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class DoubleExtensions + { + /// + /// Converts an angle from degrees to radians. + /// + /// The angle in degrees. + /// Returns in radians. + public static double DegreesToRadians(this double angle) => + Math.PI * angle / 180.0; + + /// + /// Converts the to a treating it as a Unix timestamp. + /// + /// The timestamp. + /// Optional. Whether or not the input value should be treated as milliseconds. Defaults + /// to . + /// Returns a representing seconds since the Unix + /// epoch. + public static DateTime FromUnixTimestamp(this double timestamp, bool isMillis = false) => + isMillis + ? DateTimeExtensions.UnixEpoch.AddMilliseconds(timestamp) + : DateTimeExtensions.UnixEpoch.AddSeconds(timestamp); + + /// + /// Converts the to a []. + /// + /// The number to convert. + /// Returns a []. + public static byte[] GetBytes(this double number) => + BitConverter.GetBytes(number); + + /// + /// Converts an angle from radians to degrees. + /// + /// The angle in radians. + /// Returns in degrees. + public static double RadiansToDegrees(this double angle) => + angle * (180.0 / Math.PI); + + /// + /// Rounds to the nearest value. + /// + /// The value to round. + /// The nearest value. + /// Returns the rounded value. + public static double Round(this double v, int nearest = 1) => + Math.Round(v / nearest) * nearest; + } +} diff --git a/X10D/Int16Extensions.cs b/X10D/Int16Extensions.cs new file mode 100644 index 0000000..cfcb0c3 --- /dev/null +++ b/X10D/Int16Extensions.cs @@ -0,0 +1,92 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class Int16Extensions + { + #region TimeSpan Returns + // TODO change + + public static TimeSpan Days(this ushort number) => + TimeSpan.FromDays(number); + + public static TimeSpan Hours(this ushort number) => + TimeSpan.FromHours(number); + + public static TimeSpan Milliseconds(this ushort number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Minutes(this ushort number) => + TimeSpan.FromMinutes(number); + + public static TimeSpan Seconds(this ushort number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Ticks(this ushort number) => + TimeSpan.FromTicks(number); + + public static TimeSpan Days(this short number) => + TimeSpan.FromDays(number); + + public static TimeSpan Hours(this short number) => + TimeSpan.FromHours(number); + + public static TimeSpan Milliseconds(this short number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Minutes(this short number) => + TimeSpan.FromMinutes(number); + + public static TimeSpan Seconds(this short number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Ticks(this short number) => + TimeSpan.FromTicks(number); + + #endregion + + /// + /// Converts the to a treating it as a Unix timestamp. + /// + /// The timestamp. + /// Optional. Whether or not the input value should be treated as milliseconds. Defaults + /// to .. + /// Returns a representing seconds since the Unix + /// epoch. + public static DateTime FromUnixTimestamp(this short timestamp, bool isMillis = false) => + ((long) timestamp).FromUnixTimestamp(isMillis); + + /// + /// Converts the to a []. + /// + /// The number to convert. + /// Returns a []. + public static byte[] GetBytes(this ushort number) => + BitConverter.GetBytes(number); + + /// + /// Converts the to a []. + /// + /// The number to convert. + /// Returns a []. + public static byte[] GetBytes(this short number) => + BitConverter.GetBytes(number); + + + /// + /// Determines if the is a prime number. + /// + /// The number. + /// Returns if is prime, + /// otherwise. + public static bool IsPrime(this short number) => + ((long) number).IsPrime(); + } +} \ No newline at end of file diff --git a/X10D/Int32Extensions.cs b/X10D/Int32Extensions.cs new file mode 100644 index 0000000..3112126 --- /dev/null +++ b/X10D/Int32Extensions.cs @@ -0,0 +1,91 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class Int32Extensions + { + #region TimeSpan Returns + // TODO change + + public static TimeSpan Days(this uint number) => + TimeSpan.FromDays(number); + + public static TimeSpan Hours(this uint number) => + TimeSpan.FromHours(number); + + public static TimeSpan Milliseconds(this uint number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Minutes(this uint number) => + TimeSpan.FromMinutes(number); + + public static TimeSpan Seconds(this uint number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Ticks(this uint number) => + TimeSpan.FromTicks(number); + + public static TimeSpan Days(this int number) => + TimeSpan.FromDays(number); + + public static TimeSpan Hours(this int number) => + TimeSpan.FromHours(number); + + public static TimeSpan Milliseconds(this int number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Minutes(this int number) => + TimeSpan.FromMinutes(number); + + public static TimeSpan Seconds(this int number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Ticks(this int number) => + TimeSpan.FromTicks(number); + + #endregion + + /// + /// Converts the to a treating it as a Unix timestamp. + /// + /// The timestamp. + /// Optional. Whether or not the input value should be treated as milliseconds. Defaults + /// to .. + /// Returns a representing seconds since the Unix + /// epoch. + public static DateTime FromUnixTimestamp(this int timestamp, bool isMillis = false) => + ((long)timestamp).FromUnixTimestamp(isMillis); + + /// + /// Converts the to a []. + /// + /// The number to convert. + /// Returns a []. + public static byte[] GetBytes(this uint number) => + BitConverter.GetBytes(number); + + /// + /// Converts the to a []. + /// + /// The number to convert. + /// Returns a []. + public static byte[] GetBytes(this int number) => + BitConverter.GetBytes(number); + + /// + /// Determines if the is a prime number. + /// + /// The number. + /// Returns if is prime, + /// otherwise. + public static bool IsPrime(this int number) => + ((long)number).IsPrime(); + } +} diff --git a/X10D/Int64Extensions.cs b/X10D/Int64Extensions.cs new file mode 100644 index 0000000..8c46b64 --- /dev/null +++ b/X10D/Int64Extensions.cs @@ -0,0 +1,114 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class Int64Extensions + { + #region TimeSpan Returns + // TODO change + + public static TimeSpan Days(this ulong number) => + TimeSpan.FromDays(number); + + public static TimeSpan Hours(this ulong number) => + TimeSpan.FromHours(number); + + public static TimeSpan Milliseconds(this ulong number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Minutes(this ulong number) => + TimeSpan.FromMinutes(number); + + public static TimeSpan Seconds(this ulong number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Days(this long number) => + TimeSpan.FromDays(number); + + public static TimeSpan Hours(this long number) => + TimeSpan.FromHours(number); + + public static TimeSpan Milliseconds(this long number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Minutes(this long number) => + TimeSpan.FromMinutes(number); + + public static TimeSpan Seconds(this long number) => + TimeSpan.FromSeconds(number); + + public static TimeSpan Ticks(this long number) => + TimeSpan.FromTicks(number); + + #endregion + + /// + /// Converts the to a treating it as a Unix timestamp. + /// + /// The timestamp. + /// Optional. Whether or not the input value should be treated as milliseconds. Defaults + /// to . + /// Returns a representing seconds since the Unix + /// epoch. + public static DateTime FromUnixTimestamp(this long timestamp, bool isMillis = false) => + ((double)timestamp).FromUnixTimestamp(isMillis); + + /// + /// Converts the to a []. + /// + /// The number to convert. + /// Returns a []. + public static byte[] GetBytes(this ulong number) => + BitConverter.GetBytes(number); + + /// + /// Converts the to a []. + /// + /// The number to convert. + /// Returns a []. + public static byte[] GetBytes(this long number) => + BitConverter.GetBytes(number); + + /// + /// Determines if the is a prime number. + /// + /// The number. + /// Returns if is prime, + /// otherwise. + public static bool IsPrime(this long number) + { + if (number <= 1) + { + return false; + } + + if (number == 2) + { + return true; + } + + if (number % 2 == 0) + { + return false; + } + + long boundary = (long) Math.Floor(Math.Sqrt(number)); + for (int i = 3; i <= boundary; i += 2) + { + if (number % i == 0) + { + return false; + } + } + + return true; + } + } +} diff --git a/X10D/ListExtensions.cs b/X10D/ListExtensions.cs new file mode 100644 index 0000000..586e4af --- /dev/null +++ b/X10D/ListExtensions.cs @@ -0,0 +1,54 @@ +namespace X10D +{ + #region Using Directives + + using System; + using System.Collections.Generic; + using System.Linq; + + #endregion + + /// + /// Extension methods for . + /// + public static class ListExtensions + { + /// + /// Returns a random element from using a new instance. + /// + /// The collection type. + /// The collection to draw from. + /// Returns a random element of type from . + public static T OneOf(this IEnumerable source) => + source.OneOf(new Random()); + + /// + /// Returns a random element from using the instance. + /// + /// The collection type. + /// The collection to draw from. + /// The instance. + /// Returns a random element of type from . + public static T OneOf(this IEnumerable source, Random random) => + source.ToList().OneOf(random); + + /// + /// Returns a random element from using a new instance. + /// + /// The collection type. + /// The collection to draw from. + /// Returns a random element of type from . + public static T OneOf(this IList source) => + source.OneOf(new Random()); + + /// + /// Returns a random element from using the instance. + /// + /// The collection type. + /// The collection to draw from. + /// The instance. + /// Returns a random element of type from . + public static T OneOf(this IList source, Random random) => + random.OneOf(source); + } +} diff --git a/X10D/Properties/AssemblyInfo.cs b/X10D/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1cc4852 --- /dev/null +++ b/X10D/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Extensions")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Extensions")] +[assembly: AssemblyCopyright("Copyright © 2018")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("de210f83-fc9a-4c23-ac2c-7a060960f716")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/X10D/RandomExtensions.cs b/X10D/RandomExtensions.cs new file mode 100644 index 0000000..96f23fb --- /dev/null +++ b/X10D/RandomExtensions.cs @@ -0,0 +1,35 @@ +namespace X10D +{ + #region Using Directives + + using System; + using System.Collections.Generic; + + #endregion + + /// + /// Extension methods for . + /// + public static class RandomExtensions + { + /// + /// Returns a random element from using the instance. + /// + /// The collection type. + /// The instance. + /// The collection to draw from. + /// Returns a random element of type from . + public static T OneOf(this Random random, params T[] source) => + source[random.Next(source.Length)]; + + /// + /// Returns a random element from using the instance. + /// + /// The collection type. + /// The instance. + /// The collection to draw from. + /// Returns a random element of type from . + public static T OneOf(this Random random, IList source) => + source[random.Next(source.Count)]; + } +} diff --git a/X10D/SingleExtensions.cs b/X10D/SingleExtensions.cs new file mode 100644 index 0000000..a402b1b --- /dev/null +++ b/X10D/SingleExtensions.cs @@ -0,0 +1,58 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class SingleExtensions + { + /// + /// Converts an angle from degrees to radians. + /// + /// The angle in degrees. + /// Returns in radians. + public static float DegreesToRadians(this float angle) => + (float)((double)angle).DegreesToRadians(); + + /// + /// Converts the to a treating it as a Unix timestamp. + /// + /// The timestamp. + /// Optional. Whether or not the input value should be treated as milliseconds. Defaults + /// to . + /// Returns a representing seconds since the Unix + /// epoch. + public static DateTime FromUnixTimestamp(this float timestamp, bool isMillis = false) => + ((double)timestamp).FromUnixTimestamp(isMillis); + + /// + /// Converts the to a []. + /// + /// The number to convert. + /// Returns a []. + public static byte[] GetBytes(this float number) => + BitConverter.GetBytes(number); + + /// + /// Converts an angle from radians to degrees. + /// + /// The angle in radians. + /// Returns in degrees. + public static float RadiansToDegrees(this float angle) => + (float)((double)angle).RadiansToDegrees(); + + /// + /// Rounds to the nearest value. + /// + /// The value to round. + /// The nearest value. + /// Returns the rounded value. + public static float Round(this float v, int nearest = 1) => + (float)((double)v).Round(nearest); + } +} diff --git a/X10D/StringExtensions.cs b/X10D/StringExtensions.cs new file mode 100644 index 0000000..512c007 --- /dev/null +++ b/X10D/StringExtensions.cs @@ -0,0 +1,141 @@ +namespace X10D +{ + #region Using Directives + + using System; + using System.Net; + using System.Security; + using System.Text; + + #endregion + + /// + /// Extension methods for . + /// + public static class StringExtensions + { + /// + /// Decodes a base-64 encoded string. + /// + /// The base-64 string to decode. + /// Returns the string in plain text. + public static string Base64Decode(this string data) => + Convert.FromBase64String(data).GetString(); + + /// + /// Encodes a base-64 encoded string. + /// + /// The plain text string to decode. + /// Returns the string in plain text. + public static string Base64Encode(this string value) => + Convert.ToBase64String(value.GetBytes()); + + /// + /// Parses a into an . + /// + /// The type of the Enum + /// String value to parse + /// The Enum corresponding to the stringExtensions + public static T EnumParse(this string value) => + value.EnumParse(false); + + /// + /// Parses a into an . + /// + /// The type of the Enum + /// String value to parse + /// Whether or not to ignore casing. + /// The Enum corresponding to the stringExtensions + public static T EnumParse(this string value, bool ignoreCase) + { + if (value == null) + { + throw new ArgumentNullException(nameof(value)); + } + + value = value.Trim(); + + if (value.Length == 0) + { + throw new ArgumentException("Must specify valid information for parsing in the string.", + nameof(value)); + } + + Type t = typeof(T); + + if (!t.IsEnum) + { + throw new ArgumentException("Type provided must be an Enum.", "T"); + } + + return (T) Enum.Parse(t, value, ignoreCase); + } + + /// + /// Gets a [] representing the value the with + /// encoding. + /// + /// The string to convert. + /// Returns a []. + public static byte[] GetBytes(this string str) => + str.GetBytes(Encoding.UTF8); + + /// + /// Gets a [] representing the value the with the provided encoding. + /// + /// The string to convert. + /// The encoding to use. + /// Returns a []. + public static byte[] GetBytes(this string str, Encoding encoding) => + encoding.GetBytes(str); + + /// + /// Repeats a string a specified number of times. + /// + /// The string to repeat. + /// The repeat count. + /// Returns a whose value is repeated + /// times. + public static string Repeat(this string str, int count) + { + StringBuilder builder = new StringBuilder(); + + for (int i = 0; i < count; i++) + { + builder.Append(str); + } + + return builder.ToString(); + } + /// + /// Converts a to a . + /// + /// The string to convert. + /// Returns a . + public static SecureString ToSecureString(this string str) + { + if (String.IsNullOrWhiteSpace(str)) + { + return null; + } + else + { + SecureString result = new SecureString(); + foreach (char c in str) + { + result.AppendChar(c); + } + + return result; + } + } + + /// + /// Converts a to a . + /// + /// The to convert. + /// Returns a . + public static string ToString(this SecureString str) => + new NetworkCredential(String.Empty, str).Password; + } +} diff --git a/X10D/StructExtensions.cs b/X10D/StructExtensions.cs new file mode 100644 index 0000000..1ffeff1 --- /dev/null +++ b/X10D/StructExtensions.cs @@ -0,0 +1,38 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// A set of extension methods for types. + /// + public static class StructExtensions + { + public static T Next(this T src, bool wrap = true) where T : struct + { + if (!typeof(T).IsEnum) + { + throw new ArgumentException($"Argument {typeof(T).FullName} is not an Enum"); + } + + T[] arr = (T[])Enum.GetValues(src.GetType()); + int j = Array.IndexOf(arr, src) + 1; + return arr.Length == j ? arr[wrap ? 0 : j - 1] : arr[j]; + } + + public static T Previous(this T src, bool wrap = true) where T : struct + { + if (!typeof(T).IsEnum) + { + throw new ArgumentException($"Argument {typeof(T).FullName} is not an Enum"); + } + + T[] arr = (T[])Enum.GetValues(src.GetType()); + int j = Array.IndexOf(arr, src) - 1; + return j < 0 ? arr[wrap ? arr.Length - 1 : 0] : arr[j]; + } + } +} diff --git a/X10D/TimeSpanExtensions.cs b/X10D/TimeSpanExtensions.cs new file mode 100644 index 0000000..59c2c1f --- /dev/null +++ b/X10D/TimeSpanExtensions.cs @@ -0,0 +1,24 @@ +namespace X10D +{ + #region Using Directives + + using System; + + #endregion + + /// + /// Extension methods for . + /// + public static class TimeSpanExtensions + { + /// + /// Calculates how long ago a specified was. + /// + /// The . + /// Optional. Whether or not to use instead of . + /// Defaults to . + /// Returns a . + public static DateTime Ago(this TimeSpan span, bool utc = false) => + (utc ? DateTime.UtcNow : DateTime.Now) - span; + } +} diff --git a/X10D/X10D.csproj b/X10D/X10D.csproj new file mode 100644 index 0000000..3c9c7ab --- /dev/null +++ b/X10D/X10D.csproj @@ -0,0 +1,64 @@ + + + + + Debug + AnyCPU + {DE210F83-FC9A-4C23-AC2C-7A060960F716} + Library + Properties + X10D + X10D + v4.6 + 512 + true + + + true + full + false + bin\Debug\ + DEBUG;TRACE + prompt + 4 + 7.1 + + + pdbonly + true + bin\Release\ + TRACE + prompt + 4 + 7.1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file