commit e7c3f7af917732400a41db3d2ad9a8aef3f4f8b4 Author: BlubbFish Date: Sun Feb 17 14:08:57 2019 +0100 Init RaspberryIO diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ec5a403 --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +/.vs +/Unosquare.Swan.Lite/obj +/Unosquare.Swan.Lite/bin +/Unosquare.Swan/bin +/Unosquare.Swan/obj +/Unosquare.RaspberryIO/bin +/Unosquare.RaspberryIO/obj diff --git a/Unosquare.RaspberryIO.sln b/Unosquare.RaspberryIO.sln new file mode 100644 index 0000000..6a7c776 --- /dev/null +++ b/Unosquare.RaspberryIO.sln @@ -0,0 +1,37 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 15 +VisualStudioVersion = 15.0.27703.2026 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Unosquare.RaspberryIO", "Unosquare.RaspberryIO\Unosquare.RaspberryIO.csproj", "{8C5D4DE9-377F-4EC8-873D-6EEF15F43516}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Unosquare.Swan", "Unosquare.Swan\Unosquare.Swan.csproj", "{2EA5E3E4-F8C8-4742-8C78-4B070AFCFB73}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Unosquare.Swan.Lite", "Unosquare.Swan.Lite\Unosquare.Swan.Lite.csproj", "{AB015683-62E5-47F1-861F-6D037F9C6433}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {8C5D4DE9-377F-4EC8-873D-6EEF15F43516}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {8C5D4DE9-377F-4EC8-873D-6EEF15F43516}.Debug|Any CPU.Build.0 = Debug|Any CPU + {8C5D4DE9-377F-4EC8-873D-6EEF15F43516}.Release|Any CPU.ActiveCfg = Release|Any CPU + {8C5D4DE9-377F-4EC8-873D-6EEF15F43516}.Release|Any CPU.Build.0 = Release|Any CPU + {2EA5E3E4-F8C8-4742-8C78-4B070AFCFB73}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2EA5E3E4-F8C8-4742-8C78-4B070AFCFB73}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2EA5E3E4-F8C8-4742-8C78-4B070AFCFB73}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2EA5E3E4-F8C8-4742-8C78-4B070AFCFB73}.Release|Any CPU.Build.0 = Release|Any CPU + {AB015683-62E5-47F1-861F-6D037F9C6433}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AB015683-62E5-47F1-861F-6D037F9C6433}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AB015683-62E5-47F1-861F-6D037F9C6433}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AB015683-62E5-47F1-861F-6D037F9C6433}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {2EA74659-FC8F-49F7-894C-1F14BBDEEE8C} + EndGlobalSection +EndGlobal diff --git a/Unosquare.RaspberryIO/Camera/CameraColor.cs b/Unosquare.RaspberryIO/Camera/CameraColor.cs new file mode 100644 index 0000000..6fb0c9c --- /dev/null +++ b/Unosquare.RaspberryIO/Camera/CameraColor.cs @@ -0,0 +1,134 @@ +namespace Unosquare.RaspberryIO.Camera +{ + using Swan; + using System; + using System.Linq; + + /// + /// A simple RGB color class to represent colors in RGB and YUV colorspaces. + /// + public class CameraColor + { + /// + /// Initializes a new instance of the class. + /// + /// The red. + /// The green. + /// The blue. + public CameraColor(int r, int g, int b) + : this(r, g, b, string.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The red. + /// The green. + /// The blue. + /// The well-known color name. + public CameraColor(int r, int g, int b, string name) + { + RGB = new[] { Convert.ToByte(r.Clamp(0, 255)), Convert.ToByte(g.Clamp(0, 255)), Convert.ToByte(b.Clamp(0, 255)) }; + + var y = (R * .299000f) + (G * .587000f) + (B * .114000f); + var u = (R * -.168736f) + (G * -.331264f) + (B * .500000f) + 128f; + var v = (R * .500000f) + (G * -.418688f) + (B * -.081312f) + 128f; + + YUV = new byte[] { (byte)y.Clamp(0, 255), (byte)u.Clamp(0, 255), (byte)v.Clamp(0, 255) }; + Name = name; + } + + #region Static Definitions + + /// + /// Gets the predefined white color. + /// + public static CameraColor White => new CameraColor(255, 255, 255, nameof(White)); + + /// + /// Gets the predefined red color. + /// + public static CameraColor Red => new CameraColor(255, 0, 0, nameof(Red)); + + /// + /// Gets the predefined green color. + /// + public static CameraColor Green => new CameraColor(0, 255, 0, nameof(Green)); + + /// + /// Gets the predefined blue color. + /// + public static CameraColor Blue => new CameraColor(0, 0, 255, nameof(Blue)); + + /// + /// Gets the predefined black color. + /// + public static CameraColor Black => new CameraColor(0, 0, 0, nameof(Black)); + + #endregion + + /// + /// Gets the well-known color name. + /// + public string Name { get; } + + /// + /// Gets the red byte. + /// + public byte R => RGB[0]; + + /// + /// Gets the green byte. + /// + public byte G => RGB[1]; + + /// + /// Gets the blue byte. + /// + public byte B => RGB[2]; + + /// + /// Gets the RGB byte array (3 bytes). + /// + public byte[] RGB { get; } + + /// + /// Gets the YUV byte array (3 bytes). + /// + public byte[] YUV { get; } + + /// + /// Returns a hexadecimal representation of the RGB byte array. + /// Preceded by 0x and all in lowercase + /// + /// if set to true [reverse]. + /// A string + public string ToRgbHex(bool reverse) + { + var data = RGB.ToArray(); + if (reverse) Array.Reverse(data); + return ToHex(data); + } + + /// + /// Returns a hexadecimal representation of the YUV byte array. + /// Preceded by 0x and all in lowercase + /// + /// if set to true [reverse]. + /// A string + public string ToYuvHex(bool reverse) + { + var data = YUV.ToArray(); + if (reverse) Array.Reverse(data); + return ToHex(data); + } + + /// + /// Returns a hexadecimal representation of the data byte array + /// + /// The data. + /// A string + private static string ToHex(byte[] data) => $"0x{BitConverter.ToString(data).Replace("-", string.Empty).ToLowerInvariant()}"; + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Camera/CameraController.cs b/Unosquare.RaspberryIO/Camera/CameraController.cs new file mode 100644 index 0000000..ce42d68 --- /dev/null +++ b/Unosquare.RaspberryIO/Camera/CameraController.cs @@ -0,0 +1,216 @@ +namespace Unosquare.RaspberryIO.Camera +{ + using Swan.Abstractions; + using System; + using Swan.Components; + using System.IO; + using System.Threading; + using System.Threading.Tasks; + + /// + /// The Raspberry Pi's camera controller wrapping raspistill and raspivid programs. + /// This class is a singleton + /// + public class CameraController : SingletonBase + { + #region Private Declarations + + private static readonly ManualResetEventSlim OperationDone = new ManualResetEventSlim(true); + private static readonly object SyncRoot = new object(); + private static CancellationTokenSource _videoTokenSource = new CancellationTokenSource(); + private static Task _videoStreamTask; + + #endregion + + #region Properties + + /// + /// Gets a value indicating whether the camera module is busy. + /// + /// + /// true if this instance is busy; otherwise, false. + /// + public bool IsBusy => OperationDone.IsSet == false; + + #endregion + + #region Image Capture Methods + + /// + /// Captures an image asynchronously. + /// + /// The settings. + /// The ct. + /// The image bytes + /// Cannot use camera module because it is currently busy. + public async Task CaptureImageAsync(CameraStillSettings settings, CancellationToken ct = default) + { + if (Instance.IsBusy) + throw new InvalidOperationException("Cannot use camera module because it is currently busy."); + + if (settings.CaptureTimeoutMilliseconds <= 0) + throw new ArgumentException($"{nameof(settings.CaptureTimeoutMilliseconds)} needs to be greater than 0"); + + try + { + OperationDone.Reset(); + + var output = new MemoryStream(); + var exitCode = await ProcessRunner.RunProcessAsync( + settings.CommandName, + settings.CreateProcessArguments(), + (data, proc) => + { + output.Write(data, 0, data.Length); + }, + null, + true, + ct); + + return exitCode != 0 ? new byte[] { } : output.ToArray(); + } + finally + { + OperationDone.Set(); + } + } + + /// + /// Captures an image. + /// + /// The settings. + /// The image bytes + public byte[] CaptureImage(CameraStillSettings settings) + { + return CaptureImageAsync(settings).GetAwaiter().GetResult(); + } + + /// + /// Captures a JPEG encoded image asynchronously at 90% quality. + /// + /// The width. + /// The height. + /// The ct. + /// The image bytes + public Task CaptureImageJpegAsync(int width, int height, CancellationToken ct = default) + { + var settings = new CameraStillSettings + { + CaptureWidth = width, + CaptureHeight = height, + CaptureJpegQuality = 90, + CaptureTimeoutMilliseconds = 300, + }; + + return CaptureImageAsync(settings, ct); + } + + /// + /// Captures a JPEG encoded image at 90% quality. + /// + /// The width. + /// The height. + /// The image bytes + public byte[] CaptureImageJpeg(int width, int height) => CaptureImageJpegAsync(width, height).GetAwaiter().GetResult(); + + #endregion + + #region Video Capture Methods + + /// + /// Opens the video stream with a timeout of 0 (running indefinitely) at 1080p resolution, variable bitrate and 25 FPS. + /// No preview is shown + /// + /// The on data callback. + /// The on exit callback. + public void OpenVideoStream(Action onDataCallback, Action onExitCallback = null) + { + var settings = new CameraVideoSettings + { + CaptureTimeoutMilliseconds = 0, + CaptureDisplayPreview = false, + CaptureWidth = 1920, + CaptureHeight = 1080 + }; + + OpenVideoStream(settings, onDataCallback, onExitCallback); + } + + /// + /// Opens the video stream with the supplied settings. Capture Timeout Milliseconds has to be 0 or greater + /// + /// The settings. + /// The on data callback. + /// The on exit callback. + /// Cannot use camera module because it is currently busy. + /// CaptureTimeoutMilliseconds + public void OpenVideoStream(CameraVideoSettings settings, Action onDataCallback, Action onExitCallback) + { + if (Instance.IsBusy) + throw new InvalidOperationException("Cannot use camera module because it is currently busy."); + + if (settings.CaptureTimeoutMilliseconds < 0) + throw new ArgumentException($"{nameof(settings.CaptureTimeoutMilliseconds)} needs to be greater than or equal to 0"); + + try + { + OperationDone.Reset(); + _videoStreamTask = Task.Factory.StartNew(() => VideoWorkerDoWork(settings, onDataCallback, onExitCallback), _videoTokenSource.Token); + } + catch + { + OperationDone.Set(); + throw; + } + } + + /// + /// Closes the video stream of a video stream is open. + /// + public void CloseVideoStream() + { + lock (SyncRoot) + { + if (IsBusy == false) + return; + } + + if (_videoTokenSource.IsCancellationRequested == false) + { + _videoTokenSource.Cancel(); + _videoStreamTask.Wait(); + } + + _videoTokenSource = new CancellationTokenSource(); + } + + private static async Task VideoWorkerDoWork( + CameraVideoSettings settings, + Action onDataCallback, + Action onExitCallback) + { + try + { + await ProcessRunner.RunProcessAsync( + settings.CommandName, + settings.CreateProcessArguments(), + (data, proc) => onDataCallback?.Invoke(data), + null, + true, + _videoTokenSource.Token); + + onExitCallback?.Invoke(); + } + catch + { + // swallow + } + finally + { + Instance.CloseVideoStream(); + OperationDone.Set(); + } + } + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Camera/CameraRect.cs b/Unosquare.RaspberryIO/Camera/CameraRect.cs new file mode 100644 index 0000000..b793081 --- /dev/null +++ b/Unosquare.RaspberryIO/Camera/CameraRect.cs @@ -0,0 +1,82 @@ +namespace Unosquare.RaspberryIO.Camera +{ + using Swan; + using System.Globalization; + + /// + /// Defines the Raspberry Pi camera's sensor ROI (Region of Interest) + /// + public struct CameraRect + { + /// + /// The default ROI which is the entire area. + /// + public static readonly CameraRect Default = new CameraRect { X = 0M, Y = 0M, W = 1.0M, H = 1.0M }; + + /// + /// Gets or sets the x in relative coordinates. (0.0 to 1.0) + /// + /// + /// The x. + /// + public decimal X { get; set; } + + /// + /// Gets or sets the y location in relative coordinates. (0.0 to 1.0) + /// + /// + /// The y. + /// + public decimal Y { get; set; } + + /// + /// Gets or sets the width in relative coordinates. (0.0 to 1.0) + /// + /// + /// The w. + /// + public decimal W { get; set; } + + /// + /// Gets or sets the height in relative coordinates. (0.0 to 1.0) + /// + /// + /// The h. + /// + public decimal H { get; set; } + + /// + /// Gets a value indicating whether this instance is equal to the default (The entire area). + /// + /// + /// true if this instance is default; otherwise, false. + /// + public bool IsDefault + { + get + { + Clamp(); + return X == Default.X && Y == Default.Y && W == Default.W && H == Default.H; + } + } + + /// + /// Clamps the members of this ROI to their minimum and maximum values + /// + public void Clamp() + { + X = X.Clamp(0M, 1M); + Y = Y.Clamp(0M, 1M); + W = W.Clamp(0M, 1M - X); + H = H.Clamp(0M, 1M - Y); + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() => $"{X.ToString(CultureInfo.InvariantCulture)},{Y.ToString(CultureInfo.InvariantCulture)},{W.ToString(CultureInfo.InvariantCulture)},{H.ToString(CultureInfo.InvariantCulture)}"; + } +} diff --git a/Unosquare.RaspberryIO/Camera/CameraSettingsBase.cs b/Unosquare.RaspberryIO/Camera/CameraSettingsBase.cs new file mode 100644 index 0000000..fcc27b2 --- /dev/null +++ b/Unosquare.RaspberryIO/Camera/CameraSettingsBase.cs @@ -0,0 +1,340 @@ +namespace Unosquare.RaspberryIO.Camera +{ + using Swan; + using System.Globalization; + using System.Text; + + /// + /// A base class to implement raspistill and raspivid wrappers + /// Full documentation available at + /// https://www.raspberrypi.org/documentation/raspbian/applications/camera.md + /// + public abstract class CameraSettingsBase + { + /// + /// The Invariant Culture shorthand + /// + protected static readonly CultureInfo Ci = CultureInfo.InvariantCulture; + + #region Capture Settings + + /// + /// Gets or sets the timeout milliseconds. + /// Default value is 5000 + /// Recommended value is at least 300 in order to let the light collectors open + /// + public int CaptureTimeoutMilliseconds { get; set; } = 5000; + + /// + /// Gets or sets a value indicating whether or not to show a preview window on the screen + /// + public bool CaptureDisplayPreview { get; set; } = false; + + /// + /// Gets or sets a value indicating whether a preview window is shown in full screen mode if enabled + /// + public bool CaptureDisplayPreviewInFullScreen { get; set; } = true; + + /// + /// Gets or sets a value indicating whether video stabilization should be enabled. + /// + public bool CaptureVideoStabilizationEnabled { get; set; } = false; + + /// + /// Gets or sets the display preview opacity only if the display preview property is enabled. + /// + public byte CaptureDisplayPreviewOpacity { get; set; } = 255; + + /// + /// Gets or sets the capture sensor region of interest in relative coordinates. + /// + public CameraRect CaptureSensorRoi { get; set; } = CameraRect.Default; + + /// + /// Gets or sets the capture shutter speed in microseconds. + /// Default -1, Range 0 to 6000000 (equivalent to 6 seconds) + /// + public int CaptureShutterSpeedMicroseconds { get; set; } = -1; + + /// + /// Gets or sets the exposure mode. + /// + public CameraExposureMode CaptureExposure { get; set; } = CameraExposureMode.Auto; + + /// + /// Gets or sets the picture EV compensation. Default is 0, Range is -10 to 10 + /// Camera exposure compensation is commonly stated in terms of EV units; + /// 1 EV is equal to one exposure step (or stop), corresponding to a doubling of exposure. + /// Exposure can be adjusted by changing either the lens f-number or the exposure time; + /// which one is changed usually depends on the camera's exposure mode. + /// + public int CaptureExposureCompensation { get; set; } = 0; + + /// + /// Gets or sets the capture metering mode. + /// + public CameraMeteringMode CaptureMeteringMode { get; set; } = CameraMeteringMode.Average; + + /// + /// Gets or sets the automatic white balance mode. By default it is set to Auto + /// + public CameraWhiteBalanceMode CaptureWhiteBalanceControl { get; set; } = CameraWhiteBalanceMode.Auto; + + /// + /// Gets or sets the capture white balance gain on the blue channel. Example: 1.25 + /// Only takes effect if White balance control is set to off. + /// Default is 0 + /// + public decimal CaptureWhiteBalanceGainBlue { get; set; } = 0M; + + /// + /// Gets or sets the capture white balance gain on the red channel. Example: 1.75 + /// Only takes effect if White balance control is set to off. + /// Default is 0 + /// + public decimal CaptureWhiteBalanceGainRed { get; set; } = 0M; + + /// + /// Gets or sets the dynamic range compensation. + /// DRC changes the images by increasing the range of dark areas, and decreasing the brighter areas. This can improve the image in low light areas. + /// + public CameraDynamicRangeCompensation CaptureDynamicRangeCompensation { get; set; } = + CameraDynamicRangeCompensation.Off; + + #endregion + + #region Image Properties + + /// + /// Gets or sets the width of the picture to take. + /// Less than or equal to 0 in either width or height means maximum resolution available. + /// + public int CaptureWidth { get; set; } = 640; + + /// + /// Gets or sets the height of the picture to take. + /// Less than or equal to 0 in either width or height means maximum resolution available. + /// + public int CaptureHeight { get; set; } = 480; + + /// + /// Gets or sets the picture sharpness. Default is 0, Range form -100 to 100 + /// + public int ImageSharpness { get; set; } = 0; + + /// + /// Gets or sets the picture contrast. Default is 0, Range form -100 to 100 + /// + public int ImageContrast { get; set; } = 0; + + /// + /// Gets or sets the picture brightness. Default is 50, Range form 0 to 100 + /// + public int ImageBrightness { get; set; } = 50; // from 0 to 100 + + /// + /// Gets or sets the picture saturation. Default is 0, Range form -100 to 100 + /// + public int ImageSaturation { get; set; } = 0; + + /// + /// Gets or sets the picture ISO. Default is -1 Range is 100 to 800 + /// The higher the value, the more light the sensor absorbs + /// + public int ImageIso { get; set; } = -1; + + /// + /// Gets or sets the image capture effect to be applied. + /// + public CameraImageEffect ImageEffect { get; set; } = CameraImageEffect.None; + + /// + /// Gets or sets the color effect U coordinates. + /// Default is -1, Range is 0 to 255 + /// 128:128 should be effectively a monochrome image. + /// + public int ImageColorEffectU { get; set; } = -1; // 0 to 255 + + /// + /// Gets or sets the color effect V coordinates. + /// Default is -1, Range is 0 to 255 + /// 128:128 should be effectively a monochrome image. + /// + public int ImageColorEffectV { get; set; } = -1; // 0 to 255 + + /// + /// Gets or sets the image rotation. Default is no rotation + /// + public CameraImageRotation ImageRotation { get; set; } = CameraImageRotation.None; + + /// + /// Gets or sets a value indicating whether the image should be flipped horizontally. + /// + public bool ImageFlipHorizontally { get; set; } + + /// + /// Gets or sets a value indicating whether the image should be flipped vertically. + /// + public bool ImageFlipVertically { get; set; } + + /// + /// Gets or sets the image annotations using a bitmask (or flags) notation. + /// Apply a bitwise OR to the enumeration to include multiple annotations + /// + public CameraAnnotation ImageAnnotations { get; set; } = CameraAnnotation.None; + + /// + /// Gets or sets the image annotations text. + /// Text may include date/time placeholders by using the '%' character, as used by strftime. + /// Example: ABC %Y-%m-%d %X will output ABC 2015-10-28 20:09:33 + /// + public string ImageAnnotationsText { get; set; } = string.Empty; + + /// + /// Gets or sets the font size of the text annotations + /// Default is -1, range is 6 to 160 + /// + public int ImageAnnotationFontSize { get; set; } = -1; + + /// + /// Gets or sets the color of the text annotations. + /// + /// + /// The color of the image annotation font. + /// + public CameraColor ImageAnnotationFontColor { get; set; } = null; + + /// + /// Gets or sets the background color for text annotations. + /// + /// + /// The image annotation background. + /// + public CameraColor ImageAnnotationBackground { get; set; } = null; + + #endregion + + #region Interface + + /// + /// Gets the command file executable. + /// + public abstract string CommandName { get; } + + /// + /// Creates the process arguments. + /// + /// The string that represents the process arguments + public virtual string CreateProcessArguments() + { + var sb = new StringBuilder(); + sb.Append("-o -"); // output to standard output as opposed to a file. + sb.Append($" -t {(CaptureTimeoutMilliseconds < 0 ? "0" : CaptureTimeoutMilliseconds.ToString(Ci))}"); + + // Basic Width and height + if (CaptureWidth > 0 && CaptureHeight > 0) + { + sb.Append($" -w {CaptureWidth.ToString(Ci)}"); + sb.Append($" -h {CaptureHeight.ToString(Ci)}"); + } + + // Display Preview + if (CaptureDisplayPreview) + { + if (CaptureDisplayPreviewInFullScreen) + sb.Append(" -f"); + + if (CaptureDisplayPreviewOpacity != byte.MaxValue) + sb.Append($" -op {CaptureDisplayPreviewOpacity.ToString(Ci)}"); + } + else + { + sb.Append(" -n"); // no preview + } + + // Picture Settings + if (ImageSharpness != 0) + sb.Append($" -sh {ImageSharpness.Clamp(-100, 100).ToString(Ci)}"); + + if (ImageContrast != 0) + sb.Append($" -co {ImageContrast.Clamp(-100, 100).ToString(Ci)}"); + + if (ImageBrightness != 50) + sb.Append($" -br {ImageBrightness.Clamp(0, 100).ToString(Ci)}"); + + if (ImageSaturation != 0) + sb.Append($" -sa {ImageSaturation.Clamp(-100, 100).ToString(Ci)}"); + + if (ImageIso >= 100) + sb.Append($" -ISO {ImageIso.Clamp(100, 800).ToString(Ci)}"); + + if (CaptureVideoStabilizationEnabled) + sb.Append(" -vs"); + + if (CaptureExposureCompensation != 0) + sb.Append($" -ev {CaptureExposureCompensation.Clamp(-10, 10).ToString(Ci)}"); + + if (CaptureExposure != CameraExposureMode.Auto) + sb.Append($" -ex {CaptureExposure.ToString().ToLowerInvariant()}"); + + if (CaptureWhiteBalanceControl != CameraWhiteBalanceMode.Auto) + sb.Append($" -awb {CaptureWhiteBalanceControl.ToString().ToLowerInvariant()}"); + + if (ImageEffect != CameraImageEffect.None) + sb.Append($" -ifx {ImageEffect.ToString().ToLowerInvariant()}"); + + if (ImageColorEffectU >= 0 && ImageColorEffectV >= 0) + { + sb.Append( + $" -cfx {ImageColorEffectU.Clamp(0, 255).ToString(Ci)}:{ImageColorEffectV.Clamp(0, 255).ToString(Ci)}"); + } + + if (CaptureMeteringMode != CameraMeteringMode.Average) + sb.Append($" -mm {CaptureMeteringMode.ToString().ToLowerInvariant()}"); + + if (ImageRotation != CameraImageRotation.None) + sb.Append($" -rot {((int)ImageRotation).ToString(Ci)}"); + + if (ImageFlipHorizontally) + sb.Append(" -hf"); + + if (ImageFlipVertically) + sb.Append(" -vf"); + + if (CaptureSensorRoi.IsDefault == false) + sb.Append($" -roi {CaptureSensorRoi}"); + + if (CaptureShutterSpeedMicroseconds > 0) + sb.Append($" -ss {CaptureShutterSpeedMicroseconds.Clamp(0, 6000000).ToString(Ci)}"); + + if (CaptureDynamicRangeCompensation != CameraDynamicRangeCompensation.Off) + sb.Append($" -drc {CaptureDynamicRangeCompensation.ToString().ToLowerInvariant()}"); + + if (CaptureWhiteBalanceControl == CameraWhiteBalanceMode.Off && + (CaptureWhiteBalanceGainBlue != 0M || CaptureWhiteBalanceGainRed != 0M)) + sb.Append($" -awbg {CaptureWhiteBalanceGainBlue.ToString(Ci)},{CaptureWhiteBalanceGainRed.ToString(Ci)}"); + + if (ImageAnnotationFontSize > 0) + { + sb.Append($" -ae {ImageAnnotationFontSize.Clamp(6, 160).ToString(Ci)}"); + sb.Append($",{(ImageAnnotationFontColor == null ? "0xff" : ImageAnnotationFontColor.ToYuvHex(true))}"); + + if (ImageAnnotationBackground != null) + { + ImageAnnotations |= CameraAnnotation.SolidBackground; + sb.Append($",{ImageAnnotationBackground.ToYuvHex(true)}"); + } + } + + if (ImageAnnotations != CameraAnnotation.None) + sb.Append($" -a {((int)ImageAnnotations).ToString(Ci)}"); + + if (string.IsNullOrWhiteSpace(ImageAnnotationsText) == false) + sb.Append($" -a \"{ImageAnnotationsText.Replace("\"", "'")}\""); + + return sb.ToString(); + } + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Camera/CameraStillSettings.cs b/Unosquare.RaspberryIO/Camera/CameraStillSettings.cs new file mode 100644 index 0000000..3deac71 --- /dev/null +++ b/Unosquare.RaspberryIO/Camera/CameraStillSettings.cs @@ -0,0 +1,120 @@ +namespace Unosquare.RaspberryIO.Camera +{ + using Swan; + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// Defines a wrapper for the raspistill program and its settings (command-line arguments) + /// + /// + public class CameraStillSettings : CameraSettingsBase + { + private int _rotate; + + /// + public override string CommandName => "raspistill"; + + /// + /// Gets or sets a value indicating whether the preview window (if enabled) uses native capture resolution + /// This may slow down preview FPS + /// + public bool CaptureDisplayPreviewAtResolution { get; set; } = false; + + /// + /// Gets or sets the encoding format the hardware will use for the output. + /// + public CameraImageEncodingFormat CaptureEncoding { get; set; } = CameraImageEncodingFormat.Jpg; + + /// + /// Gets or sets the quality for JPEG only encoding mode. + /// Value ranges from 0 to 100 + /// + public int CaptureJpegQuality { get; set; } = 90; + + /// + /// Gets or sets a value indicating whether the JPEG encoder should add raw bayer metadata. + /// + public bool CaptureJpegIncludeRawBayerMetadata { get; set; } = false; + + /// + /// JPEG EXIF data + /// Keys and values must be already properly escaped. Otherwise the command will fail. + /// + public Dictionary CaptureJpegExtendedInfo { get; } = new Dictionary(); + + /// + /// Gets or sets a value indicating whether [horizontal flip]. + /// + /// + /// true if [horizontal flip]; otherwise, false. + /// + public bool HorizontalFlip { get; set; } = false; + + /// + /// Gets or sets a value indicating whether [vertical flip]. + /// + /// + /// true if [vertical flip]; otherwise, false. + /// + public bool VerticalFlip { get; set; } = false; + + /// + /// Gets or sets the rotation. + /// + /// Valid range 0-359 + public int Rotation + { + get => _rotate; + set + { + if (value < 0 || value > 359) + { + throw new ArgumentOutOfRangeException(nameof(value), "Valid range 0-359"); + } + + _rotate = value; + } + } + + /// + public override string CreateProcessArguments() + { + var sb = new StringBuilder(base.CreateProcessArguments()); + sb.Append($" -e {CaptureEncoding.ToString().ToLowerInvariant()}"); + + // JPEG Encoder specific arguments + if (CaptureEncoding == CameraImageEncodingFormat.Jpg) + { + sb.Append($" -q {CaptureJpegQuality.Clamp(0, 100).ToString(Ci)}"); + + if (CaptureJpegIncludeRawBayerMetadata) + sb.Append(" -r"); + + // JPEG EXIF data + if (CaptureJpegExtendedInfo.Count > 0) + { + foreach (var kvp in CaptureJpegExtendedInfo) + { + if (string.IsNullOrWhiteSpace(kvp.Key) || string.IsNullOrWhiteSpace(kvp.Value)) + continue; + + sb.Append($" -x \"{kvp.Key.Replace("\"", "'")}={kvp.Value.Replace("\"", "'")}\""); + } + } + } + + // Display preview settings + if (CaptureDisplayPreview && CaptureDisplayPreviewAtResolution) sb.Append(" -fp"); + + if (Rotation != 0) sb.Append($" -rot {Rotation}"); + + if (HorizontalFlip) sb.Append(" -hf"); + + if (VerticalFlip) sb.Append(" -vf"); + + return sb.ToString(); + } + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Camera/CameraVideoSettings.cs b/Unosquare.RaspberryIO/Camera/CameraVideoSettings.cs new file mode 100644 index 0000000..f2470d8 --- /dev/null +++ b/Unosquare.RaspberryIO/Camera/CameraVideoSettings.cs @@ -0,0 +1,94 @@ +namespace Unosquare.RaspberryIO.Camera +{ + using Swan; + using System.Text; + + /// + /// Represents the raspivid camera settings for video capture functionality + /// + /// + public class CameraVideoSettings : CameraSettingsBase + { + /// + public override string CommandName => "raspivid"; + + /// + /// Use bits per second, so 10Mbits/s would be -b 10000000. For H264, 1080p30 a high quality bitrate would be 15Mbits/s or more. + /// Maximum bitrate is 25Mbits/s (-b 25000000), but much over 17Mbits/s won't show noticeable improvement at 1080p30. + /// Default -1 + /// + public int CaptureBitrate { get; set; } = -1; + + /// + /// Gets or sets the framerate. + /// Default 25, range 2 to 30 + /// + public int CaptureFramerate { get; set; } = 25; + + /// + /// Sets the intra refresh period (GoP) rate for the recorded video. H264 video uses a complete frame (I-frame) every intra + /// refresh period, from which subsequent frames are based. This option specifies the number of frames between each I-frame. + /// Larger numbers here will reduce the size of the resulting video, and smaller numbers make the stream less error-prone. + /// + public int CaptureKeyframeRate { get; set; } = 25; + + /// + /// Sets the initial quantisation parameter for the stream. Varies from approximately 10 to 40, and will greatly affect + /// the quality of the recording. Higher values reduce quality and decrease file size. Combine this setting with a + /// bitrate of 0 to set a completely variable bitrate. + /// + public int CaptureQuantisation { get; set; } = 23; + + /// + /// Gets or sets the profile. + /// Sets the H264 profile to be used for the encoding. + /// Default is Main mode + /// + public CameraH264Profile CaptureProfile { get; set; } = CameraH264Profile.Main; + + /// + /// Forces the stream to include PPS and SPS headers on every I-frame. Needed for certain streaming cases + /// e.g. Apple HLS. These headers are small, so don't greatly increase the file size. + /// + /// + /// true if [interleave headers]; otherwise, false. + /// + public bool CaptureInterleaveHeaders { get; set; } = true; + + /// + /// Switch on an option to display the preview after compression. This will show any compression artefacts in the preview window. In normal operation, + /// the preview will show the camera output prior to being compressed. This option is not guaranteed to work in future releases. + /// + /// + /// true if [capture display preview encoded]; otherwise, false. + /// + public bool CaptureDisplayPreviewEncoded { get; set; } = false; + + /// + public override string CreateProcessArguments() + { + var sb = new StringBuilder(base.CreateProcessArguments()); + + sb.Append($" -pf {CaptureProfile.ToString().ToLowerInvariant()}"); + if (CaptureBitrate < 0) + sb.Append($" -b {CaptureBitrate.Clamp(0, 25000000).ToString(Ci)}"); + + if (CaptureFramerate >= 2) + sb.Append($" -fps {CaptureFramerate.Clamp(2, 30).ToString(Ci)}"); + + if (CaptureDisplayPreview && CaptureDisplayPreviewEncoded) + sb.Append(" -e"); + + if (CaptureKeyframeRate > 0) + sb.Append($" -g {CaptureKeyframeRate.ToString(Ci)}"); + + if (CaptureQuantisation >= 0) + sb.Append($" -qp {CaptureQuantisation.Clamp(0, 40).ToString(Ci)}"); + + if (CaptureInterleaveHeaders) + sb.Append(" -ih"); + + return sb.ToString(); + } + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Camera/Enums.cs b/Unosquare.RaspberryIO/Camera/Enums.cs new file mode 100644 index 0000000..9473147 --- /dev/null +++ b/Unosquare.RaspberryIO/Camera/Enums.cs @@ -0,0 +1,423 @@ +namespace Unosquare.RaspberryIO.Camera +{ + using System; + + /// + /// Defines the available encoding formats for the Raspberry Pi camera module + /// + public enum CameraImageEncodingFormat + { + /// + /// The JPG + /// + Jpg, + + /// + /// The BMP + /// + Bmp, + + /// + /// The GIF + /// + Gif, + + /// + /// The PNG + /// + Png, + } + + /// + /// Defines the different exposure modes for the Raspberry Pi's camera module + /// + public enum CameraExposureMode + { + /// + /// The automatic + /// + Auto, + + /// + /// The night + /// + Night, + + /// + /// The night preview + /// + NightPreview, + + /// + /// The backlight + /// + Backlight, + + /// + /// The spotlight + /// + Spotlight, + + /// + /// The sports + /// + Sports, + + /// + /// The snow + /// + Snow, + + /// + /// The beach + /// + Beach, + + /// + /// The very long + /// + VeryLong, + + /// + /// The fixed FPS + /// + FixedFps, + + /// + /// The anti shake + /// + AntiShake, + + /// + /// The fireworks + /// + Fireworks + } + + /// + /// Defines the different AWB (Auto White Balance) modes for the Raspberry Pi's camera module + /// + public enum CameraWhiteBalanceMode + { + /// + /// No white balance + /// + Off, + + /// + /// The automatic + /// + Auto, + + /// + /// The sun + /// + Sun, + + /// + /// The cloud + /// + Cloud, + + /// + /// The shade + /// + Shade, + + /// + /// The tungsten + /// + Tungsten, + + /// + /// The fluorescent + /// + Fluorescent, + + /// + /// The incandescent + /// + Incandescent, + + /// + /// The flash + /// + Flash, + + /// + /// The horizon + /// + Horizon + } + + /// + /// Defines the available image effects for the Raspberry Pi's camera module + /// + public enum CameraImageEffect + { + /// + /// No effect + /// + None, + + /// + /// The negative + /// + Negative, + + /// + /// The solarise + /// + Solarise, + + /// + /// The whiteboard + /// + Whiteboard, + + /// + /// The blackboard + /// + Blackboard, + + /// + /// The sketch + /// + Sketch, + + /// + /// The denoise + /// + Denoise, + + /// + /// The emboss + /// + Emboss, + + /// + /// The oil paint + /// + OilPaint, + + /// + /// The hatch + /// + Hatch, + + /// + /// Graphite Pen + /// + GPen, + + /// + /// The pastel + /// + Pastel, + + /// + /// The water colour + /// + WaterColour, + + /// + /// The film + /// + Film, + + /// + /// The blur + /// + Blur, + + /// + /// The saturation + /// + Saturation, + + /// + /// The solour swap + /// + SolourSwap, + + /// + /// The washed out + /// + WashedOut, + + /// + /// The colour point + /// + ColourPoint, + + /// + /// The colour balance + /// + ColourBalance, + + /// + /// The cartoon + /// + Cartoon + } + + /// + /// Defines the different metering modes for the Raspberry Pi's camera module + /// + public enum CameraMeteringMode + { + /// + /// The average + /// + Average, + + /// + /// The spot + /// + Spot, + + /// + /// The backlit + /// + Backlit, + + /// + /// The matrix + /// + Matrix, + } + + /// + /// Defines the different image rotation modes for the Raspberry Pi's camera module + /// + public enum CameraImageRotation + { + /// + /// No rerotation + /// + None = 0, + + /// + /// 90 Degrees + /// + Degrees90 = 90, + + /// + /// 180 Degrees + /// + Degrees180 = 180, + + /// + /// 270 degrees + /// + Degrees270 = 270 + } + + /// + /// Defines the different DRC (Dynamic Range Compensation) modes for the Raspberry Pi's camera module + /// Helpful for low light photos + /// + public enum CameraDynamicRangeCompensation + { + /// + /// The off setting + /// + Off, + + /// + /// The low + /// + Low, + + /// + /// The medium + /// + Medium, + + /// + /// The high + /// + High + } + + /// + /// Defines the bit-wise mask flags for the available annotation elements for the Raspberry Pi's camera module + /// + [Flags] + public enum CameraAnnotation + { + /// + /// The none + /// + None = 0, + + /// + /// The time + /// + Time = 4, + + /// + /// The date + /// + Date = 8, + + /// + /// The shutter settings + /// + ShutterSettings = 16, + + /// + /// The caf settings + /// + CafSettings = 32, + + /// + /// The gain settings + /// + GainSettings = 64, + + /// + /// The lens settings + /// + LensSettings = 128, + + /// + /// The motion settings + /// + MotionSettings = 256, + + /// + /// The frame number + /// + FrameNumber = 512, + + /// + /// The solid background + /// + SolidBackground = 1024, + } + + /// + /// Defines the different H.264 encoding profiles to be used when capturing video. + /// + public enum CameraH264Profile + { + /// + /// BP: Primarily for lower-cost applications with limited computing resources, + /// this profile is used widely in videoconferencing and mobile applications. + /// + Baseline, + + /// + /// MP: Originally intended as the mainstream consumer profile for broadcast + /// and storage applications, the importance of this profile faded when the High profile was developed for those applications. + /// + Main, + + /// + /// HiP: The primary profile for broadcast and disc storage applications, particularly + /// for high-definition television applications (this is the profile adopted into HD DVD and Blu-ray Disc, for example). + /// + High + } +} diff --git a/Unosquare.RaspberryIO/Computer/DsiDisplay.cs b/Unosquare.RaspberryIO/Computer/DsiDisplay.cs new file mode 100644 index 0000000..aff143f --- /dev/null +++ b/Unosquare.RaspberryIO/Computer/DsiDisplay.cs @@ -0,0 +1,80 @@ +namespace Unosquare.RaspberryIO.Computer +{ + using Swan.Abstractions; + using System.Globalization; + using System.IO; + + /// + /// The Official Raspberry Pi 7-inch touch display from the foundation + /// Some docs available here: + /// http://forums.pimoroni.com/t/official-7-raspberry-pi-touch-screen-faq/959 + /// + public class DsiDisplay : SingletonBase + { + private const string BacklightFilename = "/sys/class/backlight/rpi_backlight/bl_power"; + private const string BrightnessFilename = "/sys/class/backlight/rpi_backlight/brightness"; + + /// + /// Prevents a default instance of the class from being created. + /// + private DsiDisplay() + { + // placeholder + } + + /// + /// Gets a value indicating whether the Pi Foundation Display files are present. + /// + /// + /// true if this instance is present; otherwise, false. + /// + public bool IsPresent => File.Exists(BrightnessFilename); + + /// + /// Gets or sets the brightness of the DSI display via filesystem. + /// + /// + /// The brightness. + /// + public byte Brightness + { + get + { + if (IsPresent == false) return 0; + + return byte.TryParse(File.ReadAllText(BrightnessFilename).Trim(), out var brightness) ? brightness : (byte)0; + } + set + { + if (IsPresent == false) return; + File.WriteAllText(BrightnessFilename, value.ToString(CultureInfo.InvariantCulture)); + } + } + + /// + /// Gets or sets a value indicating whether the backlight of the DSI display on. + /// This operation is performed via the file system + /// + /// + /// true if this instance is backlight on; otherwise, false. + /// + public bool IsBacklightOn + { + get + { + if (IsPresent == false) return false; + + if (int.TryParse(File.ReadAllText(BacklightFilename).Trim(), out var backlight)) + return backlight == 0; + + return false; + } + set + { + if (IsPresent == false) return; + + File.WriteAllText(BacklightFilename, value ? "0" : "1"); + } + } + } +} diff --git a/Unosquare.RaspberryIO/Computer/NetworkAdapterInfo.cs b/Unosquare.RaspberryIO/Computer/NetworkAdapterInfo.cs new file mode 100644 index 0000000..d90ba47 --- /dev/null +++ b/Unosquare.RaspberryIO/Computer/NetworkAdapterInfo.cs @@ -0,0 +1,40 @@ +namespace Unosquare.RaspberryIO.Computer +{ + using System.Net; + + /// + /// Represents a Network Adapter + /// + public class NetworkAdapterInfo + { + /// + /// Gets the name. + /// + public string Name { get; internal set; } + + /// + /// Gets the IP V4 address. + /// + public IPAddress IPv4 { get; internal set; } + + /// + /// Gets the IP V6 address. + /// + public IPAddress IPv6 { get; internal set; } + + /// + /// Gets the name of the access point. + /// + public string AccessPointName { get; internal set; } + + /// + /// Gets the MAC (Physical) address. + /// + public string MacAddress { get; internal set; } + + /// + /// Gets a value indicating whether this instance is wireless. + /// + public bool IsWireless { get; internal set; } + } +} diff --git a/Unosquare.RaspberryIO/Computer/NetworkSettings.cs b/Unosquare.RaspberryIO/Computer/NetworkSettings.cs new file mode 100644 index 0000000..6d03de0 --- /dev/null +++ b/Unosquare.RaspberryIO/Computer/NetworkSettings.cs @@ -0,0 +1,266 @@ +namespace Unosquare.RaspberryIO.Computer +{ + using Swan; + using Swan.Abstractions; + using Swan.Components; + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Text; + + /// + /// Represents the network information + /// + public class NetworkSettings : SingletonBase + { + private const string EssidTag = "ESSID:"; + + /// + /// Gets the local machine Host Name. + /// + public string HostName => Network.HostName; + + /// + /// Retrieves the wireless networks. + /// + /// The adapter. + /// A list of WiFi networks + public List RetrieveWirelessNetworks(string adapter) => RetrieveWirelessNetworks(new[] { adapter }); + + /// + /// Retrieves the wireless networks. + /// + /// The adapters. + /// A list of WiFi networks + public List RetrieveWirelessNetworks(string[] adapters = null) + { + var result = new List(); + + foreach (var networkAdapter in adapters ?? RetrieveAdapters().Where(x => x.IsWireless).Select(x => x.Name)) + { + var wirelessOutput = ProcessRunner.GetProcessOutputAsync("iwlist", $"{networkAdapter} scanning").Result; + var outputLines = + wirelessOutput.Split('\n') + .Select(x => x.Trim()) + .Where(x => string.IsNullOrWhiteSpace(x) == false) + .ToArray(); + + for (var i = 0; i < outputLines.Length; i++) + { + var line = outputLines[i]; + + if (line.StartsWith(EssidTag) == false) continue; + + var network = new WirelessNetworkInfo() + { + Name = line.Replace(EssidTag, string.Empty).Replace("\"", string.Empty) + }; + + while (true) + { + if (i + 1 >= outputLines.Length) break; + + // should look for two lines before the ESSID acording to the scan + line = outputLines[i - 2]; + + if (line.StartsWith("Quality=")) + { + network.Quality = line.Replace("Quality=", string.Empty); + break; + } + } + + while (true) + { + if (i + 1 >= outputLines.Length) break; + + // should look for a line before the ESSID acording to the scan + line = outputLines[i - 1]; + + if (line.StartsWith("Encryption key:")) + { + network.IsEncrypted = line.Replace("Encryption key:", string.Empty).Trim() == "on"; + break; + } + } + + if (result.Any(x => x.Name == network.Name) == false) + result.Add(network); + } + } + + return result.OrderBy(x => x.Name).ToList(); + } + + /// + /// Setups the wireless network. + /// + /// Name of the adapter. + /// The network ssid. + /// The password. + /// The 2-letter country code in uppercase. Default is US. + /// True if successful. Otherwise, false. + public bool SetupWirelessNetwork(string adapterName, string networkSsid, string password = null, string countryCode = "US") + { + // TODO: Get the country where the device is located to set 'country' param in payload var + var payload = $"country={countryCode}\nctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\nupdate_config=1\n"; + payload += string.IsNullOrEmpty(password) + ? $"network={{\n\tssid=\"{networkSsid}\"\n\t}}\n" + : $"network={{\n\tssid=\"{networkSsid}\"\n\tpsk=\"{password}\"\n\t}}\n"; + try + { + File.WriteAllText("/etc/wpa_supplicant/wpa_supplicant.conf", payload); + ProcessRunner.GetProcessOutputAsync("pkill", "-f wpa_supplicant").Wait(); + ProcessRunner.GetProcessOutputAsync("ifdown", adapterName).Wait(); + ProcessRunner.GetProcessOutputAsync("ifup", adapterName).Wait(); + } + catch (Exception ex) + { + ex.Log(nameof(NetworkSettings)); + return false; + } + + return true; + } + + /// + /// Retrieves the network adapters. + /// + /// A list of network adapters. + public List RetrieveAdapters() + { + const string hWaddr = "HWaddr "; + const string ether = "ether "; + + var result = new List(); + var interfacesOutput = ProcessRunner.GetProcessOutputAsync("ifconfig").Result; + var wlanOutput = ProcessRunner.GetProcessOutputAsync("iwconfig") + .Result.Split('\n') + .Where(x => x.Contains("no wireless extensions.") == false) + .ToArray(); + + var outputLines = interfacesOutput.Split('\n').Where(x => string.IsNullOrWhiteSpace(x) == false).ToArray(); + + for (var i = 0; i < outputLines.Length; i++) + { + // grab the current line + var line = outputLines[i]; + + // skip if the line is indented + if (char.IsLetterOrDigit(line[0]) == false) + continue; + + // Read the line as an adatper + var adapter = new NetworkAdapterInfo + { + Name = line.Substring(0, line.IndexOf(' ')).TrimEnd(':') + }; + + // Parse the MAC address in old version of ifconfig; it comes in the first line + if (line.IndexOf(hWaddr) >= 0) + { + var startIndexHwd = line.IndexOf(hWaddr) + hWaddr.Length; + adapter.MacAddress = line.Substring(startIndexHwd, 17).Trim(); + } + + // Parse the info in lines other than the first + for (var j = i + 1; j < outputLines.Length; j++) + { + // Get the contents of the indented line + var indentedLine = outputLines[j]; + + // We have hit the next adapter info + if (char.IsLetterOrDigit(indentedLine[0])) + { + i = j - 1; + break; + } + + // Parse the MAC address in new versions of ifconfig; it no longer comes in the first line + if (indentedLine.IndexOf(ether) >= 0 && string.IsNullOrWhiteSpace(adapter.MacAddress)) + { + var startIndexHwd = indentedLine.IndexOf(ether) + ether.Length; + adapter.MacAddress = indentedLine.Substring(startIndexHwd, 17).Trim(); + } + + // Parse the IPv4 Address + { + var addressText = ParseOutputTagFromLine(indentedLine, "inet addr:") ?? ParseOutputTagFromLine(indentedLine, "inet "); + + if (addressText != null) + { + if (IPAddress.TryParse(addressText, out var outValue)) + adapter.IPv4 = outValue; + } + } + + // Parse the IPv6 Address + { + var addressText = ParseOutputTagFromLine(indentedLine, "inet6 addr:") ?? ParseOutputTagFromLine(indentedLine, "inet6 "); + + if (addressText != null) + { + if (IPAddress.TryParse(addressText, out var outValue)) + adapter.IPv6 = outValue; + } + } + + // we have hit the end of the output in an indented line + if (j >= outputLines.Length - 1) + i = outputLines.Length; + } + + // Retrieve the wireless LAN info + var wlanInfo = wlanOutput.FirstOrDefault(x => x.StartsWith(adapter.Name)); + + if (wlanInfo != null) + { + adapter.IsWireless = true; + var essidParts = wlanInfo.Split(new[] { EssidTag }, StringSplitOptions.RemoveEmptyEntries); + if (essidParts.Length >= 2) + { + adapter.AccessPointName = essidParts[1].Replace("\"", string.Empty).Trim(); + } + } + + // Add the current adapter to the result + result.Add(adapter); + } + + return result.OrderBy(x => x.Name).ToList(); + } + + /// + /// Retrieves current wireless connected network name. + /// + /// The connected network name. + public string GetWirelessNetworkName() => ProcessRunner.GetProcessOutputAsync("iwgetid", "-r").Result; + + /// + /// Parses the output tag from the given line. + /// + /// The indented line. + /// Name of the tag. + /// The value after the tag identifier + private static string ParseOutputTagFromLine(string indentedLine, string tagName) + { + if (indentedLine.IndexOf(tagName) < 0) + return null; + + var startIndex = indentedLine.IndexOf(tagName) + tagName.Length; + var builder = new StringBuilder(1024); + for (var c = startIndex; c < indentedLine.Length; c++) + { + var currentChar = indentedLine[c]; + if (!char.IsPunctuation(currentChar) && !char.IsLetterOrDigit(currentChar)) + break; + + builder.Append(currentChar); + } + + return builder.ToString(); + } + } +} diff --git a/Unosquare.RaspberryIO/Computer/OsInfo.cs b/Unosquare.RaspberryIO/Computer/OsInfo.cs new file mode 100644 index 0000000..80ecfde --- /dev/null +++ b/Unosquare.RaspberryIO/Computer/OsInfo.cs @@ -0,0 +1,46 @@ +namespace Unosquare.RaspberryIO.Computer +{ + /// + /// Represents the OS Information + /// + public class OsInfo + { + /// + /// System name + /// + public string SysName { get; set; } + + /// + /// Node name + /// + public string NodeName { get; set; } + + /// + /// Release level + /// + public string Release { get; set; } + + /// + /// Version level + /// + public string Version { get; set; } + + /// + /// Hardware level + /// + public string Machine { get; set; } + + /// + /// Domain name + /// + public string DomainName { get; set; } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() => $"{SysName} {Release} {Version}"; + } +} diff --git a/Unosquare.RaspberryIO/Computer/PiVersion.cs b/Unosquare.RaspberryIO/Computer/PiVersion.cs new file mode 100644 index 0000000..a6af028 --- /dev/null +++ b/Unosquare.RaspberryIO/Computer/PiVersion.cs @@ -0,0 +1,134 @@ +namespace Unosquare.RaspberryIO.Computer +{ + /// + /// Defines the board revision codes of the different versions of the Raspberry Pi + /// http://www.raspberrypi-spy.co.uk/2012/09/checking-your-raspberry-pi-board-version/ + /// + public enum PiVersion + { + /// + /// The unknown version + /// + Unknown = 0, + + /// + /// The model b rev1 + /// + ModelBRev1 = 0x0002, + + /// + /// The model b rev1 ec N0001 + /// + ModelBRev1ECN0001 = 0x0003, + + /// + /// The model b rev2x04 + /// + ModelBRev2x04 = 0x0004, + + /// + /// The model b rev2x05 + /// + ModelBRev2x05 = 0x0005, + + /// + /// The model b rev2x06 + /// + ModelBRev2x06 = 0x0006, + + /// + /// The model ax07 + /// + ModelAx07 = 0x0007, + + /// + /// The model ax08 + /// + ModelAx08 = 0x0008, + + /// + /// The model ax09 + /// + ModelAx09 = 0x0009, + + /// + /// The model b rev2x0d + /// + ModelBRev2x0d, + + /// + /// The model b rev2x0e + /// + ModelBRev2x0e, + + /// + /// The model b rev2x0f + /// + ModelBRev2x0f = 0x000f, + + /// + /// The model b plus0x10 + /// + ModelBPlus0x10 = 0x0010, + + /// + /// The model b plus0x13 + /// + ModelBPlus0x13 = 0x0013, + + /// + /// The compute module0x11 + /// + ComputeModule0x11 = 0x0011, + + /// + /// The compute module0x14 + /// + ComputeModule0x14 = 0x0014, + + /// + /// The model a plus0x12 + /// + ModelAPlus0x12 = 0x0012, + + /// + /// The model a plus0x15 + /// + ModelAPlus0x15 = 0x0015, + + /// + /// The pi2 model B1V1 sony + /// + Pi2ModelB1v1Sony = 0xa01041, + + /// + /// The pi2 model B1V1 embest + /// + Pi2ModelB1v1Embest = 0xa21041, + + /// + /// The pi2 model B1V2 + /// + Pi2ModelB1v2 = 0xa22042, + + /// + /// The pi zero1v2 + /// + PiZero1v2 = 0x900092, + + /// + /// The pi zero1v3 + /// + PiZero1v3 = 0x900093, + + /// + /// The pi3 model b sony + /// + Pi3ModelBSony = 0xa02082, + + /// + /// The pi3 model b embest + /// + Pi3ModelBEmbest = 0xa22082 + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Computer/SystemInfo.cs b/Unosquare.RaspberryIO/Computer/SystemInfo.cs new file mode 100644 index 0000000..fad1ec0 --- /dev/null +++ b/Unosquare.RaspberryIO/Computer/SystemInfo.cs @@ -0,0 +1,344 @@ +namespace Unosquare.RaspberryIO.Computer +{ + using Native; + using Swan.Abstractions; + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Reflection; + + /// + /// http://raspberry-pi-guide.readthedocs.io/en/latest/system.html + /// + public sealed class SystemInfo : SingletonBase + { + private const string CpuInfoFilePath = "/proc/cpuinfo"; + private const string MemInfoFilePath = "/proc/meminfo"; + private const string UptimeFilePath = "/proc/uptime"; + private static readonly StringComparer StringComparer = StringComparer.InvariantCultureIgnoreCase; + + private static readonly object SyncRoot = new object(); + + /// + /// Prevents a default instance of the class from being created. + /// + /// Could not initialize the GPIO controller + private SystemInfo() + { + #region Obtain and format a property dictionary + + var properties = + typeof(SystemInfo).GetTypeInfo() + .GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) + .Where( + p => + p.CanWrite && p.CanRead && + (p.PropertyType == typeof(string) || p.PropertyType == typeof(string[]))) + .ToArray(); + var propDictionary = new Dictionary(StringComparer); + + foreach (var prop in properties) + { + propDictionary[prop.Name.Replace(" ", string.Empty).ToLowerInvariant().Trim()] = prop; + } + + #endregion + + #region Extract CPU information + + if (File.Exists(CpuInfoFilePath)) + { + var cpuInfoLines = File.ReadAllLines(CpuInfoFilePath); + + foreach (var line in cpuInfoLines) + { + var lineParts = line.Split(new[] { ':' }, 2); + if (lineParts.Length != 2) + continue; + + var propertyKey = lineParts[0].Trim().Replace(" ", string.Empty); + var propertyStringValue = lineParts[1].Trim(); + + if (!propDictionary.ContainsKey(propertyKey)) continue; + + var property = propDictionary[propertyKey]; + if (property.PropertyType == typeof(string)) + { + property.SetValue(this, propertyStringValue); + } + else if (property.PropertyType == typeof(string[])) + { + var propertyArrayAvalue = propertyStringValue.Split(' '); + property.SetValue(this, propertyArrayAvalue); + } + } + } + + #endregion + + #region Extract Memory Information + + if (File.Exists(MemInfoFilePath)) + { + var memInfoLines = File.ReadAllLines(MemInfoFilePath); + foreach (var line in memInfoLines) + { + var lineParts = line.Split(new[] { ':' }, 2); + if (lineParts.Length != 2) + continue; + + if (lineParts[0].ToLowerInvariant().Trim().Equals("memtotal") == false) + continue; + + var memKb = lineParts[1].ToLowerInvariant().Trim().Replace("kb", string.Empty).Trim(); + + if (int.TryParse(memKb, out var parsedMem)) + { + InstalledRam = parsedMem * 1024; + break; + } + } + } + + #endregion + + #region Board Version and Form Factor + + try + { + if (string.IsNullOrWhiteSpace(Revision) == false && + int.TryParse( + Revision.ToUpperInvariant(), + NumberStyles.HexNumber, + CultureInfo.InvariantCulture, + out var boardVersion)) + { + RaspberryPiVersion = PiVersion.Unknown; + if (Enum.GetValues(typeof(PiVersion)).Cast().Contains(boardVersion)) + { + RaspberryPiVersion = (PiVersion)boardVersion; + } + } + + WiringPiBoardRevision = WiringPi.PiBoardRev(); + } + catch + { + /* Ignore */ + } + + #endregion + + #region Version Information + + { + var libParts = WiringPi.WiringPiLibrary.Split('.'); + var major = int.Parse(libParts[libParts.Length - 2]); + var minor = int.Parse(libParts[libParts.Length - 1]); + var version = new Version(major, minor); + WiringPiVersion = version; + } + + #endregion + + #region Extract OS Info + + try + { + Standard.Uname(out var unameInfo); + OperatingSystem = new OsInfo + { + DomainName = unameInfo.DomainName, + Machine = unameInfo.Machine, + NodeName = unameInfo.NodeName, + Release = unameInfo.Release, + SysName = unameInfo.SysName, + Version = unameInfo.Version + }; + } + catch + { + OperatingSystem = new OsInfo(); + } + + #endregion + } + + /// + /// Gets the wiring pi library version. + /// + public Version WiringPiVersion { get; } + + /// + /// Gets the OS information. + /// + /// + /// The os information. + /// + public OsInfo OperatingSystem { get; } + + /// + /// Gets the Raspberry Pi version. + /// + public PiVersion RaspberryPiVersion { get; } + + /// + /// Gets the Wiring Pi board revision (1 or 2). + /// + /// + /// The wiring pi board revision. + /// + public int WiringPiBoardRevision { get; } + + /// + /// Gets the number of processor cores. + /// + public int ProcessorCount + { + get + { + if (int.TryParse(Processor, out var outIndex)) + { + return outIndex + 1; + } + + return 0; + } + } + + /// + /// Gets the installed ram in bytes. + /// + public int InstalledRam { get; } + + /// + /// Gets a value indicating whether this CPU is little endian. + /// + public bool IsLittleEndian => BitConverter.IsLittleEndian; + + /// + /// Gets the CPU model name. + /// + public string ModelName { get; private set; } + + /// + /// Gets a list of supported CPU features. + /// + public string[] Features { get; private set; } + + /// + /// Gets the CPU implementer hex code. + /// + public string CpuImplementer { get; private set; } + + /// + /// Gets the CPU architecture code. + /// + public string CpuArchitecture { get; private set; } + + /// + /// Gets the CPU variant code. + /// + public string CpuVariant { get; private set; } + + /// + /// Gets the CPU part code. + /// + public string CpuPart { get; private set; } + + /// + /// Gets the CPU revision code. + /// + public string CpuRevision { get; private set; } + + /// + /// Gets the hardware model number. + /// + public string Hardware { get; private set; } + + /// + /// Gets the hardware revision number. + /// + public string Revision { get; private set; } + + /// + /// Gets the serial number. + /// + public string Serial { get; private set; } + + /// + /// Gets the system uptime (in seconds). + /// + public double Uptime + { + get + { + try + { + if (File.Exists(UptimeFilePath) == false) return 0; + var parts = File.ReadAllText(UptimeFilePath).Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); + if (parts.Length >= 1 && float.TryParse(parts[0], out var result)) + return result; + } + catch + { + /* Ignore */ + } + + return 0; + } + } + + /// + /// Gets the uptime in TimeSpan. + /// + public TimeSpan UptimeTimeSpan => TimeSpan.FromSeconds(Uptime); + + /// + /// Placeholder for processor index + /// + private string Processor { get; set; } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + var properties = typeof(SystemInfo).GetTypeInfo().GetProperties(BindingFlags.Instance | BindingFlags.Public) + .Where(p => p.CanRead && ( + p.PropertyType == typeof(string) || + p.PropertyType == typeof(string[]) || + p.PropertyType == typeof(int) || + p.PropertyType == typeof(bool) || + p.PropertyType == typeof(TimeSpan))) + .ToArray(); + + var properyValues = new List + { + "System Information", + $"\t{nameof(WiringPiVersion),-22}: {WiringPiVersion}", + $"\t{nameof(RaspberryPiVersion),-22}: {RaspberryPiVersion}" + }; + + foreach (var property in properties) + { + if (property.PropertyType != typeof(string[])) + { + properyValues.Add($"\t{property.Name,-22}: {property.GetValue(this)}"); + } + else if (property.GetValue(this) is string[] allValues) + { + var concatValues = string.Join(" ", allValues); + properyValues.Add($"\t{property.Name,-22}: {concatValues}"); + } + } + + return string.Join(Environment.NewLine, properyValues.ToArray()); + } + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Computer/WirelessNetworkInfo.cs b/Unosquare.RaspberryIO/Computer/WirelessNetworkInfo.cs new file mode 100644 index 0000000..71d0cb9 --- /dev/null +++ b/Unosquare.RaspberryIO/Computer/WirelessNetworkInfo.cs @@ -0,0 +1,23 @@ +namespace Unosquare.RaspberryIO.Computer +{ + /// + /// Represents a wireless network information + /// + public class WirelessNetworkInfo + { + /// + /// Gets the ESSID of the Wireless network. + /// + public string Name { get; internal set; } + + /// + /// Gets the network quality. + /// + public string Quality { get; internal set; } + + /// + /// Gets a value indicating whether this instance is encrypted. + /// + public bool IsEncrypted { get; internal set; } + } +} diff --git a/Unosquare.RaspberryIO/Gpio/Enums.cs b/Unosquare.RaspberryIO/Gpio/Enums.cs new file mode 100644 index 0000000..95e0032 --- /dev/null +++ b/Unosquare.RaspberryIO/Gpio/Enums.cs @@ -0,0 +1,579 @@ +namespace Unosquare.RaspberryIO.Gpio +{ + /// + /// Defines the different drive modes of a GPIO pin + /// + public enum GpioPinDriveMode + { + /// + /// Input drive mode (perform reads) + /// + Input = 0, + + /// + /// Output drive mode (perform writes) + /// + Output = 1, + + /// + /// PWM output mode (only certain pins support this -- 2 of them at the moment) + /// + PwmOutput = 2, + + /// + /// GPIO Clock output mode (only a pin supports this at this time) + /// + GpioClock = 3 + } + + /// + /// The GPIO pin resistor mode. This is used on input pins so that their + /// lines are not floating + /// + public enum GpioPinResistorPullMode + { + /// + /// Pull resistor not active. Line floating + /// + Off = 0, + + /// + /// Pull resistor sets a default value of 0 on no-connects + /// + PullDown = 1, + + /// + /// Pull resistor sets a default value of 1 on no-connects + /// + PullUp = 2, + } + + /// + /// The PWM mode. + /// + public enum PwmMode + { + /// + /// PWM pulses are sent using mark-sign patterns (old school) + /// + MarkSign = 0, + + /// + /// PWM pulses are sent as a balanced signal (default, newer mode) + /// + Balanced = 1, + } + + /// + /// Defines the different edge detection modes for pin interrupts + /// + public enum EdgeDetection + { + /// + /// Assumes edge detection was already setup externally + /// + ExternalSetup = 0, + + /// + /// Falling Edge + /// + FallingEdge = 1, + + /// + /// Rising edge + /// + RisingEdge = 2, + + /// + /// Both, rising and falling edges + /// + RisingAndFallingEdges = 3 + } + + /// + /// Defines the GPIO Pin values 0 for low, 1 for High + /// + public enum GpioPinValue + { + /// + /// Digital high + /// + High = 1, + + /// + /// Digital low + /// + Low = 0 + } + + /// + /// Defines the Header connectors available + /// + public enum GpioHeader + { + /// + /// Not defined + /// + None, + + /// + /// The P1 connector (main connector) + /// + P1, + + /// + /// The P5 connector (auxiliary, not commonly used) + /// + P5, + } + + /// + /// Defines all the available Wiring Pi Pin Numbers + /// + public enum WiringPiPin + { + /// + /// The unknown + /// + Unknown = -1, + + /// + /// The pin00 + /// + Pin00 = 0, + + /// + /// The pin01 + /// + Pin01 = 1, + + /// + /// The pin02 + /// + Pin02 = 2, + + /// + /// The pin03 + /// + Pin03 = 3, + + /// + /// The pin04 + /// + Pin04 = 4, + + /// + /// The pin05 + /// + Pin05 = 5, + + /// + /// The pin06 + /// + Pin06 = 6, + + /// + /// The pin07 + /// + Pin07 = 7, + + /// + /// The pin08 + /// + Pin08 = 8, + + /// + /// The pin09 + /// + Pin09 = 9, + + /// + /// The pin10 + /// + Pin10 = 10, + + /// + /// The pin11 + /// + Pin11 = 11, + + /// + /// The pin12 + /// + Pin12 = 12, + + /// + /// The pin13 + /// + Pin13 = 13, + + /// + /// The pin14 + /// + Pin14 = 14, + + /// + /// The pin15 + /// + Pin15 = 15, + + /// + /// The pin16 + /// + Pin16 = 16, + + /// + /// The pin17 + /// + Pin17 = 17, + + /// + /// The pin18 + /// + Pin18 = 18, + + /// + /// The pin19 + /// + Pin19 = 19, + + /// + /// The pin20 + /// + Pin20 = 20, + + /// + /// The pin21 + /// + Pin21 = 21, + + /// + /// The pin22 + /// + Pin22 = 22, + + /// + /// The pin23 + /// + Pin23 = 23, + + /// + /// The pin24 + /// + Pin24 = 24, + + /// + /// The pin25 + /// + Pin25 = 25, + + /// + /// The pin26 + /// + Pin26 = 26, + + /// + /// The pin27 + /// + Pin27 = 27, + + /// + /// The pin28 + /// + Pin28 = 28, + + /// + /// The pin29 + /// + Pin29 = 29, + + /// + /// The pin30 + /// + Pin30 = 30, + + /// + /// The pin31 + /// + Pin31 = 31, + } + + /// + /// Enumerates the different pins on the P1 Header + /// as commonly referenced by Raspberry Pi Documentation. + /// Enumeration values correspond to the physical pin number. + /// + public enum P1 + { + /// + /// Header P1, GPIO Pin 02 + /// + Gpio02 = 3, + + /// + /// Header P1, GPIO Pin 03 + /// + Gpio03 = 5, + + /// + /// Header P1, GPIO Pin 04 + /// + Gpio04 = 7, + + /// + /// Header P1, GPIO Pin 17 + /// + Gpio17 = 11, + + /// + /// Header P1, GPIO Pin 27 + /// + Gpio27 = 13, + + /// + /// Header P1, GPIO Pin 22 + /// + Gpio22 = 15, + + /// + /// Header P1, GPIO Pin 10 + /// + Gpio10 = 19, + + /// + /// Header P1, GPIO Pin 09 + /// + Gpio09 = 21, + + /// + /// Header P1, GPIO Pin 11 + /// + Gpio11 = 23, + + /// + /// Header P1, GPIO Pin 05 + /// + Gpio05 = 29, + + /// + /// Header P1, GPIO Pin 06 + /// + Gpio06 = 31, + + /// + /// Header P1, GPIO Pin 13 + /// + Gpio13 = 33, + + /// + /// Header P1, GPIO Pin 19 + /// + Gpio19 = 35, + + /// + /// Header P1, GPIO Pin 26 + /// + Gpio26 = 37, + + /// + /// Header P1, GPIO Pin 14 + /// + Gpio14 = 8, + + /// + /// Header P1, GPIO Pin 15 + /// + Gpio15 = 10, + + /// + /// Header P1, GPIO Pin 18 + /// + Gpio18 = 12, + + /// + /// Header P1, GPIO Pin 23 + /// + Gpio23 = 16, + + /// + /// Header P1, GPIO Pin 24 + /// + Gpio24 = 18, + + /// + /// Header P1, GPIO Pin 25 + /// + Gpio25 = 22, + + /// + /// Header P1, GPIO Pin 08 + /// + Gpio08 = 24, + + /// + /// Header P1, GPIO Pin 07 + /// + Gpio07 = 26, + + /// + /// Header P1, GPIO Pin 12 + /// + Gpio12 = 32, + + /// + /// Header P1, GPIO Pin 16 + /// + Gpio16 = 36, + + /// + /// Header P1, GPIO Pin 20 + /// + Gpio20 = 38, + + /// + /// Header P1, GPIO Pin 21 + /// + Gpio21 = 40 + } + + /// + /// Enumerates the different pins on the P5 Header + /// as commonly referenced by Raspberry Pi documentation. + /// Enumeration values correspond to the physical pin number. + /// + public enum P5 + { + /// + /// Header P5, GPIO Pin 28 + /// + Gpio28 = 3, + + /// + /// Header P5, GPIO Pin 29 + /// + Gpio29 = 4, + + /// + /// Header P5, GPIO Pin 30 + /// + Gpio30 = 5, + + /// + /// Header P5, GPIO Pin 31 + /// + Gpio31 = 6 + } + + /// + /// Defines the different pin capabilities + /// + public enum PinCapability + { + /// + /// General Purpose capability: Digital and Analog Read/Write + /// + GP, + + /// + /// General Purpose Clock (not PWM) + /// + GPCLK, + + /// + /// i2c data channel + /// + I2CSDA, + + /// + /// i2c clock channel + /// + I2CSCL, + + /// + /// SPI Master Out, Slave In channel + /// + SPIMOSI, + + /// + /// SPI Master In, Slave Out channel + /// + SPIMISO, + + /// + /// SPI Clock channel + /// + SPICLK, + + /// + /// SPI Chip Select Channel + /// + SPICS, + + /// + /// UART Request to Send Channel + /// + UARTRTS, + + /// + /// UART Transmit Channel + /// + UARTTXD, + + /// + /// UART Receive Channel + /// + UARTRXD, + + /// + /// Hardware Pule Width Modulation + /// + PWM + } + + /// + /// Defines the SPI channel numbers + /// + internal enum SpiChannelNumber + { + /// + /// The channel 0 + /// + Channel0 = 0, + + /// + /// The channel 1 + /// + Channel1 = 1, + } + + /// + /// Defines GPIO controller initialization modes + /// + internal enum ControllerMode + { + /// + /// The not initialized + /// + NotInitialized, + + /// + /// The direct with wiring pi pins + /// + DirectWithWiringPiPins, + + /// + /// The direct with BCM pins + /// + DirectWithBcmPins, + + /// + /// The direct with header pins + /// + DirectWithHeaderPins, + + /// + /// The file stream with hardware pins + /// + FileStreamWithHardwarePins, + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Gpio/GpioController.cs b/Unosquare.RaspberryIO/Gpio/GpioController.cs new file mode 100644 index 0000000..48e6a7e --- /dev/null +++ b/Unosquare.RaspberryIO/Gpio/GpioController.cs @@ -0,0 +1,594 @@ +namespace Unosquare.RaspberryIO.Gpio +{ + using Native; + using Swan; + using Swan.Abstractions; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + using System.Threading.Tasks; + + /// + /// Represents a singleton of the Raspberry Pi GPIO controller + /// as an IReadOnlyCollection of GpioPins + /// Low level operations are accomplished by using the Wiring Pi library. + /// Use the Instance property to access the singleton's instance + /// + public sealed class GpioController : SingletonBase, IReadOnlyCollection + { + #region Private Declarations + + private const string WiringPiCodesEnvironmentVariable = "WIRINGPI_CODES"; + private static readonly object SyncRoot = new object(); + private readonly ReadOnlyCollection _pinCollection; + private readonly ReadOnlyDictionary _headerP1Pins; + private readonly ReadOnlyDictionary _headerP5Pins; + private readonly Dictionary _pinsByWiringPiPinNumber = new Dictionary(); + + #endregion + + #region Constructors and Initialization + + /// + /// Prevents a default instance of the class from being created. + /// It in turn initializes the controller and registers the pin -- in that order. + /// + /// Unable to initialize the GPIO controller. + private GpioController() + { + if (_pinCollection != null) + return; + + if (IsInitialized == false) + { + var initResult = Initialize(ControllerMode.DirectWithWiringPiPins); + if (initResult == false) + throw new Exception("Unable to initialize the GPIO controller."); + } + + #region Pin Registration (32 WiringPi Pins) + + RegisterPin(GpioPin.Pin00.Value); + RegisterPin(GpioPin.Pin01.Value); + RegisterPin(GpioPin.Pin02.Value); + RegisterPin(GpioPin.Pin03.Value); + RegisterPin(GpioPin.Pin04.Value); + RegisterPin(GpioPin.Pin05.Value); + RegisterPin(GpioPin.Pin06.Value); + RegisterPin(GpioPin.Pin07.Value); + RegisterPin(GpioPin.Pin08.Value); + RegisterPin(GpioPin.Pin09.Value); + RegisterPin(GpioPin.Pin10.Value); + RegisterPin(GpioPin.Pin11.Value); + RegisterPin(GpioPin.Pin12.Value); + RegisterPin(GpioPin.Pin13.Value); + RegisterPin(GpioPin.Pin14.Value); + RegisterPin(GpioPin.Pin15.Value); + RegisterPin(GpioPin.Pin16.Value); + RegisterPin(GpioPin.Pin17.Value); + RegisterPin(GpioPin.Pin18.Value); + RegisterPin(GpioPin.Pin19.Value); + RegisterPin(GpioPin.Pin20.Value); + RegisterPin(GpioPin.Pin21.Value); + RegisterPin(GpioPin.Pin22.Value); + RegisterPin(GpioPin.Pin23.Value); + RegisterPin(GpioPin.Pin24.Value); + RegisterPin(GpioPin.Pin25.Value); + RegisterPin(GpioPin.Pin26.Value); + RegisterPin(GpioPin.Pin27.Value); + RegisterPin(GpioPin.Pin28.Value); + RegisterPin(GpioPin.Pin29.Value); + RegisterPin(GpioPin.Pin30.Value); + RegisterPin(GpioPin.Pin31.Value); + + #endregion + + _pinCollection = new ReadOnlyCollection(_pinsByWiringPiPinNumber.Values.ToArray()); + var headerP1 = new Dictionary(_pinCollection.Count); + var headerP5 = new Dictionary(_pinCollection.Count); + foreach (var pin in _pinCollection) + { + var target = pin.Header == GpioHeader.P1 ? headerP1 : headerP5; + target[pin.HeaderPinNumber] = pin; + } + + _headerP1Pins = new ReadOnlyDictionary(headerP1); + _headerP5Pins = new ReadOnlyDictionary(headerP5); + } + + /// + /// Determines if the underlying GPIO controller has been initialized properly. + /// + /// + /// true if the controller is properly initialized; otherwise, false. + /// + public static bool IsInitialized + { + get + { + lock (SyncRoot) + { + return Mode != ControllerMode.NotInitialized; + } + } + } + + /// + /// Gets the number of registered pins in the controller. + /// + public int Count => _pinCollection.Count; + + #endregion + + #region Pin Addressing + + /// + /// Gets the PWM base frequency (in Hz). + /// + public int PwmBaseFrequency => 19200000; + + /// + /// Gets a red-only collection of all registered pins. + /// + public ReadOnlyCollection Pins => _pinCollection; + + /// + /// Provides all the pins on Header P1 of the Pi as a lookup by physical header pin number. + /// This header is the main header and it is the one commonly used. + /// + public ReadOnlyDictionary HeaderP1 => _headerP1Pins; + + /// + /// Provides all the pins on Header P5 of the Pi as a lookup by physical header pin number. + /// This header is the secondary header and it is rarely used. + /// + public ReadOnlyDictionary HeaderP5 => _headerP5Pins; + + #endregion + + #region Individual Pin Properties + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 00. + /// + public GpioPin Pin00 => GpioPin.Pin00.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 01. + /// + public GpioPin Pin01 => GpioPin.Pin01.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 02. + /// + public GpioPin Pin02 => GpioPin.Pin02.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 03. + /// + public GpioPin Pin03 => GpioPin.Pin03.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 04. + /// + public GpioPin Pin04 => GpioPin.Pin04.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 05. + /// + public GpioPin Pin05 => GpioPin.Pin05.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 06. + /// + public GpioPin Pin06 => GpioPin.Pin06.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 07. + /// + public GpioPin Pin07 => GpioPin.Pin07.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 08. + /// + public GpioPin Pin08 => GpioPin.Pin08.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 09. + /// + public GpioPin Pin09 => GpioPin.Pin09.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 10. + /// + public GpioPin Pin10 => GpioPin.Pin10.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 11. + /// + public GpioPin Pin11 => GpioPin.Pin11.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 12. + /// + public GpioPin Pin12 => GpioPin.Pin12.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 13. + /// + public GpioPin Pin13 => GpioPin.Pin13.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 14. + /// + public GpioPin Pin14 => GpioPin.Pin14.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 15. + /// + public GpioPin Pin15 => GpioPin.Pin15.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 16. + /// + public GpioPin Pin16 => GpioPin.Pin16.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 17. + /// + public GpioPin Pin17 => GpioPin.Pin17.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 18. + /// + public GpioPin Pin18 => GpioPin.Pin18.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 19. + /// + public GpioPin Pin19 => GpioPin.Pin19.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 20. + /// + public GpioPin Pin20 => GpioPin.Pin20.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 21. + /// + public GpioPin Pin21 => GpioPin.Pin21.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 22. + /// + public GpioPin Pin22 => GpioPin.Pin22.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 23. + /// + public GpioPin Pin23 => GpioPin.Pin23.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 24. + /// + public GpioPin Pin24 => GpioPin.Pin24.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 25. + /// + public GpioPin Pin25 => GpioPin.Pin25.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 26. + /// + public GpioPin Pin26 => GpioPin.Pin26.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 27. + /// + public GpioPin Pin27 => GpioPin.Pin27.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 28. + /// + public GpioPin Pin28 => GpioPin.Pin28.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 29. + /// + public GpioPin Pin29 => GpioPin.Pin29.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 30. + /// + public GpioPin Pin30 => GpioPin.Pin30.Value; + + /// + /// Provides direct access to Pin known to Wiring Pi (not the pin header number) as Pin 31. + /// + public GpioPin Pin31 => GpioPin.Pin31.Value; + + #endregion + + #region Indexers + + /// + /// Gets or sets the initialization mode. + /// + private static ControllerMode Mode { get; set; } = ControllerMode.NotInitialized; + + /// + /// Gets the with the specified Wiring Pi pin number. + /// + /// + /// The . + /// + /// The pin number. + /// A reference to the GPIO pin + public GpioPin this[WiringPiPin pinNumber] => _pinsByWiringPiPinNumber[pinNumber]; + + /// + /// Gets the with the specified pin number. + /// + /// + /// The . + /// + /// The pin number. + /// A reference to the GPIO pin + public GpioPin this[P1 pinNumber] => HeaderP1[(int)pinNumber]; + + /// + /// Gets the with the specified pin number. + /// + /// + /// The . + /// + /// The pin number. + /// A reference to the GPIO pin + public GpioPin this[P5 pinNumber] => HeaderP5[(int)pinNumber]; + + /// + /// Gets the with the specified Wiring Pi pin number. + /// Use the HeaderP1 and HeaderP5 lookups if you would like to retrieve pins by physical pin number. + /// + /// + /// The . + /// + /// The pin number as defined by Wiring Pi. This is not the header pin number as pin number in headers are obvoisly repeating. + /// A reference to the GPIO pin + /// When the pin index is not found + public GpioPin this[int wiringPiPinNumber] + { + get + { + if (Enum.IsDefined(typeof(WiringPiPin), wiringPiPinNumber) == false) + throw new IndexOutOfRangeException($"Pin {wiringPiPinNumber} is not registered in the GPIO controller."); + + return _pinsByWiringPiPinNumber[(WiringPiPin)wiringPiPinNumber]; + } + } + + #endregion + + #region Pin Group Methods (Read, Write, Pad Drive) + + /// + /// This sets the “strength” of the pad drivers for a particular group of pins. + /// There are 3 groups of pins and the drive strength is from 0 to 7. + /// Do not use this unless you know what you are doing. + /// + /// The group. + /// The value. + public void SetPadDrive(int group, int value) + { + lock (SyncRoot) + { + WiringPi.SetPadDrive(group, value); + } + } + + /// + /// This sets the “strength” of the pad drivers for a particular group of pins. + /// There are 3 groups of pins and the drive strength is from 0 to 7. + /// Do not use this unless you know what you are doing. + /// + /// The group. + /// The value. + /// The awaitable task + public Task SetPadDriveAsync(int group, int value) => Task.Run(() => { SetPadDrive(group, value); }); + + /// + /// This writes the 8-bit byte supplied to the first 8 GPIO pins. + /// It’s the fastest way to set all 8 bits at once to a particular value, + /// although it still takes two write operations to the Pi’s GPIO hardware. + /// + /// The value. + /// PinMode + public void WriteByte(byte value) + { + lock (SyncRoot) + { + if (this.Skip(0).Take(8).Any(p => p.PinMode != GpioPinDriveMode.Output)) + { + throw new InvalidOperationException( + $"All firts 8 pins (0 to 7) need their {nameof(GpioPin.PinMode)} to be set to {GpioPinDriveMode.Output}"); + } + + WiringPi.DigitalWriteByte(value); + } + } + + /// + /// This writes the 8-bit byte supplied to the first 8 GPIO pins. + /// It’s the fastest way to set all 8 bits at once to a particular value, + /// although it still takes two write operations to the Pi’s GPIO hardware. + /// + /// The value. + /// The awaitable task + public Task WriteByteAsync(byte value) => Task.Run(() => { WriteByte(value); }); + + /// + /// This reads the 8-bit byte supplied to the first 8 GPIO pins. + /// It’s the fastest way to get all 8 bits at once to a particular value. + /// Please note this function is undocumented and unsopported + /// + /// A byte from the GPIO + /// PinMode + public byte ReadByte() + { + lock (SyncRoot) + { + if (this.Skip(0).Take(8).Any(p => + p.PinMode != GpioPinDriveMode.Input && p.PinMode != GpioPinDriveMode.Output)) + { + throw new InvalidOperationException( + $"All firts 8 pins (0 to 7) need their {nameof(GpioPin.PinMode)} to be set to {GpioPinDriveMode.Input} or {GpioPinDriveMode.Output}"); + } + + return (byte)WiringPi.DigitalReadByte(); + } + } + + /// + /// This reads the 8-bit byte supplied to the first 8 GPIO pins. + /// It’s the fastest way to get all 8 bits at once to a particular value. + /// Please note this function is undocumented and unsopported + /// + /// A byte from the GPIO + public Task ReadByteAsync() => Task.Run(() => ReadByte()); + + #endregion + + #region IReadOnlyCollection Implementation + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// A that can be used to iterate through the collection. + /// + public IEnumerator GetEnumerator() => _pinCollection.GetEnumerator(); + + /// + /// Returns an enumerator that iterates through the collection. + /// + /// + /// An object that can be used to iterate through the collection. + /// + IEnumerator IEnumerable.GetEnumerator() => _pinCollection.GetEnumerator(); + + #endregion + + #region Helper and Init Methods + + /// + /// Gets the GPIO pin by BCM pin number. + /// + /// The BCM pin number. + /// The GPIO pin + public GpioPin GetGpioPinByBcmPinNumber(int bcmPinNumber) => this.First(pin => pin.BcmPinNumber == bcmPinNumber); + + /// + /// Converts the Wirings Pi pin number to the BCM pin number. + /// + /// The wiring pi pin number. + /// The converted pin + internal static int WiringPiToBcmPinNumber(int wiringPiPinNumber) + { + lock (SyncRoot) + { + return WiringPi.WpiPinToGpio(wiringPiPinNumber); + } + } + + /// + /// Converts the Physical (Header) pin number to BCM pin number. + /// + /// The header pin number. + /// The converted pin + internal static int HaderToBcmPinNumber(int headerPinNumber) + { + lock (SyncRoot) + { + return WiringPi.PhysPinToGpio(headerPinNumber); + } + } + + /// + /// Short-hand method of registering pins + /// + /// The pin. + private void RegisterPin(GpioPin pin) + { + if (_pinsByWiringPiPinNumber.ContainsKey(pin.WiringPiPinNumber) == false) + _pinsByWiringPiPinNumber[pin.WiringPiPinNumber] = pin; + else + throw new InvalidOperationException($"Pin {pin.WiringPiPinNumber} has been registered"); + } + + /// + /// Initializes the controller given the initialization mode and pin numbering scheme + /// + /// The mode. + /// True when successful. + /// + /// This library does not support the platform + /// + /// Library was already Initialized + /// The init mode is invalid + private bool Initialize(ControllerMode mode) + { + if (Runtime.OS != Swan.OperatingSystem.Unix) + throw new PlatformNotSupportedException("This library does not support the platform"); + + lock (SyncRoot) + { + if (IsInitialized) + throw new InvalidOperationException($"Cannot call {nameof(Initialize)} more than once."); + + Environment.SetEnvironmentVariable(WiringPiCodesEnvironmentVariable, "1", EnvironmentVariableTarget.Process); + int setpuResult; + + switch (mode) + { + case ControllerMode.DirectWithWiringPiPins: + { + setpuResult = WiringPi.WiringPiSetup(); + break; + } + + case ControllerMode.DirectWithBcmPins: + { + setpuResult = WiringPi.WiringPiSetupGpio(); + break; + } + + case ControllerMode.DirectWithHeaderPins: + { + setpuResult = WiringPi.WiringPiSetupPhys(); + break; + } + + case ControllerMode.FileStreamWithHardwarePins: + { + setpuResult = WiringPi.WiringPiSetupSys(); + break; + } + + default: + { + throw new ArgumentException($"'{mode}' is not a valid initialization mode."); + } + } + + Mode = setpuResult == 0 ? mode : ControllerMode.NotInitialized; + return IsInitialized; + } + } + + #endregion + + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Gpio/GpioPin.Factory.cs b/Unosquare.RaspberryIO/Gpio/GpioPin.Factory.cs new file mode 100644 index 0000000..f4a9d6a --- /dev/null +++ b/Unosquare.RaspberryIO/Gpio/GpioPin.Factory.cs @@ -0,0 +1,201 @@ +namespace Unosquare.RaspberryIO.Gpio +{ + using System; + + public partial class GpioPin + { + #region Static Pin Definitions + + internal static readonly Lazy Pin08 = new Lazy(() => new GpioPin(WiringPiPin.Pin08, 3) + { + Capabilities = new[] { PinCapability.GP, PinCapability.I2CSDA }, + Name = "BCM 2 (SDA)" + }); + + internal static readonly Lazy Pin09 = new Lazy(() => new GpioPin(WiringPiPin.Pin09, 5) + { + Capabilities = new[] { PinCapability.GP, PinCapability.I2CSCL }, + Name = "BCM 3 (SCL)" + }); + + internal static readonly Lazy Pin07 = new Lazy(() => new GpioPin(WiringPiPin.Pin07, 7) + { + Capabilities = new[] { PinCapability.GP, PinCapability.GPCLK }, + Name = "BCM 4 (GPCLK0)" + }); + + internal static readonly Lazy Pin00 = new Lazy(() => new GpioPin(WiringPiPin.Pin00, 11) + { + Capabilities = new[] { PinCapability.GP, PinCapability.UARTRTS }, + Name = "BCM 17" + }); + + internal static readonly Lazy Pin02 = new Lazy(() => new GpioPin(WiringPiPin.Pin02, 13) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 27" + }); + + internal static readonly Lazy Pin03 = new Lazy(() => new GpioPin(WiringPiPin.Pin03, 15) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 22" + }); + + internal static readonly Lazy Pin12 = new Lazy(() => new GpioPin(WiringPiPin.Pin12, 19) + { + Capabilities = new[] { PinCapability.GP, PinCapability.SPIMOSI }, + Name = "BCM 10 (MOSI)" + }); + + internal static readonly Lazy Pin13 = new Lazy(() => new GpioPin(WiringPiPin.Pin13, 21) + { + Capabilities = new[] { PinCapability.GP, PinCapability.SPIMISO }, + Name = "BCM 9 (MISO)" + }); + + internal static readonly Lazy Pin14 = new Lazy(() => new GpioPin(WiringPiPin.Pin14, 23) + { + Capabilities = new[] { PinCapability.GP, PinCapability.SPICLK }, + Name = "BCM 11 (SCLCK)" + }); + + internal static readonly Lazy Pin30 = new Lazy(() => new GpioPin(WiringPiPin.Pin30, 27) + { + Capabilities = new[] { PinCapability.I2CSDA }, + Name = "BCM 0 (ID_SD)" + }); + + internal static readonly Lazy Pin31 = new Lazy(() => new GpioPin(WiringPiPin.Pin31, 28) + { + Capabilities = new[] { PinCapability.I2CSCL }, + Name = "BCM 1 (ID_SC)" + }); + + internal static readonly Lazy Pin11 = new Lazy(() => new GpioPin(WiringPiPin.Pin11, 26) + { + Capabilities = new[] { PinCapability.GP, PinCapability.SPICS }, + Name = "BCM 7 (CE1)" + }); + + internal static readonly Lazy Pin10 = new Lazy(() => new GpioPin(WiringPiPin.Pin10, 24) + { + Capabilities = new[] { PinCapability.GP, PinCapability.SPICS }, + Name = "BCM 8 (CE0)" + }); + + internal static readonly Lazy Pin06 = new Lazy(() => new GpioPin(WiringPiPin.Pin06, 22) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 25" + }); + internal static readonly Lazy Pin05 = new Lazy(() => new GpioPin(WiringPiPin.Pin05, 18) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 24" + }); + + internal static readonly Lazy Pin04 = new Lazy(() => new GpioPin(WiringPiPin.Pin04, 16) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 23" + }); + + internal static readonly Lazy Pin01 = new Lazy(() => new GpioPin(WiringPiPin.Pin01, 12) + { + Capabilities = new[] { PinCapability.GP, PinCapability.PWM }, + Name = "BCM 18 (PWM0)" + }); + + internal static readonly Lazy Pin16 = new Lazy(() => new GpioPin(WiringPiPin.Pin16, 10) + { + Capabilities = new[] { PinCapability.UARTRXD }, + Name = "BCM 15 (RXD)" + }); + + internal static readonly Lazy Pin15 = new Lazy(() => new GpioPin(WiringPiPin.Pin15, 8) + { + Capabilities = new[] { PinCapability.UARTTXD }, + Name = "BCM 14 (TXD)" + }); + + internal static readonly Lazy Pin21 = new Lazy(() => new GpioPin(WiringPiPin.Pin21, 29) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 5" + }); + + internal static readonly Lazy Pin22 = new Lazy(() => new GpioPin(WiringPiPin.Pin22, 31) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 6" + }); + + internal static readonly Lazy Pin23 = new Lazy(() => new GpioPin(WiringPiPin.Pin23, 33) + { + Capabilities = new[] { PinCapability.GP, PinCapability.PWM }, + Name = "BCM 13 (PWM1)" + }); + + internal static readonly Lazy Pin24 = new Lazy(() => new GpioPin(WiringPiPin.Pin24, 35) + { + Capabilities = new[] { PinCapability.GP, PinCapability.SPIMISO }, + Name = "BCM 19 (MISO)" + }); + + internal static readonly Lazy Pin25 = new Lazy(() => new GpioPin(WiringPiPin.Pin25, 37) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 26" + }); + + internal static readonly Lazy Pin29 = new Lazy(() => new GpioPin(WiringPiPin.Pin29, 40) + { + Capabilities = new[] { PinCapability.GP, PinCapability.SPICLK }, + Name = "BCM 21 (SCLK)" + }); + + internal static readonly Lazy Pin28 = new Lazy(() => new GpioPin(WiringPiPin.Pin28, 38) + { + Capabilities = new[] { PinCapability.GP, PinCapability.SPIMOSI }, + Name = "BCM 20 (MOSI)" + }); + + internal static readonly Lazy Pin27 = new Lazy(() => new GpioPin(WiringPiPin.Pin27, 36) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 16" + }); + internal static readonly Lazy Pin26 = new Lazy(() => new GpioPin(WiringPiPin.Pin26, 32) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 12 (PWM0)" + }); + + internal static readonly Lazy Pin17 = new Lazy(() => new GpioPin(WiringPiPin.Pin17, 3) + { + Capabilities = new[] { PinCapability.GP, PinCapability.I2CSDA }, + Name = "BCM 28 (SDA)" + }); + + internal static readonly Lazy Pin18 = new Lazy(() => new GpioPin(WiringPiPin.Pin18, 4) + { + Capabilities = new[] { PinCapability.GP, PinCapability.I2CSCL }, + Name = "BCM 29 (SCL)" + }); + + internal static readonly Lazy Pin19 = new Lazy(() => new GpioPin(WiringPiPin.Pin19, 5) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 30" + }); + + internal static readonly Lazy Pin20 = new Lazy(() => new GpioPin(WiringPiPin.Pin20, 6) + { + Capabilities = new[] { PinCapability.GP }, + Name = "BCM 31" + }); + + #endregion + } +} diff --git a/Unosquare.RaspberryIO/Gpio/GpioPin.cs b/Unosquare.RaspberryIO/Gpio/GpioPin.cs new file mode 100644 index 0000000..ec4f6db --- /dev/null +++ b/Unosquare.RaspberryIO/Gpio/GpioPin.cs @@ -0,0 +1,648 @@ +namespace Unosquare.RaspberryIO.Gpio +{ + using Native; + using Swan; + using System; + using System.Linq; + using System.Threading.Tasks; + + /// + /// Represents a GPIO Pin, its location and its capabilities. + /// Full pin reference available here: + /// http://pinout.xyz/pinout/pin31_gpio6 and http://wiringpi.com/pins/ + /// + public sealed partial class GpioPin + { + #region Property Backing + + private readonly object _syncLock = new object(); + private GpioPinDriveMode m_PinMode; + private GpioPinResistorPullMode m_ResistorPullMode; + private int m_PwmRegister; + private PwmMode m_PwmMode = PwmMode.Balanced; + private uint m_PwmRange = 1024; + private int m_PwmClockDivisor = 1; + private int m_SoftPwmValue = -1; + private int m_SoftToneFrequency = -1; + + #endregion + + #region Constructor + + /// + /// Initializes a new instance of the class. + /// + /// The wiring pi pin number. + /// The header pin number. + private GpioPin(WiringPiPin wiringPiPinNumber, int headerPinNumber) + { + PinNumber = (int)wiringPiPinNumber; + WiringPiPinNumber = wiringPiPinNumber; + BcmPinNumber = GpioController.WiringPiToBcmPinNumber((int)wiringPiPinNumber); + HeaderPinNumber = headerPinNumber; + Header = (PinNumber >= 17 && PinNumber <= 20) ? GpioHeader.P5 : GpioHeader.P1; + } + + #endregion + + #region Pin Properties + + /// + /// Gets or sets the Wiring Pi pin number as an integer. + /// + public int PinNumber { get; } + + /// + /// Gets the WiringPi Pin number + /// + public WiringPiPin WiringPiPinNumber { get; } + + /// + /// Gets the BCM chip (hardware) pin number. + /// + public int BcmPinNumber { get; } + + /// + /// Gets or the physical header (physical board) pin number. + /// + public int HeaderPinNumber { get; } + + /// + /// Gets the pin's header (physical board) location. + /// + public GpioHeader Header { get; } + + /// + /// Gets the friendly name of the pin. + /// + public string Name { get; private set; } + + /// + /// Gets the hardware mode capabilities of this pin. + /// + public PinCapability[] Capabilities { get; private set; } + + #endregion + + #region Hardware-Specific Properties + + /// + /// Gets or sets the pin operating mode. + /// + /// + /// The pin mode. + /// + /// Thrown when a pin does not support the given operation mode. + public GpioPinDriveMode PinMode + { + get => m_PinMode; + + set + { + lock (_syncLock) + { + var mode = value; + if ((mode == GpioPinDriveMode.GpioClock && Capabilities.Contains(PinCapability.GPCLK) == false) || + (mode == GpioPinDriveMode.PwmOutput && Capabilities.Contains(PinCapability.PWM) == false) || + (mode == GpioPinDriveMode.Input && Capabilities.Contains(PinCapability.GP) == false) || + (mode == GpioPinDriveMode.Output && Capabilities.Contains(PinCapability.GP) == false)) + { + throw new NotSupportedException( + $"Pin {WiringPiPinNumber} '{Name}' does not support mode '{mode}'. Pin capabilities are limited to: {string.Join(", ", Capabilities)}"); + } + + WiringPi.PinMode(PinNumber, (int)mode); + m_PinMode = mode; + } + } + } + + /// + /// Gets the interrupt callback. Returns null if no interrupt + /// has been registered. + /// + public InterruptServiceRoutineCallback InterruptCallback { get; private set; } + + /// + /// Gets the interrupt edge detection mode. + /// + public EdgeDetection InterruptEdgeDetection { get; private set; } = EdgeDetection.ExternalSetup; + + #endregion + + #region Hardware PWM Members + + /// + /// This sets or gets the pull-up or pull-down resistor mode on the pin, which should be set as an input. + /// Unlike the Arduino, the BCM2835 has both pull-up an down internal resistors. + /// The parameter pud should be; PUD_OFF, (no pull up/down), PUD_DOWN (pull to ground) or PUD_UP (pull to 3.3v) + /// The internal pull up/down resistors have a value of approximately 50KΩ on the Raspberry Pi. + /// + public GpioPinResistorPullMode InputPullMode + { + get => PinMode == GpioPinDriveMode.Input ? m_ResistorPullMode : GpioPinResistorPullMode.Off; + + set + { + lock (_syncLock) + { + if (PinMode != GpioPinDriveMode.Input) + { + m_ResistorPullMode = GpioPinResistorPullMode.Off; + throw new InvalidOperationException( + $"Unable to set the {nameof(InputPullMode)} for pin {PinNumber} because operating mode is {PinMode}." + + $" Setting the {nameof(InputPullMode)} is only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.Input}"); + } + + WiringPi.PullUpDnControl(PinNumber, (int)value); + m_ResistorPullMode = value; + } + } + } + + /// + /// Gets or sets the PWM register. Values should be between 0 and 1024 + /// + /// + /// The PWM register. + /// + public int PwmRegister + { + get => m_PwmRegister; + + set + { + lock (_syncLock) + { + if (PinMode != GpioPinDriveMode.PwmOutput) + { + m_PwmRegister = 0; + + throw new InvalidOperationException( + $"Unable to write PWM register for pin {PinNumber} because operating mode is {PinMode}." + + $" Writing the PWM register is only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.PwmOutput}"); + } + + var val = value.Clamp(0, 1024); + + WiringPi.PwmWrite(PinNumber, val); + m_PwmRegister = val; + } + } + } + + /// + /// The PWM generator can run in 2 modes – “balanced” and “mark:space”. The mark:space mode is traditional, + /// however the default mode in the Pi is “balanced”. + /// + /// + /// The PWM mode. + /// + /// When pin mode is not set a Pwn output + public PwmMode PwmMode + { + get => PinMode == GpioPinDriveMode.PwmOutput ? m_PwmMode : PwmMode.Balanced; + + set + { + lock (_syncLock) + { + if (PinMode != GpioPinDriveMode.PwmOutput) + { + m_PwmMode = PwmMode.Balanced; + + throw new InvalidOperationException( + $"Unable to set PWM mode for pin {PinNumber} because operating mode is {PinMode}." + + $" Setting the PWM mode is only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.PwmOutput}"); + } + + WiringPi.PwmSetMode((int)value); + m_PwmMode = value; + } + } + } + + /// + /// This sets the range register in the PWM generator. The default is 1024. + /// + /// + /// The PWM range. + /// + /// When pin mode is not set to PWM output + public uint PwmRange + { + get => PinMode == GpioPinDriveMode.PwmOutput ? m_PwmRange : 0; + + set + { + lock (_syncLock) + { + if (PinMode != GpioPinDriveMode.PwmOutput) + { + m_PwmRange = 1024; + + throw new InvalidOperationException( + $"Unable to set PWM range for pin {PinNumber} because operating mode is {PinMode}." + + $" Setting the PWM range is only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.PwmOutput}"); + } + + WiringPi.PwmSetRange(value); + m_PwmRange = value; + } + } + } + + /// + /// Gets or sets the PWM clock divisor. + /// + /// + /// The PWM clock divisor. + /// + /// When pin mode is not set to PWM output + public int PwmClockDivisor + { + get => PinMode == GpioPinDriveMode.PwmOutput ? m_PwmClockDivisor : 0; + + set + { + lock (_syncLock) + { + if (PinMode != GpioPinDriveMode.PwmOutput) + { + m_PwmClockDivisor = 1; + + throw new InvalidOperationException( + $"Unable to set PWM range for pin {PinNumber} because operating mode is {PinMode}." + + $" Setting the PWM range is only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.PwmOutput}"); + } + + WiringPi.PwmSetClock(value); + m_PwmClockDivisor = value; + } + } + } + + #endregion + + #region Software Tone Members + + /// + /// Gets a value indicating whether this instance is in software based tone generator mode. + /// + /// + /// true if this instance is in soft tone mode; otherwise, false. + /// + public bool IsInSoftToneMode => m_SoftToneFrequency >= 0; + + /// + /// Gets or sets the soft tone frequency. 0 to 5000 Hz is typical + /// + /// + /// The soft tone frequency. + /// + /// When soft tones cannot be initialized on the pin + public int SoftToneFrequency + { + get => m_SoftToneFrequency; + + set + { + lock (_syncLock) + { + if (IsInSoftToneMode == false) + { + var setupResult = WiringPi.SoftToneCreate(PinNumber); + if (setupResult != 0) + { + throw new InvalidOperationException( + $"Unable to initialize soft tone on pin {PinNumber}. Error Code: {setupResult}"); + } + } + + WiringPi.SoftToneWrite(PinNumber, value); + m_SoftToneFrequency = value; + } + } + } + + #endregion + + #region Software PWM Members + + /// + /// Gets a value indicating whether this pin is in software based PWM mode. + /// + /// + /// true if this instance is in soft PWM mode; otherwise, false. + /// + public bool IsInSoftPwmMode => m_SoftPwmValue >= 0; + + /// + /// Gets or sets the software PWM value on the pin. + /// + /// + /// The soft PWM value. + /// + /// StartSoftPwm + public int SoftPwmValue + { + get => m_SoftPwmValue; + + set + { + lock (_syncLock) + { + if (IsInSoftPwmMode && value >= 0) + { + WiringPi.SoftPwmWrite(PinNumber, value); + m_SoftPwmValue = value; + } + else + { + throw new InvalidOperationException($"Software PWM requires a call to {nameof(StartSoftPwm)}."); + } + } + } + } + + /// + /// Gets the software PWM range used upon starting the PWM. + /// + public int SoftPwmRange { get; private set; } = -1; + + /// + /// Starts the software based PWM on this pin. + /// + /// The value. + /// The range. + /// When the pin does not suppoert PWM + /// StartSoftPwm + /// or + public void StartSoftPwm(int value, int range) + { + lock (_syncLock) + { + if (Capabilities.Contains(PinCapability.GP) == false) + throw new NotSupportedException($"Pin {PinNumber} does not support software PWM"); + + if (IsInSoftPwmMode) + throw new InvalidOperationException($"{nameof(StartSoftPwm)} has already been called."); + + var startResult = WiringPi.SoftPwmCreate(PinNumber, value, range); + + if (startResult == 0) + { + m_SoftPwmValue = value; + SoftPwmRange = range; + } + else + { + throw new InvalidOperationException( + $"Could not start software based PWM on pin {PinNumber}. Error code: {startResult}"); + } + } + } + + #endregion + + #region Output Mode (Write) Members + + /// + /// Writes the specified pin value. + /// This method performs a digital write + /// + /// The value. + public void Write(GpioPinValue value) + { + lock (_syncLock) + { + if (PinMode != GpioPinDriveMode.Output) + { + throw new InvalidOperationException( + $"Unable to write to pin {PinNumber} because operating mode is {PinMode}." + + $" Writes are only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.Output}"); + } + + WiringPi.DigitalWrite(PinNumber, (int)value); + } + } + + /// + /// Writes the value asynchronously. + /// + /// The value. + /// The awaitable task + public Task WriteAsync(GpioPinValue value) => Task.Run(() => { Write(value); }); + + /// + /// Writes the specified bit value. + /// This method performs a digital write + /// + /// if set to true [value]. + public void Write(bool value) + => Write(value ? GpioPinValue.High : GpioPinValue.Low); + + /// + /// Writes the specified bit value. + /// This method performs a digital write + /// + /// The value. + /// + /// The awaitable task + /// + public Task WriteAsync(bool value) => Task.Run(() => { Write(value); }); + + /// + /// Writes the specified value. 0 for low, any other value for high + /// This method performs a digital write + /// + /// The value. + public void Write(int value) => Write(value != 0 ? GpioPinValue.High : GpioPinValue.Low); + + /// + /// Writes the specified value. 0 for low, any other value for high + /// This method performs a digital write + /// + /// The value. + /// The awaitable task + public Task WriteAsync(int value) => Task.Run(() => { Write(value); }); + + /// + /// Writes the specified value as an analog level. + /// You will need to register additional analog modules to enable this function for devices such as the Gertboard. + /// + /// The value. + public void WriteLevel(int value) + { + lock (_syncLock) + { + if (PinMode != GpioPinDriveMode.Output) + { + throw new InvalidOperationException( + $"Unable to write to pin {PinNumber} because operating mode is {PinMode}." + + $" Writes are only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.Output}"); + } + + WiringPi.AnalogWrite(PinNumber, value); + } + } + + /// + /// Writes the specified value as an analog level. + /// You will need to register additional analog modules to enable this function for devices such as the Gertboard. + /// + /// The value. + /// The awaitable task + public Task WriteLevelAsync(int value) => Task.Run(() => { WriteLevel(value); }); + + #endregion + + #region Input Mode (Read) Members + + /// + /// Wait for specific pin status + /// + /// status to check + /// timeout to reach status + /// true/false + public bool WaitForValue(GpioPinValue status, int timeOutMillisecond) + { + if (PinMode != GpioPinDriveMode.Input) + { + throw new InvalidOperationException( + $"Unable to read from pin {PinNumber} because operating mode is {PinMode}." + + $" Reads are only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.Input}"); + } + + var hrt = new HighResolutionTimer(); + hrt.Start(); + do + { + if (ReadValue() == status) + return true; + + Pi.Timing.SleepMicroseconds(101); // 101 uses nanosleep as opposed to a loop. + } + while (hrt.ElapsedMilliseconds <= timeOutMillisecond); + + return false; + } + + /// + /// Reads the digital value on the pin as a boolean value. + /// + /// The state of the pin + public bool Read() + { + lock (_syncLock) + { + if (PinMode != GpioPinDriveMode.Input && PinMode != GpioPinDriveMode.Output) + { + throw new InvalidOperationException( + $"Unable to read from pin {PinNumber} because operating mode is {PinMode}." + + $" Reads are only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.Input} or {GpioPinDriveMode.Output}"); + } + + return WiringPi.DigitalRead(PinNumber) != 0; + } + } + + /// + /// Reads the digital value on the pin as a boolean value. + /// + /// The state of the pin + public Task ReadAsync() => Task.Run(() => Read()); + + /// + /// Reads the digital value on the pin as a High or Low value. + /// + /// The state of the pin + public GpioPinValue ReadValue() + => Read() ? GpioPinValue.High : GpioPinValue.Low; + + /// + /// Reads the digital value on the pin as a High or Low value. + /// + /// The state of the pin + public Task ReadValueAsync() => Task.Run(() => ReadValue()); + + /// + /// Reads the analog value on the pin. + /// This returns the value read on the supplied analog input pin. You will need to register + /// additional analog modules to enable this function for devices such as the Gertboard, + /// quick2Wire analog board, etc. + /// + /// The analog level + /// When the pin mode is not configured as an input. + public int ReadLevel() + { + lock (_syncLock) + { + if (PinMode != GpioPinDriveMode.Input) + { + throw new InvalidOperationException( + $"Unable to read from pin {PinNumber} because operating mode is {PinMode}." + + $" Reads are only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.Input}"); + } + + return WiringPi.AnalogRead(PinNumber); + } + } + + /// + /// Reads the analog value on the pin. + /// This returns the value read on the supplied analog input pin. You will need to register + /// additional analog modules to enable this function for devices such as the Gertboard, + /// quick2Wire analog board, etc. + /// + /// The analog level + public Task ReadLevelAsync() => Task.Run(() => ReadLevel()); + + #endregion + + #region Interrupts + + /// + /// Registers the interrupt callback on the pin. Pin mode has to be set to Input. + /// + /// The edge detection. + /// The callback. + /// callback + /// + /// An interrupt callback was already registered. + /// or + /// RegisterInterruptCallback + /// + public void RegisterInterruptCallback(EdgeDetection edgeDetection, InterruptServiceRoutineCallback callback) + { + if (callback == null) + throw new ArgumentException($"{nameof(callback)} cannot be null"); + + if (InterruptCallback != null) + throw new InvalidOperationException("An interrupt callback was already registered."); + + if (PinMode != GpioPinDriveMode.Input) + { + throw new InvalidOperationException( + $"Unable to {nameof(RegisterInterruptCallback)} for pin {PinNumber} because operating mode is {PinMode}." + + $" Calling {nameof(RegisterInterruptCallback)} is only allowed if {nameof(PinMode)} is set to {GpioPinDriveMode.Input}"); + } + + lock (_syncLock) + { + var registerResult = WiringPi.WiringPiISR(PinNumber, (int)edgeDetection, callback); + if (registerResult == 0) + { + InterruptEdgeDetection = edgeDetection; + InterruptCallback = callback; + } + else + { + HardwareException.Throw(nameof(GpioPin), nameof(RegisterInterruptCallback)); + } + } + } + + #endregion + } +} diff --git a/Unosquare.RaspberryIO/Gpio/I2CBus.cs b/Unosquare.RaspberryIO/Gpio/I2CBus.cs new file mode 100644 index 0000000..cbecc3c --- /dev/null +++ b/Unosquare.RaspberryIO/Gpio/I2CBus.cs @@ -0,0 +1,93 @@ +namespace Unosquare.RaspberryIO.Gpio +{ + using Native; + using Swan.Abstractions; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.Linq; + + /// + /// A simple wrapper for the I2c bus on the Raspberry Pi + /// + public class I2CBus : SingletonBase + { + // TODO: It would be nice to integrate i2c device detection. + private static readonly object SyncRoot = new object(); + private readonly Dictionary _devices = new Dictionary(); + + /// + /// Prevents a default instance of the class from being created. + /// + private I2CBus() + { + // placeholder + } + + /// + /// Gets the registered devices as a read only collection. + /// + public ReadOnlyCollection Devices => new ReadOnlyCollection(_devices.Values.ToArray()); + + /// + /// Gets the with the specified device identifier. + /// + /// + /// The . + /// + /// The device identifier. + /// A reference to an I2C device + public I2CDevice this[int deviceId] => GetDeviceById(deviceId); + + /// + /// Gets the device by identifier. + /// + /// The device identifier. + /// The device reference + public I2CDevice GetDeviceById(int deviceId) + { + lock (SyncRoot) + { + return _devices[deviceId]; + } + } + + /// + /// Adds a device to the bus by its Id. If the device is already registered it simply returns the existing device. + /// + /// The device identifier. + /// The device reference + /// When the device file descriptor is not found + public I2CDevice AddDevice(int deviceId) + { + lock (SyncRoot) + { + if (_devices.ContainsKey(deviceId)) + return _devices[deviceId]; + + var fileDescriptor = SetupFileDescriptor(deviceId); + if (fileDescriptor < 0) + throw new KeyNotFoundException($"Device with id {deviceId} could not be registered with the I2C bus. Error Code: {fileDescriptor}."); + + var device = new I2CDevice(deviceId, fileDescriptor); + _devices[deviceId] = device; + return device; + } + } + + /// + /// This initializes the I2C system with your given device identifier. + /// The ID is the I2C number of the device and you can use the i2cdetect program to find this out. + /// wiringPiI2CSetup() will work out which revision Raspberry Pi you have and open the appropriate device in /dev. + /// The return value is the standard Linux filehandle, or -1 if any error – in which case, you can consult errno as usual. + /// + /// The device identifier. + /// The Linux file handle + private static int SetupFileDescriptor(int deviceId) + { + lock (SyncRoot) + { + return WiringPi.WiringPiI2CSetup(deviceId); + } + } + } +} diff --git a/Unosquare.RaspberryIO/Gpio/I2CDevice.cs b/Unosquare.RaspberryIO/Gpio/I2CDevice.cs new file mode 100644 index 0000000..b9d42bf --- /dev/null +++ b/Unosquare.RaspberryIO/Gpio/I2CDevice.cs @@ -0,0 +1,195 @@ +namespace Unosquare.RaspberryIO.Gpio +{ + using System; + using System.Threading.Tasks; + using Native; + + /// + /// Represents a device on the I2C Bus + /// + public class I2CDevice + { + private readonly object _syncLock = new object(); + + /// + /// Initializes a new instance of the class. + /// + /// The device identifier. + /// The file descriptor. + internal I2CDevice(int deviceId, int fileDescriptor) + { + DeviceId = deviceId; + FileDescriptor = fileDescriptor; + } + + /// + /// Gets the device identifier. + /// + /// + /// The device identifier. + /// + public int DeviceId { get; } + + /// + /// Gets the standard POSIX file descriptor. + /// + /// + /// The file descriptor. + /// + public int FileDescriptor { get; } + + /// + /// Reads a byte from the specified file descriptor + /// + /// The byte from device + public byte Read() + { + lock (_syncLock) + { + var result = WiringPi.WiringPiI2CRead(FileDescriptor); + if (result < 0) HardwareException.Throw(nameof(I2CDevice), nameof(Read)); + return (byte)result; + } + } + + /// + /// Reads a byte from the specified file descriptor + /// + /// The byte from device + public Task ReadAsync() => Task.Run(() => Read()); + + /// + /// Reads a buffer of the specified length, one byte at a time + /// + /// The length. + /// The byte array from device + public byte[] Read(int length) + { + lock (_syncLock) + { + var buffer = new byte[length]; + for (var i = 0; i < length; i++) + { + var result = WiringPi.WiringPiI2CRead(FileDescriptor); + if (result < 0) HardwareException.Throw(nameof(I2CDevice), nameof(Read)); + buffer[i] = (byte)result; + } + + return buffer; + } + } + + /// + /// Reads a buffer of the specified length, one byte at a time + /// + /// The length. + /// The byte array from device + public Task ReadAsync(int length) => Task.Run(() => Read(length)); + + /// + /// Writes a byte of data the specified file descriptor. + /// + /// The data. + public void Write(byte data) + { + lock (_syncLock) + { + var result = WiringPi.WiringPiI2CWrite(FileDescriptor, data); + if (result < 0) HardwareException.Throw(nameof(I2CDevice), nameof(Write)); + } + } + + /// + /// Writes a byte of data the specified file descriptor. + /// + /// The data. + /// The awaitable task + public Task WriteAsync(byte data) => Task.Run(() => { Write(data); }); + + /// + /// Writes a set of bytes to the specified file descriptor. + /// + /// The data. + public void Write(byte[] data) + { + lock (_syncLock) + { + foreach (var b in data) + { + var result = WiringPi.WiringPiI2CWrite(FileDescriptor, b); + if (result < 0) HardwareException.Throw(nameof(I2CDevice), nameof(Write)); + } + } + } + + /// + /// Writes a set of bytes to the specified file descriptor. + /// + /// The data. + /// The awaitable task + public Task WriteAsync(byte[] data) + { + return Task.Run(() => { Write(data); }); + } + + /// + /// These write an 8 or 16-bit data value into the device register indicated. + /// + /// The register. + /// The data. + public void WriteAddressByte(int address, byte data) + { + lock (_syncLock) + { + var result = WiringPi.WiringPiI2CWriteReg8(FileDescriptor, address, data); + if (result < 0) HardwareException.Throw(nameof(I2CDevice), nameof(WriteAddressByte)); + } + } + + /// + /// These write an 8 or 16-bit data value into the device register indicated. + /// + /// The register. + /// The data. + public void WriteAddressWord(int address, ushort data) + { + lock (_syncLock) + { + var result = WiringPi.WiringPiI2CWriteReg16(FileDescriptor, address, data); + if (result < 0) HardwareException.Throw(nameof(I2CDevice), nameof(WriteAddressWord)); + } + } + + /// + /// These read an 8 or 16-bit value from the device register indicated. + /// + /// The register. + /// The address byte from device + public byte ReadAddressByte(int address) + { + lock (_syncLock) + { + var result = WiringPi.WiringPiI2CReadReg8(FileDescriptor, address); + if (result < 0) HardwareException.Throw(nameof(I2CDevice), nameof(ReadAddressByte)); + + return (byte)result; + } + } + + /// + /// These read an 8 or 16-bit value from the device register indicated. + /// + /// The register. + /// The address word from device + public ushort ReadAddressWord(int address) + { + lock (_syncLock) + { + var result = WiringPi.WiringPiI2CReadReg16(FileDescriptor, address); + if (result < 0) HardwareException.Throw(nameof(I2CDevice), nameof(ReadAddressWord)); + + return Convert.ToUInt16(result); + } + } + } +} diff --git a/Unosquare.RaspberryIO/Gpio/SpiBus.cs b/Unosquare.RaspberryIO/Gpio/SpiBus.cs new file mode 100644 index 0000000..ba9ebc6 --- /dev/null +++ b/Unosquare.RaspberryIO/Gpio/SpiBus.cs @@ -0,0 +1,72 @@ +namespace Unosquare.RaspberryIO.Gpio +{ + using Swan.Abstractions; + + /// + /// The SPI Bus containing the 2 SPI channels + /// + public class SpiBus : SingletonBase + { + /// + /// Prevents a default instance of the class from being created. + /// + private SpiBus() + { + // placeholder + } + + #region SPI Access + + /// + /// Gets or sets the channel 0 frequency in Hz. + /// + /// + /// The channel0 frequency. + /// + public int Channel0Frequency { get; set; } + + /// + /// Gets the SPI bus on channel 1. + /// + /// + /// The channel0. + /// + public SpiChannel Channel0 + { + get + { + if (Channel0Frequency == 0) + Channel0Frequency = SpiChannel.DefaultFrequency; + + return SpiChannel.Retrieve(SpiChannelNumber.Channel0, Channel0Frequency); + } + } + + /// + /// Gets or sets the channel 1 frequency in Hz + /// + /// + /// The channel1 frequency. + /// + public int Channel1Frequency { get; set; } + + /// + /// Gets the SPI bus on channel 1. + /// + /// + /// The channel1. + /// + public SpiChannel Channel1 + { + get + { + if (Channel1Frequency == 0) + Channel1Frequency = SpiChannel.DefaultFrequency; + + return SpiChannel.Retrieve(SpiChannelNumber.Channel1, Channel1Frequency); + } + } + + #endregion + } +} diff --git a/Unosquare.RaspberryIO/Gpio/SpiChannel.cs b/Unosquare.RaspberryIO/Gpio/SpiChannel.cs new file mode 100644 index 0000000..8e5f90e --- /dev/null +++ b/Unosquare.RaspberryIO/Gpio/SpiChannel.cs @@ -0,0 +1,154 @@ +namespace Unosquare.RaspberryIO.Gpio +{ + using Native; + using Swan; + using System; + using System.Collections.Generic; + using System.Threading.Tasks; + + /// + /// Provides access to using the SPI buses on the GPIO. + /// SPI is a bus that works like a ring shift register + /// The number of bytes pushed is equal to the number of bytes received. + /// + public sealed class SpiChannel + { + /// + /// The minimum frequency of an SPI Channel + /// + public const int MinFrequency = 500000; + + /// + /// The maximum frequency of an SPI channel + /// + public const int MaxFrequency = 32000000; + + /// + /// The default frequency of SPI channels + /// This is set to 8 Mhz wich is typical in modern hardware. + /// + public const int DefaultFrequency = 8000000; + + private static readonly object SyncRoot = new object(); + private static readonly Dictionary Buses = new Dictionary(); + private readonly object _syncLock = new object(); + + /// + /// Initializes a new instance of the class. + /// + /// The channel. + /// The frequency. + private SpiChannel(SpiChannelNumber channel, int frequency) + { + lock (SyncRoot) + { + Frequency = frequency.Clamp(MinFrequency, MaxFrequency); + Channel = (int)channel; + FileDescriptor = WiringPi.WiringPiSPISetup((int)channel, Frequency); + + if (FileDescriptor < 0) + { + HardwareException.Throw(nameof(SpiChannel), channel.ToString()); + } + } + } + + /// + /// Gets the standard initialization file descriptor. + /// anything negative means error. + /// + /// + /// The file descriptor. + /// + public int FileDescriptor { get; } + + /// + /// Gets the channel. + /// + public int Channel { get; } + + /// + /// Gets the frequency. + /// + public int Frequency { get; } + + /// + /// Sends data and simultaneously receives the data in the return buffer + /// + /// The buffer. + /// The read bytes from the ring-style bus + public byte[] SendReceive(byte[] buffer) + { + if (buffer == null || buffer.Length == 0) + return null; + + lock (_syncLock) + { + var spiBuffer = new byte[buffer.Length]; + Array.Copy(buffer, spiBuffer, buffer.Length); + + var result = WiringPi.WiringPiSPIDataRW(Channel, spiBuffer, spiBuffer.Length); + if (result < 0) HardwareException.Throw(nameof(SpiChannel), nameof(SendReceive)); + + return spiBuffer; + } + } + + /// + /// Sends data and simultaneously receives the data in the return buffer + /// + /// The buffer. + /// + /// The read bytes from the ring-style bus + /// + public Task SendReceiveAsync(byte[] buffer) => Task.Run(() => SendReceive(buffer)); + + /// + /// Writes the specified buffer the the underlying FileDescriptor. + /// Do not use this method if you expect data back. + /// This method is efficient if used in a fire-and-forget scenario + /// like sending data over to those long RGB LED strips + /// + /// The buffer. + public void Write(byte[] buffer) + { + lock (_syncLock) + { + var result = Standard.Write(FileDescriptor, buffer, buffer.Length); + + if (result < 0) + HardwareException.Throw(nameof(SpiChannel), nameof(Write)); + } + } + + /// + /// Writes the specified buffer the the underlying FileDescriptor. + /// Do not use this method if you expect data back. + /// This method is efficient if used in a fire-and-forget scenario + /// like sending data over to those long RGB LED strips + /// + /// The buffer. + /// The awaitable task + public Task WriteAsync(byte[] buffer) => Task.Run(() => { Write(buffer); }); + + /// + /// Retrieves the spi bus. If the bus channel is not registered it sets it up automatically. + /// If it had been previously registered, then the bus is simply returned. + /// + /// The channel. + /// The frequency. + /// The usable SPI channel + internal static SpiChannel Retrieve(SpiChannelNumber channel, int frequency) + { + lock (SyncRoot) + { + if (Buses.ContainsKey(channel)) + return Buses[channel]; + + var newBus = new SpiChannel(channel, frequency); + Buses[channel] = newBus; + return newBus; + } + } + } +} diff --git a/Unosquare.RaspberryIO/Native/Delegates.cs b/Unosquare.RaspberryIO/Native/Delegates.cs new file mode 100644 index 0000000..6b0cbbd --- /dev/null +++ b/Unosquare.RaspberryIO/Native/Delegates.cs @@ -0,0 +1,12 @@ +namespace Unosquare.RaspberryIO.Native +{ + /// + /// A delegate defining a callback for an Interrupt Service Routine + /// + public delegate void InterruptServiceRoutineCallback(); + + /// + /// Defines the body of a thread worker + /// + public delegate void ThreadWorker(); +} diff --git a/Unosquare.RaspberryIO/Native/HardwareException.cs b/Unosquare.RaspberryIO/Native/HardwareException.cs new file mode 100644 index 0000000..3ac43b2 --- /dev/null +++ b/Unosquare.RaspberryIO/Native/HardwareException.cs @@ -0,0 +1,73 @@ +namespace Unosquare.RaspberryIO.Native +{ + using Swan; + using System; + using System.Runtime.InteropServices; + + /// + /// Represents a low-level exception, typically thrown when return codes from a + /// low-level operation is non-zero or in some cases when it is less than zero. + /// + /// + public class HardwareException : Exception + { + /// + /// Initializes a new instance of the class. + /// + /// The error code. + /// The component. + public HardwareException(int errorCode, string component) + : base($"A hardware exception occurred. Error Code: {errorCode}") + { + ExtendedMessage = null; + + try + { + ExtendedMessage = Standard.Strerror(errorCode); + } + catch + { + // TODO: strerror not working great... + $"Could not retrieve native error description using {nameof(Standard.Strerror)}".Error(Pi.LoggerSource); + } + + ErrorCode = errorCode; + Component = component; + } + + /// + /// Gets the error code. + /// + /// + /// The error code. + /// + public int ErrorCode { get; } + + /// + /// Gets the component. + /// + /// + /// The component. + /// + public string Component { get; } + + /// + /// Gets the extended message (could be null). + /// + /// + /// The extended message. + /// + public string ExtendedMessage { get; } + + /// + /// Throws a new instance of a hardware error by retrieving the last error number (errno). + /// + /// Name of the class. + /// Name of the method. + /// When an error thrown by an API call occurs + public static void Throw(string className, string methodName) => throw new HardwareException(Marshal.GetLastWin32Error(), $"{className}.{methodName}"); + + /// + public override string ToString() => $"{GetType()}{(string.IsNullOrWhiteSpace(Component) ? string.Empty : $" on {Component}")}: ({ErrorCode}) - {Message}"; + } +} diff --git a/Unosquare.RaspberryIO/Native/HighResolutionTimer.cs b/Unosquare.RaspberryIO/Native/HighResolutionTimer.cs new file mode 100644 index 0000000..dd8e624 --- /dev/null +++ b/Unosquare.RaspberryIO/Native/HighResolutionTimer.cs @@ -0,0 +1,32 @@ +namespace Unosquare.RaspberryIO.Native +{ + using System; + using System.Diagnostics; + + /// + /// Provides access to a high- esolution, time measuring device. + /// + /// + public class HighResolutionTimer : Stopwatch + { + /// + /// Initializes a new instance of the class. + /// + /// High-resolution timer not available + public HighResolutionTimer() + { + if (!IsHighResolution) + throw new NotSupportedException("High-resolution timer not available"); + } + + /// + /// Gets the numer of microseconds per timer tick. + /// + public static double MicrosecondsPerTick { get; } = 1000000d / Frequency; + + /// + /// Gets the elapsed microseconds. + /// + public long ElapsedMicroseconds => (long)(ElapsedTicks * MicrosecondsPerTick); + } +} diff --git a/Unosquare.RaspberryIO/Native/Standard.cs b/Unosquare.RaspberryIO/Native/Standard.cs new file mode 100644 index 0000000..4ce2ac1 --- /dev/null +++ b/Unosquare.RaspberryIO/Native/Standard.cs @@ -0,0 +1,84 @@ +namespace Unosquare.RaspberryIO.Native +{ + using Swan; + using System; + using System.Runtime.InteropServices; + using System.Text; + + /// + /// Provides standard libc calls using platform-invoke + /// + internal static class Standard + { + internal const string LibCLibrary = "libc"; + + #region LibC Calls + + /// + /// Strerrors the specified error. + /// + /// The error. + /// + public static string Strerror(int error) + { + if (!Runtime.IsUsingMonoRuntime) return StrError(error); + + try + { + var buffer = new StringBuilder(256); + var result = Strerror(error, buffer, (ulong)buffer.Capacity); + return (result != -1) ? buffer.ToString() : null; + } + catch (EntryPointNotFoundException) + { + return null; + } + } + + /// + /// Changes file permissions on a Unix file system + /// + /// The filename. + /// The mode. + /// The result + [DllImport(LibCLibrary, EntryPoint = "chmod", SetLastError = true)] + public static extern int Chmod(string filename, uint mode); + + /// + /// Converts a string to a 32 bit integer. Use endpointer as IntPtr.Zero + /// + /// The number string. + /// The end pointer. + /// The number base. + /// The result + [DllImport(LibCLibrary, EntryPoint = "strtol", SetLastError = true)] + public static extern int StringToInteger(string numberString, IntPtr endPointer, int numberBase); + + /// + /// The write() function attempts to write nbytes from buffer to the file associated with handle. On text files, it expands each LF to a CR/LF. + /// The function returns the number of bytes written to the file. A return value of -1 indicates an error, with errno set appropriately. + /// + /// The fd. + /// The buffer. + /// The count. + /// The result + [DllImport(LibCLibrary, EntryPoint = "write", SetLastError = true)] + public static extern int Write(int fd, byte[] buffer, int count); + + /// + /// Fills in the structure with information about the system. + /// + /// The name. + /// The result + [DllImport(LibCLibrary, EntryPoint = "uname", SetLastError = true)] + public static extern int Uname(out SystemName name); + + [DllImport(LibCLibrary, EntryPoint = "strerror", SetLastError = true)] + private static extern string StrError(int errnum); + + [DllImport("MonoPosixHelper", EntryPoint = "Mono_Posix_Syscall_strerror_r", SetLastError = true)] + private static extern int Strerror(int error, [Out] StringBuilder buffer, ulong length); + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Native/SystemName.cs b/Unosquare.RaspberryIO/Native/SystemName.cs new file mode 100644 index 0000000..424fe8e --- /dev/null +++ b/Unosquare.RaspberryIO/Native/SystemName.cs @@ -0,0 +1,47 @@ +namespace Unosquare.RaspberryIO.Native +{ + using System.Runtime.InteropServices; + + /// + /// OS uname structure + /// + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] + internal struct SystemName + { + /// + /// System name + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] + public string SysName; + + /// + /// Node name + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] + public string NodeName; + + /// + /// Release level + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] + public string Release; + + /// + /// Version level + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] + public string Version; + + /// + /// Hardware level + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] + public string Machine; + + /// + /// Domain name + /// + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 65)] + public string DomainName; + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Native/ThreadLockKey.cs b/Unosquare.RaspberryIO/Native/ThreadLockKey.cs new file mode 100644 index 0000000..52ed4fa --- /dev/null +++ b/Unosquare.RaspberryIO/Native/ThreadLockKey.cs @@ -0,0 +1,28 @@ +namespace Unosquare.RaspberryIO.Native +{ + /// + /// Defines the different threading locking keys + /// + public enum ThreadLockKey + { + /// + /// The lock 0 + /// + Lock0 = 0, + + /// + /// The lock 1 + /// + Lock1 = 1, + + /// + /// The lock 2 + /// + Lock2 = 2, + + /// + /// The lock 3 + /// + Lock3 = 3, + } +} diff --git a/Unosquare.RaspberryIO/Native/Timing.cs b/Unosquare.RaspberryIO/Native/Timing.cs new file mode 100644 index 0000000..b0c91fb --- /dev/null +++ b/Unosquare.RaspberryIO/Native/Timing.cs @@ -0,0 +1,108 @@ +namespace Unosquare.RaspberryIO.Native +{ + using Swan; + using Swan.Abstractions; + using System; + + /// + /// Provides access to timing and threading properties and methods + /// + public class Timing : SingletonBase + { + /// + /// Prevents a default instance of the class from being created. + /// + /// Could not initialize the GPIO controller + private Timing() + { + // placeholder + } + + /// + /// This returns a number representing the number of milliseconds since your program + /// initialized the GPIO controller. + /// It returns an unsigned 32-bit number which wraps after 49 days. + /// + /// + /// The milliseconds since setup. + /// + public uint MillisecondsSinceSetup => WiringPi.Millis(); + + /// + /// This returns a number representing the number of microseconds since your + /// program initialized the GPIO controller + /// It returns an unsigned 32-bit number which wraps after approximately 71 minutes. + /// + /// + /// The microseconds since setup. + /// + public uint MicrosecondsSinceSetup => WiringPi.Micros(); + + /// + /// This causes program execution to pause for at least howLong milliseconds. + /// Due to the multi-tasking nature of Linux it could be longer. + /// Note that the maximum delay is an unsigned 32-bit integer or approximately 49 days. + /// + /// The value. + public static void SleepMilliseconds(uint value) => WiringPi.Delay(value); + + /// + /// This causes program execution to pause for at least howLong microseconds. + /// Due to the multi-tasking nature of Linux it could be longer. + /// Note that the maximum delay is an unsigned 32-bit integer microseconds or approximately 71 minutes. + /// Delays under 100 microseconds are timed using a hard-coded loop continually polling the system time, + /// Delays over 100 microseconds are done using the system nanosleep() function – + /// You may need to consider the implications of very short delays on the overall performance of the system, + /// especially if using threads. + /// + /// The value. + public void SleepMicroseconds(uint value) => WiringPi.DelayMicroseconds(value); + + /// + /// This attempts to shift your program (or thread in a multi-threaded program) to a higher priority and + /// enables a real-time scheduling. The priority parameter should be from 0 (the default) to 99 (the maximum). + /// This won’t make your program go any faster, but it will give it a bigger slice of time when other programs + /// are running. The priority parameter works relative to others – so you can make one program priority 1 and + /// another priority 2 and it will have the same effect as setting one to 10 and the other to 90 + /// (as long as no other programs are running with elevated priorities) + /// + /// The priority. + public void SetThreadPriority(int priority) + { + priority = priority.Clamp(0, 99); + var result = WiringPi.PiHiPri(priority); + if (result < 0) HardwareException.Throw(nameof(Timing), nameof(SetThreadPriority)); + } + + /// + /// This is really nothing more than a simplified interface to the Posix threads mechanism that Linux supports. + /// See the manual pages on Posix threads (man pthread) if you need more control over them. + /// + /// The worker. + /// worker + public void CreateThread(ThreadWorker worker) + { + if (worker == null) + throw new ArgumentNullException(nameof(worker)); + + var result = WiringPi.PiThreadCreate(worker); + if (result != 0) HardwareException.Throw(nameof(Timing), nameof(CreateThread)); + } + + /// + /// These allow you to synchronize variable updates from your main program to any threads running in your program. + /// keyNum is a number from 0 to 3 and represents a “key”. When another process tries to lock the same key, + /// it will be stalled until the first process has unlocked the same key. + /// + /// The key. + public void Lock(ThreadLockKey key) => WiringPi.PiLock((int)key); + + /// + /// These allow you to synchronize variable updates from your main program to any threads running in your program. + /// keyNum is a number from 0 to 3 and represents a “key”. When another process tries to lock the same key, + /// it will be stalled until the first process has unlocked the same key. + /// + /// The key. + public void Unlock(ThreadLockKey key) => WiringPi.PiUnlock((int)key); + } +} diff --git a/Unosquare.RaspberryIO/Native/WiringPi.I2C.cs b/Unosquare.RaspberryIO/Native/WiringPi.I2C.cs new file mode 100644 index 0000000..b0775b9 --- /dev/null +++ b/Unosquare.RaspberryIO/Native/WiringPi.I2C.cs @@ -0,0 +1,79 @@ +namespace Unosquare.RaspberryIO.Native +{ + using System.Runtime.InteropServices; + + public partial class WiringPi + { + #region WiringPi - I2C Library Calls + + /// + /// Simple device read. Some devices present data when you read them without having to do any register transactions. + /// + /// The fd. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiI2CRead", SetLastError = true)] + public static extern int WiringPiI2CRead(int fd); + + /// + /// These read an 8-bit value from the device register indicated. + /// + /// The fd. + /// The reg. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiI2CReadReg8", SetLastError = true)] + public static extern int WiringPiI2CReadReg8(int fd, int reg); + + /// + /// These read a 16-bit value from the device register indicated. + /// + /// The fd. + /// The reg. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiI2CReadReg16", SetLastError = true)] + public static extern int WiringPiI2CReadReg16(int fd, int reg); + + /// + /// Simple device write. Some devices accept data this way without needing to access any internal registers. + /// + /// The fd. + /// The data. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiI2CWrite", SetLastError = true)] + public static extern int WiringPiI2CWrite(int fd, int data); + + /// + /// These write an 8-bit data value into the device register indicated. + /// + /// The fd. + /// The reg. + /// The data. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiI2CWriteReg8", SetLastError = true)] + public static extern int WiringPiI2CWriteReg8(int fd, int reg, int data); + + /// + /// These write a 16-bit data value into the device register indicated. + /// + /// The fd. + /// The reg. + /// The data. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiI2CWriteReg16", SetLastError = true)] + public static extern int WiringPiI2CWriteReg16(int fd, int reg, int data); + + /// + /// This initialises the I2C system with your given device identifier. + /// The ID is the I2C number of the device and you can use the i2cdetect program to find this out. wiringPiI2CSetup() + /// will work out which revision Raspberry Pi you have and open the appropriate device in /dev. + /// The return value is the standard Linux filehandle, or -1 if any error – in which case, you can consult errno as usual. + /// E.g. the popular MCP23017 GPIO expander is usually device Id 0x20, so this is the number you would pass into wiringPiI2CSetup(). + /// + /// The dev identifier. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiI2CSetup", SetLastError = true)] + public static extern int WiringPiI2CSetup(int devId); + + #endregion + + } +} diff --git a/Unosquare.RaspberryIO/Native/WiringPi.SerialPort.cs b/Unosquare.RaspberryIO/Native/WiringPi.SerialPort.cs new file mode 100644 index 0000000..ea54bd3 --- /dev/null +++ b/Unosquare.RaspberryIO/Native/WiringPi.SerialPort.cs @@ -0,0 +1,73 @@ +namespace Unosquare.RaspberryIO.Native +{ + using System.Runtime.InteropServices; + + public partial class WiringPi + { + #region WiringPi - Serial Port + + /// + /// This opens and initialises the serial device and sets the baud rate. It sets the port into “raw” mode (character at a time and no translations), + /// and sets the read timeout to 10 seconds. The return value is the file descriptor or -1 for any error, in which case errno will be set as appropriate. + /// The wiringSerial library is intended to provide simplified control – suitable for most applications, however if you need advanced control + /// – e.g. parity control, modem control lines (via a USB adapter, there are none on the Pi’s on-board UART!) and so on, + /// then you need to do some of this the old fashioned way. + /// + /// The device. + /// The baud. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "serialOpen", SetLastError = true)] + public static extern int SerialOpen(string device, int baud); + + /// + /// Closes the device identified by the file descriptor given. + /// + /// The fd. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "serialClose", SetLastError = true)] + public static extern int SerialClose(int fd); + + /// + /// Sends the single byte to the serial device identified by the given file descriptor. + /// + /// The fd. + /// The c. + [DllImport(WiringPiLibrary, EntryPoint = "serialPutchar", SetLastError = true)] + public static extern void SerialPutchar(int fd, byte c); + + /// + /// Sends the nul-terminated string to the serial device identified by the given file descriptor. + /// + /// The fd. + /// The s. + [DllImport(WiringPiLibrary, EntryPoint = "serialPuts", SetLastError = true)] + public static extern void SerialPuts(int fd, string s); + + /// + /// Returns the number of characters available for reading, or -1 for any error condition, + /// in which case errno will be set appropriately. + /// + /// The fd. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "serialDataAvail", SetLastError = true)] + public static extern int SerialDataAvail(int fd); + + /// + /// Returns the next character available on the serial device. + /// This call will block for up to 10 seconds if no data is available (when it will return -1) + /// + /// The fd. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "serialGetchar", SetLastError = true)] + public static extern int SerialGetchar(int fd); + + /// + /// This discards all data received, or waiting to be send down the given device. + /// + /// The fd. + [DllImport(WiringPiLibrary, EntryPoint = "serialFlush", SetLastError = true)] + public static extern void SerialFlush(int fd); + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Native/WiringPi.Shift.cs b/Unosquare.RaspberryIO/Native/WiringPi.Shift.cs new file mode 100644 index 0000000..dfab07f --- /dev/null +++ b/Unosquare.RaspberryIO/Native/WiringPi.Shift.cs @@ -0,0 +1,36 @@ +namespace Unosquare.RaspberryIO.Native +{ + using System.Runtime.InteropServices; + + public partial class WiringPi + { + #region WiringPi - Shift Library + + /// + /// This shifts an 8-bit data value in with the data appearing on the dPin and the clock being sent out on the cPin. + /// Order is either LSBFIRST or MSBFIRST. The data is sampled after the cPin goes high. + /// (So cPin high, sample data, cPin low, repeat for 8 bits) The 8-bit value is returned by the function. + /// + /// The d pin. + /// The c pin. + /// The order. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "shiftIn", SetLastError = true)] + public static extern byte ShiftIn(byte dPin, byte cPin, byte order); + + /// + /// The shifts an 8-bit data value val out with the data being sent out on dPin and the clock being sent out on the cPin. + /// order is as above. Data is clocked out on the rising or falling edge – ie. dPin is set, then cPin is taken high then low + /// – repeated for the 8 bits. + /// + /// The d pin. + /// The c pin. + /// The order. + /// The value. + [DllImport(WiringPiLibrary, EntryPoint = "shiftOut", SetLastError = true)] + public static extern void ShiftOut(byte dPin, byte cPin, byte order, byte val); + + #endregion + + } +} diff --git a/Unosquare.RaspberryIO/Native/WiringPi.SoftPwm.cs b/Unosquare.RaspberryIO/Native/WiringPi.SoftPwm.cs new file mode 100644 index 0000000..30a75b5 --- /dev/null +++ b/Unosquare.RaspberryIO/Native/WiringPi.SoftPwm.cs @@ -0,0 +1,64 @@ +namespace Unosquare.RaspberryIO.Native +{ + using System.Runtime.InteropServices; + + public partial class WiringPi + { + #region WiringPi - Soft PWM (https://github.com/WiringPi/WiringPi/blob/master/wiringPi/softPwm.h) + + /// + /// This creates a software controlled PWM pin. You can use any GPIO pin and the pin numbering will be that of the wiringPiSetup() + /// function you used. Use 100 for the pwmRange, then the value can be anything from 0 (off) to 100 (fully on) for the given pin. + /// The return value is 0 for success. Anything else and you should check the global errno variable to see what went wrong. + /// + /// The pin. + /// The initial value. + /// The PWM range. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "softPwmCreate", SetLastError = true)] + public static extern int SoftPwmCreate(int pin, int initialValue, int pwmRange); + + /// + /// This updates the PWM value on the given pin. The value is checked to be in-range and pins that haven’t previously + /// been initialized via softPwmCreate will be silently ignored. + /// + /// The pin. + /// The value. + [DllImport(WiringPiLibrary, EntryPoint = "softPwmWrite", SetLastError = true)] + public static extern void SoftPwmWrite(int pin, int value); + + /// + /// This function is undocumented + /// + /// The pin. + [DllImport(WiringPiLibrary, EntryPoint = "softPwmStop", SetLastError = true)] + public static extern void SoftPwmStop(int pin); + + /// + /// This creates a software controlled tone pin. You can use any GPIO pin and the pin numbering will be that of the wiringPiSetup() function you used. + /// The return value is 0 for success. Anything else and you should check the global errno variable to see what went wrong. + /// + /// The pin. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "softToneCreate", SetLastError = true)] + public static extern int SoftToneCreate(int pin); + + /// + /// This function is undocumented + /// + /// The pin. + [DllImport(WiringPiLibrary, EntryPoint = "softToneStop", SetLastError = true)] + public static extern void SoftToneStop(int pin); + + /// + /// This updates the tone frequency value on the given pin. The tone will be played until you set the frequency to 0. + /// + /// The pin. + /// The freq. + [DllImport(WiringPiLibrary, EntryPoint = "softToneWrite", SetLastError = true)] + public static extern void SoftToneWrite(int pin, int freq); + + #endregion + + } +} diff --git a/Unosquare.RaspberryIO/Native/WiringPi.Spi.cs b/Unosquare.RaspberryIO/Native/WiringPi.Spi.cs new file mode 100644 index 0000000..4a36c97 --- /dev/null +++ b/Unosquare.RaspberryIO/Native/WiringPi.Spi.cs @@ -0,0 +1,53 @@ +namespace Unosquare.RaspberryIO.Native +{ + using System.Runtime.InteropServices; + + public partial class WiringPi + { + #region WiringPi - SPI Library Calls + + /// + /// This function is undocumented + /// + /// The channel. + /// Unknown + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiSPIGetFd", SetLastError = true)] + public static extern int WiringPiSPIGetFd(int channel); + + /// + /// This performs a simultaneous write/read transaction over the selected SPI bus. Data that was in your buffer is overwritten by data returned from the SPI bus. + /// That’s all there is in the helper library. It is possible to do simple read and writes over the SPI bus using the standard read() and write() system calls though – + /// write() may be better to use for sending data to chains of shift registers, or those LED strings where you send RGB triplets of data. + /// Devices such as A/D and D/A converters usually need to perform a concurrent write/read transaction to work. + /// + /// The channel. + /// The data. + /// The length. + /// The result + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiSPIDataRW", SetLastError = true)] + public static extern int WiringPiSPIDataRW(int channel, byte[] data, int len); + + /// + /// This function is undocumented + /// + /// The channel. + /// The speed. + /// The mode. + /// Unkown + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiSPISetupMode", SetLastError = true)] + public static extern int WiringPiSPISetupMode(int channel, int speed, int mode); + + /// + /// This is the way to initialize a channel (The Pi has 2 channels; 0 and 1). The speed parameter is an integer + /// in the range 500,000 through 32,000,000 and represents the SPI clock speed in Hz. + /// The returned value is the Linux file-descriptor for the device, or -1 on error. If an error has happened, you may use the standard errno global variable to see why. + /// + /// The channel. + /// The speed. + /// The Linux file descriptor for the device or -1 for error + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiSPISetup", SetLastError = true)] + public static extern int WiringPiSPISetup(int channel, int speed); + + #endregion + } +} diff --git a/Unosquare.RaspberryIO/Native/WiringPi.cs b/Unosquare.RaspberryIO/Native/WiringPi.cs new file mode 100644 index 0000000..df347e7 --- /dev/null +++ b/Unosquare.RaspberryIO/Native/WiringPi.cs @@ -0,0 +1,394 @@ +namespace Unosquare.RaspberryIO.Native +{ + using System; + using System.Runtime.InteropServices; + + /// + /// Provides native C WiringPi Library function call wrappers + /// All credit for the native library goes to the author of http://wiringpi.com/ + /// The wrappers were written based on https://github.com/WiringPi/WiringPi/blob/master/wiringPi/wiringPi.h + /// + public partial class WiringPi + { + internal const string WiringPiLibrary = "libwiringPi.so.2.46"; + + #region WiringPi - Core Functions (https://github.com/WiringPi/WiringPi/blob/master/wiringPi/wiringPi.h) + + /// + /// This initialises wiringPi and assumes that the calling program is going to be using the wiringPi pin numbering scheme. + /// This is a simplified numbering scheme which provides a mapping from virtual pin numbers 0 through 16 to the real underlying Broadcom GPIO pin numbers. + /// See the pins page for a table which maps the wiringPi pin number to the Broadcom GPIO pin number to the physical location on the edge connector. + /// This function needs to be called with root privileges. + /// + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiSetup", SetLastError = true)] + public static extern int WiringPiSetup(); + + /// + /// This initialises wiringPi but uses the /sys/class/gpio interface rather than accessing the hardware directly. + /// This can be called as a non-root user provided the GPIO pins have been exported before-hand using the gpio program. + /// Pin numbering in this mode is the native Broadcom GPIO numbers – the same as wiringPiSetupGpio() above, + /// so be aware of the differences between Rev 1 and Rev 2 boards. + /// + /// Note: In this mode you can only use the pins which have been exported via the /sys/class/gpio interface before you run your program. + /// You can do this in a separate shell-script, or by using the system() function from inside your program to call the gpio program. + /// Also note that some functions have no effect when using this mode as they’re not currently possible to action unless called with root privileges. + /// (although you can use system() to call gpio to set/change modes if needed) + /// + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiSetupSys", SetLastError = true)] + public static extern int WiringPiSetupSys(); + + /// + /// This is identical to wiringPiSetup, however it allows the calling programs to use the Broadcom GPIO + /// pin numbers directly with no re-mapping. + /// As above, this function needs to be called with root privileges, and note that some pins are different + /// from revision 1 to revision 2 boards. + /// + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiSetupGpio", SetLastError = true)] + public static extern int WiringPiSetupGpio(); + + /// + /// Identical to wiringPiSetup, however it allows the calling programs to use the physical pin numbers on the P1 connector only. + /// This function needs to be called with root privileges. + /// + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiSetupPhys", SetLastError = true)] + public static extern int WiringPiSetupPhys(); + + /// + /// This function is undocumented + /// + /// The pin. + /// The mode. + [DllImport(WiringPiLibrary, EntryPoint = "pinModeAlt", SetLastError = true)] + public static extern void PinModeAlt(int pin, int mode); + + /// + /// This sets the mode of a pin to either INPUT, OUTPUT, PWM_OUTPUT or GPIO_CLOCK. + /// Note that only wiringPi pin 1 (BCM_GPIO 18) supports PWM output and only wiringPi pin 7 (BCM_GPIO 4) + /// supports CLOCK output modes. + /// + /// This function has no effect when in Sys mode. If you need to change the pin mode, then you can + /// do it with the gpio program in a script before you start your program. + /// + /// The pin. + /// The mode. + [DllImport(WiringPiLibrary, EntryPoint = "pinMode", SetLastError = true)] + public static extern void PinMode(int pin, int mode); + + /// + /// This sets the pull-up or pull-down resistor mode on the given pin, which should be set as an input. + /// Unlike the Arduino, the BCM2835 has both pull-up an down internal resistors. The parameter pud should be; PUD_OFF, + /// (no pull up/down), PUD_DOWN (pull to ground) or PUD_UP (pull to 3.3v) The internal pull up/down resistors + /// have a value of approximately 50KΩ on the Raspberry Pi. + /// + /// This function has no effect on the Raspberry Pi’s GPIO pins when in Sys mode. + /// If you need to activate a pull-up/pull-down, then you can do it with the gpio program in a script before you start your program. + /// + /// The pin. + /// The pud. + [DllImport(WiringPiLibrary, EntryPoint = "pullUpDnControl", SetLastError = true)] + public static extern void PullUpDnControl(int pin, int pud); + + /// + /// This function returns the value read at the given pin. It will be HIGH or LOW (1 or 0) depending on the logic level at the pin. + /// + /// The pin. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "digitalRead", SetLastError = true)] + public static extern int DigitalRead(int pin); + + /// + /// Writes the value HIGH or LOW (1 or 0) to the given pin which must have been previously set as an output. + /// WiringPi treats any non-zero number as HIGH, however 0 is the only representation of LOW. + /// + /// The pin. + /// The value. + [DllImport(WiringPiLibrary, EntryPoint = "digitalWrite", SetLastError = true)] + public static extern void DigitalWrite(int pin, int value); + + /// + /// Writes the value to the PWM register for the given pin. The Raspberry Pi has one + /// on-board PWM pin, pin 1 (BMC_GPIO 18, Phys 12) and the range is 0-1024. + /// Other PWM devices may have other PWM ranges. + /// This function is not able to control the Pi’s on-board PWM when in Sys mode. + /// + /// The pin. + /// The value. + [DllImport(WiringPiLibrary, EntryPoint = "pwmWrite", SetLastError = true)] + public static extern void PwmWrite(int pin, int value); + + /// + /// This returns the value read on the supplied analog input pin. You will need to + /// register additional analog modules to enable this function for devices such as the Gertboard, quick2Wire analog board, etc. + /// + /// The pin. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "analogRead", SetLastError = true)] + public static extern int AnalogRead(int pin); + + /// + /// This writes the given value to the supplied analog pin. You will need to register additional + /// analog modules to enable this function for devices such as the Gertboard. + /// + /// The pin. + /// The value. + [DllImport(WiringPiLibrary, EntryPoint = "analogWrite", SetLastError = true)] + public static extern void AnalogWrite(int pin, int value); + + /// + /// This returns the board revision of the Raspberry Pi. It will be either 1 or 2. Some of the BCM_GPIO pins changed number and + /// function when moving from board revision 1 to 2, so if you are using BCM_GPIO pin numbers, then you need to be aware of the differences. + /// + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "piBoardRev", SetLastError = true)] + public static extern int PiBoardRev(); + + /// + /// This function is undocumented + /// + /// The model. + /// The memory. + /// The maker. + /// The over volted. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "piBoardId", SetLastError = true)] + public static extern int PiBoardId(ref int model, ref int mem, ref int maker, ref int overVolted); + + /// + /// This returns the BCM_GPIO pin number of the supplied wiringPi pin. It takes the board revision into account. + /// + /// The w pi pin. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "wpiPinToGpio", SetLastError = true)] + public static extern int WpiPinToGpio(int wPiPin); + + /// + /// This returns the BCM_GPIO pin number of the supplied physical pin on the P1 connector. + /// + /// The physical pin. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "physPinToGpio", SetLastError = true)] + public static extern int PhysPinToGpio(int physPin); + + /// + /// This sets the “strength” of the pad drivers for a particular group of pins. + /// There are 3 groups of pins and the drive strength is from 0 to 7. Do not use this unless you know what you are doing. + /// + /// The group. + /// The value. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "setPadDrive", SetLastError = true)] + public static extern int SetPadDrive(int group, int value); + + /// + /// Undocumented function + /// + /// The pin. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "getAlt", SetLastError = true)] + public static extern int GetAlt(int pin); + + /// + /// Undocumented function + /// + /// The pin. + /// The freq. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "pwmToneWrite", SetLastError = true)] + public static extern int PwmToneWrite(int pin, int freq); + + /// + /// This writes the 8-bit byte supplied to the first 8 GPIO pins. + /// It’s the fastest way to set all 8 bits at once to a particular value, although it still takes two write operations to the Pi’s GPIO hardware. + /// + /// The value. + [DllImport(WiringPiLibrary, EntryPoint = "digitalWriteByte", SetLastError = true)] + public static extern void DigitalWriteByte(int value); + + /// + /// This writes the 8-bit byte supplied to the first 8 GPIO pins. + /// It’s the fastest way to set all 8 bits at once to a particular value, although it still takes two write operations to the Pi’s GPIO hardware. + /// + /// The value. + [DllImport(WiringPiLibrary, EntryPoint = "digitalWriteByte2", SetLastError = true)] + public static extern void DigitalWriteByte2(int value); + + /// + /// Undocumented function + /// This reads the 8-bit byte supplied to the first 8 GPIO pins. + /// It’s the fastest way to get all 8 bits at once to a particular value. + /// + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "digitalReadByte", SetLastError = true)] + public static extern uint DigitalReadByte(); + + /// + /// Undocumented function + /// This reads the 8-bit byte supplied to the first 8 GPIO pins. + /// It’s the fastest way to get all 8 bits at once to a particular value. + /// + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "digitalReadByte2", SetLastError = true)] + public static extern uint DigitalReadByte2(); + + /// + /// The PWM generator can run in 2 modes – “balanced” and “mark:space”. The mark:space mode is traditional, + /// however the default mode in the Pi is “balanced”. You can switch modes by supplying the parameter: PWM_MODE_BAL or PWM_MODE_MS. + /// + /// The mode. + [DllImport(WiringPiLibrary, EntryPoint = "pwmSetMode", SetLastError = true)] + public static extern void PwmSetMode(int mode); + + /// + /// This sets the range register in the PWM generator. The default is 1024. + /// + /// The range. + [DllImport(WiringPiLibrary, EntryPoint = "pwmSetRange", SetLastError = true)] + public static extern void PwmSetRange(uint range); + + /// + /// This sets the divisor for the PWM clock. + /// Note: The PWM control functions can not be used when in Sys mode. + /// To understand more about the PWM system, you’ll need to read the Broadcom ARM peripherals manual. + /// + /// The divisor. + [DllImport(WiringPiLibrary, EntryPoint = "pwmSetClock", SetLastError = true)] + public static extern void PwmSetClock(int divisor); + + /// + /// Undocumented function + /// + /// The pin. + /// The freq. + [DllImport(WiringPiLibrary, EntryPoint = "gpioClockSet", SetLastError = true)] + public static extern void GpioClockSet(int pin, int freq); + + /// + /// Note: Jan 2013: The waitForInterrupt() function is deprecated – you should use the newer and easier to use wiringPiISR() function below. + /// When called, it will wait for an interrupt event to happen on that pin and your program will be stalled. The timeOut parameter is given in milliseconds, + /// or can be -1 which means to wait forever. + /// The return value is -1 if an error occurred (and errno will be set appropriately), 0 if it timed out, or 1 on a successful interrupt event. + /// Before you call waitForInterrupt, you must first initialise the GPIO pin and at present the only way to do this is to use the gpio program, either + /// in a script, or using the system() call from inside your program. + /// e.g. We want to wait for a falling-edge interrupt on GPIO pin 0, so to setup the hardware, we need to run: gpio edge 0 falling + /// before running the program. + /// + /// The pin. + /// The timeout. + /// The result code + [Obsolete] + [DllImport(WiringPiLibrary, EntryPoint = "waitForInterrupt", SetLastError = true)] + public static extern int WaitForInterrupt(int pin, int timeout); + + /// + /// This function registers a function to received interrupts on the specified pin. + /// The edgeType parameter is either INT_EDGE_FALLING, INT_EDGE_RISING, INT_EDGE_BOTH or INT_EDGE_SETUP. + /// If it is INT_EDGE_SETUP then no initialisation of the pin will happen – it’s assumed that you have already setup the pin elsewhere + /// (e.g. with the gpio program), but if you specify one of the other types, then the pin will be exported and initialised as specified. + /// This is accomplished via a suitable call to the gpio utility program, so it need to be available. + /// The pin number is supplied in the current mode – native wiringPi, BCM_GPIO, physical or Sys modes. + /// This function will work in any mode, and does not need root privileges to work. + /// The function will be called when the interrupt triggers. When it is triggered, it’s cleared in the dispatcher before calling your function, + /// so if a subsequent interrupt fires before you finish your handler, then it won’t be missed. (However it can only track one more interrupt, + /// if more than one interrupt fires while one is being handled then they will be ignored) + /// This function is run at a high priority (if the program is run using sudo, or as root) and executes concurrently with the main program. + /// It has full access to all the global variables, open file handles and so on. + /// + /// The pin. + /// The mode. + /// The method. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "wiringPiISR", SetLastError = true)] + public static extern int WiringPiISR(int pin, int mode, InterruptServiceRoutineCallback method); + + /// + /// This function creates a thread which is another function in your program previously declared using the PI_THREAD declaration. + /// This function is then run concurrently with your main program. An example may be to have this function wait for an interrupt while + /// your program carries on doing other tasks. The thread can indicate an event, or action by using global variables to + /// communicate back to the main program, or other threads. + /// + /// The method. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "piThreadCreate", SetLastError = true)] + public static extern int PiThreadCreate(ThreadWorker method); + + /// + /// These allow you to synchronise variable updates from your main program to any threads running in your program. keyNum is a number from 0 to 3 and represents a key. + /// When another process tries to lock the same key, it will be stalled until the first process has unlocked the same key. + /// You may need to use these functions to ensure that you get valid data when exchanging data between your main program and a thread + /// – otherwise it’s possible that the thread could wake-up halfway during your data copy and change the data – + /// so the data you end up copying is incomplete, or invalid. See the wfi.c program in the examples directory for an example. + /// + /// The key. + [DllImport(WiringPiLibrary, EntryPoint = "piLock", SetLastError = true)] + public static extern void PiLock(int key); + + /// + /// These allow you to synchronise variable updates from your main program to any threads running in your program. keyNum is a number from 0 to 3 and represents a key. + /// When another process tries to lock the same key, it will be stalled until the first process has unlocked the same key. + /// You may need to use these functions to ensure that you get valid data when exchanging data between your main program and a thread + /// – otherwise it’s possible that the thread could wake-up halfway during your data copy and change the data – + /// so the data you end up copying is incomplete, or invalid. See the wfi.c program in the examples directory for an example. + /// + /// The key. + [DllImport(WiringPiLibrary, EntryPoint = "piUnlock", SetLastError = true)] + public static extern void PiUnlock(int key); + + /// + /// This attempts to shift your program (or thread in a multi-threaded program) to a higher priority + /// and enables a real-time scheduling. The priority parameter should be from 0 (the default) to 99 (the maximum). + /// This won’t make your program go any faster, but it will give it a bigger slice of time when other programs are running. + /// The priority parameter works relative to others – so you can make one program priority 1 and another priority 2 + /// and it will have the same effect as setting one to 10 and the other to 90 (as long as no other + /// programs are running with elevated priorities) + /// The return value is 0 for success and -1 for error. If an error is returned, the program should then consult the errno global variable, as per the usual conventions. + /// Note: Only programs running as root can change their priority. If called from a non-root program then nothing happens. + /// + /// The priority. + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "piHiPri", SetLastError = true)] + public static extern int PiHiPri(int priority); + + /// + /// This causes program execution to pause for at least howLong milliseconds. + /// Due to the multi-tasking nature of Linux it could be longer. + /// Note that the maximum delay is an unsigned 32-bit integer or approximately 49 days. + /// + /// The how long. + [DllImport(WiringPiLibrary, EntryPoint = "delay", SetLastError = true)] + public static extern void Delay(uint howLong); + + /// + /// This causes program execution to pause for at least howLong microseconds. + /// Due to the multi-tasking nature of Linux it could be longer. + /// Note that the maximum delay is an unsigned 32-bit integer microseconds or approximately 71 minutes. + /// Delays under 100 microseconds are timed using a hard-coded loop continually polling the system time, + /// Delays over 100 microseconds are done using the system nanosleep() function – You may need to consider the implications + /// of very short delays on the overall performance of the system, especially if using threads. + /// + /// The how long. + [DllImport(WiringPiLibrary, EntryPoint = "delayMicroseconds", SetLastError = true)] + public static extern void DelayMicroseconds(uint howLong); + + /// + /// This returns a number representing the number of milliseconds since your program called one of the wiringPiSetup functions. + /// It returns an unsigned 32-bit number which wraps after 49 days. + /// + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "millis", SetLastError = true)] + public static extern uint Millis(); + + /// + /// This returns a number representing the number of microseconds since your program called one of + /// the wiringPiSetup functions. It returns an unsigned 32-bit number which wraps after approximately 71 minutes. + /// + /// The result code + [DllImport(WiringPiLibrary, EntryPoint = "micros", SetLastError = true)] + public static extern uint Micros(); + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Pi.cs b/Unosquare.RaspberryIO/Pi.cs new file mode 100644 index 0000000..c3bebf0 --- /dev/null +++ b/Unosquare.RaspberryIO/Pi.cs @@ -0,0 +1,110 @@ +namespace Unosquare.RaspberryIO +{ + using Camera; + using Computer; + using Gpio; + using Native; + using System.Threading.Tasks; + using Swan.Components; + + /// + /// Our main character. Provides access to the Raspberry Pi's GPIO, system and board information and Camera + /// + public static class Pi + { + private static readonly object SyncLock = new object(); + + /// + /// Initializes static members of the class. + /// + static Pi() + { + lock (SyncLock) + { + // Extraction of embedded resources + Resources.EmbeddedResources.ExtractAll(); + + // Instance assignments + Gpio = GpioController.Instance; + Info = SystemInfo.Instance; + Timing = Timing.Instance; + Spi = SpiBus.Instance; + I2C = I2CBus.Instance; + Camera = CameraController.Instance; + PiDisplay = DsiDisplay.Instance; + } + } + + #region Components + + /// + /// Provides access to the Raspberry Pi's GPIO as a collection of GPIO Pins. + /// + public static GpioController Gpio { get; } + + /// + /// Provides information on this Raspberry Pi's CPU and form factor. + /// + public static SystemInfo Info { get; } + + /// + /// Provides access to The PI's Timing and threading API + /// + public static Timing Timing { get; } + + /// + /// Provides access to the 2-channel SPI bus + /// + public static SpiBus Spi { get; } + + /// + /// Provides access to the functionality of the i2c bus. + /// + public static I2CBus I2C { get; } + + /// + /// Provides access to the official Raspberry Pi Camera + /// + public static CameraController Camera { get; } + + /// + /// Provides access to the official Raspberry Pi 7-inch DSI Display + /// + public static DsiDisplay PiDisplay { get; } + + /// + /// Gets the logger source name. + /// + internal static string LoggerSource => typeof(Pi).Namespace; + + #endregion + + #region Methods + + /// + /// Restarts the Pi. Must be running as SU + /// + /// The process result + public static async Task RestartAsync() => await ProcessRunner.GetProcessResultAsync("reboot", null, null); + + /// + /// Restarts the Pi. Must be running as SU + /// + /// The process result + public static ProcessResult Restart() => RestartAsync().GetAwaiter().GetResult(); + + /// + /// Halts the Pi. Must be running as SU + /// + /// The process result + public static async Task ShutdownAsync() => await ProcessRunner.GetProcessResultAsync("halt", null, null); + + /// + /// Halts the Pi. Must be running as SU + /// + /// The process result + public static ProcessResult Shutdown() => ShutdownAsync().GetAwaiter().GetResult(); + + #endregion + } +} diff --git a/Unosquare.RaspberryIO/Properties/AssemblyInfo.cs b/Unosquare.RaspberryIO/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..21d57f9 --- /dev/null +++ b/Unosquare.RaspberryIO/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die einer Assembly zugeordnet sind. +[assembly: AssemblyTitle("Unosquare Raspberry IO")] +[assembly: AssemblyDescription("The Raspberry Pi's IO Functionality in an easy-to use API for Mono/.NET Core\n\nThis library enables developers to use the various Raspberry Pi's hardware modules including the Camera to capture images and video, the GPIO pins, and both, the SPI and I2C buses.")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Unosquare")] +[assembly: AssemblyProduct("Unosquare.RaspberryIO")] +[assembly: AssemblyCopyright("Unosquare (c) 2016-2018")] +[assembly: AssemblyTrademark("https://github.com/unosquare/raspberryio")] +[assembly: AssemblyCulture("")] + +// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly +// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von +// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. +[assembly: ComVisible(false)] + +// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +[assembly: Guid("8c5d4de9-377f-4ec8-873d-6eef15f43516")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, +// indem Sie "*" wie unten gezeigt eingeben: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("0.17.0")] +[assembly: AssemblyFileVersion("0.17.0")] diff --git a/Unosquare.RaspberryIO/Resources/EmbeddedResources.cs b/Unosquare.RaspberryIO/Resources/EmbeddedResources.cs new file mode 100644 index 0000000..7c8c3b9 --- /dev/null +++ b/Unosquare.RaspberryIO/Resources/EmbeddedResources.cs @@ -0,0 +1,65 @@ +namespace Unosquare.RaspberryIO.Resources +{ + using Native; + using Swan; + using System; + using System.Collections.ObjectModel; + using System.IO; + + /// + /// Provides access to embedded assembly files + /// + internal static class EmbeddedResources + { + /// + /// Initializes static members of the class. + /// + static EmbeddedResources() + { + ResourceNames = + new ReadOnlyCollection(typeof(EmbeddedResources).Assembly().GetManifestResourceNames()); + } + + /// + /// Gets the resource names. + /// + /// + /// The resource names. + /// + public static ReadOnlyCollection ResourceNames { get; } + + /// + /// Extracts all the file resources to the specified base path. + /// + public static void ExtractAll() + { + var basePath = Runtime.EntryAssemblyDirectory; + var executablePermissions = Standard.StringToInteger("0777", IntPtr.Zero, 8); + + foreach (var resourceName in ResourceNames) + { + var filename = resourceName.Substring($"{typeof(EmbeddedResources).Namespace}.".Length); + var targetPath = Path.Combine(basePath, filename); + if (File.Exists(targetPath)) return; + + using (var stream = typeof(EmbeddedResources).Assembly() + .GetManifestResourceStream($"{typeof(EmbeddedResources).Namespace}.{filename}")) + { + using (var outputStream = File.OpenWrite(targetPath)) + { + stream?.CopyTo(outputStream); + } + + try + { + Standard.Chmod(targetPath, (uint)executablePermissions); + } + catch + { + /* Ignore */ + } + } + } + } + } +} \ No newline at end of file diff --git a/Unosquare.RaspberryIO/Resources/gpio.2.44 b/Unosquare.RaspberryIO/Resources/gpio.2.44 new file mode 100644 index 0000000..573c114 Binary files /dev/null and b/Unosquare.RaspberryIO/Resources/gpio.2.44 differ diff --git a/Unosquare.RaspberryIO/Resources/libwiringPi.so.2.46 b/Unosquare.RaspberryIO/Resources/libwiringPi.so.2.46 new file mode 100644 index 0000000..a0ee222 Binary files /dev/null and b/Unosquare.RaspberryIO/Resources/libwiringPi.so.2.46 differ diff --git a/Unosquare.RaspberryIO/Unosquare.RaspberryIO.csproj b/Unosquare.RaspberryIO/Unosquare.RaspberryIO.csproj new file mode 100644 index 0000000..656b28a --- /dev/null +++ b/Unosquare.RaspberryIO/Unosquare.RaspberryIO.csproj @@ -0,0 +1,99 @@ + + + + + Debug + AnyCPU + {8C5D4DE9-377F-4EC8-873D-6EEF15F43516} + Library + Properties + Unosquare.RaspberryIO + Unosquare.RaspberryIO + v4.7.1 + 512 + + + true + full + false + bin\Debug\ + TRACE;DEBUG;NET452 + prompt + 4 + 7.1 + + + pdbonly + true + bin\Release\ + TRACE;NET452 + prompt + 4 + 7.1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {ab015683-62e5-47f1-861f-6d037f9c6433} + Unosquare.Swan.Lite + + + {2ea5e3e4-f8c8-4742-8c78-4b070afcfb73} + Unosquare.Swan + + + + \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Abstractions/AtomicTypeBase.cs b/Unosquare.Swan.Lite/Abstractions/AtomicTypeBase.cs new file mode 100644 index 0000000..ab352db --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/AtomicTypeBase.cs @@ -0,0 +1,243 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + using System.Threading; + + /// + /// Provides a generic implementation of an Atomic (interlocked) type + /// + /// Idea taken from Memory model and .NET operations in article: + /// http://igoro.com/archive/volatile-keyword-in-c-memory-model-explained/. + /// + /// The structure type backed by a 64-bit value. + public abstract class AtomicTypeBase : IComparable, IComparable, IComparable>, IEquatable, IEquatable> + where T : struct, IComparable, IComparable, IEquatable + { + private long _backingValue; + + /// + /// Initializes a new instance of the class. + /// + /// The initial value. + protected AtomicTypeBase(long initialValue) + { + BackingValue = initialValue; + } + + /// + /// Gets or sets the value. + /// + public T Value + { + get => FromLong(BackingValue); + set => BackingValue = ToLong(value); + } + + /// + /// Gets or sets the backing value. + /// + protected long BackingValue + { + get => Interlocked.Read(ref _backingValue); + set => Interlocked.Exchange(ref _backingValue, value); + } + + /// + /// Implements the operator ==. + /// + /// a. + /// The b. + /// + /// The result of the operator. + /// + public static bool operator ==(AtomicTypeBase a, T b) => a?.Equals(b) == true; + + /// + /// Implements the operator !=. + /// + /// a. + /// The b. + /// + /// The result of the operator. + /// + public static bool operator !=(AtomicTypeBase a, T b) => a?.Equals(b) == false; + + /// + /// Implements the operator >. + /// + /// a. + /// The b. + /// + /// The result of the operator. + /// + public static bool operator >(AtomicTypeBase a, T b) => a.CompareTo(b) > 0; + + /// + /// Implements the operator <. + /// + /// a. + /// The b. + /// + /// The result of the operator. + /// + public static bool operator <(AtomicTypeBase a, T b) => a.CompareTo(b) < 0; + + /// + /// Implements the operator >=. + /// + /// a. + /// The b. + /// + /// The result of the operator. + /// + public static bool operator >=(AtomicTypeBase a, T b) => a.CompareTo(b) >= 0; + + /// + /// Implements the operator <=. + /// + /// a. + /// The b. + /// + /// The result of the operator. + /// + public static bool operator <=(AtomicTypeBase a, T b) => a.CompareTo(b) <= 0; + + /// + /// Implements the operator ++. + /// + /// The instance. + /// + /// The result of the operator. + /// + public static AtomicTypeBase operator ++(AtomicTypeBase instance) + { + Interlocked.Increment(ref instance._backingValue); + return instance; + } + + /// + /// Implements the operator --. + /// + /// The instance. + /// + /// The result of the operator. + /// + public static AtomicTypeBase operator --(AtomicTypeBase instance) + { + Interlocked.Decrement(ref instance._backingValue); + return instance; + } + + /// + /// Implements the operator -<. + /// + /// The instance. + /// The operand. + /// + /// The result of the operator. + /// + public static AtomicTypeBase operator +(AtomicTypeBase instance, long operand) + { + instance.BackingValue = instance.BackingValue + operand; + return instance; + } + + /// + /// Implements the operator -. + /// + /// The instance. + /// The operand. + /// + /// The result of the operator. + /// + public static AtomicTypeBase operator -(AtomicTypeBase instance, long operand) + { + instance.BackingValue = instance.BackingValue - operand; + return instance; + } + + /// + /// Compares the value to the other instance. + /// + /// The other instance. + /// 0 if equal, 1 if this instance is greater, -1 if this instance is less than. + /// When types are incompatible. + public int CompareTo(object other) + { + switch (other) + { + case null: + return 1; + case AtomicTypeBase atomic: + return BackingValue.CompareTo(atomic.BackingValue); + case T variable: + return Value.CompareTo(variable); + } + + throw new ArgumentException("Incompatible comparison types"); + } + + /// + /// Compares the value to the other instance. + /// + /// The other instance. + /// 0 if equal, 1 if this instance is greater, -1 if this instance is less than. + public int CompareTo(T other) => Value.CompareTo(other); + + /// + /// Compares the value to the other instance. + /// + /// The other instance. + /// 0 if equal, 1 if this instance is greater, -1 if this instance is less than. + public int CompareTo(AtomicTypeBase other) => BackingValue.CompareTo(other?.BackingValue ?? default); + + /// + /// Determines whether the specified , is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public override bool Equals(object other) + { + switch (other) + { + case AtomicTypeBase atomic: + return Equals(atomic); + case T variable: + return Equals(variable); + } + + return false; + } + + /// + /// Returns a hash code for this instance. + /// + /// + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// + public override int GetHashCode() => BackingValue.GetHashCode(); + + /// + public bool Equals(AtomicTypeBase other) => + BackingValue == (other?.BackingValue ?? default); + + /// + public bool Equals(T other) => Equals(Value, other); + + /// + /// Converts from a long value to the target type. + /// + /// The backing value. + /// The value converted form a long value. + protected abstract T FromLong(long backingValue); + + /// + /// Converts from the target type to a long value. + /// + /// The value. + /// The value converted to a long value. + protected abstract long ToLong(T value); + } +} diff --git a/Unosquare.Swan.Lite/Abstractions/ExclusiveTimer.cs b/Unosquare.Swan.Lite/Abstractions/ExclusiveTimer.cs new file mode 100644 index 0000000..5a01d61 --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/ExclusiveTimer.cs @@ -0,0 +1,197 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + using System.Threading; + + /// + /// A threading implementation that executes at most one cycle at a time + /// in a thread. Callback execution is NOT guaranteed to be carried out + /// on the same thread every time the timer fires. + /// + public sealed class ExclusiveTimer : IDisposable + { + private readonly object _syncLock = new object(); + private readonly ManualResetEventSlim _cycleDoneEvent = new ManualResetEventSlim(true); + private readonly Timer _backingTimer; + private readonly TimerCallback _userCallback; + private readonly AtomicBoolean _isDisposing = new AtomicBoolean(); + private readonly AtomicBoolean _isDisposed = new AtomicBoolean(); + private int _period; + + /// + /// Initializes a new instance of the class. + /// + /// The timer callback. + /// The state. + /// The due time. + /// The period. + public ExclusiveTimer(TimerCallback timerCallback, object state, int dueTime, int period) + { + _period = period; + _userCallback = timerCallback; + _backingTimer = new Timer(InternalCallback, state ?? this, dueTime, Timeout.Infinite); + } + + /// + /// Initializes a new instance of the class. + /// + /// The timer callback. + /// The state. + /// The due time. + /// The period. + public ExclusiveTimer(TimerCallback timerCallback, object state, TimeSpan dueTime, TimeSpan period) + : this(timerCallback, state, Convert.ToInt32(dueTime.TotalMilliseconds), Convert.ToInt32(period.TotalMilliseconds)) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// + /// The timer callback. + public ExclusiveTimer(TimerCallback timerCallback) + : this(timerCallback, null, Timeout.Infinite, Timeout.Infinite) + { + // placholder + } + + /// + /// Initializes a new instance of the class. + /// + /// The timer callback. + /// The due time. + /// The period. + public ExclusiveTimer(Action timerCallback, int dueTime, int period) + : this(s => { timerCallback?.Invoke(); }, null, dueTime, period) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// + /// The timer callback. + /// The due time. + /// The period. + public ExclusiveTimer(Action timerCallback, TimeSpan dueTime, TimeSpan period) + : this(s => { timerCallback?.Invoke(); }, null, dueTime, period) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// + /// The timer callback. + public ExclusiveTimer(Action timerCallback) + : this(timerCallback, Timeout.Infinite, Timeout.Infinite) + { + // placeholder + } + + /// + /// Gets a value indicating whether this instance is disposing. + /// + /// + /// true if this instance is disposing; otherwise, false. + /// + public bool IsDisposing => _isDisposing.Value; + + /// + /// Gets a value indicating whether this instance is disposed. + /// + /// + /// true if this instance is disposed; otherwise, false. + /// + public bool IsDisposed => _isDisposed.Value; + + /// + /// Changes the start time and the interval between method invocations for the internal timer. + /// + /// The due time. + /// The period. + public void Change(int dueTime, int period) + { + _period = period; + + _backingTimer.Change(dueTime, Timeout.Infinite); + } + + /// + /// Changes the start time and the interval between method invocations for the internal timer. + /// + /// The due time. + /// The period. + public void Change(TimeSpan dueTime, TimeSpan period) + => Change(Convert.ToInt32(dueTime.TotalMilliseconds), Convert.ToInt32(period.TotalMilliseconds)); + + /// + /// Changes the interval between method invocations for the internal timer. + /// + /// The period. + public void Resume(int period) => Change(0, period); + + /// + /// Changes the interval between method invocations for the internal timer. + /// + /// The period. + public void Resume(TimeSpan period) => Change(TimeSpan.Zero, period); + + /// + /// Pauses this instance. + /// + public void Pause() => Change(Timeout.Infinite, Timeout.Infinite); + + /// + public void Dispose() + { + lock (_syncLock) + { + if (_isDisposed == true || _isDisposing == true) + return; + + _isDisposing.Value = true; + } + + try + { + _backingTimer.Dispose(); + _cycleDoneEvent.Wait(); + _cycleDoneEvent.Dispose(); + } + finally + { + _isDisposed.Value = true; + _isDisposing.Value = false; + } + } + + /// + /// Logic that runs every time the timer hits the due time. + /// + /// The state. + private void InternalCallback(object state) + { + lock (_syncLock) + { + if (IsDisposed || IsDisposing) + return; + } + + if (_cycleDoneEvent.IsSet == false) + return; + + _cycleDoneEvent.Reset(); + + try + { + _userCallback(state); + } + finally + { + _cycleDoneEvent?.Set(); + _backingTimer?.Change(_period, Timeout.Infinite); + } + } + } +} diff --git a/Unosquare.Swan.Lite/Abstractions/ExpressionParser.cs b/Unosquare.Swan.Lite/Abstractions/ExpressionParser.cs new file mode 100644 index 0000000..85890f8 --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/ExpressionParser.cs @@ -0,0 +1,94 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + using System.Linq; + using System.Collections.Generic; + using System.Linq.Expressions; + + /// + /// Represents a generic expression parser. + /// + public abstract class ExpressionParser + { + /// + /// Resolves the expression. + /// + /// The type of expression result. + /// The tokens. + /// The representation of the expression parsed. + public virtual T ResolveExpression(IEnumerable tokens) + { + var conversion = Expression.Convert(Parse(tokens), typeof(T)); + return Expression.Lambda>(conversion).Compile()(); + } + + /// + /// Parses the specified tokens. + /// + /// The tokens. + /// The final expression. + public virtual Expression Parse(IEnumerable tokens) + { + var expressionStack = new List>(); + + foreach (var token in tokens) + { + if (expressionStack.Any() == false) + expressionStack.Add(new Stack()); + + switch (token.Type) + { + case TokenType.Wall: + expressionStack.Add(new Stack()); + break; + case TokenType.Number: + expressionStack.Last().Push(Expression.Constant(Convert.ToDecimal(token.Value))); + break; + case TokenType.Variable: + ResolveVariable(token.Value, expressionStack.Last()); + break; + case TokenType.String: + expressionStack.Last().Push(Expression.Constant(token.Value)); + break; + case TokenType.Operator: + ResolveOperator(token.Value, expressionStack.Last()); + break; + case TokenType.Function: + ResolveFunction(token.Value, expressionStack.Last()); + + if (expressionStack.Count > 1 && expressionStack.Last().Count == 1) + { + var lastValue = expressionStack.Last().Pop(); + expressionStack.Remove(expressionStack.Last()); + expressionStack.Last().Push(lastValue); + } + + break; + } + } + + return expressionStack.Last().Pop(); + } + + /// + /// Resolves the variable. + /// + /// The value. + /// The expression stack. + public abstract void ResolveVariable(string value, Stack expressionStack); + + /// + /// Resolves the operator. + /// + /// The value. + /// The expression stack. + public abstract void ResolveOperator(string value, Stack expressionStack); + + /// + /// Resolves the function. + /// + /// The value. + /// The expression stack. + public abstract void ResolveFunction(string value, Stack expressionStack); + } +} diff --git a/Unosquare.Swan.Lite/Abstractions/IObjectMap.cs b/Unosquare.Swan.Lite/Abstractions/IObjectMap.cs new file mode 100644 index 0000000..1c0419e --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/IObjectMap.cs @@ -0,0 +1,27 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + using System.Collections.Generic; + using System.Reflection; + + /// + /// Interface object map. + /// + public interface IObjectMap + { + /// + /// Gets or sets the map. + /// + Dictionary> Map { get; } + + /// + /// Gets or sets the type of the source. + /// + Type SourceType { get; } + + /// + /// Gets or sets the type of the destination. + /// + Type DestinationType { get; } + } +} diff --git a/Unosquare.Swan.Lite/Abstractions/ISyncLocker.cs b/Unosquare.Swan.Lite/Abstractions/ISyncLocker.cs new file mode 100644 index 0000000..30a8b39 --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/ISyncLocker.cs @@ -0,0 +1,24 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + + /// + /// Defines a generic interface for synchronized locking mechanisms. + /// + public interface ISyncLocker : IDisposable + { + /// + /// Acquires a writer lock. + /// The lock is released when the returned locking object is disposed. + /// + /// A disposable locking object. + IDisposable AcquireWriterLock(); + + /// + /// Acquires a reader lock. + /// The lock is released when the returned locking object is disposed. + /// + /// A disposable locking object. + IDisposable AcquireReaderLock(); + } +} diff --git a/Unosquare.Swan.Lite/Abstractions/IValidator.cs b/Unosquare.Swan.Lite/Abstractions/IValidator.cs new file mode 100644 index 0000000..b8aec9d --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/IValidator.cs @@ -0,0 +1,21 @@ +namespace Unosquare.Swan.Abstractions +{ + /// + /// A simple Validator interface. + /// + public interface IValidator + { + /// + /// The error message. + /// + string ErrorMessage { get; } + + /// + /// Checks if a value is valid. + /// + /// The type. + /// The value. + /// True if it is valid.False if it is not. + bool IsValid(T value); + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Abstractions/IWaitEvent.cs b/Unosquare.Swan.Lite/Abstractions/IWaitEvent.cs new file mode 100644 index 0000000..39758ff --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/IWaitEvent.cs @@ -0,0 +1,57 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + + /// + /// Provides a generalized API for ManualResetEvent and ManualResetEventSlim. + /// + /// + public interface IWaitEvent : IDisposable + { + /// + /// Gets a value indicating whether the event is in the completed state. + /// + bool IsCompleted { get; } + + /// + /// Gets a value indicating whether the Begin method has been called. + /// It returns false after the Complete method is called. + /// + bool IsInProgress { get; } + + /// + /// Returns true if the underlying handle is not closed and it is still valid. + /// + bool IsValid { get; } + + /// + /// Gets a value indicating whether this instance is disposed. + /// + bool IsDisposed { get; } + + /// + /// Enters the state in which waiters need to wait. + /// All future waiters will block when they call the Wait method. + /// + void Begin(); + + /// + /// Leaves the state in which waiters need to wait. + /// All current waiters will continue. + /// + void Complete(); + + /// + /// Waits for the event to be completed. + /// + void Wait(); + + /// + /// Waits for the event to be completed. + /// Returns true when there was no timeout. False if the timeout was reached. + /// + /// The maximum amount of time to wait for. + /// true when there was no timeout. false if the timeout was reached. + bool Wait(TimeSpan timeout); + } +} diff --git a/Unosquare.Swan.Lite/Abstractions/IWorker.cs b/Unosquare.Swan.Lite/Abstractions/IWorker.cs new file mode 100644 index 0000000..2efe9f5 --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/IWorker.cs @@ -0,0 +1,18 @@ +namespace Unosquare.Swan.Abstractions +{ + /// + /// A simple interface for application workers. + /// + public interface IWorker + { + /// + /// Should start the task immediately and asynchronously. + /// + void Start(); + + /// + /// Should stop the task immediately and synchronously. + /// + void Stop(); + } +} diff --git a/Unosquare.Swan.Lite/Abstractions/RunnerBase.cs b/Unosquare.Swan.Lite/Abstractions/RunnerBase.cs new file mode 100644 index 0000000..cd5f6b8 --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/RunnerBase.cs @@ -0,0 +1,169 @@ +#if !NETSTANDARD1_3 +namespace Unosquare.Swan.Abstractions +{ + using System; + using System.Collections.Generic; + using System.Threading; + using Swan; + + /// + /// Represents an background worker abstraction with a life cycle and running at a independent thread. + /// + public abstract class RunnerBase + { + private Thread _worker; + private CancellationTokenSource _cancelTokenSource; + private ManualResetEvent _workFinished; + + /// + /// Initializes a new instance of the class. + /// + /// if set to true [is enabled]. + protected RunnerBase(bool isEnabled) + { + Name = GetType().Name; + IsEnabled = isEnabled; + } + + /// + /// Gets the error messages. + /// + /// + /// The error messages. + /// + public List ErrorMessages { get; } = new List(); + + /// + /// Gets the name. + /// + /// + /// The name. + /// + public string Name { get; } + + /// + /// Gets a value indicating whether this instance is running. + /// + /// + /// true if this instance is running; otherwise, false. + /// + public bool IsRunning { get; private set; } + + /// + /// Gets a value indicating whether this instance is enabled. + /// + /// + /// true if this instance is enabled; otherwise, false. + /// + public bool IsEnabled { get; } + + /// + /// Starts this instance. + /// + public virtual void Start() + { + if (IsEnabled == false) + return; + + $"Start Requested".Debug(Name); + _cancelTokenSource = new CancellationTokenSource(); + _workFinished = new ManualResetEvent(false); + + _worker = new Thread(() => + { + _workFinished.Reset(); + IsRunning = true; + try + { + Setup(); + DoBackgroundWork(_cancelTokenSource.Token); + } + catch (ThreadAbortException) + { + $"{nameof(ThreadAbortException)} caught.".Warn(Name); + } + catch (Exception ex) + { + $"{ex.GetType()}: {ex.Message}\r\n{ex.StackTrace}".Error(Name); + } + finally + { + Cleanup(); + _workFinished?.Set(); + IsRunning = false; + "Stopped Completely".Debug(Name); + } + }) + { + IsBackground = true, + Name = $"{Name}Thread", + }; + + _worker.Start(); + } + + /// + /// Stops this instance. + /// + public virtual void Stop() + { + if (IsEnabled == false || IsRunning == false) + return; + + $"Stop Requested".Debug(Name); + _cancelTokenSource.Cancel(); + var waitRetries = 5; + while (waitRetries >= 1) + { + if (_workFinished.WaitOne(250)) + { + waitRetries = -1; + break; + } + + waitRetries--; + } + + if (waitRetries < 0) + { + "Workbench stopped gracefully".Debug(Name); + } + else + { + "Did not respond to stop request. Aborting thread and waiting . . .".Warn(Name); + _worker.Abort(); + + if (_workFinished.WaitOne(5000) == false) + "Waited and no response. Worker might have been left in an inconsistent state.".Error(Name); + else + "Waited for worker and it finally responded (OK).".Debug(Name); + } + + _workFinished.Dispose(); + _workFinished = null; + } + + /// + /// Setups this instance. + /// + protected virtual void Setup() + { + // empty + } + + /// + /// Cleanups this instance. + /// + protected virtual void Cleanup() + { + // empty + } + + /// + /// Does the background work. + /// + /// The ct. + protected abstract void DoBackgroundWork(CancellationToken ct); + } +} +#endif \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Abstractions/SettingsProvider.cs b/Unosquare.Swan.Lite/Abstractions/SettingsProvider.cs new file mode 100644 index 0000000..a13ed28 --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/SettingsProvider.cs @@ -0,0 +1,188 @@ +namespace Unosquare.Swan.Abstractions +{ + using Formatters; + using Reflection; + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + + /// + /// Represents a provider to save and load settings using a plain JSON file. + /// + /// + /// The following example shows how to save and load settings. + /// + /// using Unosquare.Swan.Abstractions; + /// + /// public class Example + /// { + /// public static void Main() + /// { + /// // get user from settings + /// var user = SettingsProvider<Settings>.Instance.Global.User; + /// + /// // modify the port + /// SettingsProvider<Settings>.Instance.Global.Port = 20; + /// + /// // if we want these settings to persist + /// SettingsProvider<Settings>.Instance.PersistGlobalSettings(); + /// } + /// + /// public class Settings + /// { + /// public int Port { get; set; } = 9696; + /// + /// public string User { get; set; } = "User"; + /// } + /// } + /// + /// + /// The type of settings model. + public sealed class SettingsProvider + : SingletonBase> + { + private readonly object _syncRoot = new object(); + + private T _global; + + /// + /// Gets or sets the configuration file path. By default the entry assembly directory is used + /// and the filename is 'appsettings.json'. + /// + /// + /// The configuration file path. + /// + public string ConfigurationFilePath { get; set; } = +#if NETSTANDARD1_3 + Path.Combine(Runtime.LocalStoragePath, "appsettings.json"); +#else + Path.Combine(Runtime.EntryAssemblyDirectory, "appsettings.json"); +#endif + + /// + /// Gets the global settings object. + /// + /// + /// The global settings object. + /// + public T Global + { + get + { + lock (_syncRoot) + { + if (Equals(_global, default(T))) + ReloadGlobalSettings(); + + return _global; + } + } + } + + /// + /// Reloads the global settings. + /// + public void ReloadGlobalSettings() + { + if (File.Exists(ConfigurationFilePath) == false || File.ReadAllText(ConfigurationFilePath).Length == 0) + { + ResetGlobalSettings(); + return; + } + + lock (_syncRoot) + _global = Json.Deserialize(File.ReadAllText(ConfigurationFilePath)); + } + + /// + /// Persists the global settings. + /// + public void PersistGlobalSettings() => File.WriteAllText(ConfigurationFilePath, Json.Serialize(Global, true)); + + /// + /// Updates settings from list. + /// + /// The list. + /// + /// A list of settings of type ref="ExtendedPropertyInfo". + /// + /// propertyList. + public List RefreshFromList(List> propertyList) + { + if (propertyList == null) + throw new ArgumentNullException(nameof(propertyList)); + + var changedSettings = new List(); + var globalProps = Runtime.PropertyTypeCache.RetrieveAllProperties(); + + foreach (var property in propertyList) + { + var propertyInfo = globalProps.FirstOrDefault(x => x.Name == property.Property); + + if (propertyInfo == null) continue; + + var originalValue = propertyInfo.GetValue(Global); + var isChanged = propertyInfo.PropertyType.IsArray + ? property.Value is IEnumerable enumerable && propertyInfo.TrySetArray(enumerable.Cast(), Global) + : SetValue(property.Value, originalValue, propertyInfo); + + if (!isChanged) continue; + + changedSettings.Add(property.Property); + PersistGlobalSettings(); + } + + return changedSettings; + } + + /// + /// Gets the list. + /// + /// A List of ExtendedPropertyInfo of the type T. + public List> GetList() + { + var jsonData = Json.Deserialize(Json.Serialize(Global)) as Dictionary; + + return jsonData?.Keys + .Select(p => new ExtendedPropertyInfo(p) { Value = jsonData[p] }) + .ToList(); + } + + /// + /// Resets the global settings. + /// + public void ResetGlobalSettings() + { + lock (_syncRoot) + _global = Activator.CreateInstance(); + + PersistGlobalSettings(); + } + + private bool SetValue(object property, object originalValue, PropertyInfo propertyInfo) + { + switch (property) + { + case null when originalValue == null: + break; + case null: + propertyInfo.SetValue(Global, null); + return true; + default: + if (propertyInfo.PropertyType.TryParseBasicType(property, out var propertyValue) && + !propertyValue.Equals(originalValue)) + { + propertyInfo.SetValue(Global, propertyValue); + return true; + } + + break; + } + + return false; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Abstractions/SingletonBase.cs b/Unosquare.Swan.Lite/Abstractions/SingletonBase.cs new file mode 100644 index 0000000..6132885 --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/SingletonBase.cs @@ -0,0 +1,59 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + + /// + /// Represents a singleton pattern abstract class. + /// + /// The type of class. + public abstract class SingletonBase : IDisposable + where T : class + { + /// + /// The static, singleton instance reference. + /// + protected static readonly Lazy LazyInstance = new Lazy( + valueFactory: () => Activator.CreateInstance(typeof(T), true) as T, + isThreadSafe: true); + + private bool _isDisposing; // To detect redundant calls + + /// + /// Gets the instance that this singleton represents. + /// If the instance is null, it is constructed and assigned when this member is accessed. + /// + /// + /// The instance. + /// + public static T Instance => LazyInstance.Value; + + /// + public void Dispose() => Dispose(true); + + /// + /// Releases unmanaged and - optionally - managed resources. + /// Call the GC.SuppressFinalize if you override this method and use + /// a non-default class finalizer (destructor). + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposeManaged) + { + if (_isDisposing) return; + + _isDisposing = true; + + // free managed resources + if (LazyInstance == null) return; + + try + { + var disposableInstance = LazyInstance.Value as IDisposable; + disposableInstance?.Dispose(); + } + catch + { + // swallow + } + } + } +} diff --git a/Unosquare.Swan.Lite/Abstractions/Tokenizer.cs b/Unosquare.Swan.Lite/Abstractions/Tokenizer.cs new file mode 100644 index 0000000..ad18cce --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/Tokenizer.cs @@ -0,0 +1,459 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// Represents a generic tokenizer. + /// + public abstract class Tokenizer + { + private const char PeriodChar = '.'; + private const char CommaChar = ','; + private const char StringQuotedChar = '"'; + private const char OpenFuncChar = '('; + private const char CloseFuncChar = ')'; + private const char NegativeChar = '-'; + + private const string OpenFuncStr = "("; + + private readonly List _operators = new List(); + + /// + /// Initializes a new instance of the class. + /// This constructor will use the following default operators: + /// + /// + /// + /// Operator + /// Precedence + /// + /// + /// = + /// 1 + /// + /// + /// != + /// 1 + /// + /// + /// > + /// 2 + /// + /// + /// < + /// 2 + /// + /// + /// >= + /// 2 + /// + /// + /// <= + /// 2 + /// + /// + /// + + /// 3 + /// + /// + /// & + /// 3 + /// + /// + /// - + /// 3 + /// + /// + /// * + /// 4 + /// + /// + /// (backslash) + /// 4 + /// + /// + /// / + /// 4 + /// + /// + /// ^ + /// 4 + /// + /// + /// + /// The input. + protected Tokenizer(string input) + { + _operators.AddRange(GetDefaultOperators()); + Tokenize(input); + } + + /// + /// Initializes a new instance of the class. + /// + /// The input. + /// The operators to use. + protected Tokenizer(string input, IEnumerable operators) + { + _operators.AddRange(operators); + Tokenize(input); + } + + /// + /// Gets the tokens. + /// + /// + /// The tokens. + /// + public List Tokens { get; } = new List(); + + /// + /// Validates the input and return the start index for tokenizer. + /// + /// The input. + /// The start index. + /// true if the input is valid, otherwise false. + public abstract bool ValidateInput(string input, out int startIndex); + + /// + /// Resolves the type of the function or member. + /// + /// The input. + /// The token type. + public abstract TokenType ResolveFunctionOrMemberType(string input); + + /// + /// Evaluates the function or member. + /// + /// The input. + /// The position. + /// true if the input is a valid function or variable, otherwise false. + public virtual bool EvaluateFunctionOrMember(string input, int position) => false; + + /// + /// Gets the default operators. + /// + /// An array with the operators to use for the tokenizer. + public virtual Operator[] GetDefaultOperators() => new[] + { + new Operator {Name = "=", Precedence = 1}, + new Operator {Name = "!=", Precedence = 1}, + new Operator {Name = ">", Precedence = 2}, + new Operator {Name = "<", Precedence = 2}, + new Operator {Name = ">=", Precedence = 2}, + new Operator {Name = "<=", Precedence = 2}, + new Operator {Name = "+", Precedence = 3}, + new Operator {Name = "&", Precedence = 3}, + new Operator {Name = "-", Precedence = 3}, + new Operator {Name = "*", Precedence = 4}, + new Operator {Name = "/", Precedence = 4}, + new Operator {Name = "\\", Precedence = 4}, + new Operator {Name = "^", Precedence = 4}, + }; + + /// + /// Shunting the yard. + /// + /// if set to true [include function stopper] (Token type Wall). + /// + /// Enumerable of the token in in. + /// + /// + /// Wrong token + /// or + /// Mismatched parenthesis. + /// + public virtual IEnumerable ShuntingYard(bool includeFunctionStopper = true) + { + var stack = new Stack(); + + foreach (var tok in Tokens) + { + switch (tok.Type) + { + case TokenType.Number: + case TokenType.Variable: + case TokenType.String: + yield return tok; + break; + case TokenType.Function: + stack.Push(tok); + break; + case TokenType.Operator: + while (stack.Any() && stack.Peek().Type == TokenType.Operator && + CompareOperators(tok.Value, stack.Peek().Value)) + yield return stack.Pop(); + + stack.Push(tok); + break; + case TokenType.Comma: + while (stack.Any() && (stack.Peek().Type != TokenType.Comma && + stack.Peek().Type != TokenType.Parenthesis)) + yield return stack.Pop(); + + break; + case TokenType.Parenthesis: + if (tok.Value == OpenFuncStr) + { + if (stack.Any() && stack.Peek().Type == TokenType.Function) + { + if (includeFunctionStopper) + yield return new Token(TokenType.Wall, tok.Value); + } + + stack.Push(tok); + } + else + { + while (stack.Peek().Value != OpenFuncStr) + yield return stack.Pop(); + + stack.Pop(); + + if (stack.Any() && stack.Peek().Type == TokenType.Function) + { + yield return stack.Pop(); + } + } + + break; + default: + throw new InvalidOperationException("Wrong token"); + } + } + + while (stack.Any()) + { + var tok = stack.Pop(); + if (tok.Type == TokenType.Parenthesis) + throw new InvalidOperationException("Mismatched parenthesis"); + + yield return tok; + } + } + + private static bool CompareOperators(Operator op1, Operator op2) => op1.RightAssociative + ? op1.Precedence < op2.Precedence + : op1.Precedence <= op2.Precedence; + + private void Tokenize(string input) + { + if (!ValidateInput(input, out var startIndex)) + { + return; + } + + for (var i = startIndex; i < input.Length; i++) + { + if (char.IsWhiteSpace(input, i)) continue; + + if (input[i] == CommaChar) + { + Tokens.Add(new Token(TokenType.Comma, new string(new[] { input[i] }))); + continue; + } + + if (input[i] == StringQuotedChar) + { + i = ExtractString(input, i); + continue; + } + + if (char.IsLetter(input, i) || EvaluateFunctionOrMember(input, i)) + { + i = ExtractFunctionOrMember(input, i); + + continue; + } + + if (char.IsNumber(input, i) || ( + input[i] == NegativeChar && + ((Tokens.Any() && Tokens.Last().Type != TokenType.Number) || !Tokens.Any()))) + { + i = ExtractNumber(input, i); + continue; + } + + if (input[i] == OpenFuncChar || + input[i] == CloseFuncChar) + { + Tokens.Add(new Token(TokenType.Parenthesis, new string(new[] { input[i] }))); + continue; + } + + i = ExtractOperator(input, i); + } + } + + private int ExtractData( + string input, + int i, + Func tokenTypeEvaluation, + Func evaluation, + int right = 0, + int left = -1) + { + var charCount = 0; + for (var j = i + right; j < input.Length; j++) + { + if (evaluation(input[j])) + break; + + charCount++; + } + + // Extract and set the value + var value = input.SliceLength(i + right, charCount); + Tokens.Add(new Token(tokenTypeEvaluation(value), value)); + + i += charCount + left; + return i; + } + + private int ExtractOperator(string input, int i) => + ExtractData(input, i, x => TokenType.Operator, x => x == OpenFuncChar || + x == CommaChar || + x == PeriodChar || + x == StringQuotedChar || + char.IsWhiteSpace(x) || + char.IsNumber(x)); + + private int ExtractFunctionOrMember(string input, int i) => + ExtractData(input, i, ResolveFunctionOrMemberType, x => x == OpenFuncChar || + x == CloseFuncChar || + x == CommaChar || + char.IsWhiteSpace(x)); + + private int ExtractNumber(string input, int i) => + ExtractData(input, i, x => TokenType.Number, + x => !char.IsNumber(x) && x != PeriodChar && x != NegativeChar); + + private int ExtractString(string input, int i) + { + var length = ExtractData(input, i, x => TokenType.String, x => x == StringQuotedChar, 1, 1); + + // open string, report issue + if (length == input.Length && input[length - 1] != StringQuotedChar) + throw new FormatException($"Parser error (Position {i}): Expected '\"' but got '{input[length - 1]}'."); + + return length; + } + + private bool CompareOperators(string op1, string op2) + => CompareOperators(GetOperatorOrDefault(op1), GetOperatorOrDefault(op2)); + + private Operator GetOperatorOrDefault(string op) + => _operators.FirstOrDefault(x => x.Name == op) ?? new Operator { Name = op, Precedence = 0 }; + } + + /// + /// Represents an operator with precedence. + /// + public class Operator + { + /// + /// Gets or sets the name. + /// + /// + /// The name. + /// + public string Name { get; set; } + + /// + /// Gets or sets the precedence. + /// + /// + /// The precedence. + /// + public int Precedence { get; set; } + + /// + /// Gets or sets a value indicating whether [right associative]. + /// + /// + /// true if [right associative]; otherwise, false. + /// + public bool RightAssociative { get; set; } + } + + /// + /// Represents a Token structure. + /// + public struct Token + { + /// + /// Initializes a new instance of the struct. + /// + /// The type. + /// The value. + public Token(TokenType type, string value) + { + Type = type; + Value = type == TokenType.Function || type == TokenType.Operator ? value.ToLowerInvariant() : value; + } + + /// + /// Gets or sets the type. + /// + /// + /// The type. + /// + public TokenType Type { get; set; } + + /// + /// Gets the value. + /// + /// + /// The value. + /// + public string Value { get; } + } + + /// + /// Enums the token types. + /// + public enum TokenType + { + /// + /// The number + /// + Number, + + /// + /// The string + /// + String, + + /// + /// The variable + /// + Variable, + + /// + /// The function + /// + Function, + + /// + /// The parenthesis + /// + Parenthesis, + + /// + /// The operator + /// + Operator, + + /// + /// The comma + /// + Comma, + + /// + /// The wall, used to specified the end of argument list of the following function + /// + Wall, + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Abstractions/ViewModelBase.cs b/Unosquare.Swan.Lite/Abstractions/ViewModelBase.cs new file mode 100644 index 0000000..5328465 --- /dev/null +++ b/Unosquare.Swan.Lite/Abstractions/ViewModelBase.cs @@ -0,0 +1,127 @@ +namespace Unosquare.Swan.Lite.Abstractions +{ + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.ComponentModel; + using System.Linq; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + + /// + /// A base class for implementing models that fire notifications when their properties change. + /// This class is ideal for implementing MVVM driven UIs. + /// + /// + public abstract class ViewModelBase : INotifyPropertyChanged + { + private readonly ConcurrentDictionary QueuedNotifications = new ConcurrentDictionary(); + private readonly bool UseDeferredNotifications; + + /// + /// Initializes a new instance of the class. + /// + /// Set to true to use deferred notifications in the background. + protected ViewModelBase(bool useDeferredNotifications) + { + UseDeferredNotifications = useDeferredNotifications; + } + + /// + /// Initializes a new instance of the class. + /// + protected ViewModelBase() + : this(false) + { + // placeholder + } + + /// + /// Occurs when a property value changes. + /// + /// + public event PropertyChangedEventHandler PropertyChanged; + + /// Checks if a property already matches a desired value. Sets the property and + /// notifies listeners only when necessary. + /// Type of the property. + /// Reference to a property with both getter and setter. + /// Desired value for the property. + /// Name of the property used to notify listeners. This + /// value is optional and can be provided automatically when invoked from compilers that + /// support CallerMemberName. + /// An rray of property names to notify in addition to notifying the changes on the current property name. + /// True if the value was changed, false if the existing value matched the + /// desired value. + protected bool SetProperty(ref T storage, T value, [CallerMemberName] string propertyName = "", string[] notifyAlso = null) + { + if (EqualityComparer.Default.Equals(storage, value)) + return false; + + storage = value; + NotifyPropertyChanged(propertyName, notifyAlso); + return true; + } + + /// + /// Notifies one or more properties changed. + /// + /// The property names. + protected void NotifyPropertyChanged(params string[] propertyNames) => NotifyPropertyChanged(null, propertyNames); + + /// + /// Notifies one or more properties changed. + /// + /// The main property. + /// The auxiliary properties. + private void NotifyPropertyChanged(string mainProperty, string[] auxiliaryProperties) + { + // Queue property notification + if (string.IsNullOrWhiteSpace(mainProperty) == false) + QueuedNotifications[mainProperty] = true; + + // Set the state for notification properties + if (auxiliaryProperties != null) + { + foreach (var property in auxiliaryProperties) + { + if (string.IsNullOrWhiteSpace(property) == false) + QueuedNotifications[property] = true; + } + } + + // Depending on operation mode, either fire the notifications in the background + // or fire them immediately + if (UseDeferredNotifications) + Task.Run(() => NotifyQueuedProperties()); + else + NotifyQueuedProperties(); + } + + /// + /// Notifies the queued properties and resets the property name to a non-queued stated. + /// + private void NotifyQueuedProperties() + { + // get a snapshot of property names. + var propertyNames = QueuedNotifications.Keys.ToArray(); + + // Iterate through the properties + foreach (var property in propertyNames) + { + // don't notify if we don't have a change + if (!QueuedNotifications[property]) continue; + + // notify and reset queued state to false + try { OnPropertyChanged(property); } + finally { QueuedNotifications[property] = false; } + } + } + + /// + /// Called when a property changes its backing value. + /// + /// Name of the property. + private void OnPropertyChanged(string propertyName) => + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName ?? string.Empty)); + } +} diff --git a/Unosquare.Swan.Lite/AtomicBoolean.cs b/Unosquare.Swan.Lite/AtomicBoolean.cs new file mode 100644 index 0000000..bb1e27b --- /dev/null +++ b/Unosquare.Swan.Lite/AtomicBoolean.cs @@ -0,0 +1,26 @@ +namespace Unosquare.Swan +{ + using Abstractions; + + /// + /// Fast, atomic boolean combining interlocked to write value and volatile to read values. + /// + public sealed class AtomicBoolean : AtomicTypeBase + { + /// + /// Initializes a new instance of the class. + /// + /// if set to true [initial value]. + public AtomicBoolean(bool initialValue = default) + : base(initialValue ? 1 : 0) + { + // placeholder + } + + /// + protected override bool FromLong(long backingValue) => backingValue != 0; + + /// + protected override long ToLong(bool value) => value ? 1 : 0; + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/AtomicDouble.cs b/Unosquare.Swan.Lite/AtomicDouble.cs new file mode 100644 index 0000000..9699d76 --- /dev/null +++ b/Unosquare.Swan.Lite/AtomicDouble.cs @@ -0,0 +1,29 @@ +namespace Unosquare.Swan +{ + using System; + using Abstractions; + + /// + /// Fast, atomic double combining interlocked to write value and volatile to read values. + /// + public sealed class AtomicDouble : AtomicTypeBase + { + /// + /// Initializes a new instance of the class. + /// + /// if set to true [initial value]. + public AtomicDouble(double initialValue = default) + : base(BitConverter.DoubleToInt64Bits(initialValue)) + { + // placeholder + } + + /// + protected override double FromLong(long backingValue) => + BitConverter.Int64BitsToDouble(backingValue); + + /// + protected override long ToLong(double value) => + BitConverter.DoubleToInt64Bits(value); + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/AtomicInteger.cs b/Unosquare.Swan.Lite/AtomicInteger.cs new file mode 100644 index 0000000..cb44e47 --- /dev/null +++ b/Unosquare.Swan.Lite/AtomicInteger.cs @@ -0,0 +1,29 @@ +namespace Unosquare.Swan +{ + using System; + using Abstractions; + + /// + /// Represents an atomically readable or writable integer. + /// + public class AtomicInteger : AtomicTypeBase + { + /// + /// Initializes a new instance of the class. + /// + /// if set to true [initial value]. + public AtomicInteger(int initialValue = default) + : base(Convert.ToInt64(initialValue)) + { + // placeholder + } + + /// + protected override int FromLong(long backingValue) => + Convert.ToInt32(backingValue); + + /// + protected override long ToLong(int value) => + Convert.ToInt64(value); + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/AtomicLong.cs b/Unosquare.Swan.Lite/AtomicLong.cs new file mode 100644 index 0000000..8506cc6 --- /dev/null +++ b/Unosquare.Swan.Lite/AtomicLong.cs @@ -0,0 +1,26 @@ +namespace Unosquare.Swan +{ + using Abstractions; + + /// + /// Fast, atomioc long combining interlocked to write value and volatile to read values. + /// + public sealed class AtomicLong : AtomicTypeBase + { + /// + /// Initializes a new instance of the class. + /// + /// if set to true [initial value]. + public AtomicLong(long initialValue = default) + : base(initialValue) + { + // placeholder + } + + /// + protected override long FromLong(long backingValue) => backingValue; + + /// + protected override long ToLong(long value) => value; + } +} diff --git a/Unosquare.Swan.Lite/Attributes/ArgumentOptionAttribute.cs b/Unosquare.Swan.Lite/Attributes/ArgumentOptionAttribute.cs new file mode 100644 index 0000000..c7267ae --- /dev/null +++ b/Unosquare.Swan.Lite/Attributes/ArgumentOptionAttribute.cs @@ -0,0 +1,102 @@ +namespace Unosquare.Swan.Attributes +{ + using System; + + /// + /// Models an option specification. + /// Based on CommandLine (Copyright 2005-2015 Giacomo Stelluti Scala and Contributors.). + /// + [AttributeUsage(AttributeTargets.Property)] + public sealed class ArgumentOptionAttribute + : Attribute + { + /// + /// Initializes a new instance of the class. + /// The default long name will be inferred from target property. + /// + public ArgumentOptionAttribute() + : this(string.Empty, string.Empty) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The long name of the option. + public ArgumentOptionAttribute(string longName) + : this(string.Empty, longName) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The short name of the option. + /// The long name of the option or null if not used. + public ArgumentOptionAttribute(char shortName, string longName) + : this(new string(shortName, 1), longName) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The short name of the option.. + public ArgumentOptionAttribute(char shortName) + : this(new string(shortName, 1), string.Empty) + { + } + + private ArgumentOptionAttribute(string shortName, string longName) + { + ShortName = shortName ?? throw new ArgumentNullException(nameof(shortName)); + LongName = longName ?? throw new ArgumentNullException(nameof(longName)); + } + + /// + /// Gets long name of this command line option. This name is usually a single English word. + /// + /// + /// The long name. + /// + public string LongName { get; } + + /// + /// Gets a short name of this command line option, made of one character. + /// + /// + /// The short name. + /// + public string ShortName { get; } + + /// + /// When applying attribute to target properties, + /// it allows you to split an argument and consume its content as a sequence. + /// + public char Separator { get; set; } = '\0'; + + /// + /// Gets or sets mapped property default value. + /// + /// + /// The default value. + /// + public object DefaultValue { get; set; } + + /// + /// Gets or sets a value indicating whether a command line option is required. + /// + /// + /// true if required; otherwise, false. + /// + public bool Required { get; set; } + + /// + /// Gets or sets a short description of this command line option. Usually a sentence summary. + /// + /// + /// The help text. + /// + public string HelpText { get; set; } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Attributes/CopyableAttribute.cs b/Unosquare.Swan.Lite/Attributes/CopyableAttribute.cs new file mode 100644 index 0000000..0fb0f29 --- /dev/null +++ b/Unosquare.Swan.Lite/Attributes/CopyableAttribute.cs @@ -0,0 +1,13 @@ +namespace Unosquare.Swan.Attributes +{ + using System; + + /// + /// Represents an attribute to select which properties are copyable between objects. + /// + /// + [AttributeUsage(AttributeTargets.Property)] + public class CopyableAttribute : Attribute + { + } +} diff --git a/Unosquare.Swan.Lite/Attributes/JsonPropertyAttribute.cs b/Unosquare.Swan.Lite/Attributes/JsonPropertyAttribute.cs new file mode 100644 index 0000000..88b8060 --- /dev/null +++ b/Unosquare.Swan.Lite/Attributes/JsonPropertyAttribute.cs @@ -0,0 +1,39 @@ +namespace Unosquare.Swan.Attributes +{ + using System; + + /// + /// An attribute used to help setup a property behavior when serialize/deserialize JSON. + /// + /// + [AttributeUsage(AttributeTargets.Property)] + public sealed class JsonPropertyAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// Name of the property. + /// if set to true [ignored]. + public JsonPropertyAttribute(string propertyName, bool ignored = false) + { + PropertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName)); + Ignored = ignored; + } + + /// + /// Gets or sets the name of the property. + /// + /// + /// The name of the property. + /// + public string PropertyName { get; } + + /// + /// Gets or sets a value indicating whether this is ignored. + /// + /// + /// true if ignored; otherwise, false. + /// + public bool Ignored { get; } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Attributes/PropertyDisplayAttribute.cs b/Unosquare.Swan.Lite/Attributes/PropertyDisplayAttribute.cs new file mode 100644 index 0000000..db0e0f2 --- /dev/null +++ b/Unosquare.Swan.Lite/Attributes/PropertyDisplayAttribute.cs @@ -0,0 +1,54 @@ +namespace Unosquare.Swan.Attributes +{ + using System; + + /// + /// An attribute used to include additional information to a Property for serialization. + /// + /// Previously we used DisplayAttribute from DataAnnotation. + /// + /// + [AttributeUsage(AttributeTargets.Property)] + public sealed class PropertyDisplayAttribute : Attribute + { + /// + /// Gets or sets the name. + /// + /// + /// The name. + /// + public string Name { get; set; } + + /// + /// Gets or sets the description. + /// + /// + /// The description. + /// + public string Description { get; set; } + + /// + /// Gets or sets the name of the group. + /// + /// + /// The name of the group. + /// + public string GroupName { get; set; } + + /// + /// Gets or sets the default value. + /// + /// + /// The default value. + /// + public object DefaultValue { get; set; } + + /// + /// Gets or sets the format string to call with method ToString. + /// + /// + /// The format. + /// + public string Format { get; set; } + } +} diff --git a/Unosquare.Swan.Lite/Attributes/StructEndiannessAttribute.cs b/Unosquare.Swan.Lite/Attributes/StructEndiannessAttribute.cs new file mode 100644 index 0000000..fed256c --- /dev/null +++ b/Unosquare.Swan.Lite/Attributes/StructEndiannessAttribute.cs @@ -0,0 +1,30 @@ +namespace Unosquare.Swan.Attributes +{ + using System; + + /// + /// An attribute used to help conversion structs back and forth into arrays of bytes via + /// extension methods included in this library ToStruct and ToBytes. + /// + /// + [AttributeUsage(AttributeTargets.Field | AttributeTargets.Struct)] + public class StructEndiannessAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The endianness. + public StructEndiannessAttribute(Endianness endianness) + { + Endianness = endianness; + } + + /// + /// Gets the endianness. + /// + /// + /// The endianness. + /// + public Endianness Endianness { get; } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Attributes/Validators.cs b/Unosquare.Swan.Lite/Attributes/Validators.cs new file mode 100644 index 0000000..3c86c74 --- /dev/null +++ b/Unosquare.Swan.Lite/Attributes/Validators.cs @@ -0,0 +1,133 @@ +namespace Unosquare.Swan.Attributes +{ + using System; + using System.Text.RegularExpressions; + using Abstractions; + + /// + /// Regex validator. + /// + [AttributeUsage(AttributeTargets.Property)] + public class MatchAttribute : Attribute, IValidator + { + /// + /// Initializes a new instance of the class. + /// + /// A regex string. + /// The error message. + /// Expression. + public MatchAttribute(string regex, string errorMessage = null) + { + Expression = regex ?? throw new ArgumentNullException(nameof(Expression)); + ErrorMessage = errorMessage ?? "String does not match the specified regular expression"; + } + + /// + /// The string regex used to find a match. + /// + public string Expression { get; } + + /// + public string ErrorMessage { get; internal set; } + + /// + public bool IsValid(T value) + { + if (Equals(value, default(T))) + return false; + + return !(value is string) + ? throw new ArgumentException("Property is not a string") + : Regex.IsMatch(value.ToString(), Expression); + } + } + + /// + /// Email validator. + /// + [AttributeUsage(AttributeTargets.Property)] + public class EmailAttribute : MatchAttribute + { + private const string EmailRegExp = + @"^(?("")("".+?(? + /// Initializes a new instance of the class. + /// + /// The error message. + public EmailAttribute(string errorMessage = null) + : base(EmailRegExp, errorMessage ?? "String is not an email") + { + } + } + + /// + /// A not null validator. + /// + [AttributeUsage(AttributeTargets.Property)] + public class NotNullAttribute : Attribute, IValidator + { + /// + public string ErrorMessage => "Value is null"; + + /// + public bool IsValid(T value) => !Equals(default(T), value); + } + + /// + /// A range constraint validator. + /// + [AttributeUsage(AttributeTargets.Property)] + public class RangeAttribute : Attribute, IValidator + { + /// + /// Initializes a new instance of the class. + /// Constructor that takes integer minimum and maximum values. + /// + /// The minimum value. + /// The maximum value. + public RangeAttribute(int min, int max) + { + if (min >= max) + throw new InvalidOperationException("Maximum value must be greater than minimum"); + + Maximum = max; + Minimum = min; + } + + /// + /// Initializes a new instance of the class. + /// Constructor that takes double minimum and maximum values. + /// + /// The minimum value. + /// The maximum value. + public RangeAttribute(double min, double max) + { + if (min >= max) + throw new InvalidOperationException("Maximum value must be greater than minimum"); + + Maximum = max; + Minimum = min; + } + + /// + public string ErrorMessage => "Value is not within the specified range"; + + /// + /// Maximum value for the range. + /// + public IComparable Maximum { get; } + + /// + /// Minimum value for the range. + /// + public IComparable Minimum { get; } + + /// + public bool IsValid(T value) + => value is IComparable comparable + ? comparable.CompareTo(Minimum) >= 0 && comparable.CompareTo(Maximum) <= 0 + : throw new ArgumentException(nameof(value)); + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Attributes/VerbOptionAttribute.cs b/Unosquare.Swan.Lite/Attributes/VerbOptionAttribute.cs new file mode 100644 index 0000000..9b9554f --- /dev/null +++ b/Unosquare.Swan.Lite/Attributes/VerbOptionAttribute.cs @@ -0,0 +1,40 @@ +namespace Unosquare.Swan.Attributes +{ + using System; + + /// + /// Models a verb option. + /// + [AttributeUsage(AttributeTargets.Property)] + public sealed class VerbOptionAttribute : Attribute + { + /// + /// Initializes a new instance of the class. + /// + /// The name. + /// name. + public VerbOptionAttribute(string name) + { + Name = name ?? throw new ArgumentNullException(nameof(name)); + } + + /// + /// Gets the name of the verb option. + /// + /// + /// Name. + /// + public string Name { get; } + + /// + /// Gets or sets a short description of this command line verb. Usually a sentence summary. + /// + /// + /// The help text. + /// + public string HelpText { get; set; } + + /// + public override string ToString() => $" {Name}\t\t{HelpText}"; + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/ArgumentParse.Validator.cs b/Unosquare.Swan.Lite/Components/ArgumentParse.Validator.cs new file mode 100644 index 0000000..6241c66 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/ArgumentParse.Validator.cs @@ -0,0 +1,159 @@ +namespace Unosquare.Swan.Components +{ + using System.Linq; + using System.Reflection; + using Attributes; + using System; + using System.Collections.Generic; + + /// + /// Provides methods to parse command line arguments. + /// Based on CommandLine (Copyright 2005-2015 Giacomo Stelluti Scala and Contributors.). + /// + public partial class ArgumentParser + { + private sealed class Validator + { + private readonly object _instance; + private readonly IEnumerable _args; + private readonly List _updatedList = new List(); + private readonly ArgumentParserSettings _settings; + + private readonly PropertyInfo[] _properties; + + public Validator( + PropertyInfo[] properties, + IEnumerable args, + object instance, + ArgumentParserSettings settings) + { + _args = args; + _instance = instance; + _settings = settings; + _properties = properties; + + PopulateInstance(); + SetDefaultValues(); + GetRequiredList(); + } + + public List UnknownList { get; } = new List(); + public List RequiredList { get; } = new List(); + + public bool IsValid() => (_settings.IgnoreUnknownArguments || !UnknownList.Any()) && !RequiredList.Any(); + + public IEnumerable GetPropertiesOptions() + => _properties.Select(p => Runtime.AttributeCache.RetrieveOne(p)) + .Where(x => x != null); + + private void GetRequiredList() + { + foreach (var targetProperty in _properties) + { + var optionAttr = Runtime.AttributeCache.RetrieveOne(targetProperty); + + if (optionAttr == null || optionAttr.Required == false) + continue; + + if (targetProperty.GetValue(_instance) == null) + { + RequiredList.Add(optionAttr.LongName ?? optionAttr.ShortName); + } + } + } + + private void SetDefaultValues() + { + foreach (var targetProperty in _properties.Except(_updatedList)) + { + var optionAttr = Runtime.AttributeCache.RetrieveOne(targetProperty); + + var defaultValue = optionAttr?.DefaultValue; + + if (defaultValue == null) + continue; + + if (SetPropertyValue(targetProperty, defaultValue.ToString(), _instance, optionAttr)) + _updatedList.Add(targetProperty); + } + } + + private void PopulateInstance() + { + const char dash = '-'; + var propertyName = string.Empty; + + foreach (var arg in _args) + { + var ignoreSetValue = string.IsNullOrWhiteSpace(propertyName); + + if (ignoreSetValue) + { + if (string.IsNullOrWhiteSpace(arg) || arg[0] != dash) continue; + + propertyName = arg.Substring(1); + + if (!string.IsNullOrWhiteSpace(propertyName) && propertyName[0] == dash) + propertyName = propertyName.Substring(1); + } + + var targetProperty = TryGetProperty(propertyName); + + if (targetProperty == null) + { + // Skip if the property is not found + UnknownList.Add(propertyName); + continue; + } + + if (!ignoreSetValue && SetPropertyValue(targetProperty, arg, _instance)) + { + _updatedList.Add(targetProperty); + propertyName = string.Empty; + } + else if (targetProperty.PropertyType == typeof(bool)) + { + // If the arg is a boolean property set it to true. + targetProperty.SetValue(_instance, true); + + _updatedList.Add(targetProperty); + propertyName = string.Empty; + } + } + + if (!string.IsNullOrEmpty(propertyName)) + { + UnknownList.Add(propertyName); + } + } + + private bool SetPropertyValue( + PropertyInfo targetProperty, + string propertyValueString, + object result, + ArgumentOptionAttribute optionAttr = null) + { + if (targetProperty.PropertyType.GetTypeInfo().IsEnum) + { + var parsedValue = Enum.Parse( + targetProperty.PropertyType, + propertyValueString, + _settings.CaseInsensitiveEnumValues); + + targetProperty.SetValue(result, Enum.ToObject(targetProperty.PropertyType, parsedValue)); + + return true; + } + + return targetProperty.PropertyType.IsArray + ? targetProperty.TrySetArray(propertyValueString.Split(optionAttr?.Separator ?? ','), result) + : targetProperty.TrySetBasicType(propertyValueString, result); + } + + private PropertyInfo TryGetProperty(string propertyName) + => _properties.FirstOrDefault(p => + string.Equals(Runtime.AttributeCache.RetrieveOne(p)?.LongName, propertyName, _settings.NameComparer) || + string.Equals(Runtime.AttributeCache.RetrieveOne(p)?.ShortName, propertyName, _settings.NameComparer)); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/ArgumentParser.TypeResolver.cs b/Unosquare.Swan.Lite/Components/ArgumentParser.TypeResolver.cs new file mode 100644 index 0000000..8834342 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/ArgumentParser.TypeResolver.cs @@ -0,0 +1,57 @@ +namespace Unosquare.Swan.Components +{ + using System.Linq; + using System.Reflection; + using Attributes; + using System; + + /// + /// Provides methods to parse command line arguments. + /// + public partial class ArgumentParser + { + private sealed class TypeResolver + { + private readonly string _selectedVerb; + + private PropertyInfo[] _properties; + + public TypeResolver(string selectedVerb) + { + _selectedVerb = selectedVerb; + } + + public PropertyInfo[] GetProperties() => _properties?.Any() == true ? _properties : null; + + public object GetOptionsObject(T instance) + { + _properties = Runtime.PropertyTypeCache.RetrieveAllProperties(true).ToArray(); + + if (!_properties.Any(x => x.GetCustomAttributes(typeof(VerbOptionAttribute), false).Any())) + return instance; + + var selectedVerb = string.IsNullOrWhiteSpace(_selectedVerb) + ? null + : _properties.FirstOrDefault(x => + Runtime.AttributeCache.RetrieveOne(x).Name.Equals(_selectedVerb)); + + if (selectedVerb == null) return null; + + var type = instance.GetType(); + + var verbProperty = type.GetProperty(selectedVerb.Name); + + if (verbProperty?.GetValue(instance) == null) + { + var propertyInstance = Activator.CreateInstance(selectedVerb.PropertyType); + verbProperty?.SetValue(instance, propertyInstance); + } + + _properties = Runtime.PropertyTypeCache.RetrieveAllProperties(selectedVerb.PropertyType, true) + .ToArray(); + + return verbProperty?.GetValue(instance); + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/ArgumentParser.cs b/Unosquare.Swan.Lite/Components/ArgumentParser.cs new file mode 100644 index 0000000..c468e35 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/ArgumentParser.cs @@ -0,0 +1,230 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Collections.Generic; + using Attributes; + using System.Linq; + + /// + /// Provides methods to parse command line arguments. + /// Based on CommandLine (Copyright 2005-2015 Giacomo Stelluti Scala and Contributors.). + /// + /// + /// The following example shows how to parse CLI arguments into objects. + /// + /// class Example + /// { + /// using System; + /// using Unosquare.Swan; + /// using Unosquare.Swan.Attributes; + /// + /// static void Main(string[] args) + /// { + /// // create an instance of the Options class + /// var options = new Options(); + /// + /// // parse the supplied command-line arguments into the options object + /// var res = Runtime.ArgumentParser.ParseArguments(args, options); + /// } + /// + /// class Options + /// { + /// [ArgumentOption('v', "verbose", HelpText = "Set verbose mode.")] + /// public bool Verbose { get; set; } + /// + /// [ArgumentOption('u', Required = true, HelpText = "Set user name.")] + /// public string Username { get; set; } + /// + /// [ArgumentOption('n', "names", Separator = ',', + /// Required = true, HelpText = "A list of files separated by a comma")] + /// public string[] Files { get; set; } + /// + /// [ArgumentOption('p', "port", DefaultValue = 22, HelpText = "Set port.")] + /// public int Port { get; set; } + /// + /// [ArgumentOption("color", DefaultValue = ConsoleColor.Red, + /// HelpText = "Set a color.")] + /// public ConsoleColor Color { get; set; } + /// } + /// } + /// + /// The following code describes how to parse CLI verbs. + /// + /// class Example2 + /// { + /// using Unosquare.Swan; + /// using Unosquare.Swan.Attributes; + /// + /// static void Main(string[] args) + /// { + /// // create an instance of the VerbOptions class + /// var options = new VerbOptions(); + /// + /// // parse the supplied command-line arguments into the options object + /// var res = Runtime.ArgumentParser.ParseArguments(args, options); + /// + /// // if there were no errors parsing + /// if (res) + /// { + /// if(options.Run != null) + /// { + /// // run verb was selected + /// } + /// + /// if(options.Print != null) + /// { + /// // print verb was selected + /// } + /// } + /// + /// // flush all error messages + /// Terminal.Flush(); + /// } + /// + /// class VerbOptions + /// { + /// [VerbOption("run", HelpText = "Run verb.")] + /// public RunVerbOption Run { get; set; } + /// + /// [VerbOption("print", HelpText = "Print verb.")] + /// public PrintVerbOption Print { get; set; } + /// } + /// + /// class RunVerbOption + /// { + /// [ArgumentOption('o', "outdir", HelpText = "Output directory", + /// DefaultValue = "", Required = false)] + /// public string OutDir { get; set; } + /// } + /// + /// class PrintVerbOption + /// { + /// [ArgumentOption('t', "text", HelpText = "Text to print", + /// DefaultValue = "", Required = false)] + /// public string Text { get; set; } + /// } + /// } + /// + /// + public partial class ArgumentParser + { + /// + /// Initializes a new instance of the class. + /// + public ArgumentParser() + : this(new ArgumentParserSettings()) + { + } + + /// + /// Initializes a new instance of the class, + /// configurable with using a delegate. + /// + /// The parse settings. + public ArgumentParser(ArgumentParserSettings parseSettings) + { + Settings = parseSettings ?? throw new ArgumentNullException(nameof(parseSettings)); + } + + /// + /// Gets the instance that implements in use. + /// + /// + /// The settings. + /// + public ArgumentParserSettings Settings { get; } + + /// + /// Parses a string array of command line arguments constructing values in an instance of type . + /// + /// The type of the options. + /// The arguments. + /// The instance. + /// + /// true if was converted successfully; otherwise, false. + /// + /// + /// The exception that is thrown when a null reference (Nothing in Visual Basic) + /// is passed to a method that does not accept it as a valid argument. + /// + /// + /// The exception that is thrown when a method call is invalid for the object's current state. + /// + public bool ParseArguments(IEnumerable args, T instance) + { + if (args == null) + throw new ArgumentNullException(nameof(args)); + + if (Equals(instance, default(T))) + throw new ArgumentNullException(nameof(instance)); + + var typeResolver = new TypeResolver(args.FirstOrDefault()); + var options = typeResolver.GetOptionsObject(instance); + + if (options == null) + { + ReportUnknownVerb(); + return false; + } + + var properties = typeResolver.GetProperties(); + + if (properties == null) + throw new InvalidOperationException($"Type {typeof(T).Name} is not valid"); + + var validator = new Validator(properties, args, options, Settings); + + if (validator.IsValid()) + return true; + + ReportIssues(validator); + return false; + } + + private static void ReportUnknownVerb() + { + "No verb was specified".WriteLine(ConsoleColor.Red); + "Valid verbs:".WriteLine(ConsoleColor.Cyan); + + Runtime.PropertyTypeCache.RetrieveAllProperties(true) + .Select(x => Runtime.AttributeCache.RetrieveOne(x)) + .Where(x => x != null) + .ToList() + .ForEach(x => x.ToString().WriteLine(ConsoleColor.Cyan)); + } + + private void ReportIssues(Validator validator) + { +#if !NETSTANDARD1_3 + if (Settings.WriteBanner) + Runtime.WriteWelcomeBanner(); +#endif + + var options = validator.GetPropertiesOptions(); + + foreach (var option in options) + { + string.Empty.WriteLine(); + + // TODO: If Enum list values + var shortName = string.IsNullOrWhiteSpace(option.ShortName) ? string.Empty : $"-{option.ShortName}"; + var longName = string.IsNullOrWhiteSpace(option.LongName) ? string.Empty : $"--{option.LongName}"; + var comma = string.IsNullOrWhiteSpace(shortName) || string.IsNullOrWhiteSpace(longName) + ? string.Empty + : ", "; + var defaultValue = option.DefaultValue == null ? string.Empty : $"(Default: {option.DefaultValue}) "; + + $" {shortName}{comma}{longName}\t\t{defaultValue}{option.HelpText}".WriteLine(ConsoleColor.Cyan); + } + + string.Empty.WriteLine(); + " --help\t\tDisplay this help screen.".WriteLine(ConsoleColor.Cyan); + + if (validator.UnknownList.Any()) + $"Unknown arguments: {string.Join(", ", validator.UnknownList)}".WriteLine(ConsoleColor.Red); + + if (validator.RequiredList.Any()) + $"Required arguments: {string.Join(", ", validator.RequiredList)}".WriteLine(ConsoleColor.Red); + } + } +} diff --git a/Unosquare.Swan.Lite/Components/ArgumentParserSettings.cs b/Unosquare.Swan.Lite/Components/ArgumentParserSettings.cs new file mode 100644 index 0000000..f3f4b25 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/ArgumentParserSettings.cs @@ -0,0 +1,53 @@ +namespace Unosquare.Swan.Components +{ + using System; + + /// + /// Provides settings for . + /// Based on CommandLine (Copyright 2005-2015 Giacomo Stelluti Scala and Contributors.). + /// + public class ArgumentParserSettings + { + /// + /// Gets or sets a value indicating whether [write banner]. + /// + /// + /// true if [write banner]; otherwise, false. + /// + public bool WriteBanner { get; set; } = true; + + /// + /// Gets or sets a value indicating whether perform case sensitive comparisons. + /// Note that case insensitivity only applies to parameters, not the values + /// assigned to them (for example, enum parsing). + /// + /// + /// true if [case sensitive]; otherwise, false. + /// + public bool CaseSensitive { get; set; } = false; + + /// + /// Gets or sets a value indicating whether perform case sensitive comparisons of values. + /// Note that case insensitivity only applies to values, not the parameters. + /// + /// + /// true if [case insensitive enum values]; otherwise, false. + /// + public bool CaseInsensitiveEnumValues { get; set; } = true; + + /// + /// Gets or sets a value indicating whether the parser shall move on to the next argument and ignore the given argument if it + /// encounter an unknown arguments. + /// + /// + /// true to allow parsing the arguments with different class options that do not have all the arguments. + /// + /// + /// This allows fragmented version class parsing, useful for project with add-on where add-ons also requires command line arguments but + /// when these are unknown by the main program at build time. + /// + public bool IgnoreUnknownArguments { get; set; } = true; + + internal StringComparison NameComparer => CaseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase; + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/Benchmark.cs b/Unosquare.Swan.Lite/Components/Benchmark.cs new file mode 100644 index 0000000..b970bc9 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/Benchmark.cs @@ -0,0 +1,130 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; + using System.Text; + + /// + /// A simple benchmarking class. + /// + /// + /// The following code demonstrates how to create a simple benchmark. + /// + /// namespace Examples.Benchmark.Simple + /// { + /// using Unosquare.Swan.Components; + /// + /// public class SimpleBenchmark + /// { + /// public static void Main() + /// { + /// using (Benchmark.Start("Test")) + /// { + /// // do some logic in here + /// } + /// + /// // dump results into a string + /// var results = Benchmark.Dump(); + /// } + /// } + /// + /// } + /// + /// + public static class Benchmark + { + private static readonly object SyncLock = new object(); + private static readonly Dictionary> Measures = new Dictionary>(); + + /// + /// Starts measuring with the given identifier. + /// + /// The identifier. + /// A disposable object that when disposed, adds a benchmark result. + public static IDisposable Start(string identifier) => new BenchmarkUnit(identifier); + + /// + /// Outputs the benchmark statistics. + /// + /// A string containing human-readable statistics. + public static string Dump() + { + var builder = new StringBuilder(); + + lock (SyncLock) + { + foreach (var kvp in Measures) + { + builder.Append($"BID: {kvp.Key,-30} | ") + .Append($"CNT: {kvp.Value.Count,6} | ") + .Append($"AVG: {kvp.Value.Average(t => t.TotalMilliseconds),8:0.000} ms. | ") + .Append($"MAX: {kvp.Value.Max(t => t.TotalMilliseconds),8:0.000} ms. | ") + .Append($"MIN: {kvp.Value.Min(t => t.TotalMilliseconds),8:0.000} ms. | ") + .Append(Environment.NewLine); + } + } + + return builder.ToString().TrimEnd(); + } + + /// + /// Adds the specified result to the given identifier. + /// + /// The identifier. + /// The elapsed. + private static void Add(string identifier, TimeSpan elapsed) + { + lock (SyncLock) + { + if (Measures.ContainsKey(identifier) == false) + Measures[identifier] = new List(1024 * 1024); + + Measures[identifier].Add(elapsed); + } + } + + /// + /// Represents a disposable benchmark unit. + /// + /// + private sealed class BenchmarkUnit : IDisposable + { + private readonly string _identifier; + private bool _isDisposed; // To detect redundant calls + private Stopwatch _stopwatch = new Stopwatch(); + + /// + /// Initializes a new instance of the class. + /// + /// The identifier. + public BenchmarkUnit(string identifier) + { + _identifier = identifier; + _stopwatch.Start(); + } + + /// + public void Dispose() => Dispose(true); + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + private void Dispose(bool alsoManaged) + { + if (_isDisposed) return; + + if (alsoManaged) + { + Add(_identifier, _stopwatch.Elapsed); + _stopwatch?.Stop(); + } + + _stopwatch = null; + _isDisposed = true; + } + } + } +} diff --git a/Unosquare.Swan.Lite/Components/CollectionCacheRepository.cs b/Unosquare.Swan.Lite/Components/CollectionCacheRepository.cs new file mode 100644 index 0000000..1438acd --- /dev/null +++ b/Unosquare.Swan.Lite/Components/CollectionCacheRepository.cs @@ -0,0 +1,44 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + + /// + /// A thread-safe collection cache repository for types. + /// + /// The type of member to cache. + public class CollectionCacheRepository + { + private readonly Lazy>> _data = + new Lazy>>(() => + new ConcurrentDictionary>(), true); + + /// + /// Determines whether the cache contains the specified key. + /// + /// The key. + /// true if the cache contains the key, otherwise false. + public bool ContainsKey(Type key) => _data.Value.ContainsKey(key); + + /// + /// Retrieves the properties stored for the specified type. + /// If the properties are not available, it calls the factory method to retrieve them + /// and returns them as an array of PropertyInfo. + /// + /// The key. + /// The factory. + /// + /// An array of the properties stored for the specified type. + /// + /// type. + public IEnumerable Retrieve(Type key, Func> factory) + { + if (factory == null) + throw new ArgumentNullException(nameof(factory)); + + return _data.Value.GetOrAdd(key, k => factory.Invoke(k).Where(item => item != null)); + } + } +} diff --git a/Unosquare.Swan.Lite/Components/EnumHelper.cs b/Unosquare.Swan.Lite/Components/EnumHelper.cs new file mode 100644 index 0000000..c4c6e6d --- /dev/null +++ b/Unosquare.Swan.Lite/Components/EnumHelper.cs @@ -0,0 +1,171 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Abstractions; + + /// + /// Provide Enumerations helpers with internal cache. + /// + public class EnumHelper + : SingletonBase>> + { + /// + /// Gets all the names and enumerators from a specific Enum type. + /// + /// The type of the attribute to be retrieved. + /// A tuple of enumerator names and their value stored for the specified type. + public static IEnumerable> Retrieve() + where T : struct, IConvertible + { + return Instance.Retrieve(typeof(T), t => Enum.GetValues(t) + .Cast() + .Select(item => Tuple.Create(Enum.GetName(t, item), item))); + } + + /// + /// Gets the cached items with the enum item value. + /// + /// The type of enumeration. + /// if set to true [humanize]. + /// + /// A collection of Type/Tuple pairs + /// that represents items with the enum item value. + /// + public static IEnumerable> GetItemsWithValue(bool humanize = true) + where T : struct, IConvertible + { + return Retrieve() + .Select(x => Tuple.Create((int) x.Item2, humanize ? x.Item1.Humanize() : x.Item1)); + } + + /// + /// Gets the flag values. + /// + /// The type of the enum. + /// The value. + /// if set to true [ignore zero]. + /// + /// A list of values in the flag. + /// + public static IEnumerable GetFlagValues(int value, bool ignoreZero = false) + where TEnum : struct, IConvertible + { + return Retrieve() + .Select(x => (int) x.Item2) + .When(() => ignoreZero, q => q.Where(f => f != 0)) + .Where(x => (x & value) == x); + } + + /// + /// Gets the flag values. + /// + /// The type of the enum. + /// The value. + /// if set to true [ignore zero]. + /// + /// A list of values in the flag. + /// + public static IEnumerable GetFlagValues(long value, bool ignoreZero = false) + where TEnum : struct, IConvertible + { + return Retrieve() + .Select(x => (long) x.Item2) + .When(() => ignoreZero, q => q.Where(f => f != 0)) + .Where(x => (x & value) == x); + } + + /// + /// Gets the flag values. + /// + /// The type of the enum. + /// The value. + /// if set to true [ignore zero]. + /// + /// A list of values in the flag. + /// + public static IEnumerable GetFlagValues(byte value, bool ignoreZero = false) + where TEnum : struct, IConvertible + { + return Retrieve() + .Select(x => (byte) x.Item2) + .When(() => ignoreZero, q => q.Where(f => f != 0)) + .Where(x => (x & value) == x); + } + + /// + /// Gets the flag names. + /// + /// The type of the enum. + /// the value. + /// if set to true [ignore zero]. + /// if set to true [humanize]. + /// + /// A list of flag names. + /// + public static IEnumerable GetFlagNames(int value, bool ignoreZero = false, bool humanize = true) + where TEnum : struct, IConvertible + { + return Retrieve() + .When(() => ignoreZero, q => q.Where(f => (int) f.Item2 != 0)) + .Where(x => ((int) x.Item2 & value) == (int) x.Item2) + .Select(x => humanize ? x.Item1.Humanize() : x.Item1); + } + + /// + /// Gets the flag names. + /// + /// The type of the enum. + /// The value. + /// if set to true [ignore zero]. + /// if set to true [humanize]. + /// + /// A list of flag names. + /// + public static IEnumerable GetFlagNames(long value, bool ignoreZero = false, bool humanize = true) + where TEnum : struct, IConvertible + { + return Retrieve() + .When(() => ignoreZero, q => q.Where(f => (long) f.Item2 != 0)) + .Where(x => ((long) x.Item2 & value) == (long) x.Item2) + .Select(x => humanize ? x.Item1.Humanize() : x.Item1); + } + + /// + /// Gets the flag names. + /// + /// The type of the enum. + /// The value. + /// if set to true [ignore zero]. + /// if set to true [humanize]. + /// + /// A list of flag names. + /// + public static IEnumerable GetFlagNames(byte value, bool ignoreZero = false, bool humanize = true) + where TEnum : struct, IConvertible + { + return Retrieve() + .When(() => ignoreZero, q => q.Where(f => (byte) f.Item2 != 0)) + .Where(x => ((byte) x.Item2 & value) == (byte) x.Item2) + .Select(x => humanize ? x.Item1.Humanize() : x.Item1); + } + + /// + /// Gets the cached items with the enum item index. + /// + /// The type of enumeration. + /// if set to true [humanize]. + /// + /// A collection of Type/Tuple pairs that represents items with the enum item value. + /// + public static IEnumerable> GetItemsWithIndex(bool humanize = true) + where T : struct, IConvertible + { + var i = 0; + + return Retrieve() + .Select(x => Tuple.Create(i++, humanize ? x.Item1.Humanize() : x.Item1)); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/ObjectComparer.cs b/Unosquare.Swan.Lite/Components/ObjectComparer.cs new file mode 100644 index 0000000..e28b9ea --- /dev/null +++ b/Unosquare.Swan.Lite/Components/ObjectComparer.cs @@ -0,0 +1,193 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + /// + /// Represents a quick object comparer using the public properties of an object + /// or the public members in a structure. + /// + public static class ObjectComparer + { + /// + /// Compare if two variables of the same type are equal. + /// + /// The type of objects to compare. + /// The left. + /// The right. + /// true if the variables are equal; otherwise, false. + public static bool AreEqual(T left, T right) => AreEqual(left, right, typeof(T)); + + /// + /// Compare if two variables of the same type are equal. + /// + /// The left. + /// The right. + /// Type of the target. + /// + /// true if the variables are equal; otherwise, false. + /// + /// targetType. + public static bool AreEqual(object left, object right, Type targetType) + { + if (targetType == null) + throw new ArgumentNullException(nameof(targetType)); + + if (Definitions.BasicTypesInfo.ContainsKey(targetType)) + return Equals(left, right); + + if (targetType.IsValueType() || targetType.IsArray) + return AreStructsEqual(left, right, targetType); + + return AreObjectsEqual(left, right, targetType); + } + + /// + /// Compare if two objects of the same type are equal. + /// + /// The type of objects to compare. + /// The left. + /// The right. + /// true if the objects are equal; otherwise, false. + public static bool AreObjectsEqual(T left, T right) + where T : class + { + return AreObjectsEqual(left, right, typeof(T)); + } + + /// + /// Compare if two objects of the same type are equal. + /// + /// The left. + /// The right. + /// Type of the target. + /// true if the objects are equal; otherwise, false. + /// targetType. + public static bool AreObjectsEqual(object left, object right, Type targetType) + { + if (targetType == null) + throw new ArgumentNullException(nameof(targetType)); + + var properties = Runtime.PropertyTypeCache.RetrieveAllProperties(targetType).ToArray(); + + foreach (var propertyTarget in properties) + { + var targetPropertyGetMethod = propertyTarget.GetCacheGetMethod(); + + if (propertyTarget.PropertyType.IsArray) + { + var leftObj = targetPropertyGetMethod(left) as IEnumerable; + var rightObj = targetPropertyGetMethod(right) as IEnumerable; + + if (!AreEnumerationsEquals(leftObj, rightObj)) + return false; + } + else + { + if (!Equals(targetPropertyGetMethod(left), targetPropertyGetMethod(right))) + return false; + } + } + + return true; + } + + /// + /// Compare if two structures of the same type are equal. + /// + /// The type of structs to compare. + /// The left. + /// The right. + /// true if the structs are equal; otherwise, false. + public static bool AreStructsEqual(T left, T right) + where T : struct + { + return AreStructsEqual(left, right, typeof(T)); + } + + /// + /// Compare if two structures of the same type are equal. + /// + /// The left. + /// The right. + /// Type of the target. + /// + /// true if the structs are equal; otherwise, false. + /// + /// targetType. + public static bool AreStructsEqual(object left, object right, Type targetType) + { + if (targetType == null) + throw new ArgumentNullException(nameof(targetType)); + + var fields = new List(Runtime.FieldTypeCache.RetrieveAllFields(targetType)) + .Union(Runtime.PropertyTypeCache.RetrieveAllProperties(targetType)); + + foreach (var targetMember in fields) + { + switch (targetMember) + { + case FieldInfo field: + if (Equals(field.GetValue(left), field.GetValue(right)) == false) + return false; + break; + case PropertyInfo property: + var targetPropertyGetMethod = property.GetCacheGetMethod(); + + if (targetPropertyGetMethod != null && + !Equals(targetPropertyGetMethod(left), targetPropertyGetMethod(right))) + return false; + break; + } + } + + return true; + } + + /// + /// Compare if two enumerables are equal. + /// + /// The type of enums to compare. + /// The left. + /// The right. + /// + /// True if two specified types are equal; otherwise, false. + /// + /// + /// left + /// or + /// right. + /// + public static bool AreEnumerationsEquals(T left, T right) + where T : IEnumerable + { + if (Equals(left, default(T))) + throw new ArgumentNullException(nameof(left)); + + if (Equals(right, default(T))) + throw new ArgumentNullException(nameof(right)); + + var leftEnumerable = left.Cast().ToArray(); + var rightEnumerable = right.Cast().ToArray(); + + if (leftEnumerable.Length != rightEnumerable.Length) + return false; + + for (var i = 0; i < leftEnumerable.Length; i++) + { + var leftEl = leftEnumerable[i]; + var rightEl = rightEnumerable[i]; + + if (!AreEqual(leftEl, rightEl, leftEl.GetType())) + { + return false; + } + } + + return true; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/ObjectMap.cs b/Unosquare.Swan.Lite/Components/ObjectMap.cs new file mode 100644 index 0000000..7743e26 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/ObjectMap.cs @@ -0,0 +1,116 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Linq.Expressions; + using System.Reflection; + using Abstractions; + + /// + /// Represents an object map. + /// + /// The type of the source. + /// The type of the destination. + /// + public class ObjectMap : IObjectMap + { + internal ObjectMap(IEnumerable intersect) + { + SourceType = typeof(TSource); + DestinationType = typeof(TDestination); + Map = intersect.ToDictionary( + property => DestinationType.GetProperty(property.Name), + property => new List {SourceType.GetProperty(property.Name)}); + } + + /// + public Dictionary> Map { get; } + + /// + public Type SourceType { get; } + + /// + public Type DestinationType { get; } + + /// + /// Maps the property. + /// + /// The type of the destination property. + /// The type of the source property. + /// The destination property. + /// The source property. + /// + /// An object map representation of type of the destination property + /// and type of the source property. + /// + public ObjectMap MapProperty + ( + Expression> destinationProperty, + Expression> sourceProperty) + { + var propertyDestinationInfo = (destinationProperty.Body as MemberExpression)?.Member as PropertyInfo; + + if (propertyDestinationInfo == null) + { + throw new ArgumentException("Invalid destination expression", nameof(destinationProperty)); + } + + var sourceMembers = GetSourceMembers(sourceProperty); + + if (sourceMembers.Any() == false) + { + throw new ArgumentException("Invalid source expression", nameof(sourceProperty)); + } + + // reverse order + sourceMembers.Reverse(); + Map[propertyDestinationInfo] = sourceMembers; + + return this; + } + + /// + /// Removes the map property. + /// + /// The type of the destination property. + /// The destination property. + /// + /// An object map representation of type of the destination property + /// and type of the source property. + /// + /// Invalid destination expression. + public ObjectMap RemoveMapProperty( + Expression> destinationProperty) + { + var propertyDestinationInfo = (destinationProperty.Body as MemberExpression)?.Member as PropertyInfo; + + if (propertyDestinationInfo == null) + throw new ArgumentException("Invalid destination expression", nameof(destinationProperty)); + + if (Map.ContainsKey(propertyDestinationInfo)) + { + Map.Remove(propertyDestinationInfo); + } + + return this; + } + + private static List GetSourceMembers(Expression> sourceProperty) + { + var sourceMembers = new List(); + var initialExpression = sourceProperty.Body as MemberExpression; + + while (true) + { + var propertySourceInfo = initialExpression?.Member as PropertyInfo; + + if (propertySourceInfo == null) break; + sourceMembers.Add(propertySourceInfo); + initialExpression = initialExpression.Expression as MemberExpression; + } + + return sourceMembers; + } + } +} diff --git a/Unosquare.Swan.Lite/Components/ObjectMapper.cs b/Unosquare.Swan.Lite/Components/ObjectMapper.cs new file mode 100644 index 0000000..76f38e8 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/ObjectMapper.cs @@ -0,0 +1,411 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Abstractions; + + /// + /// Represents an AutoMapper-like object to map from one object type + /// to another using defined properties map or using the default behaviour + /// to copy same named properties from one object to another. + /// + /// The extension methods like CopyPropertiesTo use the default behaviour. + /// + /// + /// The following code explains how to map an object's properties into an instance of type T. + /// + /// using Unosquare.Swan + /// + /// class Example + /// { + /// class Person + /// { + /// public string Name { get; set; } + /// public int Age { get; set; } + /// } + /// + /// static void Main() + /// { + /// var obj = new { Name = "Søren", Age = 42 }; + /// + /// var person = Runtime.ObjectMapper.Map<Person>(obj); + /// } + /// } + /// + /// The following code explains how to explicitly map certain properties. + /// + /// using Unosquare.Swan + /// + /// class Example + /// { + /// class User + /// { + /// public string Name { get; set; } + /// public Role Role { get; set; } + /// } + /// + /// public class Role + /// { + /// public string Name { get; set; } + /// } + /// + /// class UserDto + /// { + /// public string Name { get; set; } + /// public string Role { get; set; } + /// } + /// + /// static void Main() + /// { + /// // create a User object + /// var person = + /// new User { Name = "Phillip", Role = new Role { Name = "Admin" } }; + /// + /// // create an Object Mapper + /// var mapper = new ObjectMapper(); + /// + /// // map the User's Role.Name to UserDto's Role + /// mapper.CreateMap<User, UserDto>() + /// .MapProperty(d => d.Role, x => x.Role.Name); + /// + /// // apply the previous map and retrieve a UserDto object + /// var destination = mapper.Map<UserDto>(person); + /// } + /// } + /// + /// + public class ObjectMapper + { + private readonly List _maps = new List(); + + /// + /// Copies the specified source. + /// + /// The source. + /// The target. + /// The properties to copy. + /// The ignore properties. + /// + /// Copied properties count. + /// + /// + /// source + /// or + /// target. + /// + public static int Copy( + object source, + object target, + string[] propertiesToCopy = null, + string[] ignoreProperties = null) + { + if (source == null) + throw new ArgumentNullException(nameof(source)); + + if (target == null) + throw new ArgumentNullException(nameof(target)); + + return Copy( + target, + propertiesToCopy, + ignoreProperties, + GetSourceMap(source)); + } + + /// + /// Copies the specified source. + /// + /// The source. + /// The target. + /// The properties to copy. + /// The ignore properties. + /// + /// Copied properties count. + /// + /// + /// source + /// or + /// target. + /// + public static int Copy( + IDictionary source, + object target, + string[] propertiesToCopy = null, + string[] ignoreProperties = null) + { + if (source == null) + throw new ArgumentNullException(nameof(source)); + + if (target == null) + throw new ArgumentNullException(nameof(target)); + + return Copy( + target, + propertiesToCopy, + ignoreProperties, + source.ToDictionary( + x => x.Key.ToLowerInvariant(), + x => new TypeValuePair(typeof(object), x.Value))); + } + + /// + /// Creates the map. + /// + /// The type of the source. + /// The type of the destination. + /// + /// An object map representation of type of the destination property + /// and type of the source property. + /// + /// + /// You can't create an existing map + /// or + /// Types doesn't match. + /// + public ObjectMap CreateMap() + { + if (_maps.Any(x => x.SourceType == typeof(TSource) && x.DestinationType == typeof(TDestination))) + { + throw new InvalidOperationException("You can't create an existing map"); + } + + var sourceType = Runtime.PropertyTypeCache.RetrieveAllProperties(true); + var destinationType = Runtime.PropertyTypeCache.RetrieveAllProperties(true); + + var intersect = sourceType.Intersect(destinationType, new PropertyInfoComparer()).ToArray(); + + if (intersect.Any() == false) + { + throw new InvalidOperationException("Types doesn't match"); + } + + var map = new ObjectMap(intersect); + + _maps.Add(map); + + return map; + } + + /// + /// Maps the specified source. + /// + /// The type of the destination. + /// The source. + /// if set to true [automatic resolve]. + /// + /// A new instance of the map. + /// + /// source. + /// You can't map from type {source.GetType().Name} to {typeof(TDestination).Name}. + public TDestination Map(object source, bool autoResolve = true) + { + if (source == null) + { + throw new ArgumentNullException(nameof(source)); + } + + var destination = Activator.CreateInstance(); + var map = _maps + .FirstOrDefault(x => x.SourceType == source.GetType() && x.DestinationType == typeof(TDestination)); + + if (map != null) + { + foreach (var property in map.Map) + { + var finalSource = property.Value.Aggregate(source, + (current, sourceProperty) => sourceProperty.GetValue(current)); + + property.Key.SetValue(destination, finalSource); + } + } + else + { + if (!autoResolve) + { + throw new InvalidOperationException( + $"You can't map from type {source.GetType().Name} to {typeof(TDestination).Name}"); + } + + // Missing mapping, try to use default behavior + Copy(source, destination); + } + + return destination; + } + + private static int Copy( + object target, + IEnumerable propertiesToCopy, + IEnumerable ignoreProperties, + Dictionary sourceProperties) + { + // Filter properties + var requiredProperties = propertiesToCopy? + .Where(p => !string.IsNullOrWhiteSpace(p)) + .Select(p => p.ToLowerInvariant()); + + var ignoredProperties = ignoreProperties? + .Where(p => !string.IsNullOrWhiteSpace(p)) + .Select(p => p.ToLowerInvariant()); + + var properties = Runtime.PropertyTypeCache + .RetrieveFilteredProperties(target.GetType(), true, x => x.CanWrite); + + return properties + .Select(x => x.Name) + .Distinct() + .ToDictionary(x => x.ToLowerInvariant(), x => properties.First(y => y.Name == x)) + .Where(x => sourceProperties.Keys.Contains(x.Key)) + .When(() => requiredProperties != null, q => q.Where(y => requiredProperties.Contains(y.Key))) + .When(() => ignoredProperties != null, q => q.Where(y => !ignoredProperties.Contains(y.Key))) + .ToDictionary(x => x.Value, x => sourceProperties[x.Key]) + .Sum(x => TrySetValue(x, target) ? 1 : 0); + } + + private static bool TrySetValue(KeyValuePair property, object target) + { + try + { + SetValue(property, target); + return true; + } + catch + { + // swallow + } + + return false; + } + + private static void SetValue(KeyValuePair property, object target) + { + if (property.Value.Type.GetTypeInfo().IsEnum) + { + property.Key.SetValue(target, + Enum.ToObject(property.Key.PropertyType, property.Value.Value)); + + return; + } + + if (!property.Value.Type.IsValueType() && property.Key.PropertyType == property.Value.Type) + { + property.Key.SetValue(target, GetValue(property.Value.Value, property.Key.PropertyType)); + + return; + } + + if (property.Key.PropertyType == typeof(bool)) + { + property.Key.SetValue(target, + Convert.ToBoolean(property.Value.Value)); + + return; + } + + property.Key.TrySetBasicType(property.Value.Value, target); + } + + private static object GetValue(object source, Type targetType) + { + if (source == null) + return null; + + object target = null; + + source.CreateTarget(targetType, false, ref target); + + switch (source) + { + case string _: + target = source; + break; + case IList sourceList when target is Array targetArray: + for (var i = 0; i < sourceList.Count; i++) + { + try + { + targetArray.SetValue( + sourceList[i].GetType().IsValueType() + ? sourceList[i] + : sourceList[i].CopyPropertiesToNew(), i); + } + catch + { + // ignored + } + } + + break; + case IList sourceList when target is IList targetList: + var addMethod = targetType.GetMethods() + .FirstOrDefault( + m => m.Name.Equals(Formatters.Json.AddMethodName) && m.IsPublic && + m.GetParameters().Length == 1); + + if (addMethod == null) return target; + + foreach (var item in sourceList) + { + try + { + targetList.Add(item.GetType().IsValueType() + ? item + : item.CopyPropertiesToNew()); + } + catch + { + // ignored + } + } + + break; + default: + source.CopyPropertiesTo(target); + break; + } + + return target; + } + + private static Dictionary GetSourceMap(object source) + { + // select distinct properties because they can be duplicated by inheritance + var sourceProperties = Runtime.PropertyTypeCache + .RetrieveFilteredProperties(source.GetType(), true, x => x.CanRead) + .ToArray(); + + return sourceProperties + .Select(x => x.Name) + .Distinct() + .ToDictionary( + x => x.ToLowerInvariant(), + x => new TypeValuePair(sourceProperties.First(y => y.Name == x).PropertyType, + sourceProperties.First(y => y.Name == x).GetValue(source))); + } + + internal class TypeValuePair + { + public TypeValuePair(Type type, object value) + { + Type = type; + Value = value; + } + + public Type Type { get; } + + public object Value { get; } + } + + internal class PropertyInfoComparer : IEqualityComparer + { + public bool Equals(PropertyInfo x, PropertyInfo y) + => x != null && y != null && x.Name == y.Name && x.PropertyType == y.PropertyType; + + public int GetHashCode(PropertyInfo obj) + => obj.Name.GetHashCode() + obj.PropertyType.Name.GetHashCode(); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/ObjectValidator.cs b/Unosquare.Swan.Lite/Components/ObjectValidator.cs new file mode 100644 index 0000000..1e42cf8 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/ObjectValidator.cs @@ -0,0 +1,204 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Linq; + using System.Collections.Concurrent; + using System.Collections.Generic; + using Abstractions; + + /// + /// Represents an object validator. + /// + /// + /// The following code describes how to perform a simple object validation. + /// + /// using Unosquare.Swan.Components; + /// + /// class Example + /// { + /// public static void Main() + /// { + /// // create an instance of ObjectValidator + /// var obj = new ObjectValidator(); + /// + /// // Add a validation to the 'Simple' class with a custom error message + /// obj.AddValidator<Simple>(x => + /// !string.IsNullOrEmpty(x.Name), "Name must not be empty"); + /// + /// // check if object is valid + /// var res = obj.IsValid(new Simple { Name = "Name" }); + /// } + /// + /// class Simple + /// { + /// public string Name { get; set; } + /// } + /// } + /// + /// + /// The following code shows of to validate an object with a custom validator and some attributes using the Runtime ObjectValidator singleton. + /// + /// using Unosquare.Swan.Components; + /// + /// class Example + /// { + /// public static void Main() + /// { + /// // create an instance of ObjectValidator + /// Runtime.ObjectValidator + /// .AddValidator<Simple>(x => + /// !x.Name.Equals("Name"), "Name must not be 'Name'"); + /// + /// // validate object + /// var res = Runtime.ObjectValidator + /// .Validate(new Simple{ Name = "name", Number = 5, Email ="email@mail.com"}) + /// } + /// + /// class Simple + /// { + /// [NotNull] + /// public string Name { get; set; } + /// + /// [Range(1, 10)] + /// public int Number { get; set; } + /// + /// [Email] + /// public string Email { get; set; } + /// } + /// } + /// + /// + public class ObjectValidator + { + private readonly ConcurrentDictionary>> _predicates = + new ConcurrentDictionary>>(); + + /// + /// Validates an object given the specified validators and attributes. + /// + /// The type of the object. + /// The object. + /// A validation result. + public ObjectValidationResult Validate(T obj) + { + var errorList = new ObjectValidationResult(); + ValidateObject(obj, false, errorList.Add); + + return errorList; + } + + /// + /// Validates an object given the specified validators and attributes. + /// + /// The type. + /// The object. + /// + /// true if the specified object is valid; otherwise, false. + /// + /// obj. + public bool IsValid(T obj) => ValidateObject(obj); + + /// + /// Adds a validator to a specific class. + /// + /// The type of the object. + /// The predicate that will be evaluated. + /// The message. + /// + /// predicate + /// or + /// message. + /// + public void AddValidator(Predicate predicate, string message) + where T : class + { + if (predicate == null) + throw new ArgumentNullException(nameof(predicate)); + + if (string.IsNullOrEmpty(message)) + throw new ArgumentNullException(message); + + if (!_predicates.TryGetValue(typeof(T), out var existing)) + { + existing = new List>(); + _predicates[typeof(T)] = existing; + } + + existing.Add(Tuple.Create((Delegate) predicate, message)); + } + + private bool ValidateObject(T obj, bool returnOnError = true, Action action = null) + { + if (Equals(obj, null)) + throw new ArgumentNullException(nameof(obj)); + + if (_predicates.ContainsKey(typeof(T))) + { + foreach (var validation in _predicates[typeof(T)]) + { + if ((bool) validation.Item1.DynamicInvoke(obj)) continue; + + action?.Invoke(string.Empty, validation.Item2); + if (returnOnError) return false; + } + } + + var properties = Runtime.AttributeCache.RetrieveFromType(typeof(IValidator)); + + foreach (var prop in properties) + { + foreach (var attribute in prop.Value) + { + var val = (IValidator) attribute; + + if (val.IsValid(prop.Key.GetValue(obj, null))) continue; + + action?.Invoke(prop.Key.Name, val.ErrorMessage); + if (returnOnError) return false; + } + } + + return true; + } + } + + /// + /// Defines a validation result containing all validation errors and their properties. + /// + public class ObjectValidationResult + { + /// + /// A list of errors. + /// + public List Errors { get; set; } = new List(); + + /// + /// true if there are no errors; otherwise, false. + /// + public bool IsValid => !Errors.Any(); + + /// + /// Adds an error with a specified property name. + /// + /// The property name. + /// The error message. + public void Add(string propertyName, string errorMessage) => + Errors.Add(new ValidationError {ErrorMessage = errorMessage, PropertyName = propertyName}); + + /// + /// Defines a validation error. + /// + public class ValidationError + { + /// + /// The property name. + /// + public string PropertyName { get; set; } + + /// + /// The message error. + /// + public string ErrorMessage { get; set; } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/SyncLockerFactory.cs b/Unosquare.Swan.Lite/Components/SyncLockerFactory.cs new file mode 100644 index 0000000..633dfcf --- /dev/null +++ b/Unosquare.Swan.Lite/Components/SyncLockerFactory.cs @@ -0,0 +1,197 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Threading; + using Abstractions; + + /// + /// Provides factory methods to create synchronized reader-writer locks + /// that support a generalized locking and releasing api and syntax. + /// + public static class SyncLockerFactory + { + #region Enums and Interfaces + + /// + /// Enumerates the locking operations. + /// + private enum LockHolderType + { + Read, + Write, + } + + /// + /// Defines methods for releasing locks. + /// + private interface ISyncReleasable + { + /// + /// Releases the writer lock. + /// + void ReleaseWriterLock(); + + /// + /// Releases the reader lock. + /// + void ReleaseReaderLock(); + } + + #endregion + + #region Factory Methods + +#if !NETSTANDARD1_3 + /// + /// Creates a reader-writer lock backed by a standard ReaderWriterLock. + /// + /// The synchronized locker. + public static ISyncLocker Create() => new SyncLocker(); +#else + /// + /// Creates a reader-writer lock backed by a standard ReaderWriterLockSlim when + /// running at NETSTANDARD 1.3. + /// + /// The synchronized locker + public static ISyncLocker Create() => new SyncLockerSlim(); +#endif + + /// + /// Creates a reader-writer lock backed by a ReaderWriterLockSlim. + /// + /// The synchronized locker. + public static ISyncLocker CreateSlim() => new SyncLockerSlim(); + + /// + /// Creates a reader-writer lock. + /// + /// if set to true it uses the Slim version of a reader-writer lock. + /// The Sync Locker. + public static ISyncLocker Create(bool useSlim) => useSlim ? CreateSlim() : Create(); + + #endregion + + #region Private Classes + + /// + /// The lock releaser. Calling the dispose method releases the lock entered by the parent SyncLocker. + /// + /// + private sealed class SyncLockReleaser : IDisposable + { + private readonly ISyncReleasable _parent; + private readonly LockHolderType _operation; + + private bool _isDisposed; + + /// + /// Initializes a new instance of the class. + /// + /// The parent. + /// The operation. + public SyncLockReleaser(ISyncReleasable parent, LockHolderType operation) + { + _parent = parent; + _operation = operation; + } + + /// + public void Dispose() + { + if (_isDisposed) return; + _isDisposed = true; + + if (_operation == LockHolderType.Read) + _parent.ReleaseReaderLock(); + else + _parent.ReleaseWriterLock(); + } + } + +#if !NETSTANDARD1_3 + /// + /// The Sync Locker backed by a ReaderWriterLock. + /// + /// + /// + private sealed class SyncLocker : ISyncLocker, ISyncReleasable + { + private bool _isDisposed; + private ReaderWriterLock _locker = new ReaderWriterLock(); + + /// + public IDisposable AcquireReaderLock() + { + _locker?.AcquireReaderLock(Timeout.Infinite); + return new SyncLockReleaser(this, LockHolderType.Read); + } + + /// + public IDisposable AcquireWriterLock() + { + _locker?.AcquireWriterLock(Timeout.Infinite); + return new SyncLockReleaser(this, LockHolderType.Write); + } + + /// + public void ReleaseWriterLock() => _locker?.ReleaseWriterLock(); + + /// + public void ReleaseReaderLock() => _locker?.ReleaseReaderLock(); + + /// + public void Dispose() + { + if (_isDisposed) return; + _isDisposed = true; + _locker?.ReleaseLock(); + _locker = null; + } + } +#endif + + /// + /// The Sync Locker backed by ReaderWriterLockSlim. + /// + /// + /// + private sealed class SyncLockerSlim : ISyncLocker, ISyncReleasable + { + private bool _isDisposed; + + private ReaderWriterLockSlim _locker + = new ReaderWriterLockSlim(LockRecursionPolicy.SupportsRecursion); + + /// + public IDisposable AcquireReaderLock() + { + _locker?.EnterReadLock(); + return new SyncLockReleaser(this, LockHolderType.Read); + } + + /// + public IDisposable AcquireWriterLock() + { + _locker?.EnterWriteLock(); + return new SyncLockReleaser(this, LockHolderType.Write); + } + + /// + public void ReleaseWriterLock() => _locker?.ExitWriteLock(); + + /// + public void ReleaseReaderLock() => _locker?.ExitReadLock(); + + /// + public void Dispose() + { + if (_isDisposed) return; + _isDisposed = true; + _locker?.Dispose(); + _locker = null; + } + } + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/TimerControl.cs b/Unosquare.Swan.Lite/Components/TimerControl.cs new file mode 100644 index 0000000..09641f3 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/TimerControl.cs @@ -0,0 +1,63 @@ +#if !NETSTANDARD1_3 +namespace Unosquare.Swan.Components +{ + using System; + using System.Threading; + using Abstractions; + + /// + /// Use this singleton to wait for a specific TimeSpan or time. + /// + /// Internally this class will use a Timer and a ManualResetEvent to block until + /// the time condition is satisfied. + /// + /// + public class TimerControl : SingletonBase + { + private readonly Timer _innerTimer; + private readonly IWaitEvent _delayLock = WaitEventFactory.Create(true); + + /// + /// Initializes a new instance of the class. + /// + protected TimerControl() + { + _innerTimer = new Timer( + x => + { + try + { + _delayLock.Complete(); + _delayLock.Begin(); + } + catch + { + // ignore + } + }, + null, + 0, + 15); + } + + /// + /// Waits until the time is elapsed. + /// + /// The until date. + /// The cancellation token. + public void WaitUntil(DateTime untilDate, CancellationToken ct = default) + { + while (!ct.IsCancellationRequested && DateTime.UtcNow < untilDate) + _delayLock.Wait(); + } + + /// + /// Waits the specified wait time. + /// + /// The wait time. + /// The cancellation token. + public void Wait(TimeSpan waitTime, CancellationToken ct = default) => + WaitUntil(DateTime.UtcNow.Add(waitTime), ct); + } +} +#endif \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Components/WaitEventFactory.cs b/Unosquare.Swan.Lite/Components/WaitEventFactory.cs new file mode 100644 index 0000000..5116ee7 --- /dev/null +++ b/Unosquare.Swan.Lite/Components/WaitEventFactory.cs @@ -0,0 +1,222 @@ +#if !NETSTANDARD1_3 +namespace Unosquare.Swan.Components +{ + using System; + using System.Threading; + using Abstractions; + + /// + /// Provides a Manual Reset Event factory with a unified API. + /// + /// + /// The following example shows how to use the WaitEventFactory class. + /// + /// using Unosquare.Swan.Components; + /// + /// public class Example + /// { + /// // create a WaitEvent using the slim version + /// private static readonly IWaitEvent waitEvent = WaitEventFactory.CreateSlim(false); + /// + /// public static void Main() + /// { + /// Task.Factory.StartNew(() => + /// { + /// DoWork(1); + /// }); + /// + /// Task.Factory.StartNew(() => + /// { + /// DoWork(2); + /// }); + /// + /// // send first signal + /// waitEvent.Complete(); + /// waitEvent.Begin(); + /// + /// Thread.Sleep(TimeSpan.FromSeconds(2)); + /// + /// // send second signal + /// waitEvent.Complete(); + /// + /// Console.Readline(); + /// } + /// + /// public static void DoWork(int taskNumber) + /// { + /// $"Data retrieved:{taskNumber}".WriteLine(); + /// waitEvent.Wait(); + /// + /// Thread.Sleep(TimeSpan.FromSeconds(2)); + /// $"All finished up {taskNumber}".WriteLine(); + /// } + /// } + /// + /// + public static class WaitEventFactory + { + #region Factory Methods + + /// + /// Creates a Wait Event backed by a standard ManualResetEvent. + /// + /// if initially set to completed. Generally true. + /// The Wait Event. + public static IWaitEvent Create(bool isCompleted) => new WaitEvent(isCompleted); + + /// + /// Creates a Wait Event backed by a ManualResetEventSlim. + /// + /// if initially set to completed. Generally true. + /// The Wait Event. + public static IWaitEvent CreateSlim(bool isCompleted) => new WaitEventSlim(isCompleted); + + /// + /// Creates a Wait Event backed by a ManualResetEventSlim. + /// + /// if initially set to completed. Generally true. + /// if set to true creates a slim version of the wait event. + /// The Wait Event. + public static IWaitEvent Create(bool isCompleted, bool useSlim) => useSlim ? CreateSlim(isCompleted) : Create(isCompleted); + + #endregion + + #region Backing Classes + + /// + /// Defines a WaitEvent backed by a ManualResetEvent. + /// + private class WaitEvent : IWaitEvent + { + private ManualResetEvent _event; + + /// + /// Initializes a new instance of the class. + /// + /// if set to true [is completed]. + public WaitEvent(bool isCompleted) + { + _event = new ManualResetEvent(isCompleted); + } + + /// + public bool IsDisposed { get; private set; } + + /// + public bool IsValid + { + get + { + if (IsDisposed || _event == null) + return false; + + if (_event?.SafeWaitHandle?.IsClosed ?? true) + return false; + + return !(_event?.SafeWaitHandle?.IsInvalid ?? true); + } + } + + /// + public bool IsCompleted + { + get + { + if (IsValid == false) + return true; + + return _event?.WaitOne(0) ?? true; + } + } + + /// + public bool IsInProgress => !IsCompleted; + + /// + public void Begin() => _event?.Reset(); + + /// + public void Complete() => _event?.Set(); + + /// + void IDisposable.Dispose() + { + if (IsDisposed) return; + IsDisposed = true; + + _event?.Set(); + _event?.Dispose(); + _event = null; + } + + /// + public void Wait() => _event?.WaitOne(); + + /// + public bool Wait(TimeSpan timeout) => _event?.WaitOne(timeout) ?? true; + } + + /// + /// Defines a WaitEvent backed by a ManualResetEventSlim. + /// + private class WaitEventSlim : IWaitEvent + { + private ManualResetEventSlim _event; + + /// + /// Initializes a new instance of the class. + /// + /// if set to true [is completed]. + public WaitEventSlim(bool isCompleted) + { + _event = new ManualResetEventSlim(isCompleted); + } + + /// + public bool IsDisposed { get; private set; } + + /// + public bool IsValid + { + get + { + if (IsDisposed || _event?.WaitHandle?.SafeWaitHandle == null) return false; + + return !_event.WaitHandle.SafeWaitHandle.IsClosed && !_event.WaitHandle.SafeWaitHandle.IsInvalid; + } + } + + /// + public bool IsCompleted => IsValid == false || _event.IsSet; + + /// + public bool IsInProgress => !IsCompleted; + + /// + public void Begin() => _event?.Reset(); + + /// + public void Complete() => _event?.Set(); + + /// + void IDisposable.Dispose() + { + if (IsDisposed) return; + IsDisposed = true; + + _event?.Set(); + _event?.Dispose(); + _event = null; + } + + /// + public void Wait() => _event?.Wait(); + + /// + public bool Wait(TimeSpan timeout) => _event?.Wait(timeout) ?? true; + } + + #endregion + } +} +#endif \ No newline at end of file diff --git a/Unosquare.Swan.Lite/DateTimeSpan.cs b/Unosquare.Swan.Lite/DateTimeSpan.cs new file mode 100644 index 0000000..0f3735c --- /dev/null +++ b/Unosquare.Swan.Lite/DateTimeSpan.cs @@ -0,0 +1,174 @@ +namespace Unosquare.Swan +{ + using System; + + /// + /// Represents a struct of DateTimeSpan to compare dates and get in + /// separate fields the amount of time between those dates. + /// + /// Based on https://stackoverflow.com/a/9216404/1096693. + /// + public struct DateTimeSpan + { + /// + /// Initializes a new instance of the struct. + /// + /// The years. + /// The months. + /// The days. + /// The hours. + /// The minutes. + /// The seconds. + /// The milliseconds. + public DateTimeSpan(int years, int months, int days, int hours, int minutes, int seconds, int milliseconds) + { + Years = years; + Months = months; + Days = days; + Hours = hours; + Minutes = minutes; + Seconds = seconds; + Milliseconds = milliseconds; + } + + /// + /// Gets the years. + /// + /// + /// The years. + /// + public int Years { get; } + + /// + /// Gets the months. + /// + /// + /// The months. + /// + public int Months { get; } + + /// + /// Gets the days. + /// + /// + /// The days. + /// + public int Days { get; } + + /// + /// Gets the hours. + /// + /// + /// The hours. + /// + public int Hours { get; } + + /// + /// Gets the minutes. + /// + /// + /// The minutes. + /// + public int Minutes { get; } + + /// + /// Gets the seconds. + /// + /// + /// The seconds. + /// + public int Seconds { get; } + + /// + /// Gets the milliseconds. + /// + /// + /// The milliseconds. + /// + public int Milliseconds { get; } + + internal static DateTimeSpan CompareDates(DateTime date1, DateTime date2) + { + if (date2 < date1) + { + var sub = date1; + date1 = date2; + date2 = sub; + } + + var current = date1; + var years = 0; + var months = 0; + var days = 0; + + var phase = Phase.Years; + var span = new DateTimeSpan(); + var officialDay = current.Day; + + while (phase != Phase.Done) + { + switch (phase) + { + case Phase.Years: + if (current.AddYears(years + 1) > date2) + { + phase = Phase.Months; + current = current.AddYears(years); + } + else + { + years++; + } + + break; + case Phase.Months: + if (current.AddMonths(months + 1) > date2) + { + phase = Phase.Days; + current = current.AddMonths(months); + if (current.Day < officialDay && + officialDay <= DateTime.DaysInMonth(current.Year, current.Month)) + current = current.AddDays(officialDay - current.Day); + } + else + { + months++; + } + + break; + case Phase.Days: + if (current.AddDays(days + 1) > date2) + { + current = current.AddDays(days); + var timespan = date2 - current; + span = new DateTimeSpan( + years, + months, + days, + timespan.Hours, + timespan.Minutes, + timespan.Seconds, + timespan.Milliseconds); + phase = Phase.Done; + } + else + { + days++; + } + + break; + } + } + + return span; + } + + private enum Phase + { + Years, + Months, + Days, + Done, + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Definitions.Types.cs b/Unosquare.Swan.Lite/Definitions.Types.cs new file mode 100644 index 0000000..a96ef8a --- /dev/null +++ b/Unosquare.Swan.Lite/Definitions.Types.cs @@ -0,0 +1,132 @@ +namespace Unosquare.Swan +{ + using Reflection; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + + /// + /// Contains useful constants and definitions. + /// + public static partial class Definitions + { + #region Main Dictionary Definition + + /// + /// The basic types information. + /// + public static readonly Dictionary BasicTypesInfo = + new Dictionary + { + // Non-Nullables + {typeof(DateTime), new ExtendedTypeInfo()}, + {typeof(byte), new ExtendedTypeInfo()}, + {typeof(sbyte), new ExtendedTypeInfo()}, + {typeof(int), new ExtendedTypeInfo()}, + {typeof(uint), new ExtendedTypeInfo()}, + {typeof(short), new ExtendedTypeInfo()}, + {typeof(ushort), new ExtendedTypeInfo()}, + {typeof(long), new ExtendedTypeInfo()}, + {typeof(ulong), new ExtendedTypeInfo()}, + {typeof(float), new ExtendedTypeInfo()}, + {typeof(double), new ExtendedTypeInfo()}, + {typeof(char), new ExtendedTypeInfo()}, + {typeof(bool), new ExtendedTypeInfo()}, + {typeof(decimal), new ExtendedTypeInfo()}, + {typeof(Guid), new ExtendedTypeInfo()}, + + // Strings is also considered a basic type (it's the only basic reference type) + {typeof(string), new ExtendedTypeInfo()}, + + // Nullables + {typeof(DateTime?), new ExtendedTypeInfo()}, + {typeof(byte?), new ExtendedTypeInfo()}, + {typeof(sbyte?), new ExtendedTypeInfo()}, + {typeof(int?), new ExtendedTypeInfo()}, + {typeof(uint?), new ExtendedTypeInfo()}, + {typeof(short?), new ExtendedTypeInfo()}, + {typeof(ushort?), new ExtendedTypeInfo()}, + {typeof(long?), new ExtendedTypeInfo()}, + {typeof(ulong?), new ExtendedTypeInfo()}, + {typeof(float?), new ExtendedTypeInfo()}, + {typeof(double?), new ExtendedTypeInfo()}, + {typeof(char?), new ExtendedTypeInfo()}, + {typeof(bool?), new ExtendedTypeInfo()}, + {typeof(decimal?), new ExtendedTypeInfo()}, + {typeof(Guid?), new ExtendedTypeInfo()}, + + // Additional Types + {typeof(TimeSpan), new ExtendedTypeInfo()}, + {typeof(TimeSpan?), new ExtendedTypeInfo()}, + {typeof(IPAddress), new ExtendedTypeInfo()}, + }; + + #endregion + + /// + /// Contains all basic types, including string, date time, and all of their nullable counterparts. + /// + /// + /// All basic types. + /// + public static List AllBasicTypes { get; } = new List(BasicTypesInfo.Keys.ToArray()); + + /// + /// Gets all numeric types including their nullable counterparts. + /// Note that Booleans and Guids are not considered numeric types. + /// + /// + /// All numeric types. + /// + public static List AllNumericTypes { get; } = new List( + BasicTypesInfo + .Where(kvp => kvp.Value.IsNumeric) + .Select(kvp => kvp.Key).ToArray()); + + /// + /// Gets all numeric types without their nullable counterparts. + /// Note that Booleans and Guids are not considered numeric types. + /// + /// + /// All numeric value types. + /// + public static List AllNumericValueTypes { get; } = new List( + BasicTypesInfo + .Where(kvp => kvp.Value.IsNumeric && kvp.Value.IsNullableValueType == false) + .Select(kvp => kvp.Key).ToArray()); + + /// + /// Contains all basic value types. i.e. excludes string and nullables. + /// + /// + /// All basic value types. + /// + public static List AllBasicValueTypes { get; } = new List( + BasicTypesInfo + .Where(kvp => kvp.Value.IsValueType) + .Select(kvp => kvp.Key).ToArray()); + + /// + /// Contains all basic value types including the string type. i.e. excludes nullables. + /// + /// + /// All basic value and string types. + /// + public static List AllBasicValueAndStringTypes { get; } = new List( + BasicTypesInfo + .Where(kvp => kvp.Value.IsValueType || kvp.Key == typeof(string)) + .Select(kvp => kvp.Key).ToArray()); + + /// + /// Gets all nullable value types. i.e. excludes string and all basic value types. + /// + /// + /// All basic nullable value types. + /// + public static List AllBasicNullableValueTypes { get; } = new List( + BasicTypesInfo + .Where(kvp => kvp.Value.IsNullableValueType) + .Select(kvp => kvp.Key).ToArray()); + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Definitions.cs b/Unosquare.Swan.Lite/Definitions.cs new file mode 100644 index 0000000..c321369 --- /dev/null +++ b/Unosquare.Swan.Lite/Definitions.cs @@ -0,0 +1,39 @@ +namespace Unosquare.Swan +{ + using System.Text; + + /// + /// Contains useful constants and definitions. + /// + public static partial class Definitions + { + /// + /// The MS Windows codepage 1252 encoding used in some legacy scenarios + /// such as default CSV text encoding from Excel. + /// + public static readonly Encoding Windows1252Encoding; + + /// + /// The encoding associated with the default ANSI code page in the operating + /// system's regional and language settings. + /// + public static readonly Encoding CurrentAnsiEncoding; + + /// + /// Initializes the class. + /// + static Definitions() + { + CurrentAnsiEncoding = Encoding.GetEncoding(default(int)); + try + { + Windows1252Encoding = Encoding.GetEncoding(1252); + } + catch + { + // ignore, the codepage is not available use default + Windows1252Encoding = CurrentAnsiEncoding; + } + } + } +} diff --git a/Unosquare.Swan.Lite/Enums.cs b/Unosquare.Swan.Lite/Enums.cs new file mode 100644 index 0000000..0e52562 --- /dev/null +++ b/Unosquare.Swan.Lite/Enums.cs @@ -0,0 +1,60 @@ +namespace Unosquare.Swan +{ + /// + /// Enumeration of Operating Systems. + /// + public enum OperatingSystem + { + /// + /// Unknown OS + /// + Unknown, + + /// + /// Windows + /// + Windows, + + /// + /// UNIX/Linux + /// + Unix, + + /// + /// macOS (OSX) + /// + Osx, + } + + /// + /// Enumerates the different Application Worker States. + /// + public enum AppWorkerState + { + /// + /// The stopped + /// + Stopped, + + /// + /// The running + /// + Running, + } + + /// + /// Defines Endianness, big or little. + /// + public enum Endianness + { + /// + /// In big endian, you store the most significant byte in the smallest address. + /// + Big, + + /// + /// In little endian, you store the least significant byte in the smallest address. + /// + Little, + } +} diff --git a/Unosquare.Swan.Lite/Eventing.cs b/Unosquare.Swan.Lite/Eventing.cs new file mode 100644 index 0000000..5e0ffcf --- /dev/null +++ b/Unosquare.Swan.Lite/Eventing.cs @@ -0,0 +1,168 @@ +namespace Unosquare.Swan +{ + using System; + + /// + /// Event arguments representing the message that is logged + /// on to the terminal. Use the properties to forward the data to + /// your logger of choice. + /// + /// + public class LogMessageReceivedEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The sequence. + /// Type of the message. + /// The UTC date. + /// The source. + /// The message. + /// The extended data. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + public LogMessageReceivedEventArgs( + ulong sequence, + LogMessageType messageType, + DateTime utcDate, + string source, + string message, + object extendedData, + string callerMemberName, + string callerFilePath, + int callerLineNumber) + { + Sequence = sequence; + MessageType = messageType; + UtcDate = utcDate; + Source = source; + Message = message; + CallerMemberName = callerMemberName; + CallerFilePath = callerFilePath; + CallerLineNumber = callerLineNumber; + ExtendedData = extendedData; + } + + /// + /// Gets logging message sequence. + /// + /// + /// The sequence. + /// + public ulong Sequence { get; } + + /// + /// Gets the type of the message. + /// It can be a combination as the enumeration is a set of bitwise flags. + /// + /// + /// The type of the message. + /// + public LogMessageType MessageType { get; } + + /// + /// Gets the UTC date at which the event at which the message was logged. + /// + /// + /// The UTC date. + /// + public DateTime UtcDate { get; } + + /// + /// Gets the name of the source where the logging message + /// came from. This can come empty if the logger did not set it. + /// + /// + /// The source. + /// + public string Source { get; } + + /// + /// Gets the body of the message. + /// + /// + /// The message. + /// + public string Message { get; } + + /// + /// Gets the name of the caller member. + /// + /// + /// The name of the caller member. + /// + public string CallerMemberName { get; } + + /// + /// Gets the caller file path. + /// + /// + /// The caller file path. + /// + public string CallerFilePath { get; } + + /// + /// Gets the caller line number. + /// + /// + /// The caller line number. + /// + public int CallerLineNumber { get; } + + /// + /// Gets an object representing extended data. + /// It could be an exception or anything else. + /// + /// + /// The extended data. + /// + public object ExtendedData { get; } + + /// + /// Gets the Extended Data properties cast as an Exception (if possible) + /// Otherwise, it return null. + /// + /// + /// The exception. + /// + public Exception Exception => ExtendedData as Exception; + } + + /// + /// Event arguments representing a message logged and about to be + /// displayed on the terminal (console). Set the CancelOutput property in the + /// event handler to prevent the terminal from displaying the message. + /// + /// + public class LogMessageDisplayingEventArgs : LogMessageReceivedEventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The instance containing the event data. + public LogMessageDisplayingEventArgs(LogMessageReceivedEventArgs data) + : base( + data.Sequence, + data.MessageType, + data.UtcDate, + data.Source, + data.Message, + data.ExtendedData, + data.CallerMemberName, + data.CallerFilePath, + data.CallerLineNumber) + { + CancelOutput = false; + } + + /// + /// Gets or sets a value indicating whether the displaying of the + /// logging message should be canceled. + /// + /// + /// true if [cancel output]; otherwise, false. + /// + public bool CancelOutput { get; set; } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Extensions.ByteArrays.cs b/Unosquare.Swan.Lite/Extensions.ByteArrays.cs new file mode 100644 index 0000000..6891b28 --- /dev/null +++ b/Unosquare.Swan.Lite/Extensions.ByteArrays.cs @@ -0,0 +1,672 @@ +namespace Unosquare.Swan +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Provides various extension methods for byte arrays and streams. + /// + public static class ByteArrayExtensions + { + /// + /// Converts an array of bytes to its lower-case, hexadecimal representation. + /// + /// The bytes. + /// if set to true add the 0x prefix tot he output. + /// + /// The specified string instance; no actual conversion is performed. + /// + /// bytes. + public static string ToLowerHex(this byte[] bytes, bool addPrefix = false) + => ToHex(bytes, addPrefix, "x2"); + + /// + /// Converts an array of bytes to its upper-case, hexadecimal representation. + /// + /// The bytes. + /// if set to true [add prefix]. + /// + /// The specified string instance; no actual conversion is performed. + /// + /// bytes. + public static string ToUpperHex(this byte[] bytes, bool addPrefix = false) + => ToHex(bytes, addPrefix, "X2"); + + /// + /// Converts an array of bytes to a sequence of dash-separated, hexadecimal, + /// uppercase characters. + /// + /// The bytes. + /// + /// A string of hexadecimal pairs separated by hyphens, where each pair represents + /// the corresponding element in value; for example, "7F-2C-4A-00". + /// + public static string ToDashedHex(this byte[] bytes) => BitConverter.ToString(bytes); + + /// + /// Converts an array of bytes to a base-64 encoded string. + /// + /// The bytes. + /// A converted from an array of bytes. + public static string ToBase64(this byte[] bytes) => Convert.ToBase64String(bytes); + + /// + /// Converts a set of hexadecimal characters (uppercase or lowercase) + /// to a byte array. String length must be a multiple of 2 and + /// any prefix (such as 0x) has to be avoided for this to work properly. + /// + /// The hexadecimal. + /// + /// A byte array containing the results of encoding the specified set of characters. + /// + /// hex. + public static byte[] ConvertHexadecimalToBytes(this string hex) + { + if (string.IsNullOrWhiteSpace(hex)) + throw new ArgumentNullException(nameof(hex)); + + return Enumerable + .Range(0, hex.Length / 2) + .Select(x => Convert.ToByte(hex.Substring(x * 2, 2), 16)) + .ToArray(); + } + + /// + /// Gets the bit value at the given offset. + /// + /// The b. + /// The offset. + /// The length. + /// + /// Bit value at the given offset. + /// + public static byte GetBitValueAt(this byte b, byte offset, byte length = 1) => (byte)((b >> offset) & ~(0xff << length)); + + /// + /// Sets the bit value at the given offset. + /// + /// The b. + /// The offset. + /// The length. + /// The value. + /// Bit value at the given offset. + public static byte SetBitValueAt(this byte b, byte offset, byte length, byte value) + { + var mask = ~(0xff << length); + var valueAt = (byte)(value & mask); + + return (byte)((valueAt << offset) | (b & ~(mask << offset))); + } + + /// + /// Sets the bit value at the given offset. + /// + /// The b. + /// The offset. + /// The value. + /// Bit value at the given offset. + public static byte SetBitValueAt(this byte b, byte offset, byte value) => b.SetBitValueAt(offset, 1, value); + + /// + /// Splits a byte array delimited by the specified sequence of bytes. + /// Each individual element in the result will contain the split sequence terminator if it is found to be delimited by it. + /// For example if you split [1,2,3,4] by a sequence of [2,3] this method will return a list with 2 byte arrays, one containing [1,2,3] and the + /// second one containing 4. Use the Trim extension methods to remove terminator sequences. + /// + /// The buffer. + /// The offset at which to start splitting bytes. Any bytes before this will be discarded. + /// The sequence. + /// + /// A byte array containing the results the specified sequence of bytes. + /// + /// + /// buffer + /// or + /// sequence. + /// + public static List Split(this byte[] buffer, int offset, params byte[] sequence) + { + if (buffer == null) + throw new ArgumentNullException(nameof(buffer)); + + if (sequence == null) + throw new ArgumentNullException(nameof(sequence)); + + var seqOffset = offset.Clamp(0, buffer.Length - 1); + + var result = new List(); + + while (seqOffset < buffer.Length) + { + var separatorStartIndex = buffer.GetIndexOf(sequence, seqOffset); + + if (separatorStartIndex >= 0) + { + var item = new byte[separatorStartIndex - seqOffset + sequence.Length]; + Array.Copy(buffer, seqOffset, item, 0, item.Length); + result.Add(item); + seqOffset += item.Length; + } + else + { + var item = new byte[buffer.Length - seqOffset]; + Array.Copy(buffer, seqOffset, item, 0, item.Length); + result.Add(item); + break; + } + } + + return result; + } + + /// + /// Clones the specified buffer, byte by byte. + /// + /// The buffer. + /// A byte array containing the results of encoding the specified set of characters. + public static byte[] DeepClone(this byte[] buffer) + { + if (buffer == null) + return null; + + var result = new byte[buffer.Length]; + Array.Copy(buffer, result, buffer.Length); + return result; + } + + /// + /// Removes the specified sequence from the start of the buffer if the buffer begins with such sequence. + /// + /// The buffer. + /// The sequence. + /// + /// A new trimmed byte array. + /// + /// buffer. + public static byte[] TrimStart(this byte[] buffer, params byte[] sequence) + { + if (buffer == null) + throw new ArgumentNullException(nameof(buffer)); + + if (buffer.StartsWith(sequence) == false) + return buffer.DeepClone(); + + var result = new byte[buffer.Length - sequence.Length]; + Array.Copy(buffer, sequence.Length, result, 0, result.Length); + return result; + } + + /// + /// Removes the specified sequence from the end of the buffer if the buffer ends with such sequence. + /// + /// The buffer. + /// The sequence. + /// + /// A byte array containing the results of encoding the specified set of characters. + /// + /// buffer. + public static byte[] TrimEnd(this byte[] buffer, params byte[] sequence) + { + if (buffer == null) + throw new ArgumentNullException(nameof(buffer)); + + if (buffer.EndsWith(sequence) == false) + return buffer.DeepClone(); + + var result = new byte[buffer.Length - sequence.Length]; + Array.Copy(buffer, 0, result, 0, result.Length); + return result; + } + + /// + /// Removes the specified sequence from the end and the start of the buffer + /// if the buffer ends and/or starts with such sequence. + /// + /// The buffer. + /// The sequence. + /// A byte array containing the results of encoding the specified set of characters. + public static byte[] Trim(this byte[] buffer, params byte[] sequence) + { + var trimStart = buffer.TrimStart(sequence); + return trimStart.TrimEnd(sequence); + } + + /// + /// Determines if the specified buffer ends with the given sequence of bytes. + /// + /// The buffer. + /// The sequence. + /// + /// True if the specified buffer is ends; otherwise, false. + /// + /// buffer. + public static bool EndsWith(this byte[] buffer, params byte[] sequence) + { + if (buffer == null) + throw new ArgumentNullException(nameof(buffer)); + + var startIndex = buffer.Length - sequence.Length; + return buffer.GetIndexOf(sequence, startIndex) == startIndex; + } + + /// + /// Determines if the specified buffer starts with the given sequence of bytes. + /// + /// The buffer. + /// The sequence. + /// true if the specified buffer starts; otherwise, false. + public static bool StartsWith(this byte[] buffer, params byte[] sequence) => buffer.GetIndexOf(sequence) == 0; + + /// + /// Determines whether the buffer contains the specified sequence. + /// + /// The buffer. + /// The sequence. + /// + /// true if [contains] [the specified sequence]; otherwise, false. + /// + public static bool Contains(this byte[] buffer, params byte[] sequence) => buffer.GetIndexOf(sequence) >= 0; + + /// + /// Determines whether the buffer exactly matches, byte by byte the specified sequence. + /// + /// The buffer. + /// The sequence. + /// + /// true if [is equal to] [the specified sequence]; otherwise, false. + /// + /// buffer. + public static bool IsEqualTo(this byte[] buffer, params byte[] sequence) + { + if (ReferenceEquals(buffer, sequence)) + return true; + + if (buffer == null) + throw new ArgumentNullException(nameof(buffer)); + + return buffer.Length == sequence.Length && buffer.GetIndexOf(sequence) == 0; + } + + /// + /// Returns the first instance of the matched sequence based on the given offset. + /// If nomatches are found then this method returns -1. + /// + /// The buffer. + /// The sequence. + /// The offset. + /// The index of the sequence. + /// + /// buffer + /// or + /// sequence. + /// + public static int GetIndexOf(this byte[] buffer, byte[] sequence, int offset = 0) + { + if (buffer == null) + throw new ArgumentNullException(nameof(buffer)); + if (sequence == null) + throw new ArgumentNullException(nameof(sequence)); + if (sequence.Length == 0) + return -1; + if (sequence.Length > buffer.Length) + return -1; + + var seqOffset = offset < 0 ? 0 : offset; + + var matchedCount = 0; + for (var i = seqOffset; i < buffer.Length; i++) + { + if (buffer[i] == sequence[matchedCount]) + matchedCount++; + else + matchedCount = 0; + + if (matchedCount == sequence.Length) + return i - (matchedCount - 1); + } + + return -1; + } + + /// + /// Appends the Memory Stream with the specified buffer. + /// + /// The stream. + /// The buffer. + /// + /// The same MemoryStream instance. + /// + /// + /// stream + /// or + /// buffer. + /// + public static MemoryStream Append(this MemoryStream stream, byte[] buffer) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + + if (buffer == null) + throw new ArgumentNullException(nameof(buffer)); + + stream.Write(buffer, 0, buffer.Length); + return stream; + } + + /// + /// Appends the Memory Stream with the specified buffer. + /// + /// The stream. + /// The buffer. + /// + /// Block of bytes to the current stream using data read from a buffer. + /// + /// buffer. + public static MemoryStream Append(this MemoryStream stream, IEnumerable buffer) => Append(stream, buffer?.ToArray()); + + /// + /// Appends the Memory Stream with the specified set of buffers. + /// + /// The stream. + /// The buffers. + /// + /// Block of bytes to the current stream using data read from a buffer. + /// + /// buffers. + public static MemoryStream Append(this MemoryStream stream, IEnumerable buffers) + { + if (buffers == null) + throw new ArgumentNullException(nameof(buffers)); + + foreach (var buffer in buffers) + Append(stream, buffer); + + return stream; + } + + /// + /// Converts an array of bytes into text with the specified encoding. + /// + /// The buffer. + /// The encoding. + /// A that contains the results of decoding the specified sequence of bytes. + public static string ToText(this IEnumerable buffer, Encoding encoding) => encoding.GetString(buffer.ToArray()); + + /// + /// Converts an array of bytes into text with UTF8 encoding. + /// + /// The buffer. + /// A that contains the results of decoding the specified sequence of bytes. + public static string ToText(this IEnumerable buffer) => buffer.ToText(Encoding.UTF8); + + /// + /// Retrieves a sub-array from the specified . A sub-array starts at + /// the specified element position in . + /// + /// + /// An array of T that receives a sub-array, or an empty array of T if any problems with + /// the parameters. + /// + /// + /// An array of T from which to retrieve a sub-array. + /// + /// + /// An that represents the zero-based starting position of + /// a sub-array in . + /// + /// + /// An that represents the number of elements to retrieve. + /// + /// + /// The type of elements in . + /// + public static T[] SubArray(this T[] array, int startIndex, int length) + { + int len; + if (array == null || (len = array.Length) == 0) + return new T[0]; + + if (startIndex < 0 || length <= 0 || startIndex + length > len) + return new T[0]; + + if (startIndex == 0 && length == len) + return array; + + var subArray = new T[length]; + Array.Copy(array, startIndex, subArray, 0, length); + + return subArray; + } + + /// + /// Retrieves a sub-array from the specified . A sub-array starts at + /// the specified element position in . + /// + /// + /// An array of T that receives a sub-array, or an empty array of T if any problems with + /// the parameters. + /// + /// + /// An array of T from which to retrieve a sub-array. + /// + /// + /// A that represents the zero-based starting position of + /// a sub-array in . + /// + /// + /// A that represents the number of elements to retrieve. + /// + /// + /// The type of elements in . + /// + public static T[] SubArray(this T[] array, long startIndex, long length) => array.SubArray((int)startIndex, (int)length); + + /// + /// Reads the bytes asynchronous. + /// + /// The stream. + /// The length. + /// Length of the buffer. + /// The cancellation token. + /// + /// A byte array containing the results of encoding the specified set of characters. + /// + /// stream. + public static async Task ReadBytesAsync(this Stream stream, long length, int bufferLength, CancellationToken ct = default) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + + using (var dest = new MemoryStream()) + { + try + { + var buff = new byte[bufferLength]; + while (length > 0) + { + if (length < bufferLength) + bufferLength = (int)length; + + var nread = await stream.ReadAsync(buff, 0, bufferLength, ct).ConfigureAwait(false); + if (nread == 0) + break; + + dest.Write(buff, 0, nread); + length -= nread; + } + } + catch + { + // ignored + } + + return dest.ToArray(); + } + } + + /// + /// Reads the bytes asynchronous. + /// + /// The stream. + /// The length. + /// The cancellation token. + /// + /// A byte array containing the results of encoding the specified set of characters. + /// + /// stream. + public static async Task ReadBytesAsync(this Stream stream, int length, CancellationToken ct = default) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + + var buff = new byte[length]; + var offset = 0; + try + { + while (length > 0) + { + var nread = await stream.ReadAsync(buff, offset, length, ct).ConfigureAwait(false); + if (nread == 0) + break; + + offset += nread; + length -= nread; + } + } + catch + { + // ignored + } + + return buff.SubArray(0, offset); + } + + /// + /// Converts an array of sbytes to an array of bytes. + /// + /// The sbyte array. + /// + /// The byte array from conversion. + /// + /// sbyteArray. + public static byte[] ToByteArray(this sbyte[] sbyteArray) + { + if (sbyteArray == null) + throw new ArgumentNullException(nameof(sbyteArray)); + + var byteArray = new byte[sbyteArray.Length]; + for (var index = 0; index < sbyteArray.Length; index++) + byteArray[index] = (byte)sbyteArray[index]; + + return byteArray; + } + + /// + /// Receives a byte array and returns it transformed in an sbyte array. + /// + /// The byte array. + /// + /// The sbyte array from conversion. + /// + /// byteArray. + public static sbyte[] ToSByteArray(this byte[] byteArray) + { + if (byteArray == null) + throw new ArgumentNullException(nameof(byteArray)); + + var sbyteArray = new sbyte[byteArray.Length]; + for (var index = 0; index < byteArray.Length; index++) + sbyteArray[index] = (sbyte)byteArray[index]; + return sbyteArray; + } + + /// + /// Gets the sbytes from a string. + /// + /// The encoding. + /// The s. + /// The sbyte array from string. + public static sbyte[] GetSBytes(this Encoding encoding, string s) + => encoding.GetBytes(s).ToSByteArray(); + + /// + /// Gets the string from a sbyte array. + /// + /// The encoding. + /// The data. + /// The string. + public static string GetString(this Encoding encoding, sbyte[] data) + => encoding.GetString(data.ToByteArray()); + + /// + /// Reads a number of characters from the current source Stream and writes the data to the target array at the + /// specified index. + /// + /// The source stream. + /// The target. + /// The start. + /// The count. + /// + /// The number of bytes read. + /// + /// + /// sourceStream + /// or + /// target. + /// + public static int ReadInput(this Stream sourceStream, ref sbyte[] target, int start, int count) + { + if (sourceStream == null) + throw new ArgumentNullException(nameof(sourceStream)); + + if (target == null) + throw new ArgumentNullException(nameof(target)); + + // Returns 0 bytes if not enough space in target + if (target.Length == 0) + return 0; + + var receiver = new byte[target.Length]; + var bytesRead = 0; + var startIndex = start; + var bytesToRead = count; + while (bytesToRead > 0) + { + var n = sourceStream.Read(receiver, startIndex, bytesToRead); + if (n == 0) + break; + bytesRead += n; + startIndex += n; + bytesToRead -= n; + } + + // Returns -1 if EOF + if (bytesRead == 0) + return -1; + + for (var i = start; i < start + bytesRead; i++) + target[i] = (sbyte)receiver[i]; + + return bytesRead; + } + + private static string ToHex(byte[] bytes, bool addPrefix, string format) + { + if (bytes == null) + throw new ArgumentNullException(nameof(bytes)); + + var sb = new StringBuilder(bytes.Length * 2); + + foreach (var item in bytes) + sb.Append(item.ToString(format, CultureInfo.InvariantCulture)); + + return $"{(addPrefix ? "0x" : string.Empty)}{sb}"; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Extensions.Dates.cs b/Unosquare.Swan.Lite/Extensions.Dates.cs new file mode 100644 index 0000000..b527e7c --- /dev/null +++ b/Unosquare.Swan.Lite/Extensions.Dates.cs @@ -0,0 +1,230 @@ +namespace Unosquare.Swan +{ + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// Provides various extension methods for dates. + /// + public static class DateExtensions + { + private static readonly Dictionary DateRanges = new Dictionary() + { + { "minute", 59}, + { "hour", 23}, + { "dayOfMonth", 31}, + { "month", 12}, + { "dayOfWeek", 6}, + }; + + /// + /// Converts the date to a YYYY-MM-DD string. + /// + /// The date. + /// The concatenation of date.Year, date.Month and date.Day. + public static string ToSortableDate(this DateTime date) + => $"{date.Year:0000}-{date.Month:00}-{date.Day:00}"; + + /// + /// Converts the date to a YYYY-MM-DD HH:II:SS string. + /// + /// The date. + /// The concatenation of date.Year, date.Month, date.Day, date.Hour, date.Minute and date.Second. + public static string ToSortableDateTime(this DateTime date) + => $"{date.Year:0000}-{date.Month:00}-{date.Day:00} {date.Hour:00}:{date.Minute:00}:{date.Second:00}"; + + /// + /// Parses a YYYY-MM-DD and optionally it time part, HH:II:SS into a DateTime. + /// + /// The sortable date. + /// + /// A new instance of the DateTime structure to + /// the specified year, month, day, hour, minute and second. + /// + /// sortableDate. + /// + /// Represents errors that occur during application execution. + /// + /// + /// Unable to parse sortable date and time. - sortableDate. + /// + public static DateTime ToDateTime(this string sortableDate) + { + if (string.IsNullOrWhiteSpace(sortableDate)) + throw new ArgumentNullException(nameof(sortableDate)); + + var hour = 0; + var minute = 0; + var second = 0; + + var dateTimeParts = sortableDate.Split(' '); + + try + { + if (dateTimeParts.Length != 1 && dateTimeParts.Length != 2) + throw new Exception(); + + var dateParts = dateTimeParts[0].Split('-'); + if (dateParts.Length != 3) throw new Exception(); + + var year = int.Parse(dateParts[0]); + var month = int.Parse(dateParts[1]); + var day = int.Parse(dateParts[2]); + + if (dateTimeParts.Length > 1) + { + var timeParts = dateTimeParts[1].Split(':'); + if (timeParts.Length != 3) throw new Exception(); + + hour = int.Parse(timeParts[0]); + minute = int.Parse(timeParts[1]); + second = int.Parse(timeParts[2]); + } + + return new DateTime(year, month, day, hour, minute, second); + } + catch (Exception) + { + throw new ArgumentException("Unable to parse sortable date and time.", nameof(sortableDate)); + } + } + + /// + /// Creates a date's range. + /// + /// The start date. + /// The end date. + /// + /// A sequence of integral numbers within a specified date's range. + /// + public static IEnumerable DateRange(this DateTime startDate, DateTime endDate) + => Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d)); + + /// + /// Rounds up a date to match a timespan. + /// + /// The datetime. + /// The timespan to match. + /// + /// A new instance of the DateTime structure to the specified datetime and timespan ticks. + /// + public static DateTime RoundUp(this DateTime date, TimeSpan timeSpan) + => new DateTime(((date.Ticks + timeSpan.Ticks - 1) / timeSpan.Ticks) * timeSpan.Ticks); + + /// + /// Get this datetime as a Unix epoch timestamp (seconds since Jan 1, 1970, midnight UTC). + /// + /// The date to convert. + /// Seconds since Unix epoch. + public static long ToUnixEpochDate(this DateTime date) + { +#if NETSTANDARD2_0 + return new DateTimeOffset(date).ToUniversalTime().ToUnixTimeSeconds(); +#else + var epochTicks = new DateTime(1970, 1, 1).Ticks; + + return (date.Ticks - epochTicks) / TimeSpan.TicksPerSecond; +#endif + } + + /// + /// Compares a Date to another and returns a DateTimeSpan. + /// + /// The date start. + /// The date end. + /// A DateTimeSpan with the Years, Months, Days, Hours, Minutes, Seconds and Milliseconds between the dates. + public static DateTimeSpan GetDateTimeSpan(this DateTime dateStart, DateTime dateEnd) + => DateTimeSpan.CompareDates(dateStart, dateEnd); + + /// + /// Compare the Date elements(Months, Days, Hours, Minutes). + /// + /// The date. + /// The minute (0-59). + /// The hour. (0-23). + /// The day of month. (1-31). + /// The month. (1-12). + /// The day of week. (0-6)(Sunday = 0). + /// Returns true if Months, Days, Hours and Minutes match, otherwise false. + public static bool AsCronCanRun(this DateTime date, int? minute = null, int? hour = null, int? dayOfMonth = null, int? month = null, int? dayOfWeek = null) + { + var results = new List + { + GetElementParts(minute, date.Minute), + GetElementParts(hour, date.Hour), + GetElementParts(dayOfMonth, date.Day), + GetElementParts(month, date.Month), + GetElementParts(dayOfWeek, (int) date.DayOfWeek), + }; + + return results.Any(x => x != false); + } + + /// + /// Compare the Date elements(Months, Days, Hours, Minutes). + /// + /// The date. + /// The minute (0-59). + /// The hour. (0-23). + /// The day of month. (1-31). + /// The month. (1-12). + /// The day of week. (0-6)(Sunday = 0). + /// Returns true if Months, Days, Hours and Minutes match, otherwise false. + public static bool AsCronCanRun(this DateTime date, string minute = "*", string hour = "*", string dayOfMonth = "*", string month = "*", string dayOfWeek = "*") + { + var results = new List + { + GetElementParts(minute, nameof(minute), date.Minute), + GetElementParts(hour, nameof(hour), date.Hour), + GetElementParts(dayOfMonth, nameof(dayOfMonth), date.Day), + GetElementParts(month, nameof(month), date.Month), + GetElementParts(dayOfWeek, nameof(dayOfWeek), (int) date.DayOfWeek), + }; + + return results.Any(x => x != false); + } + + private static bool? GetElementParts(int? status, int value) => status.HasValue ? status.Value == value : (bool?) null; + + private static bool? GetElementParts(string parts, string type, int value) + { + if (string.IsNullOrWhiteSpace(parts) || parts == "*") return null; + + if (parts.Contains(",")) + { + return parts.Split(',').Select(int.Parse).Contains(value); + } + + var stop = DateRanges[type]; + + if (parts.Contains("/")) + { + var multiple = int.Parse(parts.Split('/').Last()); + var start = type == "dayOfMonth" || type == "month" ? 1 : 0; + + for (var i = start; i <= stop; i += multiple) + if (i == value) return true; + + return false; + } + + if (parts.Contains("-")) + { + var range = parts.Split('-'); + var start = int.Parse(range.First()); + stop = Math.Max(stop, int.Parse(range.Last())); + + if ((type == "dayOfMonth" || type == "month") && start == 0) + start = 1; + + for (var i = start; i <= stop; i++) + if (i == value) return true; + + return false; + } + + return int.Parse(parts) == value; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Extensions.Dictionaries.cs b/Unosquare.Swan.Lite/Extensions.Dictionaries.cs new file mode 100644 index 0000000..d1c8415 --- /dev/null +++ b/Unosquare.Swan.Lite/Extensions.Dictionaries.cs @@ -0,0 +1,77 @@ +namespace Unosquare.Swan +{ + using System; + using System.Collections.Generic; + + /// + /// Extension methods. + /// + public static partial class Extensions + { + /// + /// Gets the value if exists or default. + /// + /// The type of the key. + /// The type of the value. + /// The dictionary. + /// The key. + /// The default value. + /// + /// The value of the provided key or default. + /// + /// dict. + public static TValue GetValueOrDefault(this IDictionary dict, TKey key, TValue defaultValue = default) + { + if (dict == null) + throw new ArgumentNullException(nameof(dict)); + + return dict.ContainsKey(key) ? dict[key] : defaultValue; + } + + /// + /// Adds a key/value pair to the Dictionary if the key does not already exist. + /// If the value is null, the key will not be updated. + /// + /// Based on ConcurrentDictionary.GetOrAdd method. + /// + /// The type of the key. + /// The type of the value. + /// The dictionary. + /// The key. + /// The value factory. + /// The value for the key. + public static TValue GetOrAdd(this IDictionary dict, TKey key, Func valueFactory) + { + if (dict == null) + throw new ArgumentNullException(nameof(dict)); + + if (!dict.ContainsKey(key)) + { + var value = valueFactory(key); + if (Equals(value, default)) return default; + dict[key] = value; + } + + return dict[key]; + } + + /// + /// Executes the item action for each element in the Dictionary. + /// + /// The type of the key. + /// The type of the value. + /// The dictionary. + /// The item action. + /// dict. + public static void ForEach(this IDictionary dict, Action itemAction) + { + if (dict == null) + throw new ArgumentNullException(nameof(dict)); + + foreach (var kvp in dict) + { + itemAction(kvp.Key, kvp.Value); + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Extensions.Functional.cs b/Unosquare.Swan.Lite/Extensions.Functional.cs new file mode 100644 index 0000000..ff7c80e --- /dev/null +++ b/Unosquare.Swan.Lite/Extensions.Functional.cs @@ -0,0 +1,179 @@ +namespace Unosquare.Swan +{ + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// Functional programming extension methods. + /// + public static class FunctionalExtensions + { + /// + /// Whens the specified condition. + /// + /// The type of IQueryable. + /// The list. + /// The condition. + /// The function. + /// + /// The IQueryable. + /// + /// + /// this + /// or + /// condition + /// or + /// fn. + /// + public static IQueryable When( + this IQueryable list, + Func condition, + Func, IQueryable> fn) + { + if (list == null) + throw new ArgumentNullException(nameof(list)); + + if (condition == null) + throw new ArgumentNullException(nameof(condition)); + + if (fn == null) + throw new ArgumentNullException(nameof(fn)); + + return condition() ? fn(list) : list; + } + + /// + /// Whens the specified condition. + /// + /// The type of IEnumerable. + /// The list. + /// The condition. + /// The function. + /// + /// The IEnumerable. + /// + /// + /// this + /// or + /// condition + /// or + /// fn. + /// + public static IEnumerable When( + this IEnumerable list, + Func condition, + Func, IEnumerable> fn) + { + if (list == null) + throw new ArgumentNullException(nameof(list)); + + if (condition == null) + throw new ArgumentNullException(nameof(condition)); + + if (fn == null) + throw new ArgumentNullException(nameof(fn)); + + return condition() ? fn(list) : list; + } + + /// + /// Adds the value when the condition is true. + /// + /// The type of IList element. + /// The list. + /// The condition. + /// The value. + /// + /// The IList. + /// + /// + /// this + /// or + /// condition + /// or + /// value. + /// + public static IList AddWhen( + this IList list, + Func condition, + Func value) + { + if (list == null) + throw new ArgumentNullException(nameof(list)); + + if (condition == null) + throw new ArgumentNullException(nameof(condition)); + + if (value == null) + throw new ArgumentNullException(nameof(value)); + + if (condition()) + list.Add(value()); + + return list; + } + + /// + /// Adds the value when the condition is true. + /// + /// The type of IList element. + /// The list. + /// if set to true [condition]. + /// The value. + /// + /// The IList. + /// + /// list. + public static IList AddWhen( + this IList list, + bool condition, + T value) + { + if (list == null) + throw new ArgumentNullException(nameof(list)); + + if (condition) + list.Add(value); + + return list; + } + + /// + /// Adds the range when the condition is true. + /// + /// The type of List element. + /// The list. + /// The condition. + /// The value. + /// + /// The List. + /// + /// + /// this + /// or + /// condition + /// or + /// value. + /// + public static List AddRangeWhen( + this List list, + Func condition, + Func> value) + { + if (list == null) + throw new ArgumentNullException(nameof(list)); + + if (condition == null) + throw new ArgumentNullException(nameof(condition)); + + if (value == null) + throw new ArgumentNullException(nameof(value)); + + if (condition()) + list.AddRange(value()); + + return list; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Extensions.Reflection.cs b/Unosquare.Swan.Lite/Extensions.Reflection.cs new file mode 100644 index 0000000..5c5b138 --- /dev/null +++ b/Unosquare.Swan.Lite/Extensions.Reflection.cs @@ -0,0 +1,469 @@ +namespace Unosquare.Swan +{ + using System; + using System.Collections.Concurrent; + using System.Collections; + using System.Linq; + using System.Reflection; + using System.Collections.Generic; + using Attributes; + + /// + /// Provides various extension methods for Reflection and Types. + /// + public static class ReflectionExtensions + { + private static readonly Lazy, Func>> CacheGetMethods = + new Lazy, Func>>(() => new ConcurrentDictionary, Func>(), true); + + private static readonly Lazy, Action>> CacheSetMethods = + new Lazy, Action>>(() => new ConcurrentDictionary, Action>(), true); + + #region Assembly Extensions + + /// + /// Gets all types within an assembly in a safe manner. + /// + /// The assembly. + /// + /// Array of Type objects representing the types specified by an assembly. + /// + /// assembly. + public static IEnumerable GetAllTypes(this Assembly assembly) + { + if (assembly == null) + throw new ArgumentNullException(nameof(assembly)); + + try + { + return assembly.GetTypes(); + } + catch (ReflectionTypeLoadException e) + { + return e.Types.Where(t => t != null); + } + } + + #endregion + + #region Type Extensions + + /// + /// The closest programmatic equivalent of default(T). + /// + /// The type. + /// + /// Default value of this type. + /// + /// type. + public static object GetDefault(this Type type) + { + if (type == null) + throw new ArgumentNullException(nameof(type)); + + return type.IsValueType() ? Activator.CreateInstance(type) : null; + } + + /// + /// Determines whether this type is compatible with ICollection. + /// + /// The type. + /// + /// true if the specified source type is collection; otherwise, false. + /// + /// sourceType. + public static bool IsCollection(this Type sourceType) + { + if (sourceType == null) + throw new ArgumentNullException(nameof(sourceType)); + + return sourceType != typeof(string) && + typeof(IEnumerable).IsAssignableFrom(sourceType); + } + + /// + /// Gets a method from a type given the method name, binding flags, generic types and parameter types. + /// + /// Type of the source. + /// The binding flags. + /// Name of the method. + /// The generic types. + /// The parameter types. + /// + /// An object that represents the method with the specified name. + /// + /// + /// The exception that is thrown when binding to a member results in more than one member matching the + /// binding criteria. This class cannot be inherited. + /// + public static MethodInfo GetMethod( + this Type type, + BindingFlags bindingFlags, + string methodName, + Type[] genericTypes, + Type[] parameterTypes) + { + if (type == null) + throw new ArgumentNullException(nameof(type)); + + if (methodName == null) + throw new ArgumentNullException(nameof(methodName)); + + if (genericTypes == null) + throw new ArgumentNullException(nameof(genericTypes)); + + if (parameterTypes == null) + throw new ArgumentNullException(nameof(parameterTypes)); + + var methods = type + .GetMethods(bindingFlags) + .Where(mi => string.Equals(methodName, mi.Name, StringComparison.Ordinal)) + .Where(mi => mi.ContainsGenericParameters) + .Where(mi => mi.GetGenericArguments().Length == genericTypes.Length) + .Where(mi => mi.GetParameters().Length == parameterTypes.Length) + .Select(mi => mi.MakeGenericMethod(genericTypes)) + .Where(mi => mi.GetParameters().Select(pi => pi.ParameterType).SequenceEqual(parameterTypes)) + .ToList(); + + return methods.Count > 1 ? throw new AmbiguousMatchException() : methods.FirstOrDefault(); + } + + /// + /// Determines whether this instance is class. + /// + /// The type. + /// + /// true if the specified type is class; otherwise, false. + /// + public static bool IsClass(this Type type) => type.GetTypeInfo().IsClass; + + /// + /// Determines whether this instance is abstract. + /// + /// The type. + /// + /// true if the specified type is abstract; otherwise, false. + /// + public static bool IsAbstract(this Type type) => type.GetTypeInfo().IsAbstract; + + /// + /// Determines whether this instance is interface. + /// + /// The type. + /// + /// true if the specified type is interface; otherwise, false. + /// + public static bool IsInterface(this Type type) => type.GetTypeInfo().IsInterface; + + /// + /// Determines whether this instance is primitive. + /// + /// The type. + /// + /// true if the specified type is primitive; otherwise, false. + /// + public static bool IsPrimitive(this Type type) => type.GetTypeInfo().IsPrimitive; + + /// + /// Determines whether [is value type]. + /// + /// The type. + /// + /// true if [is value type] [the specified type]; otherwise, false. + /// + public static bool IsValueType(this Type type) => type.GetTypeInfo().IsValueType; + + /// + /// Determines whether [is generic type]. + /// + /// The type. + /// + /// true if [is generic type] [the specified type]; otherwise, false. + /// + public static bool IsGenericType(this Type type) => type.GetTypeInfo().IsGenericType; + + /// + /// Determines whether [is generic parameter]. + /// + /// The type. + /// + /// true if [is generic parameter] [the specified type]; otherwise, false. + /// + public static bool IsGenericParameter(this Type type) => type.IsGenericParameter; + + /// + /// Determines whether the specified attribute type is defined. + /// + /// The type. + /// Type of the attribute. + /// if set to true [inherit]. + /// + /// true if the specified attribute type is defined; otherwise, false. + /// + public static bool IsDefined(this Type type, Type attributeType, bool inherit) => + type.GetTypeInfo().IsDefined(attributeType, inherit); + + /// + /// Gets the custom attributes. + /// + /// The type. + /// Type of the attribute. + /// if set to true [inherit]. + /// + /// Attributes associated with the property represented by this PropertyInfo object. + /// + public static Attribute[] GetCustomAttributes(this Type type, Type attributeType, bool inherit) => + type.GetTypeInfo().GetCustomAttributes(attributeType, inherit).Cast().ToArray(); + + /// + /// Determines whether [is generic type definition]. + /// + /// The type. + /// + /// true if [is generic type definition] [the specified type]; otherwise, false. + /// + public static bool IsGenericTypeDefinition(this Type type) => type.GetTypeInfo().IsGenericTypeDefinition; + + /// + /// Bases the type. + /// + /// The type. + /// returns a type of data. + public static Type BaseType(this Type type) => type.GetTypeInfo().BaseType; + + /// + /// Assemblies the specified type. + /// + /// The type. + /// returns an Assembly object. + public static Assembly Assembly(this Type type) => type.GetTypeInfo().Assembly; + + /// + /// Determines whether [is i enumerable request]. + /// + /// The type. + /// + /// true if [is i enumerable request] [the specified type]; otherwise, false. + /// + /// type. + public static bool IsIEnumerable(this Type type) + => type == null + ? throw new ArgumentNullException(nameof(type)) + : type.IsGenericType() && type.GetGenericTypeDefinition() == typeof(IEnumerable<>); + + #endregion + + /// + /// Tries to parse using the basic types. + /// + /// The type. + /// The value. + /// The result. + /// + /// true if parsing was successful; otherwise, false. + /// + public static bool TryParseBasicType(this Type type, object value, out object result) + => TryParseBasicType(type, value.ToStringInvariant(), out result); + + /// + /// Tries to parse using the basic types. + /// + /// The type. + /// The value. + /// The result. + /// + /// true if parsing was successful; otherwise, false. + /// + public static bool TryParseBasicType(this Type type, string value, out object result) + { + result = null; + + return Definitions.BasicTypesInfo.ContainsKey(type) && Definitions.BasicTypesInfo[type].TryParse(value, out result); + } + + /// + /// Tries the type of the set basic value to a property. + /// + /// The property. + /// The value. + /// The object. + /// + /// true if parsing was successful; otherwise, false. + /// + public static bool TrySetBasicType(this PropertyInfo property, object value, object obj) + { + try + { + if (property.PropertyType.TryParseBasicType(value, out var propertyValue)) + { + property.SetValue(obj, propertyValue); + return true; + } + } + catch + { + // swallow + } + + return false; + } + + /// + /// Tries the type of the set to an array a basic type. + /// + /// The type. + /// The value. + /// The array. + /// The index. + /// + /// true if parsing was successful; otherwise, false. + /// + public static bool TrySetArrayBasicType(this Type type, object value, Array array, int index) + { + try + { + if (value == null) + { + array.SetValue(null, index); + return true; + } + + if (type.TryParseBasicType(value, out var propertyValue)) + { + array.SetValue(propertyValue, index); + return true; + } + + if (type.GetTypeInfo().IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) + { + array.SetValue(null, index); + return true; + } + } + catch + { + // swallow + } + + return false; + } + + /// + /// Tries to set a property array with another array. + /// + /// The property. + /// The value. + /// The object. + /// + /// true if parsing was successful; otherwise, false. + /// + public static bool TrySetArray(this PropertyInfo propertyInfo, IEnumerable value, object obj) + { + var elementType = propertyInfo.PropertyType.GetElementType(); + + if (elementType == null) + return false; + + var targetArray = Array.CreateInstance(elementType, value.Count()); + + var i = 0; + + foreach (var sourceElement in value) + { + var result = elementType.TrySetArrayBasicType(sourceElement, targetArray, i++); + + if (!result) return false; + } + + propertyInfo.SetValue(obj, targetArray); + + return true; + } + + /// + /// Gets property actual value or PropertyDisplayAttribute.DefaultValue if presented. + /// + /// If the PropertyDisplayAttribute.Format value is presented, the property value + /// will be formatted accordingly. + /// + /// If the object contains a null value, a empty string will be returned. + /// + /// The property information. + /// The object. + /// The property value or null. + public static string ToFormattedString(this PropertyInfo propertyInfo, object obj) + { + try + { + var value = propertyInfo.GetValue(obj); + var attr = Runtime.AttributeCache.RetrieveOne(propertyInfo); + + if (attr == null) return value?.ToString() ?? string.Empty; + + var valueToFormat = value ?? attr.DefaultValue; + + return string.IsNullOrEmpty(attr.Format) + ? (valueToFormat?.ToString() ?? string.Empty) + : ConvertObjectAndFormat(propertyInfo.PropertyType, valueToFormat, attr.Format); + } + catch + { + return null; + } + } + + /// + /// Gets a MethodInfo from a Property Get method. + /// + /// The property information. + /// if set to true [non public]. + /// + /// The cached MethodInfo. + /// + public static Func GetCacheGetMethod(this PropertyInfo propertyInfo, bool nonPublic = false) + { + var key = Tuple.Create(!nonPublic, propertyInfo); + + return !nonPublic && !CacheGetMethods.Value.ContainsKey(key) && !propertyInfo.GetGetMethod(true).IsPublic + ? null + : CacheGetMethods.Value + .GetOrAdd(key, + x => y => x.Item2.GetGetMethod(nonPublic).Invoke(y, null)); + } + + /// + /// Gets a MethodInfo from a Property Set method. + /// + /// The property information. + /// if set to true [non public]. + /// + /// The cached MethodInfo. + /// + public static Action GetCacheSetMethod(this PropertyInfo propertyInfo, bool nonPublic = false) + { + var key = Tuple.Create(!nonPublic, propertyInfo); + + return !nonPublic && !CacheSetMethods.Value.ContainsKey(key) && !propertyInfo.GetSetMethod(true).IsPublic + ? null + : CacheSetMethods.Value + .GetOrAdd(key, + x => (obj, args) => x.Item2.GetSetMethod(nonPublic).Invoke(obj, args)); + } + + private static string ConvertObjectAndFormat(Type propertyType, object value, string format) + { + if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?)) + return Convert.ToDateTime(value).ToString(format); + if (propertyType == typeof(int) || propertyType == typeof(int?)) + return Convert.ToInt32(value).ToString(format); + if (propertyType == typeof(decimal) || propertyType == typeof(decimal?)) + return Convert.ToDecimal(value).ToString(format); + if (propertyType == typeof(double) || propertyType == typeof(double?)) + return Convert.ToDouble(value).ToString(format); + if (propertyType == typeof(byte) || propertyType == typeof(byte?)) + return Convert.ToByte(value).ToString(format); + + return value?.ToString() ?? string.Empty; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Extensions.Strings.cs b/Unosquare.Swan.Lite/Extensions.Strings.cs new file mode 100644 index 0000000..db5b1d4 --- /dev/null +++ b/Unosquare.Swan.Lite/Extensions.Strings.cs @@ -0,0 +1,520 @@ +namespace Unosquare.Swan +{ + using Formatters; + using System; + using System.IO; + using System.Linq; + using System.Security.Cryptography; + using System.Text; + using System.Text.RegularExpressions; + + /// + /// String related extension methods. + /// + public static class StringExtensions + { + #region Private Declarations + + private const RegexOptions StandardRegexOptions = + RegexOptions.Multiline | RegexOptions.Compiled | RegexOptions.CultureInvariant; + + private static readonly string[] ByteSuffixes = {"B", "KB", "MB", "GB", "TB"}; + + private static readonly Lazy Md5Hasher = new Lazy(MD5.Create, true); + private static readonly Lazy SHA1Hasher = new Lazy(SHA1.Create, true); + private static readonly Lazy SHA256Hasher = new Lazy(SHA256.Create, true); + private static readonly Lazy SHA512Hasher = new Lazy(SHA512.Create, true); + + private static readonly Lazy SplitLinesRegex = + new Lazy( + () => new Regex("\r\n|\r|\n", StandardRegexOptions)); + + private static readonly Lazy UnderscoreRegex = + new Lazy( + () => new Regex(@"_", StandardRegexOptions)); + + private static readonly Lazy CamelCaseRegEx = + new Lazy( + () => + new Regex(@"[a-z][A-Z]", + StandardRegexOptions)); + + private static readonly Lazy SplitCamelCaseString = new Lazy(() => + { + return m => + { + var x = m.ToString(); + return x[0] + " " + x.Substring(1, x.Length - 1); + }; + }); + + private static readonly Lazy InvalidFilenameChars = + new Lazy(() => Path.GetInvalidFileNameChars().Select(c => c.ToString()).ToArray()); + + #endregion + + /// + /// Computes the MD5 hash of the given stream. + /// Do not use for large streams as this reads ALL bytes at once. + /// + /// The stream. + /// if set to true [create hasher]. + /// + /// The computed hash code. + /// + /// stream. + public static byte[] ComputeMD5(this Stream stream, bool createHasher = false) + { + if (stream == null) + throw new ArgumentNullException(nameof(stream)); + +#if NET452 + var md5 = MD5.Create(); + const int bufferSize = 4096; + + var readAheadBuffer = new byte[bufferSize]; + var readAheadBytesRead = stream.Read(readAheadBuffer, 0, readAheadBuffer.Length); + + do + { + var bytesRead = readAheadBytesRead; + var buffer = readAheadBuffer; + + readAheadBuffer = new byte[bufferSize]; + readAheadBytesRead = stream.Read(readAheadBuffer, 0, readAheadBuffer.Length); + + if (readAheadBytesRead == 0) + md5.TransformFinalBlock(buffer, 0, bytesRead); + else + md5.TransformBlock(buffer, 0, bytesRead, buffer, 0); + } + while (readAheadBytesRead != 0); + + return md5.Hash; +#else + using (var ms = new MemoryStream()) + { + stream.Position = 0; + stream.CopyTo(ms); + + return (createHasher ? MD5.Create() : Md5Hasher.Value).ComputeHash(ms.ToArray()); + } +#endif + } + + /// + /// Computes the MD5 hash of the given string using UTF8 byte encoding. + /// + /// The input string. + /// if set to true [create hasher]. + /// The computed hash code. + public static byte[] ComputeMD5(this string value, bool createHasher = false) => + Encoding.UTF8.GetBytes(value).ComputeMD5(createHasher); + + /// + /// Computes the MD5 hash of the given byte array. + /// + /// The data. + /// if set to true [create hasher]. + /// The computed hash code. + public static byte[] ComputeMD5(this byte[] data, bool createHasher = false) => + (createHasher ? MD5.Create() : Md5Hasher.Value).ComputeHash(data); + + /// + /// Computes the SHA-1 hash of the given string using UTF8 byte encoding. + /// + /// The input string. + /// if set to true [create hasher]. + /// + /// The computes a Hash-based Message Authentication Code (HMAC) + /// using the SHA1 hash function. + /// + public static byte[] ComputeSha1(this string value, bool createHasher = false) + { + var inputBytes = Encoding.UTF8.GetBytes(value); + return (createHasher ? SHA1.Create() : SHA1Hasher.Value).ComputeHash(inputBytes); + } + + /// + /// Computes the SHA-256 hash of the given string using UTF8 byte encoding. + /// + /// The input string. + /// if set to true [create hasher]. + /// + /// The computes a Hash-based Message Authentication Code (HMAC) + /// by using the SHA256 hash function. + /// + public static byte[] ComputeSha256(this string value, bool createHasher = false) + { + var inputBytes = Encoding.UTF8.GetBytes(value); + return (createHasher ? SHA256.Create() : SHA256Hasher.Value).ComputeHash(inputBytes); + } + + /// + /// Computes the SHA-512 hash of the given string using UTF8 byte encoding. + /// + /// The input string. + /// if set to true [create hasher]. + /// + /// The computes a Hash-based Message Authentication Code (HMAC) + /// using the SHA512 hash function. + /// + public static byte[] ComputeSha512(this string value, bool createHasher = false) + { + var inputBytes = Encoding.UTF8.GetBytes(value); + return (createHasher ? SHA512.Create() : SHA512Hasher.Value).ComputeHash(inputBytes); + } + + /// + /// Returns a string that represents the given item + /// It tries to use InvariantCulture if the ToString(IFormatProvider) + /// overload exists. + /// + /// The item. + /// A that represents the current object. + public static string ToStringInvariant(this object obj) + { + if (obj == null) + return string.Empty; + + var itemType = obj.GetType(); + + if (itemType == typeof(string)) + return obj as string; + + return Definitions.BasicTypesInfo.ContainsKey(itemType) + ? Definitions.BasicTypesInfo[itemType].ToStringInvariant(obj) + : obj.ToString(); + } + + /// + /// Returns a string that represents the given item + /// It tries to use InvariantCulture if the ToString(IFormatProvider) + /// overload exists. + /// + /// The type to get the string. + /// The item. + /// A that represents the current object. + public static string ToStringInvariant(this T item) + { + if (typeof(string) == typeof(T)) + return Equals(item, default(T)) ? string.Empty : item as string; + + return ToStringInvariant(item as object); + } + + /// + /// Removes the control characters from a string except for those specified. + /// + /// The input. + /// When specified, these characters will not be removed. + /// + /// A string that represents the current object. + /// + /// input. + public static string RemoveControlCharsExcept(this string value, params char[] excludeChars) + { + if (value == null) + throw new ArgumentNullException(nameof(value)); + + if (excludeChars == null) + excludeChars = new char[] { }; + + return new string(value + .Where(c => char.IsControl(c) == false || excludeChars.Contains(c)) + .ToArray()); + } + + /// + /// Removes all control characters from a string, including new line sequences. + /// + /// The input. + /// A that represents the current object. + /// input. + public static string RemoveControlChars(this string value) => value.RemoveControlCharsExcept(null); + + /// + /// Outputs JSON string representing this object. + /// + /// The object. + /// if set to true format the output. + /// A that represents the current object. + public static string ToJson(this object obj, bool format = true) => + obj == null ? string.Empty : Json.Serialize(obj, format); + + /// + /// Returns text representing the properties of the specified object in a human-readable format. + /// While this method is fairly expensive computationally speaking, it provides an easy way to + /// examine objects. + /// + /// The object. + /// A that represents the current object. + public static string Stringify(this object obj) + { + if (obj == null) + return "(null)"; + + try + { + var jsonText = Json.Serialize(obj, false, "$type"); + var jsonData = Json.Deserialize(jsonText); + + return new HumanizeJson(jsonData, 0).GetResult(); + } + catch + { + return obj.ToStringInvariant(); + } + } + + /// + /// Retrieves a section of the string, inclusive of both, the start and end indexes. + /// This behavior is unlike JavaScript's Slice behavior where the end index is non-inclusive + /// If the string is null it returns an empty string. + /// + /// The string. + /// The start index. + /// The end index. + /// Retrieves a substring from this instance. + public static string Slice(this string value, int startIndex, int endIndex) + { + if (value == null) + return string.Empty; + + var end = endIndex.Clamp(startIndex, value.Length - 1); + + return startIndex >= end ? string.Empty : value.Substring(startIndex, (end - startIndex) + 1); + } + + /// + /// Gets a part of the string clamping the length and startIndex parameters to safe values. + /// If the string is null it returns an empty string. This is basically just a safe version + /// of string.Substring. + /// + /// The string. + /// The start index. + /// The length. + /// Retrieves a substring from this instance. + public static string SliceLength(this string str, int startIndex, int length) + { + if (str == null) + return string.Empty; + + var start = startIndex.Clamp(0, str.Length - 1); + var len = length.Clamp(0, str.Length - start); + + return len == 0 ? string.Empty : str.Substring(start, len); + } + + /// + /// Splits the specified text into r, n or rn separated lines. + /// + /// The text. + /// + /// An array whose elements contain the substrings from this instance + /// that are delimited by one or more characters in separator. + /// + public static string[] ToLines(this string value) => + value == null ? new string[] { } : SplitLinesRegex.Value.Split(value); + + /// + /// Humanizes (make more human-readable) an identifier-style string + /// in either camel case or snake case. For example, CamelCase will be converted to + /// Camel Case and Snake_Case will be converted to Snake Case. + /// + /// The identifier-style string. + /// A that represents the current object. + public static string Humanize(this string value) + { + if (value == null) + return string.Empty; + + var returnValue = UnderscoreRegex.Value.Replace(value, " "); + returnValue = CamelCaseRegEx.Value.Replace(returnValue, SplitCamelCaseString.Value); + return returnValue; + } + + /// + /// Indents the specified multi-line text with the given amount of leading spaces + /// per line. + /// + /// The text. + /// The spaces. + /// A that represents the current object. + public static string Indent(this string value, int spaces = 4) + { + if (value == null) value = string.Empty; + if (spaces <= 0) return value; + + var lines = value.ToLines(); + var builder = new StringBuilder(); + var indentStr = new string(' ', spaces); + + foreach (var line in lines) + { + builder.AppendLine($"{indentStr}{line}"); + } + + return builder.ToString().TrimEnd(); + } + + /// + /// Gets the line and column number (i.e. not index) of the + /// specified character index. Useful to locate text in a multi-line + /// string the same way a text editor does. + /// Please not that the tuple contains first the line number and then the + /// column number. + /// + /// The string. + /// Index of the character. + /// A 2-tuple whose value is (item1, item2). + public static Tuple TextPositionAt(this string value, int charIndex) + { + if (value == null) + return Tuple.Create(0, 0); + + var index = charIndex.Clamp(0, value.Length - 1); + + var lineIndex = 0; + var colNumber = 0; + + for (var i = 0; i <= index; i++) + { + if (value[i] == '\n') + { + lineIndex++; + colNumber = 0; + continue; + } + + if (value[i] != '\r') + colNumber++; + } + + return Tuple.Create(lineIndex + 1, colNumber); + } + + /// + /// Makes the file name system safe. + /// + /// The s. + /// + /// A string with a safe file name. + /// + /// s. + public static string ToSafeFilename(this string value) + { + return value == null + ? throw new ArgumentNullException(nameof(value)) + : InvalidFilenameChars.Value + .Aggregate(value, (current, c) => current.Replace(c, string.Empty)) + .Slice(0, 220); + } + + /// + /// Formats a long into the closest bytes string. + /// + /// The bytes length. + /// + /// The string representation of the current Byte object, formatted as specified by the format parameter. + /// + public static string FormatBytes(this long bytes) => ((ulong) bytes).FormatBytes(); + + /// + /// Formats a long into the closest bytes string. + /// + /// The bytes length. + /// + /// A copy of format in which the format items have been replaced by the string + /// representations of the corresponding arguments. + /// + public static string FormatBytes(this ulong bytes) + { + int i; + double dblSByte = bytes; + + for (i = 0; i < ByteSuffixes.Length && bytes >= 1024; i++, bytes /= 1024) + { + dblSByte = bytes / 1024.0; + } + + return $"{dblSByte:0.##} {ByteSuffixes[i]}"; + } + + /// + /// Truncates the specified value. + /// + /// The value. + /// The maximum length. + /// + /// Retrieves a substring from this instance. + /// The substring starts at a specified character position and has a specified length. + /// + public static string Truncate(this string value, int maximumLength) => + Truncate(value, maximumLength, string.Empty); + + /// + /// Truncates the specified value and append the omission last. + /// + /// The value. + /// The maximum length. + /// The omission. + /// + /// Retrieves a substring from this instance. + /// The substring starts at a specified character position and has a specified length. + /// + public static string Truncate(this string value, int maximumLength, string omission) + { + if (value == null) + return null; + + return value.Length > maximumLength + ? value.Substring(0, maximumLength) + (omission ?? string.Empty) + : value; + } + + /// + /// Determines whether the specified contains any of characters in + /// the specified array of . + /// + /// + /// true if contains any of ; + /// otherwise, false. + /// + /// + /// A to test. + /// + /// + /// An array of that contains characters to find. + /// + public static bool Contains(this string value, params char[] chars) => + chars?.Length == 0 || (!string.IsNullOrEmpty(value) && value.IndexOfAny(chars) > -1); + + /// + /// Replaces all chars in a string. + /// + /// The value. + /// The replace value. + /// The chars. + /// The string with the characters replaced. + public static string ReplaceAll(this string value, string replaceValue, params char[] chars) => + chars.Aggregate(value, (current, c) => current.Replace(new string(new[] {c}), replaceValue)); + + /// + /// Convert hex character to an integer. Return -1 if char is something + /// other than a hex char. + /// + /// The c. + /// Converted integer. + public static int Hex2Int(this char value) + { + return value >= '0' && value <= '9' + ? value - '0' + : value >= 'A' && value <= 'F' + ? value - 'A' + 10 + : value >= 'a' && value <= 'f' + ? value - 'a' + 10 + : -1; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Extensions.ValueTypes.cs b/Unosquare.Swan.Lite/Extensions.ValueTypes.cs new file mode 100644 index 0000000..6454eac --- /dev/null +++ b/Unosquare.Swan.Lite/Extensions.ValueTypes.cs @@ -0,0 +1,168 @@ +namespace Unosquare.Swan +{ + using System; + using System.Reflection; + using System.Runtime.InteropServices; + using Attributes; + + /// + /// Provides various extension methods for value types and structs. + /// + public static class ValueTypeExtensions + { + /// + /// Clamps the specified value between the minimum and the maximum. + /// + /// The type of value to clamp. + /// The value. + /// The minimum. + /// The maximum. + /// A value that indicates the relative order of the objects being compared. + public static T Clamp(this T value, T min, T max) + where T : struct, IComparable + { + if (value.CompareTo(min) < 0) return min; + + return value.CompareTo(max) > 0 ? max : value; + } + + /// + /// Clamps the specified value between the minimum and the maximum. + /// + /// The value. + /// The minimum. + /// The maximum. + /// A value that indicates the relative order of the objects being compared. + public static int Clamp(this int value, int min, int max) + => value < min ? min : (value > max ? max : value); + + /// + /// Determines whether the specified value is between a minimum and a maximum value. + /// + /// The type of value to check. + /// The value. + /// The minimum. + /// The maximum. + /// + /// true if the specified minimum is between; otherwise, false. + /// + public static bool IsBetween(this T value, T min, T max) + where T : struct, IComparable + { + return value.CompareTo(min) >= 0 && value.CompareTo(max) <= 0; + } + + /// + /// Converts an array of bytes into the given struct type. + /// + /// The type of structure to convert. + /// The data. + /// a struct type derived from convert an array of bytes ref=ToStruct". + public static T ToStruct(this byte[] data) + where T : struct + { + return ToStruct(data, 0, data.Length); + } + + /// + /// Converts an array of bytes into the given struct type. + /// + /// The type of structure to convert. + /// The data. + /// The offset. + /// The length. + /// + /// A managed object containing the data pointed to by the ptr parameter. + /// + /// data. + public static T ToStruct(this byte[] data, int offset, int length) + where T : struct + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + + var buffer = new byte[length]; + Array.Copy(data, offset, buffer, 0, buffer.Length); + var handle = GCHandle.Alloc(GetStructBytes(buffer), GCHandleType.Pinned); + + try + { + return Marshal.PtrToStructure(handle.AddrOfPinnedObject()); + } + finally + { + handle.Free(); + } + } + + /// + /// Converts a struct to an array of bytes. + /// + /// The type of structure to convert. + /// The object. + /// A byte array containing the results of encoding the specified set of characters. + public static byte[] ToBytes(this T obj) + where T : struct + { + var data = new byte[Marshal.SizeOf(obj)]; + var handle = GCHandle.Alloc(data, GCHandleType.Pinned); + + try + { + Marshal.StructureToPtr(obj, handle.AddrOfPinnedObject(), false); + return GetStructBytes(data); + } + finally + { + handle.Free(); + } + } + + /// + /// Swaps the endianness of an unsigned long to an unsigned integer. + /// + /// The bytes contained in a long. + /// + /// A 32-bit unsigned integer equivalent to the ulong + /// contained in longBytes. + /// + public static uint SwapEndianness(this ulong longBytes) + => (uint) (((longBytes & 0x000000ff) << 24) + + ((longBytes & 0x0000ff00) << 8) + + ((longBytes & 0x00ff0000) >> 8) + + ((longBytes & 0xff000000) >> 24)); + + private static byte[] GetStructBytes(byte[] data) + { + if (data == null) + throw new ArgumentNullException(nameof(data)); + +#if !NETSTANDARD1_3 + var fields = typeof(T).GetTypeInfo() + .GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); +#else + var fields = typeof(T).GetTypeInfo().DeclaredFields; +#endif + var endian = Runtime.AttributeCache.RetrieveOne(); + + foreach (var field in fields) + { + if (endian == null && !field.IsDefined(typeof(StructEndiannessAttribute), false)) + continue; + + var offset = Marshal.OffsetOf(field.Name).ToInt32(); + var length = Marshal.SizeOf(field.FieldType); + + endian = endian ?? Runtime.AttributeCache.RetrieveOne(field); + + if (endian != null && (endian.Endianness == Endianness.Big && BitConverter.IsLittleEndian || + endian.Endianness == Endianness.Little && !BitConverter.IsLittleEndian)) + { + Array.Reverse(data, offset, length); + } + } + + return data; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Extensions.cs b/Unosquare.Swan.Lite/Extensions.cs new file mode 100644 index 0000000..01e8ab9 --- /dev/null +++ b/Unosquare.Swan.Lite/Extensions.cs @@ -0,0 +1,331 @@ +namespace Unosquare.Swan +{ + using Attributes; + using System; + using System.Collections; + using System.Collections.Generic; + using System.Diagnostics; + using System.Linq; + using System.Reflection; + using System.Threading.Tasks; + + /// + /// Extension methods. + /// + public static partial class Extensions + { + /// + /// Iterates over the public, instance, readable properties of the source and + /// tries to write a compatible value to a public, instance, writable property in the destination. + /// + /// The type of the source. + /// The source. + /// The target. + /// Number of properties that was copied successful. + public static int CopyPropertiesTo(this T source, object target) + where T : class + { + var copyable = GetCopyableProperties(target); + return copyable.Any() + ? CopyOnlyPropertiesTo(source, target, copyable.ToArray()) + : CopyPropertiesTo(source, target, null); + } + + /// + /// Iterates over the public, instance, readable properties of the source and + /// tries to write a compatible value to a public, instance, writable property in the destination. + /// + /// The source. + /// The destination. + /// The ignore properties. + /// + /// Number of properties that were successfully copied. + /// + public static int CopyPropertiesTo(this object source, object target, string[] ignoreProperties = null) + => Components.ObjectMapper.Copy(source, target, null, ignoreProperties); + + /// + /// Iterates over the public, instance, readable properties of the source and + /// tries to write a compatible value to a public, instance, writable property in the destination. + /// + /// The type of the source. + /// The source. + /// The target. + /// Number of properties that was copied successful. + public static int CopyOnlyPropertiesTo(this T source, object target) + where T : class + { + return CopyOnlyPropertiesTo(source, target, null); + } + + /// + /// Iterates over the public, instance, readable properties of the source and + /// tries to write a compatible value to a public, instance, writable property in the destination. + /// + /// The source. + /// The destination. + /// Properties to copy. + /// + /// Number of properties that were successfully copied. + /// + public static int CopyOnlyPropertiesTo(this object source, object target, string[] propertiesToCopy) + { + return Components.ObjectMapper.Copy(source, target, propertiesToCopy); + } + + /// + /// Copies the properties to new instance of T. + /// + /// The new object type. + /// The source. + /// The ignore properties. + /// + /// The specified type with properties copied. + /// + /// source. + public static T DeepClone(this T source, string[] ignoreProperties = null) + where T : class + { + return source.CopyPropertiesToNew(ignoreProperties); + } + + /// + /// Copies the properties to new instance of T. + /// + /// The new object type. + /// The source. + /// The ignore properties. + /// + /// The specified type with properties copied. + /// + /// source. + public static T CopyPropertiesToNew(this object source, string[] ignoreProperties = null) + where T : class + { + if (source == null) + throw new ArgumentNullException(nameof(source)); + + var target = Activator.CreateInstance(); + var copyable = target.GetCopyableProperties(); + + if (copyable.Any()) + source.CopyOnlyPropertiesTo(target, copyable.ToArray()); + else + source.CopyPropertiesTo(target, ignoreProperties); + + return target; + } + + /// + /// Copies the only properties to new instance of T. + /// + /// Object Type. + /// The source. + /// The properties to copy. + /// + /// The specified type with properties copied. + /// + /// source. + public static T CopyOnlyPropertiesToNew(this object source, string[] propertiesToCopy) + where T : class + { + if (source == null) + throw new ArgumentNullException(nameof(source)); + + var target = Activator.CreateInstance(); + source.CopyOnlyPropertiesTo(target, propertiesToCopy); + return target; + } + + /// + /// Iterates over the keys of the source and tries to write a compatible value to a public, + /// instance, writable property in the destination. + /// + /// The source. + /// The target. + /// The ignore keys. + /// Number of properties that was copied successful. + public static int CopyKeyValuePairTo( + this IDictionary source, + object target, + string[] ignoreKeys = null) + { + return Components.ObjectMapper.Copy(source, target, null, ignoreKeys); + } + + /// + /// Measures the elapsed time of the given action as a TimeSpan + /// This method uses a high precision Stopwatch. + /// + /// The target. + /// + /// A time interval that represents a specified time, where the specification is in units of ticks. + /// + /// target. + public static TimeSpan Benchmark(this Action target) + { + if (target == null) + throw new ArgumentNullException(nameof(target)); + + var sw = new Stopwatch(); + + try + { + sw.Start(); + target.Invoke(); + } + catch + { + // swallow + } + finally + { + sw.Stop(); + } + + return TimeSpan.FromTicks(sw.ElapsedTicks); + } + + /// + /// Does the specified action. + /// + /// The action. + /// The retry interval. + /// The retry count. + public static void Retry( + this Action action, + TimeSpan retryInterval = default, + int retryCount = 3) + { + if (action == null) + throw new ArgumentNullException(nameof(action)); + + Retry(() => + { + action(); + return null; + }, + retryInterval, + retryCount); + } + + /// + /// Does the specified action. + /// + /// The type of the source. + /// The action. + /// The retry interval. + /// The retry count. + /// + /// The return value of the method that this delegate encapsulates. + /// + /// action. + /// Represents one or many errors that occur during application execution. + public static T Retry( + this Func action, + TimeSpan retryInterval = default, + int retryCount = 3) + { + if (action == null) + throw new ArgumentNullException(nameof(action)); + + if (retryInterval == default) + retryInterval = TimeSpan.FromSeconds(1); + + var exceptions = new List(); + + for (var retry = 0; retry < retryCount; retry++) + { + try + { + if (retry > 0) + Task.Delay(retryInterval).Wait(); + + return action(); + } + catch (Exception ex) + { + exceptions.Add(ex); + } + } + + throw new AggregateException(exceptions); + } + + /// + /// Retrieves the exception message, plus all the inner exception messages separated by new lines. + /// + /// The ex. + /// The prior message. + /// A that represents this instance. + public static string ExceptionMessage(this Exception ex, string priorMessage = "") + { + while (true) + { + if (ex == null) + throw new ArgumentNullException(nameof(ex)); + + var fullMessage = string.IsNullOrWhiteSpace(priorMessage) + ? ex.Message + : priorMessage + "\r\n" + ex.Message; + + if (string.IsNullOrWhiteSpace(ex.InnerException?.Message)) + return fullMessage; + + ex = ex.InnerException; + priorMessage = fullMessage; + } + } + + /// + /// Gets the copyable properties. + /// + /// The object. + /// + /// Array of properties. + /// + /// model. + public static IEnumerable GetCopyableProperties(this object obj) + { + if (obj == null) + throw new ArgumentNullException(nameof(obj)); + + return Runtime.PropertyTypeCache + .RetrieveAllProperties(obj.GetType(), true) + .Select(x => new { x.Name, HasAttribute = Runtime.AttributeCache.RetrieveOne(x) != null}) + .Where(x => x.HasAttribute) + .Select(x => x.Name); + } + + /// + /// Returns true if the object is valid. + /// + /// The object. + /// + /// true if the specified model is valid; otherwise, false. + /// + public static bool IsValid(this object obj) => Runtime.ObjectValidator.IsValid(obj); + + internal static void CreateTarget( + this object source, + Type targetType, + bool includeNonPublic, + ref object target) + { + switch (source) + { + case string _: + break; // do nothing. Simply skip creation + case IList sourceObjectList when targetType.IsArray: // When using arrays, there is no default constructor, attempt to build a compatible array + var elementType = targetType.GetElementType(); + + if (elementType != null) + target = Array.CreateInstance(elementType, sourceObjectList.Count); + break; + default: + target = Activator.CreateInstance(targetType, includeNonPublic); + break; + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Formatters/CsvReader.cs b/Unosquare.Swan.Lite/Formatters/CsvReader.cs new file mode 100644 index 0000000..210d8d9 --- /dev/null +++ b/Unosquare.Swan.Lite/Formatters/CsvReader.cs @@ -0,0 +1,650 @@ +namespace Unosquare.Swan.Formatters +{ + using Reflection; + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Text; + + /// + /// Represents a reader designed for CSV text. + /// It is capable of deserializing objects from individual lines of CSV text, + /// transforming CSV lines of text into objects, + /// or simply reading the lines of CSV as an array of strings. + /// + /// + /// + /// The following example describes how to load a list of objects from a CSV file. + /// + /// using Unosquare.Swan.Formatters; + /// + /// class Example + /// { + /// class Person + /// { + /// public string Name { get; set; } + /// public int Age { get; set; } + /// } + /// + /// static void Main() + /// { + /// // load records from a CSV file + /// var loadedRecords = + /// CsvReader.LoadRecords<Person>("C:\\Users\\user\\Documents\\file.csv"); + /// + /// // loadedRecords = + /// // [ + /// // { Age = 20, Name = "George" } + /// // { Age = 18, Name = "Juan" } + /// // ] + /// } + /// } + /// + /// The following code explains how to read a CSV formatted string. + /// + /// using Unosquare.Swan.Formatters; + /// using System.Text; + /// using Unosquare.Swan.Formatters; + /// + /// class Example + /// { + /// static void Main() + /// { + /// // data to be read + /// var data = @"Company,OpenPositions,MainTechnology,Revenue + /// Co,2,""C#, MySQL, JavaScript, HTML5 and CSS3"",500 + /// Ca,2,""C#, MySQL, JavaScript, HTML5 and CSS3"",600"; + /// + /// using(var stream = new MemoryStream(Encoding.UTF8.GetBytes(data))) + /// { + /// // create a CSV reader + /// var reader = new CsvReader(stream, false, Encoding.UTF8); + /// } + /// } + /// } + /// + /// + public class CsvReader : IDisposable + { + private static readonly PropertyTypeCache TypeCache = new PropertyTypeCache(); + + private readonly object _syncLock = new object(); + + private ulong _count; + private char _escapeCharacter = '"'; + private char _separatorCharacter = ','; + + private bool _hasDisposed; // To detect redundant calls + private string[] _headings; + private Dictionary _defaultMap; + private StreamReader _reader; + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The stream. + /// if set to true leaves the input stream open. + /// The text encoding. + public CsvReader(Stream inputStream, bool leaveOpen, Encoding textEncoding) + { + if (inputStream == null) + throw new ArgumentNullException(nameof(inputStream)); + + if (textEncoding == null) + throw new ArgumentNullException(nameof(textEncoding)); + + _reader = new StreamReader(inputStream, textEncoding, true, 2048, leaveOpen); + } + + /// + /// Initializes a new instance of the class. + /// It will automatically close the stream upon disposing. + /// + /// The stream. + /// The text encoding. + public CsvReader(Stream stream, Encoding textEncoding) + : this(stream, false, textEncoding) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// It automatically closes the stream when disposing this reader + /// and uses the Windows 1253 encoding. + /// + /// The stream. + public CsvReader(Stream stream) + : this(stream, false, Definitions.Windows1252Encoding) + { + } + + /// + /// Initializes a new instance of the class. + /// It uses the Windows 1252 Encoding by default and it automatically closes the file + /// when this reader is disposed of. + /// + /// The filename. + public CsvReader(string filename) + : this(File.OpenRead(filename), false, Definitions.Windows1252Encoding) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// It automatically closes the file when disposing this reader. + /// + /// The filename. + /// The encoding. + public CsvReader(string filename, Encoding encoding) + : this(File.OpenRead(filename), false, encoding) + { + // placeholder + } + + #endregion + + #region Properties + + /// + /// Gets number of lines that have been read, including the headings. + /// + /// + /// The count. + /// + public ulong Count + { + get + { + lock (_syncLock) + { + return _count; + } + } + } + + /// + /// Gets or sets the escape character. + /// By default it is the double quote '"'. + /// + /// + /// The escape character. + /// + public char EscapeCharacter + { + get => _escapeCharacter; + set + { + lock (_syncLock) + { + _escapeCharacter = value; + } + } + } + + /// + /// Gets or sets the separator character. + /// By default it is the comma character ','. + /// + /// + /// The separator character. + /// + public char SeparatorCharacter + { + get => _separatorCharacter; + set + { + lock (_syncLock) + { + _separatorCharacter = value; + } + } + } + + /// + /// Gets a value indicating whether the stream reader is at the end of the stream + /// In other words, if no more data can be read, this will be set to true. + /// + /// + /// true if [end of stream]; otherwise, false. + /// + public bool EndOfStream + { + get + { + lock (_syncLock) + { + return _reader.EndOfStream; + } + } + } + + #endregion + + #region Generic, Main ReadLine method + + /// + /// Reads a line of CSV text into an array of strings. + /// + /// An array of the specified element type containing copies of the elements of the ArrayList. + /// Cannot read past the end of the stream. + public string[] ReadLine() + { + lock (_syncLock) + { + if (_reader.EndOfStream) + throw new EndOfStreamException("Cannot read past the end of the stream"); + + var values = ParseRecord(_reader, _escapeCharacter, _separatorCharacter); + _count++; + return values; + } + } + + #endregion + + #region Read Methods + + /// + /// Skips a line of CSV text. + /// This operation does not increment the Count property and it is useful when you need to read the headings + /// skipping over a few lines as Reading headings is only supported + /// as the first read operation (i.e. while count is still 0). + /// + /// Cannot read past the end of the stream. + public void SkipRecord() + { + lock (_syncLock) + { + if (_reader.EndOfStream) + throw new EndOfStreamException("Cannot read past the end of the stream"); + + ParseRecord(_reader, _escapeCharacter, _separatorCharacter); + } + } + + /// + /// Reads a line of CSV text and stores the values read as a representation of the column names + /// to be used for parsing objects. You have to call this method before calling ReadObject methods. + /// + /// An array of the specified element type containing copies of the elements of the ArrayList. + /// + /// Reading headings is only supported as the first read operation. + /// or + /// ReadHeadings. + /// + /// Cannot read past the end of the stream. + public string[] ReadHeadings() + { + lock (_syncLock) + { + if (_headings != null) + throw new InvalidOperationException($"The {nameof(ReadHeadings)} method had already been called."); + + if (_count != 0) + throw new InvalidOperationException("Reading headings is only supported as the first read operation."); + + _headings = ReadLine(); + _defaultMap = _headings.ToDictionary(x => x, x => x); + + return _headings.ToArray(); + } + } + + /// + /// Reads a line of CSV text, converting it into a dynamic object in which properties correspond to the names of the headings. + /// + /// The mappings between CSV headings (keys) and object properties (values). + /// Object of the type of the elements in the collection of key/value pairs. + /// ReadHeadings. + /// Cannot read past the end of the stream. + /// map. + public IDictionary ReadObject(IDictionary map) + { + lock (_syncLock) + { + if (_headings == null) + throw new InvalidOperationException($"Call the {nameof(ReadHeadings)} method before reading as an object."); + + if (map == null) + throw new ArgumentNullException(nameof(map)); + + var result = new Dictionary(); + var values = ReadLine(); + + for (var i = 0; i < _headings.Length; i++) + { + if (i > values.Length - 1) + break; + + result[_headings[i]] = values[i]; + } + + return result; + } + } + + /// + /// Reads a line of CSV text, converting it into a dynamic object + /// The property names correspond to the names of the CSV headings. + /// + /// Object of the type of the elements in the collection of key/value pairs. + public IDictionary ReadObject() => ReadObject(_defaultMap); + + /// + /// Reads a line of CSV text converting it into an object of the given type, using a map (or Dictionary) + /// where the keys are the names of the headings and the values are the names of the instance properties + /// in the given Type. The result object must be already instantiated. + /// + /// The type of object to map. + /// The map. + /// The result. + /// map + /// or + /// result. + /// ReadHeadings. + /// Cannot read past the end of the stream. + public void ReadObject(IDictionary map, ref T result) + { + lock (_syncLock) + { + // Check arguments + { + if (map == null) + throw new ArgumentNullException(nameof(map)); + + if (_reader.EndOfStream) + throw new EndOfStreamException("Cannot read past the end of the stream"); + + if (_headings == null) + throw new InvalidOperationException($"Call the {nameof(ReadHeadings)} method before reading as an object."); + + if (Equals(result, default(T))) + throw new ArgumentNullException(nameof(result)); + } + + // Read line and extract values + var values = ReadLine(); + + // Extract properties from cache + var properties = TypeCache + .RetrieveFilteredProperties(typeof(T), true, x => x.CanWrite && Definitions.BasicTypesInfo.ContainsKey(x.PropertyType)); + + // Assign property values for each heading + for (var i = 0; i < _headings.Length; i++) + { + // break if no more headings are matched + if (i > values.Length - 1) + break; + + // skip if no heading is available or the heading is empty + if (map.ContainsKey(_headings[i]) == false && + string.IsNullOrWhiteSpace(map[_headings[i]]) == false) + continue; + + // Prepare the target property + var propertyName = map[_headings[i]]; + + // Parse and assign the basic type value to the property if exists + properties + .FirstOrDefault(p => p.Name.Equals(propertyName))? + .TrySetBasicType(values[i], result); + } + } + } + + /// + /// Reads a line of CSV text converting it into an object of the given type, using a map (or Dictionary) + /// where the keys are the names of the headings and the values are the names of the instance properties + /// in the given Type. + /// + /// The type of object to map. + /// The map of CSV headings (keys) and Type property names (values). + /// The conversion of specific type of object. + /// map. + /// ReadHeadings. + /// Cannot read past the end of the stream. + public T ReadObject(IDictionary map) + where T : new() + { + var result = Activator.CreateInstance(); + ReadObject(map, ref result); + return result; + } + + /// + /// Reads a line of CSV text converting it into an object of the given type, and assuming + /// the property names of the target type match the heading names of the file. + /// + /// The type of object. + /// The conversion of specific type of object. + public T ReadObject() + where T : new() + { + return ReadObject(_defaultMap); + } + + #endregion + + #region Support Methods + + /// + /// Parses a line of standard CSV text into an array of strings. + /// Note that quoted values might have new line sequences in them. Field values will contain such sequences. + /// + /// The reader. + /// The escape character. + /// The separator character. + /// An array of the specified element type containing copies of the elements of the ArrayList. + private static string[] ParseRecord(StreamReader reader, char escapeCharacter = '"', char separatorCharacter = ',') + { + var values = new List(); + var currentValue = new StringBuilder(1024); + var currentState = ReadState.WaitingForNewField; + string line; + + while ((line = reader.ReadLine()) != null) + { + for (var charIndex = 0; charIndex < line.Length; charIndex++) + { + // Get the current and next character + var currentChar = line[charIndex]; + var nextChar = charIndex < line.Length - 1 ? line[charIndex + 1] : new char?(); + + // Perform logic based on state and decide on next state + switch (currentState) + { + case ReadState.WaitingForNewField: + { + currentValue.Clear(); + + if (currentChar == escapeCharacter) + { + currentState = ReadState.PushingQuoted; + continue; + } + + if (currentChar == separatorCharacter) + { + values.Add(currentValue.ToString()); + currentState = ReadState.WaitingForNewField; + continue; + } + + currentValue.Append(currentChar); + currentState = ReadState.PushingNormal; + continue; + } + + case ReadState.PushingNormal: + { + // Handle field content delimiter by comma + if (currentChar == separatorCharacter) + { + currentState = ReadState.WaitingForNewField; + values.Add(currentValue.ToString()); + currentValue.Clear(); + continue; + } + + // Handle double quote escaping + if (currentChar == escapeCharacter && nextChar.HasValue && nextChar == escapeCharacter) + { + // advance 1 character now. The loop will advance one more. + currentValue.Append(currentChar); + charIndex++; + continue; + } + + currentValue.Append(currentChar); + break; + } + + case ReadState.PushingQuoted: + { + // Handle field content delimiter by ending double quotes + if (currentChar == escapeCharacter && (nextChar.HasValue == false || nextChar != escapeCharacter)) + { + currentState = ReadState.PushingNormal; + continue; + } + + // Handle double quote escaping + if (currentChar == escapeCharacter && nextChar.HasValue && nextChar == escapeCharacter) + { + // advance 1 character now. The loop will advance one more. + currentValue.Append(currentChar); + charIndex++; + continue; + } + + currentValue.Append(currentChar); + break; + } + } + } + + // determine if we need to continue reading a new line if it is part of the quoted + // field value + if (currentState == ReadState.PushingQuoted) + { + // we need to add the new line sequence to the output of the field + // because we were pushing a quoted value + currentValue.Append(Environment.NewLine); + } + else + { + // push anything that has not been pushed (flush) into a last value + values.Add(currentValue.ToString()); + currentValue.Clear(); + + // stop reading more lines we have reached the end of the CSV record + break; + } + } + + // If we ended up pushing quoted and no closing quotes we might + // have additional text in yt + if (currentValue.Length > 0) + { + values.Add(currentValue.ToString()); + } + + return values.ToArray(); + } + + #endregion + + #region Helpers + + /// + /// Loads the records from the stream + /// This method uses Windows 1252 encoding. + /// + /// The type of IList items to load. + /// The stream. + /// A generic collection of objects that can be individually accessed by index. + public static IList LoadRecords(Stream stream) + where T : new() + { + var result = new List(); + + using (var reader = new CsvReader(stream)) + { + reader.ReadHeadings(); + while (!reader.EndOfStream) + { + result.Add(reader.ReadObject()); + } + } + + return result; + } + + /// + /// Loads the records from the give file path. + /// This method uses Windows 1252 encoding. + /// + /// The type of IList items to load. + /// The file path. + /// A generic collection of objects that can be individually accessed by index. + public static IList LoadRecords(string filePath) + where T : new() + { + return LoadRecords(File.OpenRead(filePath)); + } + + #endregion + + #region IDisposable Support + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposing) + { + if (_hasDisposed) return; + + if (disposing) + { + try + { + _reader.Dispose(); + } + finally + { + _reader = null; + } + } + + _hasDisposed = true; + } + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + Dispose(true); + } + + #endregion + + /// + /// Defines the 3 different read states + /// for the parsing state machine. + /// + private enum ReadState + { + WaitingForNewField, + PushingNormal, + PushingQuoted, + } + } +} diff --git a/Unosquare.Swan.Lite/Formatters/CsvWriter.cs b/Unosquare.Swan.Lite/Formatters/CsvWriter.cs new file mode 100644 index 0000000..51de982 --- /dev/null +++ b/Unosquare.Swan.Lite/Formatters/CsvWriter.cs @@ -0,0 +1,478 @@ +namespace Unosquare.Swan.Formatters +{ + using Reflection; + using System; + using System.Collections; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Reflection; + using System.Text; + + /// + /// A CSV writer useful for exporting a set of objects. + /// + /// + /// The following code describes how to save a list of objects into a CSV file. + /// + /// using System.Collections.Generic; + /// using Unosquare.Swan.Formatters; + /// + /// class Example + /// { + /// class Person + /// { + /// public string Name { get; set; } + /// public int Age { get; set; } + /// } + /// + /// static void Main() + /// { + /// // create a list of people + /// var people = new List<Person> + /// { + /// new Person { Name = "Artyom", Age = 20 }, + /// new Person { Name = "Aloy", Age = 18 } + /// } + /// + /// // write items inside file.csv + /// CsvWriter.SaveRecords(people, "C:\\Users\\user\\Documents\\file.csv"); + /// + /// // output + /// // | Name | Age | + /// // | Artyom | 20 | + /// // | Aloy | 18 | + /// } + /// } + /// + /// + public class CsvWriter : IDisposable + { + private static readonly PropertyTypeCache TypeCache = new PropertyTypeCache(); + + private readonly object _syncLock = new object(); + private readonly Stream _outputStream; + private readonly Encoding _encoding; + private readonly bool _leaveStreamOpen; + private bool _isDisposing; + private ulong _mCount; + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The output stream. + /// if set to true [leave open]. + /// The encoding. + public CsvWriter(Stream outputStream, bool leaveOpen, Encoding encoding) + { + _outputStream = outputStream; + _encoding = encoding; + _leaveStreamOpen = leaveOpen; + } + + /// + /// Initializes a new instance of the class. + /// It automatically closes the stream when disposing this writer. + /// + /// The output stream. + /// The encoding. + public CsvWriter(Stream outputStream, Encoding encoding) + : this(outputStream, false, encoding) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// It uses the Windows 1252 encoding and automatically closes + /// the stream upon disposing this writer. + /// + /// The output stream. + public CsvWriter(Stream outputStream) + : this(outputStream, false, Definitions.Windows1252Encoding) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// It opens the file given file, automatically closes the stream upon + /// disposing of this writer, and uses the Windows 1252 encoding. + /// + /// The filename. + public CsvWriter(string filename) + : this(File.OpenWrite(filename), false, Definitions.Windows1252Encoding) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// It opens the file given file, automatically closes the stream upon + /// disposing of this writer, and uses the given text encoding for output. + /// + /// The filename. + /// The encoding. + public CsvWriter(string filename, Encoding encoding) + : this(File.OpenWrite(filename), false, encoding) + { + // placeholder + } + + #endregion + + #region Properties + + /// + /// Gets or sets the field separator character. + /// + /// + /// The separator character. + /// + public char SeparatorCharacter { get; set; } = ','; + + /// + /// Gets or sets the escape character to use to escape field values. + /// + /// + /// The escape character. + /// + public char EscapeCharacter { get; set; } = '"'; + + /// + /// Gets or sets the new line character sequence to use when writing a line. + /// + /// + /// The new line sequence. + /// + public string NewLineSequence { get; set; } = Environment.NewLine; + + /// + /// Defines a list of properties to ignore when outputting CSV lines. + /// + /// + /// The ignore property names. + /// + public List IgnorePropertyNames { get; } = new List(); + + /// + /// Gets number of lines that have been written, including the headings line. + /// + /// + /// The count. + /// + public ulong Count + { + get + { + lock (_syncLock) + { + return _mCount; + } + } + } + + #endregion + + #region Helpers + + /// + /// Saves the items to a stream. + /// It uses the Windows 1252 text encoding for output. + /// + /// The type of enumeration. + /// The items. + /// The stream. + /// true if stream is truncated, default false. + /// Number of item saved. + public static int SaveRecords(IEnumerable items, Stream stream, bool truncateData = false) + { + // truncate the file if it had data + if (truncateData && stream.Length > 0) + stream.SetLength(0); + + using (var writer = new CsvWriter(stream)) + { + writer.WriteHeadings(); + writer.WriteObjects(items); + return (int)writer.Count; + } + } + + /// + /// Saves the items to a CSV file. + /// If the file exits, it overwrites it. If it does not, it creates it. + /// It uses the Windows 1252 text encoding for output. + /// + /// The type of enumeration. + /// The items. + /// The file path. + /// Number of item saved. + public static int SaveRecords(IEnumerable items, string filePath) => SaveRecords(items, File.OpenWrite(filePath), true); + + #endregion + + #region Generic, main Write Line Method + + /// + /// Writes a line of CSV text. Items are converted to strings. + /// If items are found to be null, empty strings are written out. + /// If items are not string, the ToStringInvariant() method is called on them. + /// + /// The items. + public void WriteLine(params object[] items) + => WriteLine(items.Select(x => x == null ? string.Empty : x.ToStringInvariant())); + + /// + /// Writes a line of CSV text. Items are converted to strings. + /// If items are found to be null, empty strings are written out. + /// If items are not string, the ToStringInvariant() method is called on them. + /// + /// The items. + public void WriteLine(IEnumerable items) + => WriteLine(items.Select(x => x == null ? string.Empty : x.ToStringInvariant())); + + /// + /// Writes a line of CSV text. + /// If items are found to be null, empty strings are written out. + /// + /// The items. + public void WriteLine(params string[] items) => WriteLine((IEnumerable) items); + + /// + /// Writes a line of CSV text. + /// If items are found to be null, empty strings are written out. + /// + /// The items. + public void WriteLine(IEnumerable items) + { + lock (_syncLock) + { + var length = items.Count(); + var separatorBytes = _encoding.GetBytes(new[] { SeparatorCharacter }); + var endOfLineBytes = _encoding.GetBytes(NewLineSequence); + + // Declare state variables here to avoid recreation, allocation and + // reassignment in every loop + bool needsEnclosing; + string textValue; + byte[] output; + + for (var i = 0; i < length; i++) + { + textValue = items.ElementAt(i); + + // Determine if we need the string to be enclosed + // (it either contains an escape, new line, or separator char) + needsEnclosing = textValue.IndexOf(SeparatorCharacter) >= 0 + || textValue.IndexOf(EscapeCharacter) >= 0 + || textValue.IndexOf('\r') >= 0 + || textValue.IndexOf('\n') >= 0; + + // Escape the escape characters by repeating them twice for every instance + textValue = textValue.Replace($"{EscapeCharacter}", + $"{EscapeCharacter}{EscapeCharacter}"); + + // Enclose the text value if we need to + if (needsEnclosing) + textValue = string.Format($"{EscapeCharacter}{textValue}{EscapeCharacter}", textValue); + + // Get the bytes to write to the stream and write them + output = _encoding.GetBytes(textValue); + _outputStream.Write(output, 0, output.Length); + + // only write a separator if we are moving in between values. + // the last value should not be written. + if (i < length - 1) + _outputStream.Write(separatorBytes, 0, separatorBytes.Length); + } + + // output the newline sequence + _outputStream.Write(endOfLineBytes, 0, endOfLineBytes.Length); + _mCount += 1; + } + } + + #endregion + + #region Write Object Method + + /// + /// Writes a row of CSV text. It handles the special cases where the object is + /// a dynamic object or and array. It also handles non-collection objects fine. + /// If you do not like the way the output is handled, you can simply write an extension + /// method of this class and use the WriteLine method instead. + /// + /// The item. + /// item. + public void WriteObject(object item) + { + if (item == null) + throw new ArgumentNullException(nameof(item)); + + lock (_syncLock) + { + switch (item) + { + case IDictionary typedItem: + WriteLine(GetFilteredDictionary(typedItem)); + return; + case ICollection typedItem: + WriteLine(typedItem.Cast()); + return; + default: + WriteLine(GetFilteredTypeProperties(item.GetType()) + .Select(x => x.ToFormattedString(item))); + break; + } + } + } + + /// + /// Writes a row of CSV text. It handles the special cases where the object is + /// a dynamic object or and array. It also handles non-collection objects fine. + /// If you do not like the way the output is handled, you can simply write an extension + /// method of this class and use the WriteLine method instead. + /// + /// The type of object to write. + /// The item. + public void WriteObject(T item) => WriteObject(item as object); + + /// + /// Writes a set of items, one per line and atomically by repeatedly calling the + /// WriteObject method. For more info check out the description of the WriteObject + /// method. + /// + /// The type of object to write. + /// The items. + public void WriteObjects(IEnumerable items) + { + lock (_syncLock) + { + foreach (var item in items) + WriteObject(item); + } + } + + #endregion + + #region Write Headings Methods + + /// + /// Writes the headings. + /// + /// The type of object to extract headings. + /// type. + public void WriteHeadings(Type type) + { + if (type == null) + throw new ArgumentNullException(nameof(type)); + + var properties = GetFilteredTypeProperties(type).Select(p => p.Name).Cast(); + WriteLine(properties); + } + + /// + /// Writes the headings. + /// + /// The type of object to extract headings. + public void WriteHeadings() => WriteHeadings(typeof(T)); + + /// + /// Writes the headings. + /// + /// The dictionary to extract headings. + /// dictionary. + public void WriteHeadings(IDictionary dictionary) + { + if (dictionary == null) + throw new ArgumentNullException(nameof(dictionary)); + + WriteLine(GetFilteredDictionary(dictionary, true)); + } + +#if NET452 + /// + /// Writes the headings. + /// + /// The object to extract headings. + /// item + /// Unable to cast dynamic object to a suitable dictionary - item + public void WriteHeadings(dynamic item) + { + if (item == null) + throw new ArgumentNullException(nameof(item)); + + if (!(item is IDictionary dictionary)) + throw new ArgumentException("Unable to cast dynamic object to a suitable dictionary", nameof(item)); + + WriteHeadings(dictionary); + } +#else + /// + /// Writes the headings. + /// + /// The object to extract headings. + /// obj. + public void WriteHeadings(object obj) + { + if (obj == null) + throw new ArgumentNullException(nameof(obj)); + + WriteHeadings(obj.GetType()); + } +#endif + + #endregion + + #region IDisposable Support + + /// + public void Dispose() => Dispose(true); + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + protected virtual void Dispose(bool disposeAlsoManaged) + { + if (_isDisposing) return; + + if (disposeAlsoManaged) + { + if (_leaveStreamOpen == false) + { + _outputStream.Dispose(); + } + } + + _isDisposing = true; + } + + #endregion + + #region Support Methods + + private IEnumerable GetFilteredDictionary(IDictionary dictionary, bool filterKeys = false) + => dictionary + .Keys + .Cast() + .Select(key => key == null ? string.Empty : key.ToStringInvariant()) + .Where(stringKey => !IgnorePropertyNames.Contains(stringKey)) + .Select(stringKey => + filterKeys + ? stringKey + : dictionary[stringKey] == null ? string.Empty : dictionary[stringKey].ToStringInvariant()); + + private IEnumerable GetFilteredTypeProperties(Type type) + => TypeCache.Retrieve(type, t => + t.GetProperties(BindingFlags.Public | BindingFlags.Instance) + .Where(p => p.CanRead)) + .Where(p => !IgnorePropertyNames.Contains(p.Name)); + + #endregion + + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Formatters/HumanizeJson.cs b/Unosquare.Swan.Lite/Formatters/HumanizeJson.cs new file mode 100644 index 0000000..4806deb --- /dev/null +++ b/Unosquare.Swan.Lite/Formatters/HumanizeJson.cs @@ -0,0 +1,150 @@ +namespace Unosquare.Swan.Formatters +{ + using System.Collections.Generic; + using System.Linq; + using System.Text; + + internal class HumanizeJson + { + private readonly StringBuilder _builder = new StringBuilder(); + private readonly int _indent; + private readonly string _indentStr; + private readonly object _obj; + + public HumanizeJson(object obj, int indent) + { + if (obj == null) + { + return; + } + + _indent = indent; + _indentStr = new string(' ', indent * 4); + _obj = obj; + + ParseObject(); + } + + public string GetResult() => _builder == null ? string.Empty : _builder.ToString().TrimEnd(); + + private void ParseObject() + { + switch (_obj) + { + case Dictionary dictionary: + AppendDictionary(dictionary); + break; + case List list: + AppendList(list); + break; + default: + AppendString(); + break; + } + } + + private void AppendDictionary(Dictionary objects) + { + foreach (var kvp in objects) + { + if (kvp.Value == null) continue; + + var writeOutput = false; + + switch (kvp.Value) + { + case Dictionary valueDictionary: + if (valueDictionary.Count > 0) + { + writeOutput = true; + _builder + .Append($"{_indentStr}{kvp.Key,-16}: object") + .AppendLine(); + } + + break; + case List valueList: + if (valueList.Count > 0) + { + writeOutput = true; + _builder + .Append($"{_indentStr}{kvp.Key,-16}: array[{valueList.Count}]") + .AppendLine(); + } + + break; + default: + writeOutput = true; + _builder.Append($"{_indentStr}{kvp.Key,-16}: "); + break; + } + + if (writeOutput) + _builder.AppendLine(new HumanizeJson(kvp.Value, _indent + 1).GetResult()); + } + } + + private void AppendList(List objects) + { + var index = 0; + foreach (var value in objects) + { + var writeOutput = false; + + switch (value) + { + case Dictionary valueDictionary: + if (valueDictionary.Count > 0) + { + writeOutput = true; + _builder + .Append($"{_indentStr}[{index}]: object") + .AppendLine(); + } + + break; + case List valueList: + if (valueList.Count > 0) + { + writeOutput = true; + _builder + .Append($"{_indentStr}[{index}]: array[{valueList.Count}]") + .AppendLine(); + } + + break; + default: + writeOutput = true; + _builder.Append($"{_indentStr}[{index}]: "); + break; + } + + index++; + + if (writeOutput) + _builder.AppendLine(new HumanizeJson(value, _indent + 1).GetResult()); + } + } + + private void AppendString() + { + var stringValue = _obj.ToString(); + + if (stringValue.Length + _indentStr.Length > 96 || stringValue.IndexOf('\r') >= 0 || + stringValue.IndexOf('\n') >= 0) + { + _builder.AppendLine(); + var stringLines = stringValue.ToLines().Select(l => l.Trim()); + + foreach (var line in stringLines) + { + _builder.AppendLine($"{_indentStr}{line}"); + } + } + else + { + _builder.Append($"{stringValue}"); + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Formatters/Json.Converter.cs b/Unosquare.Swan.Lite/Formatters/Json.Converter.cs new file mode 100644 index 0000000..a1aa96e --- /dev/null +++ b/Unosquare.Swan.Lite/Formatters/Json.Converter.cs @@ -0,0 +1,335 @@ +namespace Unosquare.Swan.Formatters +{ + using System; + using System.Collections; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using System.Text; + using Attributes; + + /// + /// A very simple, light-weight JSON library written by Mario + /// to teach Geo how things are done + /// + /// This is an useful helper for small tasks but it doesn't represent a full-featured + /// serializer such as the beloved Json.NET. + /// + public static partial class Json + { + private class Converter + { + private static readonly ConcurrentDictionary MemberInfoNameCache = + new ConcurrentDictionary(); + + private static readonly ConcurrentDictionary ListAddMethodCache = new ConcurrentDictionary(); + + private readonly object _target; + private readonly Type _targetType; + private readonly bool _includeNonPublic; + + private Converter( + object source, + Type targetType, + ref object targetInstance, + bool includeNonPublic) + { + _targetType = targetInstance != null ? targetInstance.GetType() : targetType; + _includeNonPublic = includeNonPublic; + + if (source == null) + { + return; + } + + var sourceType = source.GetType(); + + if (_targetType == null || _targetType == typeof(object)) _targetType = sourceType; + if (sourceType == _targetType) + { + _target = source; + return; + } + + if (!TrySetInstance(targetInstance, source, ref _target)) + return; + + ResolveObject(source, ref _target); + } + + /// + /// Converts a json deserialized object (simple type, dictionary or list) to a new instance of the specified target type. + /// + /// The source. + /// Type of the target. + /// if set to true [include non public]. + /// The target object. + internal static object FromJsonResult(object source, + Type targetType, + bool includeNonPublic) + { + object nullRef = null; + return new Converter(source, targetType, ref nullRef, includeNonPublic).GetResult(); + } + + private static object FromJsonResult(object source, + Type targetType, + ref object targetInstance, + bool includeNonPublic) + { + return new Converter(source, targetType, ref targetInstance, includeNonPublic).GetResult(); + } + + private static Type GetAddMethodParameterType(Type targetType) + => ListAddMethodCache.GetOrAdd(targetType, + x => x.GetMethods() + .FirstOrDefault( + m => m.Name.Equals(AddMethodName) && m.IsPublic && m.GetParameters().Length == 1)? + .GetParameters()[0] + .ParameterType); + + private static void GetByteArray(string sourceString, ref object target) + { + try + { + target = Convert.FromBase64String(sourceString); + } // Try conversion from Base 64 + catch + { + target = Encoding.UTF8.GetBytes(sourceString); + } // Get the string bytes in UTF8 + } + + private static object GetSourcePropertyValue(IDictionary sourceProperties, + MemberInfo targetProperty) + { + var targetPropertyName = MemberInfoNameCache.GetOrAdd( + targetProperty, + x => Runtime.AttributeCache.RetrieveOne(x)?.PropertyName ?? x.Name); + + return sourceProperties.GetValueOrDefault(targetPropertyName); + } + + private bool TrySetInstance(object targetInstance, object source, ref object target) + { + if (targetInstance == null) + { + // Try to create a default instance + try + { + source.CreateTarget(_targetType, _includeNonPublic, ref target); + } + catch + { + return false; + } + } + else + { + target = targetInstance; + } + + return true; + } + + private object GetResult() => _target ?? _targetType.GetDefault(); + + private void ResolveObject(object source, ref object target) + { + switch (source) + { + // Case 0: Special Cases Handling (Source and Target are of specific convertible types) + // Case 0.1: Source is string, Target is byte[] + case string sourceString when _targetType == typeof(byte[]): + GetByteArray(sourceString, ref target); + break; + + // Case 1.1: Source is Dictionary, Target is IDictionary + case Dictionary sourceProperties when target is IDictionary targetDictionary: + PopulateDictionary(sourceProperties, targetDictionary); + break; + + // Case 1.2: Source is Dictionary, Target is not IDictionary (i.e. it is a complex type) + case Dictionary sourceProperties: + PopulateObject(sourceProperties); + break; + + // Case 2.1: Source is List, Target is Array + case List sourceList when target is Array targetArray: + PopulateArray(sourceList, targetArray); + break; + + // Case 2.2: Source is List, Target is IList + case List sourceList when target is IList targetList: + PopulateIList(sourceList, targetList); + break; + + // Case 3: Source is a simple type; Attempt conversion + default: + var sourceStringValue = source.ToStringInvariant(); + + // Handle basic types or enumerations if not + if (!_targetType.TryParseBasicType(sourceStringValue, out target)) + GetEnumValue(sourceStringValue, ref target); + + break; + } + } + + private void PopulateIList(IList objects, IList list) + { + var parameterType = GetAddMethodParameterType(_targetType); + if (parameterType == null) return; + + foreach (var item in objects) + { + try + { + list.Add(FromJsonResult( + item, + parameterType, + _includeNonPublic)); + } + catch + { + // ignored + } + } + } + + private void PopulateArray(IList objects, Array array) + { + var elementType = _targetType.GetElementType(); + + for (var i = 0; i < objects.Count; i++) + { + try + { + var targetItem = FromJsonResult( + objects[i], + elementType, + _includeNonPublic); + array.SetValue(targetItem, i); + } + catch + { + // ignored + } + } + } + + private void GetEnumValue(string sourceStringValue, ref object target) + { + var enumType = Nullable.GetUnderlyingType(_targetType); + if (enumType == null && _targetType.GetTypeInfo().IsEnum) enumType = _targetType; + if (enumType == null) return; + + try + { + target = Enum.Parse(enumType, sourceStringValue); + } + catch + { + // ignored + } + } + + private void PopulateDictionary(IDictionary sourceProperties, IDictionary targetDictionary) + { + // find the add method of the target dictionary + var addMethod = _targetType.GetMethods() + .FirstOrDefault( + m => m.Name.Equals(AddMethodName) && m.IsPublic && m.GetParameters().Length == 2); + + // skip if we don't have a compatible add method + if (addMethod == null) return; + var addMethodParameters = addMethod.GetParameters(); + if (addMethodParameters[0].ParameterType != typeof(string)) return; + + // Retrieve the target entry type + var targetEntryType = addMethodParameters[1].ParameterType; + + // Add the items to the target dictionary + foreach (var sourceProperty in sourceProperties) + { + try + { + var targetEntryValue = FromJsonResult( + sourceProperty.Value, + targetEntryType, + _includeNonPublic); + targetDictionary.Add(sourceProperty.Key, targetEntryValue); + } + catch + { + // ignored + } + } + } + + private void PopulateObject(IDictionary sourceProperties) + { + if (_targetType.IsValueType()) + { + PopulateFields(sourceProperties); + } + + PopulateProperties(sourceProperties); + } + + private void PopulateProperties(IDictionary sourceProperties) + { + var properties = PropertyTypeCache.RetrieveFilteredProperties(_targetType, false, p => p.CanWrite); + + foreach (var property in properties) + { + var sourcePropertyValue = GetSourcePropertyValue(sourceProperties, property); + if (sourcePropertyValue == null) continue; + + try + { + var currentPropertyValue = !property.PropertyType.IsArray + ? property.GetCacheGetMethod(_includeNonPublic)(_target) + : null; + + var targetPropertyValue = FromJsonResult( + sourcePropertyValue, + property.PropertyType, + ref currentPropertyValue, + _includeNonPublic); + + property.GetCacheSetMethod(_includeNonPublic)(_target, new[] { targetPropertyValue }); + } + catch + { + // ignored + } + } + } + + private void PopulateFields(IDictionary sourceProperties) + { + foreach (var field in FieldTypeCache.RetrieveAllFields(_targetType)) + { + var sourcePropertyValue = GetSourcePropertyValue(sourceProperties, field); + if (sourcePropertyValue == null) continue; + + var targetPropertyValue = FromJsonResult( + sourcePropertyValue, + field.FieldType, + _includeNonPublic); + + try + { + field.SetValue(_target, targetPropertyValue); + } + catch + { + // ignored + } + } + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Formatters/Json.Deserializer.cs b/Unosquare.Swan.Lite/Formatters/Json.Deserializer.cs new file mode 100644 index 0000000..0f724ca --- /dev/null +++ b/Unosquare.Swan.Lite/Formatters/Json.Deserializer.cs @@ -0,0 +1,374 @@ +namespace Unosquare.Swan.Formatters +{ + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// A very simple, light-weight JSON library written by Mario + /// to teach Geo how things are done + /// + /// This is an useful helper for small tasks but it doesn't represent a full-featured + /// serializer such as the beloved Json.NET. + /// + public partial class Json + { + /// + /// A simple JSON Deserializer. + /// + private class Deserializer + { + #region State Variables + + private readonly object _result; + private readonly Dictionary _resultObject; + private readonly List _resultArray; + + private readonly ReadState _state = ReadState.WaitingForRootOpen; + private readonly string _currentFieldName; + private readonly string _json; + + private int _index; + + #endregion + + private Deserializer(string json, int startIndex) + { + _json = json; + + for (_index = startIndex; _index < _json.Length; _index++) + { + #region Wait for { or [ + + if (_state == ReadState.WaitingForRootOpen) + { + if (char.IsWhiteSpace(_json, _index)) continue; + + if (_json[_index] == OpenObjectChar) + { + _resultObject = new Dictionary(); + _state = ReadState.WaitingForField; + continue; + } + + if (_json[_index] == OpenArrayChar) + { + _resultArray = new List(); + _state = ReadState.WaitingForValue; + continue; + } + + throw CreateParserException($"'{OpenObjectChar}' or '{OpenArrayChar}'"); + } + + #endregion + + #region Wait for opening field " (only applies for object results) + + if (_state == ReadState.WaitingForField) + { + if (char.IsWhiteSpace(_json, _index)) continue; + + // Handle empty arrays and empty objects + if ((_resultObject != null && _json[_index] == CloseObjectChar) + || (_resultArray != null && _json[_index] == CloseArrayChar)) + { + _result = _resultObject ?? _resultArray as object; + return; + } + + if (_json[_index] != StringQuotedChar) + throw CreateParserException($"'{StringQuotedChar}'"); + + var charCount = GetFieldNameCount(); + + _currentFieldName = Unescape(_json.SliceLength(_index + 1, charCount)); + _index += charCount + 1; + _state = ReadState.WaitingForColon; + continue; + } + + #endregion + + #region Wait for field-value separator : (only applies for object results + + if (_state == ReadState.WaitingForColon) + { + if (char.IsWhiteSpace(_json, _index)) continue; + + if (_json[_index] != ValueSeparatorChar) + throw CreateParserException($"'{ValueSeparatorChar}'"); + + _state = ReadState.WaitingForValue; + continue; + } + + #endregion + + #region Wait for and Parse the value + + if (_state == ReadState.WaitingForValue) + { + if (char.IsWhiteSpace(_json, _index)) continue; + + // Handle empty arrays and empty objects + if ((_resultObject != null && _json[_index] == CloseObjectChar) + || (_resultArray != null && _json[_index] == CloseArrayChar)) + { + _result = _resultObject ?? _resultArray as object; + return; + } + + // determine the value based on what it starts with + switch (_json[_index]) + { + case StringQuotedChar: // expect a string + ExtractStringQuoted(); + break; + + case OpenObjectChar: // expect object + case OpenArrayChar: // expect array + ExtractObject(); + break; + + case 't': // expect true + ExtractConstant(TrueLiteral, true); + break; + + case 'f': // expect false + ExtractConstant(FalseLiteral, false); + break; + + case 'n': // expect null + ExtractConstant(NullLiteral, null); + break; + + default: // expect number + ExtractNumber(); + break; + } + + _currentFieldName = null; + _state = ReadState.WaitingForNextOrRootClose; + continue; + } + + #endregion + + #region Wait for closing ], } or an additional field or value , + + if (_state != ReadState.WaitingForNextOrRootClose) continue; + + if (char.IsWhiteSpace(_json, _index)) continue; + + if (_json[_index] == FieldSeparatorChar) + { + if (_resultObject != null) + { + _state = ReadState.WaitingForField; + _currentFieldName = null; + continue; + } + + _state = ReadState.WaitingForValue; + continue; + } + + if ((_resultObject != null && _json[_index] == CloseObjectChar) || + (_resultArray != null && _json[_index] == CloseArrayChar)) + { + _result = _resultObject ?? _resultArray as object; + return; + } + + throw CreateParserException($"'{FieldSeparatorChar}' '{CloseObjectChar}' or '{CloseArrayChar}'"); + + #endregion + } + } + + internal static object DeserializeInternal(string json) => new Deserializer(json, 0)._result; + + private static string Unescape(string str) + { + // check if we need to unescape at all + if (str.IndexOf(StringEscapeChar) < 0) + return str; + + var builder = new StringBuilder(str.Length); + for (var i = 0; i < str.Length; i++) + { + if (str[i] != StringEscapeChar) + { + builder.Append(str[i]); + continue; + } + + if (i + 1 > str.Length - 1) + break; + + // escape sequence begins here + switch (str[i + 1]) + { + case 'u': + i = ExtractEscapeSequence(str, i, builder); + break; + case 'b': + builder.Append('\b'); + i += 1; + break; + case 't': + builder.Append('\t'); + i += 1; + break; + case 'n': + builder.Append('\n'); + i += 1; + break; + case 'f': + builder.Append('\f'); + i += 1; + break; + case 'r': + builder.Append('\r'); + i += 1; + break; + default: + builder.Append(str[i + 1]); + i += 1; + break; + } + } + + return builder.ToString(); + } + + private static int ExtractEscapeSequence(string str, int i, StringBuilder builder) + { + var startIndex = i + 2; + var endIndex = i + 5; + if (endIndex > str.Length - 1) + { + builder.Append(str[i + 1]); + i += 1; + return i; + } + + var hexCode = str.Slice(startIndex, endIndex).ConvertHexadecimalToBytes(); + builder.Append(Encoding.BigEndianUnicode.GetChars(hexCode)); + i += 5; + return i; + } + + private int GetFieldNameCount() + { + var charCount = 0; + for (var j = _index + 1; j < _json.Length; j++) + { + if (_json[j] == StringQuotedChar && _json[j - 1] != StringEscapeChar) + break; + + charCount++; + } + + return charCount; + } + + private void ExtractObject() + { + // Extract and set the value + var deserializer = new Deserializer(_json, _index); + + if (_currentFieldName != null) + _resultObject[_currentFieldName] = deserializer._result; + else + _resultArray.Add(deserializer._result); + + _index = deserializer._index; + } + + private void ExtractNumber() + { + var charCount = 0; + for (var j = _index; j < _json.Length; j++) + { + if (char.IsWhiteSpace(_json[j]) || _json[j] == FieldSeparatorChar + || (_resultObject != null && _json[j] == CloseObjectChar) + || (_resultArray != null && _json[j] == CloseArrayChar)) + break; + + charCount++; + } + + // Extract and set the value + var stringValue = _json.SliceLength(_index, charCount); + + if (decimal.TryParse(stringValue, out var value) == false) + throw CreateParserException("[number]"); + + if (_currentFieldName != null) + _resultObject[_currentFieldName] = value; + else + _resultArray.Add(value); + + _index += charCount - 1; + } + + private void ExtractConstant(string boolValue, bool? value) + { + if (!_json.SliceLength(_index, boolValue.Length).Equals(boolValue)) + throw CreateParserException($"'{ValueSeparatorChar}'"); + + // Extract and set the value + if (_currentFieldName != null) + _resultObject[_currentFieldName] = value; + else + _resultArray.Add(value); + + _index += boolValue.Length - 1; + } + + private void ExtractStringQuoted() + { + var charCount = 0; + var escapeCharFound = false; + for (var j = _index + 1; j < _json.Length; j++) + { + if (_json[j] == StringQuotedChar && !escapeCharFound) + break; + + escapeCharFound = _json[j] == StringEscapeChar && !escapeCharFound; + charCount++; + } + + // Extract and set the value + var value = Unescape(_json.SliceLength(_index + 1, charCount)); + if (_currentFieldName != null) + _resultObject[_currentFieldName] = value; + else + _resultArray.Add(value); + + _index += charCount + 1; + } + + private FormatException CreateParserException(string expected) + { + var textPosition = _json.TextPositionAt(_index); + return new FormatException( + $"Parser error (Line {textPosition.Item1}, Col {textPosition.Item2}, State {_state}): Expected {expected} but got '{_json[_index]}'."); + } + + /// + /// Defines the different JSON read states. + /// + private enum ReadState + { + WaitingForRootOpen, + WaitingForField, + WaitingForColon, + WaitingForValue, + WaitingForNextOrRootClose, + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Formatters/Json.Serializer.cs b/Unosquare.Swan.Lite/Formatters/Json.Serializer.cs new file mode 100644 index 0000000..66c7867 --- /dev/null +++ b/Unosquare.Swan.Lite/Formatters/Json.Serializer.cs @@ -0,0 +1,359 @@ +namespace Unosquare.Swan.Formatters +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using System.Text; + + /// + /// A very simple, light-weight JSON library written by Mario + /// to teach Geo how things are done + /// + /// This is an useful helper for small tasks but it doesn't represent a full-featured + /// serializer such as the beloved Json.NET. + /// + public partial class Json + { + /// + /// A simple JSON serializer. + /// + private class Serializer + { + #region Private Declarations + + private static readonly Dictionary IndentStrings = new Dictionary(); + + private readonly SerializerOptions _options; + private readonly string _result; + private readonly StringBuilder _builder; + private readonly string _lastCommaSearch; + + #endregion + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The object. + /// The depth. + /// The options. + private Serializer(object obj, int depth, SerializerOptions options) + { + if (depth > 20) + { + throw new InvalidOperationException( + "The max depth (20) has been reached. Serializer can not continue."); + } + + // Basic Type Handling (nulls, strings, number, date and bool) + _result = ResolveBasicType(obj); + + if (string.IsNullOrWhiteSpace(_result) == false) + return; + + _options = options; + _lastCommaSearch = FieldSeparatorChar + (_options.Format ? Environment.NewLine : string.Empty); + + // Handle circular references correctly and avoid them + if (options.IsObjectPresent(obj)) + { + _result = $"{{ \"$circref\": \"{Escape(obj.GetHashCode().ToStringInvariant(), false)}\" }}"; + return; + } + + // At this point, we will need to construct the object with a StringBuilder. + _builder = new StringBuilder(); + + switch (obj) + { + case IDictionary itemsZero when itemsZero.Count == 0: + _result = EmptyObjectLiteral; + break; + case IDictionary items: + _result = ResolveDictionary(items, depth); + break; + case IEnumerable enumerableZero when !enumerableZero.Cast().Any(): + _result = EmptyArrayLiteral; + break; + case IEnumerable enumerableBytes when enumerableBytes is byte[] bytes: + _result = Serialize(bytes.ToBase64(), depth, _options); + break; + case IEnumerable enumerable: + _result = ResolveEnumerable(enumerable, depth); + break; + default: + _result = ResolveObject(obj, depth); + break; + } + } + + internal static string Serialize(object obj, int depth, SerializerOptions options) + { + return new Serializer(obj, depth, options)._result; + } + + #endregion + + #region Helper Methods + + private static string ResolveBasicType(object obj) + { + switch (obj) + { + case null: + return NullLiteral; + case string s: + return Escape(s, true); + case bool b: + return b ? TrueLiteral : FalseLiteral; + case Type _: + case Assembly _: + case MethodInfo _: + case PropertyInfo _: + case EventInfo _: + return Escape(obj.ToString(), true); + case DateTime d: + return $"{StringQuotedChar}{d:s}{StringQuotedChar}"; + default: + var targetType = obj.GetType(); + + if (!Definitions.BasicTypesInfo.ContainsKey(targetType)) + return string.Empty; + + var escapedValue = Escape(Definitions.BasicTypesInfo[targetType].ToStringInvariant(obj), false); + + return decimal.TryParse(escapedValue, out _) + ? $"{escapedValue}" + : $"{StringQuotedChar}{escapedValue}{StringQuotedChar}"; + } + } + + private static bool IsNonEmptyJsonArrayOrObject(string serialized) + { + if (serialized.Equals(EmptyObjectLiteral) || serialized.Equals(EmptyArrayLiteral)) return false; + + // find the first position the character is not a space + return serialized.Where(c => c != ' ').Select(c => c == OpenObjectChar || c == OpenArrayChar).FirstOrDefault(); + } + + private static string Escape(string str, bool quoted) + { + if (str == null) + return string.Empty; + + var builder = new StringBuilder(str.Length * 2); + if (quoted) builder.Append(StringQuotedChar); + Escape(str, builder); + if (quoted) builder.Append(StringQuotedChar); + return builder.ToString(); + } + + private static void Escape(string str, StringBuilder builder) + { + foreach (var currentChar in str) + { + switch (currentChar) + { + case '\\': + case '"': + case '/': + builder + .Append('\\') + .Append(currentChar); + break; + case '\b': + builder.Append("\\b"); + break; + case '\t': + builder.Append("\\t"); + break; + case '\n': + builder.Append("\\n"); + break; + case '\f': + builder.Append("\\f"); + break; + case '\r': + builder.Append("\\r"); + break; + default: + if (currentChar < ' ') + { + var escapeBytes = BitConverter.GetBytes((ushort)currentChar); + if (BitConverter.IsLittleEndian == false) + Array.Reverse(escapeBytes); + + builder.Append("\\u") + .Append(escapeBytes[1].ToString("X").PadLeft(2, '0')) + .Append(escapeBytes[0].ToString("X").PadLeft(2, '0')); + } + else + { + builder.Append(currentChar); + } + + break; + } + } + } + + private Dictionary CreateDictionary( + Dictionary fields, + string targetType, + object target) + { + // Create the dictionary and extract the properties + var objectDictionary = new Dictionary(); + + if (string.IsNullOrWhiteSpace(_options.TypeSpecifier) == false) + objectDictionary[_options.TypeSpecifier] = targetType; + + foreach (var field in fields) + { + // Build the dictionary using property names and values + // Note: used to be: property.GetValue(target); but we would be reading private properties + try + { + objectDictionary[field.Key] = field.Value is PropertyInfo property + ? property.GetCacheGetMethod(_options.IncludeNonPublic)(target) + : (field.Value as FieldInfo)?.GetValue(target); + } + catch + { + /* ignored */ + } + } + + return objectDictionary; + } + + private string ResolveDictionary(IDictionary items, int depth) + { + Append(OpenObjectChar, depth); + AppendLine(); + + // Iterate through the elements and output recursively + var writeCount = 0; + foreach (var key in items.Keys) + { + // Serialize and append the key (first char indented) + Append(StringQuotedChar, depth + 1); + Escape(key.ToString(), _builder); + _builder + .Append(StringQuotedChar) + .Append(ValueSeparatorChar) + .Append(" "); + + // Serialize and append the value + var serializedValue = Serialize(items[key], depth + 1, _options); + + if (IsNonEmptyJsonArrayOrObject(serializedValue)) AppendLine(); + Append(serializedValue, 0); + + // Add a comma and start a new line -- We will remove the last one when we are done writing the elements + Append(FieldSeparatorChar, 0); + AppendLine(); + writeCount++; + } + + // Output the end of the object and set the result + RemoveLastComma(); + Append(CloseObjectChar, writeCount > 0 ? depth : 0); + return _builder.ToString(); + } + + private string ResolveObject(object target, int depth) + { + var targetType = target.GetType(); + var fields = _options.GetProperties(targetType); + + if (fields.Count == 0 && string.IsNullOrWhiteSpace(_options.TypeSpecifier)) + return EmptyObjectLiteral; + + // If we arrive here, then we convert the object into a + // dictionary of property names and values and call the serialization + // function again + var objectDictionary = CreateDictionary(fields, targetType.ToString(), target); + + return Serialize(objectDictionary, depth, _options); + } + + private string ResolveEnumerable(IEnumerable target, int depth) + { + // Cast the items as a generic object array + var items = target.Cast(); + + Append(OpenArrayChar, depth); + AppendLine(); + + // Iterate through the elements and output recursively + var writeCount = 0; + foreach (var entry in items) + { + var serializedValue = Serialize(entry, depth + 1, _options); + + if (IsNonEmptyJsonArrayOrObject(serializedValue)) + Append(serializedValue, 0); + else + Append(serializedValue, depth + 1); + + Append(FieldSeparatorChar, 0); + AppendLine(); + writeCount++; + } + + // Output the end of the array and set the result + RemoveLastComma(); + Append(CloseArrayChar, writeCount > 0 ? depth : 0); + return _builder.ToString(); + } + + private void SetIndent(int depth) + { + if (_options.Format == false || depth <= 0) return; + + _builder.Append(IndentStrings.GetOrAdd(depth, x => new string(' ', x * 4))); + } + + /// + /// Removes the last comma in the current string builder. + /// + private void RemoveLastComma() + { + if (_builder.Length < _lastCommaSearch.Length) + return; + + if (_lastCommaSearch.Where((t, i) => _builder[_builder.Length - _lastCommaSearch.Length + i] != t).Any()) + { + return; + } + + // If we got this far, we simply remove the comma character + _builder.Remove(_builder.Length - _lastCommaSearch.Length, 1); + } + + private void Append(string text, int depth) + { + SetIndent(depth); + _builder.Append(text); + } + + private void Append(char text, int depth) + { + SetIndent(depth); + _builder.Append(text); + } + + private void AppendLine() + { + if (_options.Format == false) return; + _builder.Append(Environment.NewLine); + } + + #endregion + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Formatters/Json.SerializerOptions.cs b/Unosquare.Swan.Lite/Formatters/Json.SerializerOptions.cs new file mode 100644 index 0000000..fc6a7f5 --- /dev/null +++ b/Unosquare.Swan.Lite/Formatters/Json.SerializerOptions.cs @@ -0,0 +1,107 @@ +namespace Unosquare.Swan.Formatters +{ + using System; + using System.Collections.Generic; + using System.Collections.Concurrent; + using System.Linq; + using System.Reflection; + using Attributes; + + /// + /// A very simple, light-weight JSON library written by Mario + /// to teach Geo how things are done + /// + /// This is an useful helper for small tasks but it doesn't represent a full-featured + /// serializer such as the beloved Json.NET. + /// + public partial class Json + { + private class SerializerOptions + { + private static readonly ConcurrentDictionary, MemberInfo>> + TypeCache = new ConcurrentDictionary, MemberInfo>>(); + + private readonly string[] _includeProperties; + private readonly string[] _excludeProperties; + private readonly Dictionary> _parentReferences = new Dictionary>(); + + public SerializerOptions( + bool format, + string typeSpecifier, + string[] includeProperties, + string[] excludeProperties = null, + bool includeNonPublic = true, + IReadOnlyCollection parentReferences = null) + { + _includeProperties = includeProperties; + _excludeProperties = excludeProperties; + + IncludeNonPublic = includeNonPublic; + Format = format; + TypeSpecifier = typeSpecifier; + + if (parentReferences == null) + return; + + foreach (var parentReference in parentReferences.Where(x => x.IsAlive)) + { + IsObjectPresent(parentReference.Target); + } + } + + public bool Format { get; } + public string TypeSpecifier { get; } + public bool IncludeNonPublic { get; } + + internal bool IsObjectPresent(object target) + { + var hashCode = target.GetHashCode(); + + if (_parentReferences.ContainsKey(hashCode)) + { + if (_parentReferences[hashCode].Any(p => ReferenceEquals(p.Target, target))) + return true; + + _parentReferences[hashCode].Add(new WeakReference(target)); + return false; + } + + _parentReferences.Add(hashCode, new List { new WeakReference(target) }); + return false; + } + + internal Dictionary GetProperties(Type targetType) + => GetPropertiesCache(targetType) + .When(() => _includeProperties?.Length > 0, + query => query.Where(p => _includeProperties.Contains(p.Key.Item1))) + .When(() => _excludeProperties?.Length > 0, + query => query.Where(p => !_excludeProperties.Contains(p.Key.Item1))) + .ToDictionary(x => x.Key.Item2, x => x.Value); + + private static Dictionary, MemberInfo> GetPropertiesCache(Type targetType) + { + if (TypeCache.TryGetValue(targetType, out var current)) + return current; + + var fields = + new List(PropertyTypeCache.RetrieveAllProperties(targetType).Where(p => p.CanRead)); + + // If the target is a struct (value type) navigate the fields. + if (targetType.IsValueType()) + { + fields.AddRange(FieldTypeCache.RetrieveAllFields(targetType)); + } + + var value = fields + .ToDictionary( + x => Tuple.Create(x.Name, + x.GetCustomAttribute()?.PropertyName ?? x.Name), + x => x); + + TypeCache.TryAdd(targetType, value); + + return value; + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Formatters/Json.cs b/Unosquare.Swan.Lite/Formatters/Json.cs new file mode 100644 index 0000000..ddb3084 --- /dev/null +++ b/Unosquare.Swan.Lite/Formatters/Json.cs @@ -0,0 +1,331 @@ +namespace Unosquare.Swan.Formatters +{ + using Reflection; + using System; + using Components; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + using Attributes; + + /// + /// A very simple, light-weight JSON library written by Mario + /// to teach Geo how things are done + /// + /// This is an useful helper for small tasks but it doesn't represent a full-featured + /// serializer such as the beloved Json.NET. + /// + public static partial class Json + { + #region Constants + + internal const string AddMethodName = "Add"; + + private const char OpenObjectChar = '{'; + private const char CloseObjectChar = '}'; + + private const char OpenArrayChar = '['; + private const char CloseArrayChar = ']'; + + private const char FieldSeparatorChar = ','; + private const char ValueSeparatorChar = ':'; + + private const char StringEscapeChar = '\\'; + private const char StringQuotedChar = '"'; + + private const string EmptyObjectLiteral = "{ }"; + private const string EmptyArrayLiteral = "[ ]"; + private const string TrueLiteral = "true"; + private const string FalseLiteral = "false"; + private const string NullLiteral = "null"; + + #endregion + + private static readonly PropertyTypeCache PropertyTypeCache = new PropertyTypeCache(); + private static readonly FieldTypeCache FieldTypeCache = new FieldTypeCache(); + private static readonly CollectionCacheRepository IgnoredPropertiesCache = new CollectionCacheRepository(); + + #region Public API + + /// + /// Serializes the specified object into a JSON string. + /// + /// The object. + /// if set to true it formats and indents the output. + /// The type specifier. Leave null or empty to avoid setting. + /// if set to true non-public getters will be also read. + /// The included property names. + /// The excluded property names. + /// + /// A that represents the current object. + /// + /// + /// The following example describes how to serialize a simple object. + /// + /// using Unosquare.Swan.Formatters; + /// + /// class Example + /// { + /// static void Main() + /// { + /// var obj = new { One = "One", Two = "Two" }; + /// + /// var serial = Json.Serialize(obj); // {"One": "One","Two": "Two"} + /// } + /// } + /// + /// The following example details how to serialize an object using the . + /// + /// using Unosquare.Swan.Attributes; + /// using Unosquare.Swan.Formatters; + /// + /// class Example + /// { + /// class JsonPropertyExample + /// { + /// [JsonProperty("data")] + /// public string Data { get; set; } + /// + /// [JsonProperty("ignoredData", true)] + /// public string IgnoredData { get; set; } + /// } + /// + /// static void Main() + /// { + /// var obj = new JsonPropertyExample() { Data = "OK", IgnoredData = "OK" }; + /// + /// // {"data": "OK"} + /// var serializedObj = Json.Serialize(obj); + /// } + /// } + /// + /// + public static string Serialize( + object obj, + bool format = false, + string typeSpecifier = null, + bool includeNonPublic = false, + string[] includedNames = null, + string[] excludedNames = null) + { + return Serialize(obj, format, typeSpecifier, includeNonPublic, includedNames, excludedNames, null); + } + + /// + /// Serializes the specified object into a JSON string. + /// + /// The object. + /// if set to true it formats and indents the output. + /// The type specifier. Leave null or empty to avoid setting. + /// if set to true non-public getters will be also read. + /// The included property names. + /// The excluded property names. + /// The parent references. + /// + /// A that represents the current object. + /// + public static string Serialize( + object obj, + bool format, + string typeSpecifier, + bool includeNonPublic, + string[] includedNames, + string[] excludedNames, + List parentReferences) + { + if (obj != null && (obj is string || Definitions.AllBasicValueTypes.Contains(obj.GetType()))) + { + return SerializePrimitiveValue(obj); + } + + var options = new SerializerOptions( + format, + typeSpecifier, + includedNames, + GetExcludedNames(obj?.GetType(), excludedNames), + includeNonPublic, + parentReferences); + + return Serializer.Serialize(obj, 0, options); + } + + /// + /// Serializes the specified object only including the specified property names. + /// + /// The object. + /// if set to true it formats and indents the output. + /// The include names. + /// A that represents the current object. + /// + /// The following example shows how to serialize a simple object including the specified properties. + /// + /// using Unosquare.Swan.Formatters; + /// + /// class Example + /// { + /// static void Main() + /// { + /// // object to serialize + /// var obj = new { One = "One", Two = "Two", Three = "Three" }; + /// + /// // the included names + /// var includedNames = new[] { "Two", "Three" }; + /// + /// // serialize only the included names + /// var data = Json.SerializeOnly(basicObject, true, includedNames); + /// // {"Two": "Two","Three": "Three" } + /// } + /// } + /// + /// + public static string SerializeOnly(object obj, bool format, params string[] includeNames) + { + var options = new SerializerOptions(format, null, includeNames); + + return Serializer.Serialize(obj, 0, options); + } + + /// + /// Serializes the specified object excluding the specified property names. + /// + /// The object. + /// if set to true it formats and indents the output. + /// The exclude names. + /// A that represents the current object. + /// + /// The following code shows how to serialize a simple object exluding the specified properties. + /// + /// using Unosquare.Swan.Formatters; + /// + /// class Example + /// { + /// static void Main() + /// { + /// // object to serialize + /// var obj = new { One = "One", Two = "Two", Three = "Three" }; + /// + /// // the excluded names + /// var excludeNames = new[] { "Two", "Three" }; + /// + /// // serialize excluding + /// var data = Json.SerializeExcluding(basicObject, false, includedNames); + /// // {"One": "One"} + /// } + /// } + /// + /// + public static string SerializeExcluding(object obj, bool format, params string[] excludeNames) + { + var options = new SerializerOptions(format, null, null, excludeNames); + + return Serializer.Serialize(obj, 0, options); + } + + /// + /// Deserializes the specified json string as either a Dictionary[string, object] or as a List[object] + /// depending on the syntax of the JSON string. + /// + /// The json. + /// Type of the current deserializes. + /// + /// The following code shows how to deserialize a JSON string into a Dictionary. + /// + /// using Unosquare.Swan.Formatters; + /// + /// class Example + /// { + /// static void Main() + /// { + /// // json to deserialize + /// var basicJson = "{\"One\":\"One\",\"Two\":\"Two\",\"Three\":\"Three\"}"; + /// + /// // deserializes the specified json into a Dictionary<string, object>. + /// var data = Json.Deserialize(basicJson); + /// } + /// } + /// + /// + public static object Deserialize(string json) => Deserializer.DeserializeInternal(json); + + /// + /// Deserializes the specified json string and converts it to the specified object type. + /// Non-public constructors and property setters are ignored. + /// + /// The type of object to deserialize. + /// The json. + /// The deserialized specified type object. + /// + /// The following code describes how to deserialize a JSON string into an object of type T. + /// + /// using Unosquare.Swan.Formatters; + /// + /// class Example + /// { + /// static void Main() + /// { + /// // json type BasicJson to serialize + /// var basicJson = "{\"One\":\"One\",\"Two\":\"Two\",\"Three\":\"Three\"}"; + /// + /// // deserializes the specified string in a new instance of the type BasicJson. + /// var data = Json.Deserialize<BasicJson>(basicJson); + /// } + /// } + /// + /// + public static T Deserialize(string json) => (T)Deserialize(json, typeof(T)); + + /// + /// Deserializes the specified json string and converts it to the specified object type. + /// + /// The type of object to deserialize. + /// The json. + /// if set to true, it also uses the non-public constructors and property setters. + /// The deserialized specified type object. + public static T Deserialize(string json, bool includeNonPublic) => (T)Deserialize(json, typeof(T), includeNonPublic); + + /// + /// Deserializes the specified json string and converts it to the specified object type. + /// + /// The json. + /// Type of the result. + /// if set to true, it also uses the non-public constructors and property setters. + /// Type of the current conversion from json result. + public static object Deserialize(string json, Type resultType, bool includeNonPublic = false) + => Converter.FromJsonResult(Deserializer.DeserializeInternal(json), resultType, includeNonPublic); + + #endregion + + #region Private API + + private static string[] GetExcludedNames(Type type, string[] excludedNames) + { + if (type == null) + return excludedNames; + + var excludedByAttr = IgnoredPropertiesCache.Retrieve(type, t => t.GetProperties() + .Where(x => Runtime.AttributeCache.RetrieveOne(x)?.Ignored == true) + .Select(x => x.Name)); + + if (excludedByAttr?.Any() != true) + return excludedNames; + + return excludedNames == null + ? excludedByAttr.ToArray() + : excludedByAttr.Intersect(excludedNames).ToArray(); + } + + private static string SerializePrimitiveValue(object obj) + { + switch (obj) + { + case string stringValue: + return stringValue; + case bool boolValue: + return boolValue ? TrueLiteral : FalseLiteral; + default: + return obj.ToString(); + } + } + #endregion + } +} diff --git a/Unosquare.Swan.Lite/Properties/AssemblyInfo.cs b/Unosquare.Swan.Lite/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..1f8d176 --- /dev/null +++ b/Unosquare.Swan.Lite/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die einer Assembly zugeordnet sind. +[assembly: AssemblyTitle("Unosquare SWAN")] +[assembly: AssemblyDescription("Repeating code and reinventing the wheel is generally considered bad practice. At Unosquare we are committed to beautiful code and great software. Swan is a collection of classes and extension methods that we and other good developers have developed and evolved over the years. We found ourselves copying and pasting the same code for every project every time we started it. We decide to kill that cycle once and for all. This is the result of that idea. Our philosophy is that SWAN should have no external dependencies, it should be cross-platform, and it should be useful.")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Unosquare")] +[assembly: AssemblyProduct("Unosquare.Swan.Lite")] +[assembly: AssemblyCopyright("Copyright (c) 2016-2019 - Unosquare")] +[assembly: AssemblyTrademark("https://github.com/unosquare/swan")] +[assembly: AssemblyCulture("")] + +// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly +// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von +// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. +[assembly: ComVisible(false)] + +// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +[assembly: Guid("ab015683-62e5-47f1-861f-6d037f9c6433")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, +// indem Sie "*" wie unten gezeigt eingeben: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0")] +[assembly: AssemblyFileVersion("1.0.0")] diff --git a/Unosquare.Swan.Lite/Reflection/AttributeCache.cs b/Unosquare.Swan.Lite/Reflection/AttributeCache.cs new file mode 100644 index 0000000..77dd83d --- /dev/null +++ b/Unosquare.Swan.Lite/Reflection/AttributeCache.cs @@ -0,0 +1,174 @@ +namespace Unosquare.Swan.Reflection +{ + using System; + using System.Collections.Generic; + using System.Reflection; + using System.Collections.Concurrent; + using System.Linq; + + /// + /// A thread-safe cache of attributes belonging to a given key (MemberInfo or Type). + /// + /// The Retrieve method is the most useful one in this class as it + /// calls the retrieval process if the type is not contained + /// in the cache. + /// + public class AttributeCache + { + private readonly Lazy, IEnumerable>> _data = + new Lazy, IEnumerable>>(() => + new ConcurrentDictionary, IEnumerable>(), true); + + /// + /// Initializes a new instance of the class. + /// + /// The property cache object. + public AttributeCache(PropertyTypeCache propertyCache = null) + { + PropertyTypeCache = propertyCache ?? Runtime.PropertyTypeCache; + } + + /// + /// A PropertyTypeCache object for caching properties and their attributes. + /// + public PropertyTypeCache PropertyTypeCache { get; } + + /// + /// Determines whether [contains] [the specified member]. + /// + /// The type of the attribute to be retrieved. + /// The member. + /// + /// true if [contains] [the specified member]; otherwise, false. + /// + public bool Contains(MemberInfo member) => _data.Value.ContainsKey(new Tuple(member, typeof(T))); + + /// + /// Gets specific attributes from a member constrained to an attribute. + /// + /// The type of the attribute to be retrieved. + /// The member. + /// true to inspect the ancestors of element; otherwise, false. + /// An array of the attributes stored for the specified type. + public IEnumerable Retrieve(MemberInfo member, bool inherit = false) + where T : Attribute + { + if (member == null) + throw new ArgumentNullException(nameof(member)); + + return Retrieve(new Tuple(member, typeof(T)), t => member.GetCustomAttributes(inherit)); + } + + /// + /// Gets all attributes of a specific type from a member. + /// + /// The member. + /// The attribute type. + /// true to inspect the ancestors of element; otherwise, false. + /// An array of the attributes stored for the specified type. + public IEnumerable Retrieve(MemberInfo member, Type type, bool inherit = false) + { + if (member == null) + throw new ArgumentNullException(nameof(member)); + + if (type == null) + throw new ArgumentNullException(nameof(type)); + + return Retrieve( + new Tuple(member, type), + t => member.GetCustomAttributes(type, inherit)); + } + + /// + /// Gets one attribute of a specific type from a member. + /// + /// The attribute type. + /// The member. + /// true to inspect the ancestors of element; otherwise, false. + /// An attribute stored for the specified type. + public T RetrieveOne(MemberInfo member, bool inherit = false) + where T : Attribute + { + if (member == null) + return default; + + var attr = Retrieve( + new Tuple(member, typeof(T)), + t => member.GetCustomAttributes(typeof(T), inherit)); + + return ConvertToAttribute(attr); + } + + /// + /// Gets one attribute of a specific type from a generic type. + /// + /// The type of the attribute. + /// The type to retrieve the attribute. + /// if set to true [inherit]. + /// An attribute stored for the specified type. + public TAttribute RetrieveOne(bool inherit = false) + where TAttribute : Attribute + { + var attr = Retrieve( + new Tuple(typeof(T), typeof(TAttribute)), + t => typeof(T).GetCustomAttributes(typeof(TAttribute), inherit)); + + return ConvertToAttribute(attr); + } + + /// + /// Gets all properties an their attributes of a given type constrained to only attributes. + /// + /// The type of the attribute to retrieve. + /// The type of the object. + /// true to inspect the ancestors of element; otherwise, false. + /// A dictionary of the properties and their attributes stored for the specified type. + public Dictionary> Retrieve(Type type, bool inherit = false) + where T : Attribute + { + if (type == null) + throw new ArgumentNullException(nameof(type)); + + return PropertyTypeCache.RetrieveAllProperties(type, true) + .ToDictionary(x => x, x => Retrieve(x, inherit)); + } + + /// + /// Gets all properties and their attributes of a given type. + /// + /// The object type used to extract the properties from. + /// Type of the attribute. + /// true to inspect the ancestors of element; otherwise, false. + /// + /// A dictionary of the properties and their attributes stored for the specified type. + /// + public Dictionary> RetrieveFromType(Type attributeType, bool inherit = false) + { + if (attributeType == null) + throw new ArgumentNullException(nameof(attributeType)); + + return PropertyTypeCache.RetrieveAllProperties(true) + .ToDictionary(x => x, x => Retrieve(x, attributeType, inherit)); + } + + private static T ConvertToAttribute(IEnumerable attr) + where T : Attribute + { + if (attr?.Any() != true) + return default; + + if (attr.Count() == 1) + return (T) Convert.ChangeType(attr.First(), typeof(T)); + + throw new AmbiguousMatchException("Multiple custom attributes of the same type found."); + } + + private IEnumerable Retrieve(Tuple key, Func, IEnumerable> factory) + { + if (factory == null) + throw new ArgumentNullException(nameof(factory)); + + return _data.Value.GetOrAdd(key, k => factory.Invoke(k).Where(item => item != null)); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Reflection/ExtendedPropertyInfo.cs b/Unosquare.Swan.Lite/Reflection/ExtendedPropertyInfo.cs new file mode 100644 index 0000000..6b405ff --- /dev/null +++ b/Unosquare.Swan.Lite/Reflection/ExtendedPropertyInfo.cs @@ -0,0 +1,107 @@ +namespace Unosquare.Swan.Reflection +{ + using System; + using System.Reflection; + using Attributes; + + /// + /// Represents a Property object from a Object Reflection Property with extended values. + /// + public class ExtendedPropertyInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The property information. + public ExtendedPropertyInfo(PropertyInfo propertyInfo) + { + if (propertyInfo == null) + { + throw new ArgumentNullException(nameof(propertyInfo)); + } + + Property = propertyInfo.Name; + DataType = propertyInfo.PropertyType.Name; + + foreach (PropertyDisplayAttribute display in Runtime.AttributeCache.Retrieve(propertyInfo, true)) + { + Name = display.Name; + Description = display.Description; + GroupName = display.GroupName; + DefaultValue = display.DefaultValue; + } + } + + /// + /// Gets or sets the property. + /// + /// + /// The property. + /// + public string Property { get; } + + /// + /// Gets or sets the type of the data. + /// + /// + /// The type of the data. + /// + public string DataType { get; } + + /// + /// Gets or sets the value. + /// + /// + /// The value. + /// + public object Value { get; set; } + + /// + /// Gets or sets the default value. + /// + /// + /// The default value. + /// + public object DefaultValue { get; } + + /// + /// Gets or sets the name. + /// + /// + /// The name. + /// + public string Name { get; } + + /// + /// Gets or sets the description. + /// + /// + /// The description. + /// + public string Description { get; } + + /// + /// Gets or sets the name of the group. + /// + /// + /// The name of the group. + /// + public string GroupName { get; } + } + + /// + /// Represents a Property object from a Object Reflection Property with extended values. + /// + /// The type of the object. + public class ExtendedPropertyInfo : ExtendedPropertyInfo + { + /// + /// Initializes a new instance of the class. + /// + /// The property. + public ExtendedPropertyInfo(string property) + : base(typeof(T).GetProperty(property)) + { + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Reflection/ExtendedTypeInfo.cs b/Unosquare.Swan.Lite/Reflection/ExtendedTypeInfo.cs new file mode 100644 index 0000000..457d2d9 --- /dev/null +++ b/Unosquare.Swan.Lite/Reflection/ExtendedTypeInfo.cs @@ -0,0 +1,290 @@ +namespace Unosquare.Swan.Reflection +{ + using System; + using System.Collections.Generic; + using System.ComponentModel; + using System.Globalization; + using System.Linq; + using System.Reflection; + + /// + /// Provides extended information about a type. + /// + /// This class is mainly used to define sets of types within the Definition class + /// and it is not meant for other than querying the BasicTypesInfo dictionary. + /// + public class ExtendedTypeInfo + { + #region Static Declarations + + private const string TryParseMethodName = nameof(byte.TryParse); + private const string ToStringMethodName = nameof(ToString); + + private static readonly Type[] NumericTypes = + { + typeof(byte), + typeof(sbyte), + typeof(decimal), + typeof(double), + typeof(float), + typeof(int), + typeof(uint), + typeof(long), + typeof(ulong), + typeof(short), + typeof(ushort), + }; + + #endregion + + #region State Management + + private readonly ParameterInfo[] _tryParseParameters; + private readonly int _toStringArgumentLength; + + #endregion + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The t. + public ExtendedTypeInfo(Type t) + { + Type = t ?? throw new ArgumentNullException(nameof(t)); + IsNullableValueType = Type.GetTypeInfo().IsGenericType + && Type.GetGenericTypeDefinition() == typeof(Nullable<>); + + IsValueType = t.GetTypeInfo().IsValueType; + + UnderlyingType = IsNullableValueType ? + new NullableConverter(Type).UnderlyingType : + Type; + + IsNumeric = NumericTypes.Contains(UnderlyingType); + + // Extract the TryParse method info + try + { + TryParseMethodInfo = UnderlyingType.GetMethod(TryParseMethodName, + new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider), UnderlyingType.MakeByRefType() }) ?? + UnderlyingType.GetMethod(TryParseMethodName, + new[] { typeof(string), UnderlyingType.MakeByRefType() }); + + _tryParseParameters = TryParseMethodInfo?.GetParameters(); + } + catch + { + // ignored + } + + // Extract the ToString method Info + try + { + ToStringMethodInfo = UnderlyingType.GetMethod(ToStringMethodName, + new[] { typeof(IFormatProvider) }) ?? + UnderlyingType.GetMethod(ToStringMethodName, + new Type[] { }); + + _toStringArgumentLength = ToStringMethodInfo?.GetParameters().Length ?? 0; + } + catch + { + // ignored + } + } + + #endregion + + #region Properties + + /// + /// Gets the type this extended info class provides for. + /// + /// + /// The type. + /// + public Type Type { get; } + + /// + /// Gets a value indicating whether the type is a nullable value type. + /// + /// + /// true if this instance is nullable value type; otherwise, false. + /// + public bool IsNullableValueType { get; } + + /// + /// Gets a value indicating whether the type or underlying type is numeric. + /// + /// + /// true if this instance is numeric; otherwise, false. + /// + public bool IsNumeric { get; } + + /// + /// Gets a value indicating whether the type is value type. + /// Nullable value types have this property set to False. + /// + public bool IsValueType { get; } + + /// + /// When dealing with nullable value types, this property will + /// return the underlying value type of the nullable, + /// Otherwise it will return the same type as the Type property. + /// + /// + /// The type of the underlying. + /// + public Type UnderlyingType { get; } + + /// + /// Gets the try parse method information. If the type does not contain + /// a suitable TryParse static method, it will return null. + /// + /// + /// The try parse method information. + /// + public MethodInfo TryParseMethodInfo { get; } + + /// + /// Gets the ToString method info + /// It will prefer the overload containing the IFormatProvider argument. + /// + /// + /// To string method information. + /// + public MethodInfo ToStringMethodInfo { get; } + + /// + /// Gets a value indicating whether the type contains a suitable TryParse method. + /// + /// + /// true if this instance can parse natively; otherwise, false. + /// + public bool CanParseNatively => TryParseMethodInfo != null; + + #endregion + + #region Methods + + /// + /// Gets the default value of this type. For reference types it return null. + /// For value types it returns the default value. + /// + /// Default value of this type. + public object GetDefault() => Type.GetTypeInfo().IsValueType ? Activator.CreateInstance(Type) : null; + + /// + /// Tries to parse the string into an object of the type this instance represents. + /// Returns false when no suitable TryParse methods exists for the type or when parsing fails + /// for any reason. When possible, this method uses CultureInfo.InvariantCulture and NumberStyles.Any. + /// + /// The s. + /// The result. + /// true if parse was converted successfully; otherwise, false. + public bool TryParse(string s, out object result) + { + result = GetDefault(); + + try + { + if (Type == typeof(string)) + { + result = Convert.ChangeType(s, Type); + return true; + } + + if (IsNullableValueType && string.IsNullOrEmpty(s)) + { + result = GetDefault(); + return true; + } + + if (CanParseNatively == false) + { + result = GetDefault(); + return false; + } + + // Build the arguments of the TryParse method + var dynamicArguments = new List { s }; + + for (var pi = 1; pi < _tryParseParameters.Length - 1; pi++) + { + var argInfo = _tryParseParameters[pi]; + if (argInfo.ParameterType == typeof(IFormatProvider)) + dynamicArguments.Add(CultureInfo.InvariantCulture); + else if (argInfo.ParameterType == typeof(NumberStyles)) + dynamicArguments.Add(NumberStyles.Any); + else + dynamicArguments.Add(null); + } + + dynamicArguments.Add(null); + var parseArguments = dynamicArguments.ToArray(); + + if ((bool)TryParseMethodInfo.Invoke(null, parseArguments) == false) + { + result = GetDefault(); + return false; + } + + result = parseArguments[parseArguments.Length - 1]; + return true; + } + catch + { + return false; + } + } + + /// + /// Converts this instance to its string representation, + /// trying to use the CultureInfo.InvariantCulture + /// IFormat provider if the overload is available. + /// + /// The instance. + /// A that represents the current object. + public string ToStringInvariant(object instance) + { + if (instance == null) + return string.Empty; + + return _toStringArgumentLength != 1 + ? instance.ToString() + : ToStringMethodInfo.Invoke(instance, new object[] {CultureInfo.InvariantCulture}) as string; + } + + #endregion + } + + /// + /// Provides extended information about a type. + /// + /// This class is mainly used to define sets of types within the Constants class + /// and it is not meant for other than querying the BasicTypesInfo dictionary. + /// + /// The type of extended type information. + public class ExtendedTypeInfo : ExtendedTypeInfo + { + /// + /// Initializes a new instance of the class. + /// + public ExtendedTypeInfo() + : base(typeof(T)) + { + // placeholder + } + + /// + /// Converts this instance to its string representation, + /// trying to use the CultureInfo.InvariantCulture + /// IFormat provider if the overload is available. + /// + /// The instance. + /// A that represents the current object. + public string ToStringInvariant(T instance) => base.ToStringInvariant(instance); + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Reflection/MethodInfoCache.cs b/Unosquare.Swan.Lite/Reflection/MethodInfoCache.cs new file mode 100644 index 0000000..f4c41c9 --- /dev/null +++ b/Unosquare.Swan.Lite/Reflection/MethodInfoCache.cs @@ -0,0 +1,118 @@ +namespace Unosquare.Swan.Reflection +{ + using System; + using System.Reflection; + using System.Collections.Concurrent; + + /// + /// Represents a Method Info Cache. + /// + public class MethodInfoCache : ConcurrentDictionary + { + /// + /// Retrieves the properties stored for the specified type. + /// If the properties are not available, it calls the factory method to retrieve them + /// and returns them as an array of PropertyInfo. + /// + /// The type of type. + /// The name. + /// The alias. + /// The types. + /// + /// The cached MethodInfo. + /// + /// name + /// or + /// factory. + /// type. + public MethodInfo Retrieve(string name, string alias, params Type[] types) + => Retrieve(typeof(T), name, alias, types); + + /// + /// Retrieves the specified name. + /// + /// The type of type. + /// The name. + /// The types. + /// + /// The cached MethodInfo. + /// + public MethodInfo Retrieve(string name, params Type[] types) + => Retrieve(typeof(T), name, name, types); + + /// + /// Retrieves the specified type. + /// + /// The type. + /// The name. + /// The types. + /// + /// An array of the properties stored for the specified type. + /// + public MethodInfo Retrieve(Type type, string name, params Type[] types) + => Retrieve(type, name, name, types); + + /// + /// Retrieves the specified type. + /// + /// The type. + /// The name. + /// The alias. + /// The types. + /// + /// The cached MethodInfo. + /// + public MethodInfo Retrieve(Type type, string name, string alias, params Type[] types) + { + if (type == null) + throw new ArgumentNullException(nameof(type)); + + if (alias == null) + throw new ArgumentNullException(nameof(alias)); + + if (name == null) + throw new ArgumentNullException(nameof(name)); + + return GetOrAdd( + alias, + x => type.GetMethod(name, types ?? new Type[0])); + } + + /// + /// Retrieves the specified name. + /// + /// The type of type. + /// The name. + /// + /// The cached MethodInfo. + /// + public MethodInfo Retrieve(string name) + => Retrieve(typeof(T), name); + + /// + /// Retrieves the specified type. + /// + /// The type. + /// The name. + /// + /// The cached MethodInfo. + /// + /// + /// type + /// or + /// name. + /// + public MethodInfo Retrieve(Type type, string name) + { + if (type == null) + throw new ArgumentNullException(nameof(type)); + + if (name == null) + throw new ArgumentNullException(nameof(name)); + + return GetOrAdd( + name, + type.GetMethod); + } + } +} diff --git a/Unosquare.Swan.Lite/Reflection/TypeCache.cs b/Unosquare.Swan.Lite/Reflection/TypeCache.cs new file mode 100644 index 0000000..ca80ac7 --- /dev/null +++ b/Unosquare.Swan.Lite/Reflection/TypeCache.cs @@ -0,0 +1,135 @@ +namespace Unosquare.Swan.Reflection +{ + using System.Linq; + using System; + using System.Collections.Generic; + using System.Reflection; + using Components; + + /// + /// A thread-safe cache of members belonging to a given type. + /// + /// The Retrieve method is the most useful one in this class as it + /// calls the retrieval process if the type is not contained + /// in the cache. + /// + /// The type of Member to be cached. + public abstract class TypeCache : CollectionCacheRepository + where T : MemberInfo + { + /// + /// Determines whether the cache contains the specified type. + /// + /// The type of the out. + /// + /// true if [contains]; otherwise, false. + /// + public bool Contains() => ContainsKey(typeof(TOut)); + + /// + /// Retrieves the properties stored for the specified type. + /// If the properties are not available, it calls the factory method to retrieve them + /// and returns them as an array of PropertyInfo. + /// + /// The type of the out. + /// The factory. + /// An array of the properties stored for the specified type. + public IEnumerable Retrieve(Func> factory) + => Retrieve(typeof(TOut), factory); + } + + /// + /// A thread-safe cache of properties belonging to a given type. + /// + /// The Retrieve method is the most useful one in this class as it + /// calls the retrieval process if the type is not contained + /// in the cache. + /// + public class PropertyTypeCache : TypeCache + { + /// + /// Retrieves all properties. + /// + /// The type to inspect. + /// if set to true [only public]. + /// + /// A collection with all the properties in the given type. + /// + public IEnumerable RetrieveAllProperties(bool onlyPublic = false) + => Retrieve(onlyPublic ? GetAllPublicPropertiesFunc() : GetAllPropertiesFunc()); + + /// + /// Retrieves all properties. + /// + /// The type. + /// if set to true [only public]. + /// + /// A collection with all the properties in the given type. + /// + public IEnumerable RetrieveAllProperties(Type type, bool onlyPublic = false) + => Retrieve(type, onlyPublic ? GetAllPublicPropertiesFunc() : GetAllPropertiesFunc()); + + /// + /// Retrieves the filtered properties. + /// + /// The type. + /// if set to true [only public]. + /// The filter. + /// + /// A collection with all the properties in the given type. + /// + public IEnumerable RetrieveFilteredProperties( + Type type, + bool onlyPublic, + Func filter) + => Retrieve(type, + onlyPublic ? GetAllPublicPropertiesFunc(filter) : GetAllPropertiesFunc(filter)); + + private static Func> GetAllPropertiesFunc( + Func filter = null) + => GetPropertiesFunc( + BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, + filter); + + private static Func> GetAllPublicPropertiesFunc( + Func filter = null) + => GetPropertiesFunc(BindingFlags.Public | BindingFlags.Instance, filter); + + private static Func> GetPropertiesFunc(BindingFlags flags, + Func filter = null) + => t => t.GetProperties(flags) + .Where(filter ?? (p => p.CanRead || p.CanWrite)); + } + + /// + /// A thread-safe cache of fields belonging to a given type + /// The Retrieve method is the most useful one in this class as it + /// calls the retrieval process if the type is not contained + /// in the cache. + /// + public class FieldTypeCache : TypeCache + { + /// + /// Retrieves all fields. + /// + /// The type to inspect. + /// + /// A collection with all the fields in the given type. + /// + public IEnumerable RetrieveAllFields() + => Retrieve(GetAllFieldsFunc()); + + /// + /// Retrieves all fields. + /// + /// The type. + /// + /// A collection with all the fields in the given type. + /// + public IEnumerable RetrieveAllFields(Type type) + => Retrieve(type, GetAllFieldsFunc()); + + private static Func> GetAllFieldsFunc() + => t => t.GetFields(BindingFlags.Public | BindingFlags.Instance); + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Runtime.cs b/Unosquare.Swan.Lite/Runtime.cs new file mode 100644 index 0000000..81992b7 --- /dev/null +++ b/Unosquare.Swan.Lite/Runtime.cs @@ -0,0 +1,366 @@ +namespace Unosquare.Swan +{ + using Components; + using System; + using System.IO; + using System.Threading; + using Reflection; +#if !NETSTANDARD1_3 + using System.Reflection; +#endif + + /// + /// Provides utility methods to retrieve information about the current application. + /// +#if !NETSTANDARD1_3 + public class Runtime : MarshalByRefObject +#else + public static class Runtime +#endif + { + private static readonly Lazy _propertyTypeCache = new Lazy(() => new PropertyTypeCache()); + + private static readonly Lazy _attributeCache = new Lazy(() => new AttributeCache()); + + private static readonly Lazy _objectValidator = new Lazy(() => new ObjectValidator()); + + private static readonly Lazy _fieldTypeCache = new Lazy(() => new FieldTypeCache()); + + private static readonly Lazy _methodInfoCache = new Lazy(() => new MethodInfoCache()); + +#if NET452 + private static readonly Lazy EntryAssemblyLazy = new Lazy(() => Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly()); +#endif + +#if NETSTANDARD2_0 + private static readonly Lazy EntryAssemblyLazy = new Lazy(Assembly.GetEntryAssembly); +#endif + +#if NET452 + private static readonly Lazy ProcessLazy = new Lazy(System.Diagnostics.Process.GetCurrentProcess); +#endif + +#if !NETSTANDARD1_3 + private static readonly Lazy CompanyNameLazy = new Lazy(() => + { + var attribute = + EntryAssembly.GetCustomAttribute(typeof(AssemblyCompanyAttribute)) as AssemblyCompanyAttribute; + return attribute?.Company ?? string.Empty; + }); + + private static readonly Lazy ProductNameLazy = new Lazy(() => + { + var attribute = + EntryAssembly.GetCustomAttribute(typeof(AssemblyProductAttribute)) as AssemblyProductAttribute; + return attribute?.Product ?? string.Empty; + }); + + private static readonly Lazy ProductTrademarkLazy = new Lazy(() => + { + var attribute = + EntryAssembly.GetCustomAttribute(typeof(AssemblyTrademarkAttribute)) as AssemblyTrademarkAttribute; + return attribute?.Trademark ?? string.Empty; + }); +#endif + + private static readonly Lazy _argumentParser = + new Lazy(() => new ArgumentParser()); + + private static readonly Lazy _objectMapper = new Lazy(() => new ObjectMapper()); + +#if !NETSTANDARD1_3 + private static readonly string ApplicationMutexName = "Global\\{{" + EntryAssembly.FullName + "}}"; +#else + private const string ApplicationMutexName = "Global\\{{SWANINSTANCE}}"; +#endif + + private static readonly object SyncLock = new object(); + + private static OperatingSystem? _oS; + + #region Properties + + /// + /// Gets the current Operating System. + /// + /// + /// The os. + /// + public static OperatingSystem OS + { + get + { + if (_oS.HasValue == false) + { + var windowsDirectory = Environment.GetEnvironmentVariable("windir"); + if (string.IsNullOrEmpty(windowsDirectory) == false + && windowsDirectory.Contains(@"\") + && Directory.Exists(windowsDirectory)) + { + _oS = OperatingSystem.Windows; + } + else + { + _oS = File.Exists(@"/proc/sys/kernel/ostype") ? OperatingSystem.Unix : OperatingSystem.Osx; + } + } + + return _oS ?? OperatingSystem.Unknown; + } + } + +#if NET452 + /// + /// Gets the process associated with the current application. + /// + /// + /// The process. + /// + public static System.Diagnostics.Process Process => ProcessLazy.Value; +#endif + + /// + /// Checks if this application (including version number) is the only instance currently running. + /// + /// + /// true if this instance is the only instance; otherwise, false. + /// + public static bool IsTheOnlyInstance + { + get + { + lock (SyncLock) + { + try + { + // Try to open existing mutex. + Mutex.OpenExisting(ApplicationMutexName); + } + catch + { + try + { + // If exception occurred, there is no such mutex. + var appMutex = new Mutex(true, ApplicationMutexName); + $"Application Mutex created {appMutex} named '{ApplicationMutexName}'".Debug( + typeof(Runtime)); + + // Only one instance. + return true; + } + catch + { + // Sometimes the user can't create the Global Mutex + } + } + + // More than one instance. + return false; + } + } + } + + /// + /// Gets a value indicating whether this application instance is using the MONO runtime. + /// + /// + /// true if this instance is using MONO runtime; otherwise, false. + /// + public static bool IsUsingMonoRuntime => Type.GetType("Mono.Runtime") != null; + + /// + /// Gets the property type cache. + /// + /// + /// The property type cache. + /// + public static PropertyTypeCache PropertyTypeCache => _propertyTypeCache.Value; + + /// + /// Gets the attribute cache. + /// + /// + /// The attribute cache. + /// + public static AttributeCache AttributeCache => _attributeCache.Value; + + /// + /// Gets the object validator. + /// + /// + /// The object validator. + /// + public static ObjectValidator ObjectValidator => _objectValidator.Value; + + /// + /// Gets the field type cache. + /// + /// + /// The field type cache. + /// + public static FieldTypeCache FieldTypeCache => _fieldTypeCache.Value; + + /// + /// Gets the method information cache. + /// + /// + /// The method information cache. + /// + public static MethodInfoCache MethodInfoCache => _methodInfoCache.Value; + +#if !NETSTANDARD1_3 + /// + /// Gets the assembly that started the application. + /// + /// + /// The entry assembly. + /// + public static Assembly EntryAssembly => EntryAssemblyLazy.Value; + + /// + /// Gets the name of the entry assembly. + /// + /// + /// The name of the entry assembly. + /// + public static AssemblyName EntryAssemblyName => EntryAssemblyLazy.Value.GetName(); + + /// + /// Gets the entry assembly version. + /// + public static Version EntryAssemblyVersion => EntryAssemblyName.Version; + + /// + /// Gets the full path to the folder containing the assembly that started the application. + /// + /// + /// The entry assembly directory. + /// + public static string EntryAssemblyDirectory + { + get + { + var uri = new UriBuilder(EntryAssembly.CodeBase); + var path = Uri.UnescapeDataString(uri.Path); + return Path.GetDirectoryName(path); + } + } + + /// + /// Gets the name of the company. + /// + /// + /// The name of the company. + /// + public static string CompanyName => CompanyNameLazy.Value; + + /// + /// Gets the name of the product. + /// + /// + /// The name of the product. + /// + public static string ProductName => ProductNameLazy.Value; + + /// + /// Gets the trademark. + /// + /// + /// The product trademark. + /// + public static string ProductTrademark => ProductTrademarkLazy.Value; +#endif + + /// + /// Gets a local storage path with a version. + /// + /// + /// The local storage path. + /// + public static string LocalStoragePath + { + get + { +#if !NETSTANDARD1_3 + var localAppDataPath = +#if NET452 + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + EntryAssemblyName.Name); +#else + Path.GetDirectoryName(EntryAssembly.Location); +#endif + + var returnPath = Path.Combine(localAppDataPath, EntryAssemblyVersion.ToString()); +#else + var returnPath = Directory.GetCurrentDirectory(); // Use current path... +#endif + + if (Directory.Exists(returnPath) == false) + { + Directory.CreateDirectory(returnPath); + } + + return returnPath; + } + } + + /// + /// Gets the singleton instance created with basic defaults. + /// + /// + /// The argument parser. + /// + public static ArgumentParser ArgumentParser => _argumentParser.Value; + + /// + /// Gets the object mapper instance created with basic defaults. + /// + /// + /// The object mapper. + /// + public static ObjectMapper ObjectMapper => _objectMapper.Value; + + #endregion + + #region Methods + +#if !NETSTANDARD1_3 + /// + /// Writes a standard banner to the standard output + /// containing the company name, product name, assembly version and trademark. + /// + /// The color. + public static void WriteWelcomeBanner(ConsoleColor color = ConsoleColor.Gray) + { + $"{CompanyName} {ProductName} [Version {EntryAssemblyVersion}]".WriteLine(color); + $"{ProductTrademark}".WriteLine(color); + } + + /// + /// Gets all the loaded assemblies in the current application domain. + /// + /// An array of assemblies. + public static Assembly[] GetAssemblies() => AppDomain.CurrentDomain.GetAssemblies(); + + /// + /// Build a full path pointing to the current user's desktop with the given filename. + /// + /// The filename. + /// + /// The fully qualified location of path, such as "C:\MyFile.txt". + /// + /// filename. + public static string GetDesktopFilePath(string filename) + { + if (string.IsNullOrWhiteSpace(filename)) + throw new ArgumentNullException(nameof(filename)); + + var pathWithFilename = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), + filename); + return Path.GetFullPath(pathWithFilename); + } +#endif + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Terminal.Enums.cs b/Unosquare.Swan.Lite/Terminal.Enums.cs new file mode 100644 index 0000000..77d709e --- /dev/null +++ b/Unosquare.Swan.Lite/Terminal.Enums.cs @@ -0,0 +1,89 @@ +namespace Unosquare.Swan +{ + using System; + + /// + /// Defines a set of bitwise standard terminal writers. + /// + [Flags] + public enum TerminalWriters + { + /// + /// Prevents output + /// + None = 0, + + /// + /// Writes to the Console.Out + /// + StandardOutput = 1, + + /// + /// Writes to the Console.Error + /// + StandardError = 2, + + /// + /// Writes to the System.Diagnostics.Debug + /// + Diagnostics = 4, + + /// + /// Writes to all possible terminal writers + /// + All = StandardOutput | Diagnostics | StandardError, + + /// + /// The error and debug writers + /// + ErrorAndDebug = StandardError | Diagnostics, + + /// + /// The output and debug writers + /// + OutputAndDebug = StandardOutput | Diagnostics, + } + + /// + /// Defines the bitwise flags to determine + /// which types of messages get printed on the current console. + /// + [Flags] + public enum LogMessageType + { + /// + /// The none message type + /// + None = 0, + + /// + /// The information message type + /// + Info = 1, + + /// + /// The debug message type + /// + Debug = 2, + + /// + /// The trace message type + /// + Trace = 4, + + /// + /// The error message type + /// + Error = 8, + + /// + /// The warning message type + /// + Warning = 16, + + /// + /// The fatal message type + /// + Fatal = 32, + } +} diff --git a/Unosquare.Swan.Lite/Terminal.Graphics.cs b/Unosquare.Swan.Lite/Terminal.Graphics.cs new file mode 100644 index 0000000..e6afad7 --- /dev/null +++ b/Unosquare.Swan.Lite/Terminal.Graphics.cs @@ -0,0 +1,47 @@ +namespace Unosquare.Swan +{ + using System; + + /// + /// A console terminal helper to create nicer output and receive input from the user + /// This class is thread-safe :). + /// + public static partial class Terminal + { + /// + /// Represents a Table to print in console. + /// + private static class Table + { + /// + /// Gets or sets the color of the border. + /// + /// + /// The color of the border. + /// + private static ConsoleColor BorderColor { get; } = ConsoleColor.DarkGreen; + + public static void Vertical() => ((byte)179).Write(BorderColor); + + public static void RightTee() => ((byte)180).Write(BorderColor); + + public static void TopRight() => ((byte)191).Write(BorderColor); + + public static void BottomLeft() => ((byte)192).Write(BorderColor); + + public static void BottomTee() => ((byte)193).Write(BorderColor); + + public static void TopTee() => ((byte)194).Write(BorderColor); + + public static void LeftTee() => ((byte)195).Write(BorderColor); + + public static void Horizontal(int length) => ((byte)196).Write(BorderColor, length); + + public static void Tee() => ((byte)197).Write(BorderColor); + + public static void BottomRight() => ((byte)217).Write(BorderColor); + + public static void TopLeft() => ((byte)218).Write(BorderColor); + } + } +} diff --git a/Unosquare.Swan.Lite/Terminal.Interaction.cs b/Unosquare.Swan.Lite/Terminal.Interaction.cs new file mode 100644 index 0000000..7c47bda --- /dev/null +++ b/Unosquare.Swan.Lite/Terminal.Interaction.cs @@ -0,0 +1,216 @@ +namespace Unosquare.Swan +{ + using System; + using System.Collections.Generic; + + /// + /// A console terminal helper to create nicer output and receive input from the user + /// This class is thread-safe :). + /// + public static partial class Terminal + { + #region ReadKey + + /// + /// Reads a key from the Terminal. This is the closest equivalent to Console.ReadKey. + /// + /// if set to true the pressed key will not be rendered to the output. + /// if set to true the output will continue to be shown. + /// This is useful for services and daemons that are running as console applications and wait for a key to exit the program. + /// The console key information. + public static ConsoleKeyInfo ReadKey(bool intercept, bool disableLocking = false) + { + if (IsConsolePresent == false) return default; + if (disableLocking) return Console.ReadKey(intercept); + + lock (SyncLock) + { + Flush(); + InputDone.Reset(); + try + { + Console.CursorVisible = true; + return Console.ReadKey(intercept); + } + finally + { + Console.CursorVisible = false; + InputDone.Set(); + } + } + } + + /// + /// Reads a key from the Terminal. + /// + /// The prompt. + /// if set to true [prevent echo]. + /// The console key information. + public static ConsoleKeyInfo ReadKey(this string prompt, bool preventEcho) + { + if (IsConsolePresent == false) return default; + + lock (SyncLock) + { + if (prompt != null) + { + ($" {(string.IsNullOrWhiteSpace(Settings.LoggingTimeFormat) ? string.Empty : DateTime.Now.ToString(Settings.LoggingTimeFormat) + " ")}" + + $"{Settings.UserInputPrefix} << {prompt} ").Write(ConsoleColor.White); + } + + var input = ReadKey(true); + var echo = preventEcho ? string.Empty : input.Key.ToString(); + echo.WriteLine(); + return input; + } + } + + /// + /// Reads a key from the terminal preventing the key from being echoed. + /// + /// The prompt. + /// A value that identifies the console key. + public static ConsoleKeyInfo ReadKey(this string prompt) => prompt.ReadKey(true); + + #endregion + + #region Other Terminal Read Methods + + /// + /// Reads a line of text from the console. + /// + /// The read line. + public static string ReadLine() + { + if (IsConsolePresent == false) return default; + + lock (SyncLock) + { + Flush(); + InputDone.Reset(); + + try + { + Console.CursorVisible = true; + return Console.ReadLine(); + } + finally + { + Console.CursorVisible = false; + InputDone.Set(); + } + } + } + + /// + /// Reads a number from the input. If unable to parse, it returns the default number. + /// + /// The prompt. + /// The default number. + /// + /// Conversions of string representation of a number to its 32-bit signed integer equivalent. + /// + public static int ReadNumber(this string prompt, int defaultNumber) + { + if (IsConsolePresent == false) return defaultNumber; + + lock (SyncLock) + { + $" {DateTime.Now:HH:mm:ss} USR << {prompt} (default is {defaultNumber}): ".Write(ConsoleColor.White); + + var input = ReadLine(); + return int.TryParse(input, out var parsedInt) ? parsedInt : defaultNumber; + } + } + + /// + /// Creates a table prompt where the user can enter an option based on the options dictionary provided. + /// + /// The title. + /// The options. + /// Any key option. + /// A value that identifies the console key that was pressed. + public static ConsoleKeyInfo ReadPrompt(this string title, Dictionary options, string anyKeyOption) + { + if (IsConsolePresent == false) return default; + + const ConsoleColor textColor = ConsoleColor.White; + var lineLength = Console.BufferWidth; + var lineAlign = -(lineLength - 2); + var textFormat = "{0," + lineAlign + "}"; + + // lock the output as an atomic operation + lock (SyncLock) + { + { // Top border + Table.TopLeft(); + Table.Horizontal(-lineAlign); + Table.TopRight(); + } + + { // Title + Table.Vertical(); + var titleText = string.Format( + textFormat, + string.IsNullOrWhiteSpace(title) ? " Select an option from the list below." : $" {title}"); + titleText.Write(textColor); + Table.Vertical(); + } + + { // Title Bottom + Table.LeftTee(); + Table.Horizontal(lineLength - 2); + Table.RightTee(); + } + + // Options + foreach (var kvp in options) + { + Table.Vertical(); + string.Format(textFormat, + $" {"[ " + kvp.Key + " ]",-10} {kvp.Value}").Write(textColor); + Table.Vertical(); + } + + // Any Key Options + if (string.IsNullOrWhiteSpace(anyKeyOption) == false) + { + Table.Vertical(); + string.Format(textFormat, " ").Write(ConsoleColor.Gray); + Table.Vertical(); + + Table.Vertical(); + string.Format(textFormat, + $" {" ",-10} {anyKeyOption}").Write(ConsoleColor.Gray); + Table.Vertical(); + } + + { // Input section + Table.LeftTee(); + Table.Horizontal(lineLength - 2); + Table.RightTee(); + + Table.Vertical(); + string.Format(textFormat, + Settings.UserOptionText).Write(ConsoleColor.Green); + Table.Vertical(); + + Table.BottomLeft(); + Table.Horizontal(lineLength - 2); + Table.BottomRight(); + } + } + + var inputLeft = Settings.UserOptionText.Length + 3; + + SetCursorPosition(inputLeft, CursorTop - 2); + var userInput = ReadKey(true); + userInput.Key.ToString().Write(ConsoleColor.Gray); + + SetCursorPosition(0, CursorTop + 2); + return userInput; + } + + #endregion + } +} diff --git a/Unosquare.Swan.Lite/Terminal.Logging.cs b/Unosquare.Swan.Lite/Terminal.Logging.cs new file mode 100644 index 0000000..dadf1c3 --- /dev/null +++ b/Unosquare.Swan.Lite/Terminal.Logging.cs @@ -0,0 +1,746 @@ +namespace Unosquare.Swan +{ + using System; + using System.Runtime.CompilerServices; + using System.Threading.Tasks; + + /// + /// A console terminal helper to create nicer output and receive input from the user + /// This class is thread-safe :). + /// + public static partial class Terminal + { + #region Private Declarations + + private static ulong _loggingSequence; + + #endregion + + #region Events + + /// + /// Occurs asynchronously, whenever a logging message is received by the terminal. + /// Only called when Terminal writes data via Info, Error, Trace, Warn, Fatal, Debug methods, regardless of whether or not + /// the console is present. Subscribe to this event to pass data on to your own logger. + /// + public static event EventHandler OnLogMessageReceived; + + /// + /// Occurs synchronously (so handle quickly), whenever a logging message is about to be enqueued to the + /// console output. Setting the CancelOutput to true in the event arguments prevents the + /// logging message to be written out to the console. + /// Message filtering only works with logging methods such as Trace, Debug, Info, Warn, Fatal, Error and Dump + /// Standard Write methods do not get filtering capabilities. + /// + public static event EventHandler OnLogMessageDisplaying; + + #endregion + + #region Main Logging Method + + /// + /// Logs a message. + /// + /// Type of the message. + /// The text. + /// Name of the source. + /// The extended data. Could be an exception, or a dictionary of properties or anything the user specifies. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + private static void LogMessage( + LogMessageType messageType, + string message, + string sourceName, + object extendedData, + string callerMemberName, + string callerFilePath, + int callerLineNumber) + { + lock (SyncLock) + { + if (!Settings.GlobalLoggingMessageType.HasFlag(messageType)) + return; + + var prefix = GetConsoleColorAndPrefix(messageType, out var color); + + #region Create and Format the Output + + var sequence = _loggingSequence; + var date = DateTime.UtcNow; + _loggingSequence++; + + var loggerMessage = string.IsNullOrWhiteSpace(message) ? + string.Empty : message.RemoveControlCharsExcept('\n'); + + var outputMessage = CreateOutputMessage(sourceName, loggerMessage, prefix, date); + + // Log the message asynchronously with the appropriate event args + var eventArgs = new LogMessageReceivedEventArgs( + sequence, + messageType, + date, + sourceName, + loggerMessage, + extendedData, + callerMemberName, + callerFilePath, + callerLineNumber); + + #endregion + + #region Fire Up External Logging Logic (Asynchronously) + + if (OnLogMessageReceived != null) + { + Task.Run(() => + { + try + { + OnLogMessageReceived?.Invoke(sourceName, eventArgs); + } + catch + { + // Ignore + } + }); + } + + #endregion + + #region Display the Message by Writing to the Output Queue + + // Check if we are skipping these messages to be displayed based on settings + if (!Settings.DisplayLoggingMessageType.HasFlag(messageType)) + return; + + Write(messageType, sourceName, eventArgs, outputMessage, color); + + #endregion + } + } + + private static void Write( + LogMessageType messageType, + string sourceName, + LogMessageReceivedEventArgs eventArgs, + string outputMessage, + ConsoleColor color) + { + // Select the writer based on the message type + var writer = IsConsolePresent + ? messageType.HasFlag(LogMessageType.Error) ? TerminalWriters.StandardError : TerminalWriters.StandardOutput + : TerminalWriters.None; + + // Set the writer to Diagnostics if appropriate (Error and Debugging data go to the Diagnostics debugger + // if it is attached at all + if (IsDebuggerAttached + && (IsConsolePresent == false || messageType.HasFlag(LogMessageType.Debug) || + messageType.HasFlag(LogMessageType.Error))) + writer = writer | TerminalWriters.Diagnostics; + + // Check if we really need to write this out + if (writer == TerminalWriters.None) return; + + // Further format the output in the case there is an exception being logged + if (writer.HasFlag(TerminalWriters.StandardError) && eventArgs.Exception != null) + { + try + { + outputMessage = + $"{outputMessage}{Environment.NewLine}{eventArgs.Exception.Stringify().Indent()}"; + } + catch + { + // Ignore + } + } + + // Filter output messages via events + var displayingEventArgs = new LogMessageDisplayingEventArgs(eventArgs); + OnLogMessageDisplaying?.Invoke(sourceName, displayingEventArgs); + if (displayingEventArgs.CancelOutput == false) + outputMessage.WriteLine(color, writer); + } + + private static string GetConsoleColorAndPrefix(LogMessageType messageType, out ConsoleColor color) + { + string prefix; + + // Select color and prefix based on message type + // and settings + switch (messageType) + { + case LogMessageType.Debug: + color = Settings.DebugColor; + prefix = Settings.DebugPrefix; + break; + case LogMessageType.Error: + color = Settings.ErrorColor; + prefix = Settings.ErrorPrefix; + break; + case LogMessageType.Info: + color = Settings.InfoColor; + prefix = Settings.InfoPrefix; + break; + case LogMessageType.Trace: + color = Settings.TraceColor; + prefix = Settings.TracePrefix; + break; + case LogMessageType.Warning: + color = Settings.WarnColor; + prefix = Settings.WarnPrefix; + break; + case LogMessageType.Fatal: + color = Settings.FatalColor; + prefix = Settings.FatalPrefix; + break; + default: + color = Settings.DefaultColor; + prefix = new string(' ', Settings.InfoPrefix.Length); + break; + } + + return prefix; + } + + private static string CreateOutputMessage(string sourceName, string loggerMessage, string prefix, DateTime date) + { + var friendlySourceName = string.IsNullOrWhiteSpace(sourceName) + ? string.Empty + : sourceName.SliceLength(sourceName.LastIndexOf('.') + 1, sourceName.Length); + + var outputMessage = string.IsNullOrWhiteSpace(sourceName) + ? loggerMessage + : $"[{friendlySourceName}] {loggerMessage}"; + + return string.IsNullOrWhiteSpace(Settings.LoggingTimeFormat) + ? $" {prefix} >> {outputMessage}" + : $" {date.ToLocalTime().ToString(Settings.LoggingTimeFormat)} {prefix} >> {outputMessage}"; + } + + #endregion + + #region Standard Public API + + #region Debug + + /// + /// Logs a debug message to the console. + /// + /// The message. + /// The source. + /// The extended data. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Debug( + this string message, + string source = null, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Debug, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a debug message to the console. + /// + /// The message. + /// The source. + /// The extended data. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + public static void Debug( + this string message, + Type source, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Debug, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a debug message to the console. + /// + /// The exception. + /// The source. + /// The message. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Debug( + this Exception extendedData, + string source, + string message, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Debug, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + #endregion + + #region Trace + + /// + /// Logs a trace message to the console. + /// + /// The text. + /// The source. + /// The extended data. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Trace( + this string message, + string source = null, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Trace, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a trace message to the console. + /// + /// The message. + /// The source. + /// The extended data. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + public static void Trace( + this string message, + Type source, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Trace, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a trace message to the console. + /// + /// The extended data. + /// The source. + /// The message. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Trace( + this Exception extendedData, + string source, + string message, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Trace, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + #endregion + + #region Warn + + /// + /// Logs a warning message to the console. + /// + /// The text. + /// The source. + /// The extended data. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Warn( + this string message, + string source = null, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Warning, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a warning message to the console. + /// + /// The message. + /// The source. + /// The extended data. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + public static void Warn( + this string message, + Type source, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Warning, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a warning message to the console. + /// + /// The extended data. + /// The source. + /// The message. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Warn( + this Exception extendedData, + string source, + string message, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Warning, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + #endregion + + #region Fatal + + /// + /// Logs a warning message to the console. + /// + /// The text. + /// The source. + /// The extended data. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Fatal( + this string message, + string source = null, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Fatal, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a warning message to the console. + /// + /// The message. + /// The source. + /// The extended data. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + public static void Fatal( + this string message, + Type source, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Fatal, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a warning message to the console. + /// + /// The extended data. + /// The source. + /// The message. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Fatal( + this Exception extendedData, + string source, + string message, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Fatal, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + #endregion + + #region Info + + /// + /// Logs an info message to the console. + /// + /// The text. + /// The source. + /// The extended data. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Info( + this string message, + string source = null, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Info, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs an info message to the console. + /// + /// The message. + /// The source. + /// The extended data. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + public static void Info( + this string message, + Type source, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Info, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs an info message to the console. + /// + /// The extended data. + /// The source. + /// The message. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Info( + this Exception extendedData, + string source, + string message, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Info, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + #endregion + + #region Error + + /// + /// Logs an error message to the console's standard error. + /// + /// The text. + /// The source. + /// The extended data. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Error( + this string message, + string source = null, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Error, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs an error message to the console's standard error. + /// + /// The message. + /// The source. + /// The extended data. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + public static void Error( + this string message, + Type source, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Error, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs an error message to the console's standard error. + /// + /// The exception. + /// The source. + /// The message. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Error( + this Exception ex, + string source, + string message, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Error, message, source, ex, callerMemberName, callerFilePath, callerLineNumber); + } + + #endregion + + #endregion + + #region Extended Public API + + /// + /// Logs the specified message. + /// + /// The message. + /// The source. + /// Type of the message. + /// The extended data. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Log( + this string message, + string source, + LogMessageType messageType, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(messageType, message, source, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs the specified message. + /// + /// The message. + /// The source. + /// Type of the message. + /// The extended data. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + public static void Log( + this string message, + Type source, + LogMessageType messageType, + object extendedData = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(messageType, message, source?.FullName, extendedData, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs an error message to the console's standard error. + /// + /// The ex. + /// The source. + /// The message. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Log( + this Exception ex, + string source = null, + string message = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Error, message ?? ex.Message, source ?? ex.Source, ex, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs an error message to the console's standard error. + /// + /// The ex. + /// The source. + /// The message. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Log( + this Exception ex, + Type source = null, + string message = null, + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + LogMessage(LogMessageType.Error, message ?? ex.Message, source?.FullName ?? ex.Source, ex, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a trace message showing all possible non-null properties of the given object + /// This method is expensive as it uses Stringify internally. + /// + /// The object. + /// The source. + /// The title. + /// Name of the caller member. This is automatically populated. + /// The caller file path. This is automatically populated. + /// The caller line number. This is automatically populated. + public static void Dump( + this object obj, + string source, + string text = "Object Dump", + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + if (obj == null) return; + var message = $"{text} ({obj.GetType()}): {Environment.NewLine}{obj.Stringify().Indent(5)}"; + LogMessage(LogMessageType.Trace, message, source, obj, callerMemberName, callerFilePath, callerLineNumber); + } + + /// + /// Logs a trace message showing all possible non-null properties of the given object + /// This method is expensive as it uses Stringify internally. + /// + /// The object. + /// The source. + /// The text. + /// Name of the caller member. + /// The caller file path. + /// The caller line number. + public static void Dump( + this object obj, + Type source, + string text = "Object Dump", + [CallerMemberName] string callerMemberName = "", + [CallerFilePath] string callerFilePath = "", + [CallerLineNumber] int callerLineNumber = 0) + { + if (obj == null) return; + var message = $"{text} ({obj.GetType()}): {Environment.NewLine}{obj.Stringify().Indent(5)}"; + LogMessage(LogMessageType.Trace, message, source?.FullName, obj, callerMemberName, callerFilePath, callerLineNumber); + } + + #endregion + } +} diff --git a/Unosquare.Swan.Lite/Terminal.Output.cs b/Unosquare.Swan.Lite/Terminal.Output.cs new file mode 100644 index 0000000..f73ba81 --- /dev/null +++ b/Unosquare.Swan.Lite/Terminal.Output.cs @@ -0,0 +1,174 @@ +namespace Unosquare.Swan +{ + using System; + using System.Linq; + + /// + /// A console terminal helper to create nicer output and receive input from the user + /// This class is thread-safe :). + /// + public static partial class Terminal + { + #region Helper Methods + + /// + /// Prints all characters in the current code page. + /// This is provided for debugging purposes only. + /// + public static void PrintCurrentCodePage() + { + if (!IsConsolePresent) return; + + lock (SyncLock) + { + $"Output Encoding: {OutputEncoding}".WriteLine(); + for (byte byteValue = 0; byteValue < byte.MaxValue; byteValue++) + { + var charValue = OutputEncoding.GetChars(new[] { byteValue })[0]; + + switch (byteValue) + { + case 8: // Backspace + case 9: // Tab + case 10: // Line feed + case 13: // Carriage return + charValue = '.'; + break; + } + + $"{byteValue:000} {charValue} ".Write(); + + // 7 is a beep -- Console.Beep() also works + if (byteValue == 7) " ".Write(); + + if ((byteValue + 1) % 8 == 0) + WriteLine(); + } + + WriteLine(); + } + } + + #endregion + + #region Write Methods + + /// + /// Writes a character a number of times, optionally adding a new line at the end. + /// + /// The character code. + /// The color. + /// The count. + /// if set to true [new line]. + /// The writer flags. + public static void Write(this byte charCode, ConsoleColor? color = null, int count = 1, bool newLine = false, TerminalWriters writerFlags = TerminalWriters.StandardOutput) + { + lock (SyncLock) + { + var bytes = new byte[count]; + for (var i = 0; i < bytes.Length; i++) + { + bytes[i] = charCode; + } + + if (newLine) + { + var newLineBytes = OutputEncoding.GetBytes(Environment.NewLine); + bytes = bytes.Union(newLineBytes).ToArray(); + } + + var buffer = OutputEncoding.GetChars(bytes); + var context = new OutputContext + { + OutputColor = color ?? Settings.DefaultColor, + OutputText = buffer, + OutputWriters = writerFlags, + }; + + EnqueueOutput(context); + } + } + + /// + /// Writes the specified character in the default color. + /// + /// The character code. + /// The color. + /// The writer flags. + public static void Write(this char charCode, ConsoleColor? color = null, TerminalWriters writerFlags = TerminalWriters.StandardOutput) + { + lock (SyncLock) + { + var context = new OutputContext + { + OutputColor = color ?? Settings.DefaultColor, + OutputText = new[] { charCode }, + OutputWriters = writerFlags, + }; + + EnqueueOutput(context); + } + } + + /// + /// Writes the specified text in the given color. + /// + /// The text. + /// The color. + /// The writer flags. + public static void Write(this string text, ConsoleColor? color = null, TerminalWriters writerFlags = TerminalWriters.StandardOutput) + { + if (text == null) return; + + lock (SyncLock) + { + var buffer = OutputEncoding.GetBytes(text); + var context = new OutputContext + { + OutputColor = color ?? Settings.DefaultColor, + OutputText = OutputEncoding.GetChars(buffer), + OutputWriters = writerFlags, + }; + + EnqueueOutput(context); + } + } + + #endregion + + #region WriteLine Methods + + /// + /// Writes a New Line Sequence to the standard output. + /// + /// The writer flags. + public static void WriteLine(TerminalWriters writerFlags = TerminalWriters.StandardOutput) + => Environment.NewLine.Write(Settings.DefaultColor, writerFlags); + + /// + /// Writes a line of text in the current console foreground color + /// to the standard output. + /// + /// The text. + /// The color. + /// The writer flags. + public static void WriteLine(this string text, ConsoleColor? color = null, TerminalWriters writerFlags = TerminalWriters.StandardOutput) + => Write($"{text ?? string.Empty}{Environment.NewLine}", color, writerFlags); + + /// + /// As opposed to WriteLine methods, it prepends a Carriage Return character to the text + /// so that the console moves the cursor one position up after the text has been written out. + /// + /// The text. + /// The color. + /// The writer flags. + public static void OverwriteLine(this string text, ConsoleColor? color = null, TerminalWriters writerFlags = TerminalWriters.StandardOutput) + { + Write($"\r{text ?? string.Empty}", color, writerFlags); + Flush(); + CursorLeft = 0; + } + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.Swan.Lite/Terminal.Settings.cs b/Unosquare.Swan.Lite/Terminal.Settings.cs new file mode 100644 index 0000000..d904fd2 --- /dev/null +++ b/Unosquare.Swan.Lite/Terminal.Settings.cs @@ -0,0 +1,195 @@ +namespace Unosquare.Swan +{ + using System; + + /// + /// A console terminal helper to create nicer output and receive input from the user + /// This class is thread-safe :). + /// + public static partial class Terminal + { + /// + /// Terminal global settings. + /// + public static class Settings + { + static Settings() + { + if (IsDebuggerAttached) + { + DisplayLoggingMessageType = + LogMessageType.Debug | + LogMessageType.Error | + LogMessageType.Info | + LogMessageType.Trace | + LogMessageType.Warning | + LogMessageType.Fatal; + } + else + { + DisplayLoggingMessageType = + LogMessageType.Error | + LogMessageType.Info | + LogMessageType.Warning | + LogMessageType.Fatal; + } + + GlobalLoggingMessageType = DisplayLoggingMessageType; + } + + /// + /// Gets or sets the default output color. + /// + /// + /// The default color. + /// + public static ConsoleColor DefaultColor { get; set; } = Console.ForegroundColor; + + /// + /// Gets or sets the color of the information output logging. + /// + /// + /// The color of the information. + /// + public static ConsoleColor InfoColor { get; set; } = ConsoleColor.Cyan; + + /// + /// Gets or sets the color of the debug output logging. + /// + /// + /// The color of the debug. + /// + public static ConsoleColor DebugColor { get; set; } = ConsoleColor.Gray; + + /// + /// Gets or sets the color of the trace output logging. + /// + /// + /// The color of the trace. + /// + public static ConsoleColor TraceColor { get; set; } = ConsoleColor.DarkGray; + + /// + /// Gets or sets the color of the warning logging. + /// + /// + /// The color of the warn. + /// + public static ConsoleColor WarnColor { get; set; } = ConsoleColor.Yellow; + + /// + /// Gets or sets the color of the error logging. + /// + /// + /// The color of the error. + /// + public static ConsoleColor ErrorColor { get; set; } = ConsoleColor.DarkRed; + + /// + /// Gets or sets the color of the error logging. + /// + /// + /// The color of the error. + /// + public static ConsoleColor FatalColor { get; set; } = ConsoleColor.Red; + + /// + /// Gets or sets the information logging prefix. + /// + /// + /// The information prefix. + /// + public static string InfoPrefix { get; set; } = "INF"; + + /// + /// Gets or sets the user input prefix. + /// + /// + /// The user input prefix. + /// + public static string UserInputPrefix { get; set; } = "USR"; + + /// + /// Gets or sets the user option text. + /// + /// + /// The user option text. + /// + public static string UserOptionText { get; set; } = " Option: "; + + /// + /// Gets or sets the debug logging prefix. + /// + /// + /// The debug prefix. + /// + public static string DebugPrefix { get; set; } = "DBG"; + + /// + /// Gets or sets the trace logging prefix. + /// + /// + /// The trace prefix. + /// + public static string TracePrefix { get; set; } = "TRC"; + + /// + /// Gets or sets the warning logging prefix. + /// + /// + /// The warn prefix. + /// + public static string WarnPrefix { get; set; } = "WRN"; + + /// + /// Gets or sets the fatal logging prefix. + /// + /// + /// The fatal prefix. + /// + public static string FatalPrefix { get; set; } = "FAT"; + + /// + /// Gets or sets the error logging prefix. + /// + /// + /// The error prefix. + /// + public static string ErrorPrefix { get; set; } = "ERR"; + + /// + /// Gets or sets the logging time format. + /// set to null or empty to prevent output. + /// + /// + /// The logging time format. + /// + public static string LoggingTimeFormat { get; set; } = "HH:mm:ss.fff"; + + /// + /// Gets or sets the logging message types (in a bitwise mask) + /// to display in the console. + /// + /// + /// The console options. + /// + public static LogMessageType DisplayLoggingMessageType { get; set; } + + /// + /// Gets or sets the logging message types (in a bitwise mask) to global logging. + /// + /// + /// The type of the global logging message. + /// + public static LogMessageType GlobalLoggingMessageType { get; set; } + + /// + /// Gets or sets a value indicating whether [override is console present]. + /// + /// + /// true if [override is console present]; otherwise, false. + /// + public static bool OverrideIsConsolePresent { get; set; } + } + } +} diff --git a/Unosquare.Swan.Lite/Terminal.cs b/Unosquare.Swan.Lite/Terminal.cs new file mode 100644 index 0000000..ee04468 --- /dev/null +++ b/Unosquare.Swan.Lite/Terminal.cs @@ -0,0 +1,360 @@ +namespace Unosquare.Swan +{ + using Abstractions; + using System; + using System.Collections.Concurrent; + using System.Text; + using System.Threading; + + /// + /// A console terminal helper to create nicer output and receive input from the user. + /// This class is thread-safe :). + /// + public static partial class Terminal + { + #region Private Declarations + + private const int OutputFlushInterval = 15; + private static readonly ExclusiveTimer DequeueOutputTimer; + private static readonly object SyncLock = new object(); + private static readonly ConcurrentQueue OutputQueue = new ConcurrentQueue(); + + private static readonly ManualResetEventSlim OutputDone = new ManualResetEventSlim(false); + private static readonly ManualResetEventSlim InputDone = new ManualResetEventSlim(true); + + private static bool? _isConsolePresent; + + #endregion + + #region Constructors + + /// + /// Initializes static members of the class. + /// + static Terminal() + { + lock (SyncLock) + { + if (DequeueOutputTimer != null) return; + + if (IsConsolePresent) + { +#if !NET452 + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); +#endif + Console.CursorVisible = false; + } + + // Here we start the output task, fire-and-forget + DequeueOutputTimer = new ExclusiveTimer(DequeueOutputCycle); + DequeueOutputTimer.Resume(OutputFlushInterval); + } + } + + #endregion + + #region Synchronized Cursor Movement + + /// + /// Gets or sets the cursor left position. + /// + /// + /// The cursor left. + /// + public static int CursorLeft + { + get + { + if (IsConsolePresent == false) return -1; + lock (SyncLock) + { + Flush(); + return Console.CursorLeft; + } + } + set + { + if (IsConsolePresent == false) return; + lock (SyncLock) + { + Flush(); + Console.CursorLeft = value; + } + } + } + + /// + /// Gets or sets the cursor top position. + /// + /// + /// The cursor top. + /// + public static int CursorTop + { + get + { + if (IsConsolePresent == false) return -1; + lock (SyncLock) + { + Flush(); + return Console.CursorTop; + } + } + set + { + if (IsConsolePresent == false) return; + + lock (SyncLock) + { + Flush(); + Console.CursorTop = value; + } + } + } + + #endregion + + #region Properties + + /// + /// Gets a value indicating whether the Console is present. + /// + /// + /// true if this instance is console present; otherwise, false. + /// + public static bool IsConsolePresent + { + get + { + if (Settings.OverrideIsConsolePresent) return true; + + if (_isConsolePresent == null) + { + _isConsolePresent = true; + try + { + var windowHeight = Console.WindowHeight; + _isConsolePresent = windowHeight >= 0; + } + catch + { + _isConsolePresent = false; + } + } + + return _isConsolePresent.Value; + } + } + + /// + /// Gets a value indicating whether a debugger is attached. + /// + /// + /// true if this instance is debugger attached; otherwise, false. + /// + public static bool IsDebuggerAttached => System.Diagnostics.Debugger.IsAttached; + + /// + /// Gets the available output writers in a bitwise mask. + /// + /// + /// The available writers. + /// + public static TerminalWriters AvailableWriters + { + get + { + var writers = TerminalWriters.None; + if (IsConsolePresent) + writers = TerminalWriters.StandardError | TerminalWriters.StandardOutput; + + if (IsDebuggerAttached) + writers = writers | TerminalWriters.Diagnostics; + + return writers; + } + } + + /// + /// Gets or sets the output encoding for the current console. + /// + /// + /// The output encoding. + /// + public static Encoding OutputEncoding + { + get => Console.OutputEncoding; + set => Console.OutputEncoding = value; + } + + #endregion + + #region Methods + + /// + /// Waits for all of the queued output messages to be written out to the console. + /// Call this method if it is important to display console text before + /// quitting the application such as showing usage or help. + /// Set the timeout to null or TimeSpan.Zero to wait indefinitely. + /// + /// The timeout. Set the amount of time to black before this method exits. + public static void Flush(TimeSpan? timeout = null) + { + if (timeout == null) timeout = TimeSpan.Zero; + var startTime = DateTime.UtcNow; + + while (OutputQueue.Count > 0) + { + // Manually trigger a timer cycle to run immediately + DequeueOutputTimer.Change(0, OutputFlushInterval); + + // Wait for the output to finish + if (OutputDone.Wait(OutputFlushInterval)) + break; + + // infinite timeout + if (timeout.Value == TimeSpan.Zero) + continue; + + // break if we have reached a timeout condition + if (DateTime.UtcNow.Subtract(startTime) >= timeout.Value) + break; + } + } + + /// + /// Sets the cursor position. + /// + /// The left. + /// The top. + public static void SetCursorPosition(int left, int top) + { + if (IsConsolePresent == false) return; + + lock (SyncLock) + { + Flush(); + Console.SetCursorPosition(left.Clamp(0, left), top.Clamp(0, top)); + } + } + + /// + /// Moves the output cursor one line up starting at left position 0 + /// Please note that backlining the cursor does not clear the contents of the + /// previous line so you might need to clear it by writing an empty string the + /// length of the console width. + /// + public static void BacklineCursor() => SetCursorPosition(0, CursorTop - 1); + + /// + /// Enqueues the output to be written to the console + /// This is the only method that should enqueue to the output + /// Please note that if AvailableWriters is None, then no output will be enqueued. + /// + /// The context. + private static void EnqueueOutput(OutputContext context) + { + lock (SyncLock) + { + var availableWriters = AvailableWriters; + + if (availableWriters == TerminalWriters.None || context.OutputWriters == TerminalWriters.None) + { + OutputDone.Set(); + return; + } + + if ((context.OutputWriters & availableWriters) == TerminalWriters.None) + return; + + OutputDone.Reset(); + OutputQueue.Enqueue(context); + } + } + + /// + /// Runs a Terminal I/O cycle in the thread. + /// + private static void DequeueOutputCycle() + { + if (AvailableWriters == TerminalWriters.None) + { + OutputDone.Set(); + return; + } + + InputDone.Wait(); + + if (OutputQueue.Count <= 0) + { + OutputDone.Set(); + return; + } + + OutputDone.Reset(); + + while (OutputQueue.Count > 0) + { + if (OutputQueue.TryDequeue(out var context) == false) continue; + + // Process Console output and Skip over stuff we can't display so we don't stress the output too much. + if (IsConsolePresent && (Settings.OverrideIsConsolePresent || OutputQueue.Count <= Console.BufferHeight)) + { + // Output to the standard output + if (context.OutputWriters.HasFlag(TerminalWriters.StandardOutput)) + { + Console.ForegroundColor = context.OutputColor; + Console.Out.Write(context.OutputText); + Console.ResetColor(); + Console.ForegroundColor = context.OriginalColor; + } + + // output to the standard error + if (context.OutputWriters.HasFlag(TerminalWriters.StandardError)) + { + Console.ForegroundColor = context.OutputColor; + Console.Error.Write(context.OutputText); + Console.ResetColor(); + Console.ForegroundColor = context.OriginalColor; + } + } + + // Process Debugger output + if (IsDebuggerAttached && context.OutputWriters.HasFlag(TerminalWriters.Diagnostics)) + { + System.Diagnostics.Debug.Write(new string(context.OutputText)); + } + } + } + + #endregion + + #region Output Context + + /// + /// Represents an asynchronous output context. + /// + private sealed class OutputContext + { + /// + /// Initializes a new instance of the class. + /// + public OutputContext() + { + OriginalColor = Settings.DefaultColor; + OutputWriters = IsConsolePresent + ? TerminalWriters.StandardOutput + : IsDebuggerAttached + ? TerminalWriters.Diagnostics + : TerminalWriters.None; + } + + public ConsoleColor OriginalColor { get; } + public ConsoleColor OutputColor { get; set; } + public char[] OutputText { get; set; } + public TerminalWriters OutputWriters { get; set; } + } + + #endregion + } +} diff --git a/Unosquare.Swan.Lite/Unosquare.Swan.Lite.csproj b/Unosquare.Swan.Lite/Unosquare.Swan.Lite.csproj new file mode 100644 index 0000000..4b8bf92 --- /dev/null +++ b/Unosquare.Swan.Lite/Unosquare.Swan.Lite.csproj @@ -0,0 +1,120 @@ + + + + + Debug + AnyCPU + {AB015683-62E5-47F1-861F-6D037F9C6433} + Library + Properties + Unosquare.Swan.Lite + Unosquare.Swan.Lite + v4.7.1 + 512 + + + true + full + false + bin\Debug\ + TRACE;DEBUG;NET452 + prompt + 4 + 7.1 + + + pdbonly + true + bin\Release\ + TRACE;NET452 + prompt + 4 + 7.1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Unosquare.Swan/Abstractions/AppWorkerBase.cs b/Unosquare.Swan/Abstractions/AppWorkerBase.cs new file mode 100644 index 0000000..583b626 --- /dev/null +++ b/Unosquare.Swan/Abstractions/AppWorkerBase.cs @@ -0,0 +1,214 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + using System.Threading; + using System.Threading.Tasks; + + /// + /// A base implementation of an Application service containing a worker task that performs background processing. + /// + /// + /// The following code describes how to implement the class. + /// + /// using System; + /// using System.Threading.Tasks; + /// using Unosquare.Swan; + /// using Unosquare.Swan.Abstractions; + /// + /// class Worker : AppWorkerBase + /// { + /// // an action that will be executed if the worker is stopped + /// public Action OnExit { get; set; } + /// + /// // override the base loop method, this is the code will + /// // execute until the cancellation token is canceled. + /// protected override Task WorkerThreadLoop() + /// { + /// // delay a second and then proceed + /// await Task.Delay(TimeSpan.FromMilliseconds(1000), CancellationToken); + /// + /// // just print out this + /// $"Working...".WriteLine(); + /// } + /// + /// // Once the worker is stopped this code will be executed + /// protected override void OnWorkerThreadExit() + /// { + /// // execute the base method + /// base.OnWorkerThreadExit(); + /// + /// // then if the OnExit Action is not null execute it + /// OnExit?.Invoke(); + /// } + /// } + /// + /// + public abstract class AppWorkerBase + : IWorker, IDisposable + { + private readonly object _syncLock = new object(); + private AppWorkerState _workerState = AppWorkerState.Stopped; + private CancellationTokenSource _tokenSource; + + /// + /// Initializes a new instance of the class. + /// + protected AppWorkerBase() + { + State = AppWorkerState.Stopped; + IsBusy = false; + } + + /// + /// Occurs when [state changed]. + /// + public event EventHandler StateChanged; + + #region Properties + + /// + /// Gets the state of the application service. + /// In other words, useful to know whether the service is running. + /// + /// + /// The state. + /// + public AppWorkerState State + { + get => _workerState; + + private set + { + lock (_syncLock) + { + if (value == _workerState) return; + + $"Service state changing from {State} to {value}".Debug(GetType().Name); + var newState = value; + var oldState = _workerState; + _workerState = value; + + StateChanged?.Invoke(this, new AppWorkerStateChangedEventArgs(oldState, newState)); + } + } + } + + /// + /// Gets the cancellation token. + /// + /// + /// The cancellation token. + /// + public CancellationToken CancellationToken => _tokenSource?.Token ?? default; + + /// + /// Gets a value indicating whether the thread is busy. + /// + /// + /// true if this instance is busy; otherwise, false. + /// + public bool IsBusy { get; private set; } + + #endregion + + #region AppWorkerBase Methods + + /// + /// Performs internal service initialization tasks required before starting the service. + /// + /// Service cannot be initialized because it seems to be currently running. + public virtual void Initialize() => CheckIsRunning(); + + /// + /// Service cannot be started because it seems to be currently running. + public virtual void Start() + { + CheckIsRunning(); + + CreateWorker(); + State = AppWorkerState.Running; + } + + /// + /// Service cannot be stopped because it is not running. + public virtual void Stop() + { + if (State != AppWorkerState.Running) + return; + + _tokenSource?.Cancel(); + "Service stop requested.".Debug(GetType().Name); + State = AppWorkerState.Stopped; + } + + /// + public void Dispose() => _tokenSource?.Dispose(); + + #endregion + + #region Abstract and Virtual Methods + + /// + /// Called when an unhandled exception is thrown. + /// + /// The ex. + protected virtual void OnWorkerThreadLoopException(Exception ex) + => "Service exception detected.".Debug(GetType().Name, ex); + + /// + /// This method is called when the user loop has exited. + /// + protected virtual void OnWorkerThreadExit() => "Service thread is stopping.".Debug(GetType().Name); + + /// + /// Implement this method as a loop that checks whether CancellationPending has been set to true + /// If so, immediately exit the loop. + /// + /// A task representing the execution of the worker. + protected abstract Task WorkerThreadLoop(); + + private void CheckIsRunning() + { + if (State != AppWorkerState.Stopped) + throw new InvalidOperationException("Service cannot be initialized because it seems to be currently running."); + } + + private void CreateWorker() + { + _tokenSource = new CancellationTokenSource(); + _tokenSource.Token.Register(() => + { + IsBusy = false; + OnWorkerThreadExit(); + }); + + Task.Run(async () => + { + IsBusy = true; + + try + { + while (!CancellationToken.IsCancellationRequested) + { + await WorkerThreadLoop().ConfigureAwait(false); + } + } + catch (AggregateException) + { + // Ignored + } + catch (Exception ex) + { + ex.Log(GetType().Name); + OnWorkerThreadLoopException(ex); + + if (!_tokenSource.IsCancellationRequested) + _tokenSource.Cancel(); + } + }, + _tokenSource.Token); + } + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Abstractions/AppWorkerStateChangedEventArgs.cs b/Unosquare.Swan/Abstractions/AppWorkerStateChangedEventArgs.cs new file mode 100644 index 0000000..a34e6fe --- /dev/null +++ b/Unosquare.Swan/Abstractions/AppWorkerStateChangedEventArgs.cs @@ -0,0 +1,37 @@ +namespace Unosquare.Swan.Abstractions +{ + using System; + + /// + /// Represents event arguments whenever the state of an application service changes. + /// + public class AppWorkerStateChangedEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The old state. + /// The new state. + public AppWorkerStateChangedEventArgs(AppWorkerState oldState, AppWorkerState newState) + { + OldState = oldState; + NewState = newState; + } + + /// + /// Gets the state to which the application service changed. + /// + /// + /// The new state. + /// + public AppWorkerState NewState { get; } + + /// + /// Gets the old state. + /// + /// + /// The old state. + /// + public AppWorkerState OldState { get; } + } +} diff --git a/Unosquare.Swan/Abstractions/ServiceBase.cs b/Unosquare.Swan/Abstractions/ServiceBase.cs new file mode 100644 index 0000000..4fa01c6 --- /dev/null +++ b/Unosquare.Swan/Abstractions/ServiceBase.cs @@ -0,0 +1,89 @@ +#if !NET452 +namespace Unosquare.Swan.Abstractions +{ + /// + /// Mimic a Windows ServiceBase class. Useful to keep compatibility with applications + /// running as services in OS different to Windows. + /// + public abstract class ServiceBase + { + /// + /// Gets or sets a value indicating whether the service can be stopped once it has started. + /// + /// + /// true if this instance can stop; otherwise, false. + /// + public bool CanStop { get; set; } = true; + + /// + /// Gets or sets a value indicating whether the service should be notified when the system is shutting down. + /// + /// + /// true if this instance can shutdown; otherwise, false. + /// + public bool CanShutdown { get; set; } + + /// + /// Gets or sets a value indicating whether the service can be paused and resumed. + /// + /// + /// true if this instance can pause and continue; otherwise, false. + /// + public bool CanPauseAndContinue { get; set; } + + /// + /// Gets or sets the exit code. + /// + /// + /// The exit code. + /// + public int ExitCode { get; set; } + + /// + /// Indicates whether to report Start, Stop, Pause, and Continue commands in the event log. + /// + /// + /// true if [automatic log]; otherwise, false. + /// + public bool AutoLog { get; set; } + + /// + /// Gets or sets the name of the service. + /// + /// + /// The name of the service. + /// + public string ServiceName { get; set; } + + /// + /// Stops the executing service. + /// + public void Stop() + { + if (!CanStop) return; + + CanStop = false; + OnStop(); + } + + /// + /// When implemented in a derived class, executes when a Start command is sent to the service by the Service Control Manager (SCM) + /// or when the operating system starts (for a service that starts automatically). Specifies actions to take when the service starts. + /// + /// The arguments. + protected virtual void OnStart(string[] args) + { + // do nothing + } + + /// + /// When implemented in a derived class, executes when a Stop command is sent to the service by the Service Control Manager (SCM). + /// Specifies actions to take when a service stops running. + /// + protected virtual void OnStop() + { + // do nothing + } + } +} +#endif \ No newline at end of file diff --git a/Unosquare.Swan/Components/CircularBuffer.cs b/Unosquare.Swan/Components/CircularBuffer.cs new file mode 100644 index 0000000..c8cf6db --- /dev/null +++ b/Unosquare.Swan/Components/CircularBuffer.cs @@ -0,0 +1,204 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Runtime.InteropServices; + + /// + /// A fixed-size buffer that acts as an infinite length one. + /// This buffer is backed by unmanaged, very fast memory so ensure you call + /// the dispose method when you are done using it. + /// Only for Windows. + /// + /// + public sealed class CircularBuffer : IDisposable + { + private readonly object _syncLock = new object(); + private IntPtr _buffer = IntPtr.Zero; + + /// + /// Initializes a new instance of the class. + /// + /// Length of the buffer. + public CircularBuffer(int bufferLength) + { +#if !NET452 + if (Runtime.OS != Swan.OperatingSystem.Windows) + throw new InvalidOperationException("CircularBuffer component is only available in Windows"); +#endif + + Length = bufferLength; + _buffer = Marshal.AllocHGlobal(Length); + } + + #region Properties + + /// + /// Gets the capacity of this buffer. + /// + /// + /// The length. + /// + public int Length { get; private set; } + + /// + /// Gets the current, 0-based read index. + /// + /// + /// The index of the read. + /// + public int ReadIndex { get; private set; } + + /// + /// Gets the current, 0-based write index. + /// + /// + /// The index of the write. + /// + public int WriteIndex { get; private set; } + + /// + /// Gets an the object associated with the last write. + /// + /// + /// The write tag. + /// + public TimeSpan WriteTag { get; private set; } = TimeSpan.MinValue; + + /// + /// Gets the available bytes to read. + /// + /// + /// The readable count. + /// + public int ReadableCount { get; private set; } + + /// + /// Gets the number of bytes that can be written. + /// + /// + /// The writable count. + /// + public int WritableCount => Length - ReadableCount; + + /// + /// Gets percentage of used bytes (readbale/available, from 0.0 to 1.0). + /// + /// + /// The capacity percent. + /// + public double CapacityPercent => 1.0 * ReadableCount / Length; + + #endregion + + #region Methods + + /// + /// Reads the specified number of bytes into the target array. + /// + /// The requested bytes. + /// The target. + /// The target offset. + /// + /// Exception that is thrown when a method call is invalid for the object's current state. + /// + public void Read(int requestedBytes, byte[] target, int targetOffset) + { + lock (_syncLock) + { + if (requestedBytes > ReadableCount) + { + throw new InvalidOperationException( + $"Unable to read {requestedBytes} bytes. Only {ReadableCount} bytes are available"); + } + + var readCount = 0; + while (readCount < requestedBytes) + { + var copyLength = Math.Min(Length - ReadIndex, requestedBytes - readCount); + var sourcePtr = _buffer + ReadIndex; + Marshal.Copy(sourcePtr, target, targetOffset + readCount, copyLength); + + readCount += copyLength; + ReadIndex += copyLength; + ReadableCount -= copyLength; + + if (ReadIndex >= Length) + ReadIndex = 0; + } + } + } + + /// + /// Writes data to the backing buffer using the specified pointer and length. + /// and associating a write tag for this operation. + /// + /// The source. + /// The length. + /// The write tag. + /// Unable to write to circular buffer. Call the Read method to make some additional room. + public void Write(IntPtr source, int length, TimeSpan writeTag) + { + lock (_syncLock) + { + if (ReadableCount + length > Length) + { + throw new InvalidOperationException( + $"Unable to write to circular buffer. Call the {nameof(Read)} method to make some additional room."); + } + + var writeCount = 0; + while (writeCount < length) + { + var copyLength = Math.Min(Length - WriteIndex, length - writeCount); + var sourcePtr = source + writeCount; + var targetPtr = _buffer + WriteIndex; + CopyMemory(targetPtr, sourcePtr, (uint) copyLength); + + writeCount += copyLength; + WriteIndex += copyLength; + ReadableCount += copyLength; + + if (WriteIndex >= Length) + WriteIndex = 0; + } + + WriteTag = writeTag; + } + } + + /// + /// Resets all states as if this buffer had just been created. + /// + public void Clear() + { + lock (_syncLock) + { + WriteIndex = 0; + ReadIndex = 0; + WriteTag = TimeSpan.MinValue; + ReadableCount = 0; + } + } + + /// + public void Dispose() + { + if (_buffer == IntPtr.Zero) return; + + Marshal.FreeHGlobal(_buffer); + _buffer = IntPtr.Zero; + Length = 0; + } + + /// + /// Fast pointer memory block copy function. + /// + /// The destination. + /// The source. + /// The length. + [DllImport("kernel32")] + public static extern void CopyMemory(IntPtr destination, IntPtr source, uint length); + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/CsProjFile.cs b/Unosquare.Swan/Components/CsProjFile.cs new file mode 100644 index 0000000..12b05db --- /dev/null +++ b/Unosquare.Swan/Components/CsProjFile.cs @@ -0,0 +1,109 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.IO; + using System.Linq; + using System.Xml.Linq; + + /// + /// Represents a CsProjFile (and FsProjFile) parser. + /// + /// + /// Based on https://github.com/maartenba/dotnetcli-init. + /// + /// The type of CsProjMetadataBase. + /// + public class CsProjFile + : IDisposable + where T : CsProjMetadataBase + { + private readonly Stream _stream; + private readonly bool _leaveOpen; + private readonly XDocument _xmlDocument; + + /// + /// Initializes a new instance of the class. + /// + /// The filename. + public CsProjFile(string filename = null) + : this(OpenFile(filename)) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// + /// The stream. + /// if set to true [leave open]. + /// Project file is not of the new .csproj type. + public CsProjFile(Stream stream, bool leaveOpen = false) + { + _stream = stream; + _leaveOpen = leaveOpen; + + _xmlDocument = XDocument.Load(stream); + + var projectElement = _xmlDocument.Descendants("Project").FirstOrDefault(); + var sdkAttribute = projectElement?.Attribute("Sdk"); + var sdk = sdkAttribute?.Value; + if (sdk != "Microsoft.NET.Sdk" && sdk != "Microsoft.NET.Sdk.Web") + { + throw new ArgumentException("Project file is not of the new .csproj type."); + } + + Metadata = Activator.CreateInstance(); + Metadata.SetData(_xmlDocument); + } + + /// + /// Gets the metadata. + /// + /// + /// The nu get metadata. + /// + public T Metadata { get; } + + /// + /// Saves this instance. + /// + public void Save() + { + _stream.SetLength(0); + _stream.Position = 0; + + _xmlDocument.Save(_stream); + } + + /// + public void Dispose() + { + if (!_leaveOpen) + { + _stream?.Dispose(); + } + } + + private static FileStream OpenFile(string filename) + { + if (filename == null) + { + filename = Directory + .EnumerateFiles(Directory.GetCurrentDirectory(), "*.csproj", SearchOption.TopDirectoryOnly) + .FirstOrDefault(); + } + + if (filename == null) + { + filename = Directory + .EnumerateFiles(Directory.GetCurrentDirectory(), "*.fsproj", SearchOption.TopDirectoryOnly) + .FirstOrDefault(); + } + + if (string.IsNullOrWhiteSpace(filename)) + throw new ArgumentNullException(nameof(filename)); + + return File.Open(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/CsProjMetadataBase.cs b/Unosquare.Swan/Components/CsProjMetadataBase.cs new file mode 100644 index 0000000..d4085c4 --- /dev/null +++ b/Unosquare.Swan/Components/CsProjMetadataBase.cs @@ -0,0 +1,73 @@ +namespace Unosquare.Swan.Components +{ + using System.Linq; + using System.Xml.Linq; + + /// + /// Represents a CsProj metadata abstract class + /// to use with CsProjFile parser. + /// + public abstract class CsProjMetadataBase + { + private XDocument _xmlDocument; + + /// + /// Gets the package identifier. + /// + /// + /// The package identifier. + /// + public string PackageId => FindElement(nameof(PackageId))?.Value; + + /// + /// Gets the name of the assembly. + /// + /// + /// The name of the assembly. + /// + public string AssemblyName => FindElement(nameof(AssemblyName))?.Value; + + /// + /// Gets the target frameworks. + /// + /// + /// The target frameworks. + /// + public string TargetFrameworks => FindElement(nameof(TargetFrameworks))?.Value; + + /// + /// Gets the target framework. + /// + /// + /// The target framework. + /// + public string TargetFramework => FindElement(nameof(TargetFramework))?.Value; + + /// + /// Gets the version. + /// + /// + /// The version. + /// + public string Version => FindElement(nameof(Version))?.Value; + + /// + /// Parses the cs proj tags. + /// + /// The arguments. + public abstract void ParseCsProjTags(ref string[] args); + + /// + /// Sets the data. + /// + /// The XML document. + public void SetData(XDocument xmlDocument) => _xmlDocument = xmlDocument; + + /// + /// Finds the element. + /// + /// Name of the element. + /// A XElement. + protected XElement FindElement(string elementName) => _xmlDocument.Descendants(elementName).FirstOrDefault(); + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/DelayProvider.cs b/Unosquare.Swan/Components/DelayProvider.cs new file mode 100644 index 0000000..51a3a24 --- /dev/null +++ b/Unosquare.Swan/Components/DelayProvider.cs @@ -0,0 +1,144 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Diagnostics; + using System.Threading; + using System.Threading.Tasks; + using Abstractions; + + /// + /// Represents logic providing several delay mechanisms. + /// + /// + /// The following example shows how to implement delay mechanisms. + /// + /// using Unosquare.Swan.Components; + /// + /// public class Example + /// { + /// public static void Main() + /// { + /// // using the ThreadSleep strategy + /// using (var delay = new DelayProvider(DelayProvider.DelayStrategy.ThreadSleep)) + /// { + /// // retrieve how much time was delayed + /// var time = delay.WaitOne(); + /// } + /// } + /// } + /// + /// + public sealed class DelayProvider : IDisposable + { + private readonly object _syncRoot = new object(); + private readonly Stopwatch _delayStopwatch = new Stopwatch(); + + private bool _isDisposed; + private IWaitEvent _delayEvent; + + /// + /// Initializes a new instance of the class. + /// + /// The strategy. + public DelayProvider(DelayStrategy strategy = DelayStrategy.TaskDelay) + { + Strategy = strategy; + } + + /// + /// Enumerates the different ways of providing delays. + /// + public enum DelayStrategy + { + /// + /// Using the Thread.Sleep(15) mechanism. + /// + ThreadSleep, + + /// + /// Using the Task.Delay(1).Wait mechanism. + /// + TaskDelay, + + /// + /// Using a wait event that completes in a background ThreadPool thread. + /// + ThreadPool, + } + + /// + /// Gets the selected delay strategy. + /// + public DelayStrategy Strategy { get; } + + /// + /// Creates the smallest possible, synchronous delay based on the selected strategy. + /// + /// The elapsed time of the delay. + public TimeSpan WaitOne() + { + lock (_syncRoot) + { + if (_isDisposed) return TimeSpan.Zero; + + _delayStopwatch.Restart(); + + switch (Strategy) + { + case DelayStrategy.ThreadSleep: + DelaySleep(); + break; + case DelayStrategy.TaskDelay: + DelayTask(); + break; +#if !NETSTANDARD1_3 + case DelayStrategy.ThreadPool: + DelayThreadPool(); + break; +#endif + } + + return _delayStopwatch.Elapsed; + } + } + + #region Dispose Pattern + + /// + public void Dispose() + { + lock (_syncRoot) + { + if (_isDisposed) return; + _isDisposed = true; + _delayEvent?.Dispose(); + } + } + + #endregion + + #region Private Delay Mechanisms + + private static void DelaySleep() => Thread.Sleep(15); + + private static void DelayTask() => Task.Delay(1).Wait(); + +#if !NETSTANDARD1_3 + private void DelayThreadPool() + { + if (_delayEvent == null) + _delayEvent = WaitEventFactory.Create(isCompleted: true, useSlim: true); + + _delayEvent.Begin(); + ThreadPool.QueueUserWorkItem((s) => + { + DelaySleep(); + _delayEvent.Complete(); + }); + + _delayEvent.Wait(); + } +#endif + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/DependencyContainer.cs b/Unosquare.Swan/Components/DependencyContainer.cs new file mode 100644 index 0000000..f7d0ee7 --- /dev/null +++ b/Unosquare.Swan/Components/DependencyContainer.cs @@ -0,0 +1,754 @@ +namespace Unosquare.Swan.Components +{ + using Exceptions; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Reflection; + + /// + /// The concrete implementation of a simple IoC container + /// based largely on TinyIoC (https://github.com/grumpydev/TinyIoC). + /// + /// + public partial class DependencyContainer : IDisposable + { + private readonly object _autoRegisterLock = new object(); + + private bool _disposed; + + static DependencyContainer() + { + } + + /// + /// Initializes a new instance of the class. + /// + public DependencyContainer() + { + RegisteredTypes = new TypesConcurrentDictionary(this); + Register(this); + + // Only register the TinyMessenger singleton if we are the root container + if (Parent == null) + Register(); + } + + private DependencyContainer(DependencyContainer parent) + : this() + { + Parent = parent; + } + + /// + /// Lazy created Singleton instance of the container for simple scenarios. + /// + public static DependencyContainer Current { get; } = new DependencyContainer(); + + internal DependencyContainer Parent { get; } + + internal TypesConcurrentDictionary RegisteredTypes { get; } + + /// + public void Dispose() + { + if (_disposed) return; + + _disposed = true; + + foreach (var disposable in RegisteredTypes.Values.Select(item => item as IDisposable)) + { + disposable?.Dispose(); + } + + GC.SuppressFinalize(this); + } + + /// + /// Gets the child container. + /// + /// A new instance of the class. + public DependencyContainer GetChildContainer() => new DependencyContainer(this); + + #region Registration + +#if !NETSTANDARD1_3 + /// + /// Attempt to automatically register all non-generic classes and interfaces in the current app domain. + /// Types will only be registered if they pass the supplied registration predicate. + /// + /// What action to take when encountering duplicate implementations of an interface/base class. + /// Predicate to determine if a particular type should be registered. + public void AutoRegister( + DependencyContainerDuplicateImplementationActions duplicateAction = + DependencyContainerDuplicateImplementationActions.RegisterSingle, + Func registrationPredicate = null) + { + AutoRegister( + Runtime.GetAssemblies().Where(a => !IsIgnoredAssembly(a)), + duplicateAction, + registrationPredicate); + } +#endif + + /// + /// Attempt to automatically register all non-generic classes and interfaces in the specified assemblies + /// Types will only be registered if they pass the supplied registration predicate. + /// + /// Assemblies to process. + /// What action to take when encountering duplicate implementations of an interface/base class. + /// Predicate to determine if a particular type should be registered. + public void AutoRegister( + IEnumerable assemblies, + DependencyContainerDuplicateImplementationActions duplicateAction = + DependencyContainerDuplicateImplementationActions.RegisterSingle, + Func registrationPredicate = null) + { + lock (_autoRegisterLock) + { + var types = assemblies + .SelectMany(a => a.GetAllTypes()) + .Where(t => !IsIgnoredType(t, registrationPredicate)) + .ToList(); + + var concreteTypes = types + .Where(type => + type.IsClass() && !type.IsAbstract() && + (type != GetType() && (type.DeclaringType != GetType()) && !type.IsGenericTypeDefinition())) + .ToList(); + + foreach (var type in concreteTypes) + { + try + { + RegisteredTypes.Register(type, string.Empty, GetDefaultObjectFactory(type, type)); + } + catch (MethodAccessException) + { + // Ignore methods we can't access - added for Silverlight + } + } + + var abstractInterfaceTypes = types.Where( + type => + ((type.IsInterface() || type.IsAbstract()) && (type.DeclaringType != GetType()) && + (!type.IsGenericTypeDefinition()))); + + foreach (var type in abstractInterfaceTypes) + { + var localType = type; + var implementations = concreteTypes + .Where(implementationType => localType.IsAssignableFrom(implementationType)).ToList(); + + if (implementations.Skip(1).Any()) + { + if (duplicateAction == DependencyContainerDuplicateImplementationActions.Fail) + throw new DependencyContainerRegistrationException(type, implementations); + + if (duplicateAction == DependencyContainerDuplicateImplementationActions.RegisterMultiple) + { + RegisterMultiple(type, implementations); + } + } + + var firstImplementation = implementations.FirstOrDefault(); + + if (firstImplementation == null) continue; + + try + { + RegisteredTypes.Register(type, string.Empty, GetDefaultObjectFactory(type, firstImplementation)); + } + catch (MethodAccessException) + { + // Ignore methods we can't access - added for Silverlight + } + } + } + } + + /// + /// Creates/replaces a named container class registration with default options. + /// + /// Type to register. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register(Type registerType, string name = "") + => RegisteredTypes.Register( + registerType, + name, + GetDefaultObjectFactory(registerType, registerType)); + + /// + /// Creates/replaces a named container class registration with a given implementation and default options. + /// + /// Type to register. + /// Type to instantiate that implements RegisterType. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register(Type registerType, Type registerImplementation, string name = "") => + RegisteredTypes.Register(registerType, name, GetDefaultObjectFactory(registerType, registerImplementation)); + + /// + /// Creates/replaces a named container class registration with a specific, strong referenced, instance. + /// + /// Type to register. + /// Instance of RegisterType to register. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register(Type registerType, object instance, string name = "") => + RegisteredTypes.Register(registerType, name, new InstanceFactory(registerType, registerType, instance)); + + /// + /// Creates/replaces a named container class registration with a specific, strong referenced, instance. + /// + /// Type to register. + /// Type of instance to register that implements RegisterType. + /// Instance of RegisterImplementation to register. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register( + Type registerType, + Type registerImplementation, + object instance, + string name = "") + => RegisteredTypes.Register(registerType, name, new InstanceFactory(registerType, registerImplementation, instance)); + + /// + /// Creates/replaces a container class registration with a user specified factory. + /// + /// Type to register. + /// Factory/lambda that returns an instance of RegisterType. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register( + Type registerType, + Func, object> factory, + string name = "") + => RegisteredTypes.Register(registerType, name, new DelegateFactory(registerType, factory)); + + /// + /// Creates/replaces a named container class registration with default options. + /// + /// Type to register. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register(string name = "") + where TRegister : class + { + return Register(typeof(TRegister), name); + } + + /// + /// Creates/replaces a named container class registration with a given implementation and default options. + /// + /// Type to register. + /// Type to instantiate that implements RegisterType. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register(string name = "") + where TRegister : class + where TRegisterImplementation : class, TRegister + { + return Register(typeof(TRegister), typeof(TRegisterImplementation), name); + } + + /// + /// Creates/replaces a named container class registration with a specific, strong referenced, instance. + /// + /// Type to register. + /// Instance of RegisterType to register. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register(TRegister instance, string name = "") + where TRegister : class + { + return Register(typeof(TRegister), instance, name); + } + + /// + /// Creates/replaces a named container class registration with a specific, strong referenced, instance. + /// + /// Type to register. + /// Type of instance to register that implements RegisterType. + /// Instance of RegisterImplementation to register. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register(TRegisterImplementation instance, + string name = "") + where TRegister : class + where TRegisterImplementation : class, TRegister + { + return Register(typeof(TRegister), typeof(TRegisterImplementation), instance, name); + } + + /// + /// Creates/replaces a named container class registration with a user specified factory. + /// + /// Type to register. + /// Factory/lambda that returns an instance of RegisterType. + /// Name of registration. + /// RegisterOptions for fluent API. + public RegisterOptions Register( + Func, TRegister> factory, string name = "") + where TRegister : class + { + if (factory == null) + { + throw new ArgumentNullException(nameof(factory)); + } + + return Register(typeof(TRegister), factory, name); + } + + /// + /// Register multiple implementations of a type. + /// + /// Internally this registers each implementation using the full name of the class as its registration name. + /// + /// Type that each implementation implements. + /// Types that implement RegisterType. + /// MultiRegisterOptions for the fluent API. + public MultiRegisterOptions RegisterMultiple(IEnumerable implementationTypes) => + RegisterMultiple(typeof(TRegister), implementationTypes); + + /// + /// Register multiple implementations of a type. + /// + /// Internally this registers each implementation using the full name of the class as its registration name. + /// + /// Type that each implementation implements. + /// Types that implement RegisterType. + /// MultiRegisterOptions for the fluent API. + public MultiRegisterOptions RegisterMultiple(Type registrationType, IEnumerable implementationTypes) + { + if (implementationTypes == null) + throw new ArgumentNullException(nameof(implementationTypes), "types is null."); + + foreach (var type in implementationTypes.Where(type => !registrationType.IsAssignableFrom(type))) + { + throw new ArgumentException( + $"types: The type {registrationType.FullName} is not assignable from {type.FullName}"); + } + + if (implementationTypes.Count() != implementationTypes.Distinct().Count()) + { + var queryForDuplicatedTypes = implementationTypes + .GroupBy(i => i) + .Where(j => j.Count() > 1) + .Select(j => j.Key.FullName); + + var fullNamesOfDuplicatedTypes = string.Join(",\n", queryForDuplicatedTypes.ToArray()); + + throw new ArgumentException( + $"types: The same implementation type cannot be specified multiple times for {registrationType.FullName}\n\n{fullNamesOfDuplicatedTypes}"); + } + + var registerOptions = implementationTypes + .Select(type => Register(registrationType, type, type.FullName)) + .ToList(); + + return new MultiRegisterOptions(registerOptions); + } + + #endregion + + #region Unregistration + + /// + /// Remove a named container class registration. + /// + /// Type to unregister. + /// Name of registration. + /// true if the registration is successfully found and removed; otherwise, false. + public bool Unregister(string name = "") => Unregister(typeof(TRegister), name); + + /// + /// Remove a named container class registration. + /// + /// Type to unregister. + /// Name of registration. + /// true if the registration is successfully found and removed; otherwise, false. + public bool Unregister(Type registerType, string name = "") => + RegisteredTypes.RemoveRegistration(new TypeRegistration(registerType, name)); + + #endregion + + #region Resolution + + /// + /// Attempts to resolve a named type using specified options and the supplied constructor parameters. + /// + /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). + /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. + /// + /// Type to resolve. + /// Name of registration. + /// Resolution options. + /// Instance of type. + /// Unable to resolve the type. + public object Resolve( + Type resolveType, + string name = null, + DependencyContainerResolveOptions options = null) + => RegisteredTypes.ResolveInternal(new TypeRegistration(resolveType, name), options ?? DependencyContainerResolveOptions.Default); + + /// + /// Attempts to resolve a named type using specified options and the supplied constructor parameters. + /// + /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). + /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. + /// + /// Type to resolve. + /// Name of registration. + /// Resolution options. + /// Instance of type. + /// Unable to resolve the type. + public TResolveType Resolve( + string name = null, + DependencyContainerResolveOptions options = null) + where TResolveType : class + { + return (TResolveType)Resolve(typeof(TResolveType), name, options); + } + + /// + /// Attempts to predict whether a given type can be resolved with the supplied constructor parameters options. + /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). + /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. + /// Note: Resolution may still fail if user defined factory registrations fail to construct objects when called. + /// + /// Type to resolve. + /// The name. + /// Resolution options. + /// + /// Bool indicating whether the type can be resolved. + /// + public bool CanResolve( + Type resolveType, + string name = null, + DependencyContainerResolveOptions options = null) => + RegisteredTypes.CanResolve(new TypeRegistration(resolveType, name), options); + + /// + /// Attempts to predict whether a given named type can be resolved with the supplied constructor parameters options. + /// + /// Parameters are used in conjunction with normal container resolution to find the most suitable constructor (if one exists). + /// All user supplied parameters must exist in at least one resolvable constructor of RegisterType or resolution will fail. + /// + /// Note: Resolution may still fail if user defined factory registrations fail to construct objects when called. + /// + /// Type to resolve. + /// Name of registration. + /// Resolution options. + /// Bool indicating whether the type can be resolved. + public bool CanResolve( + string name = null, + DependencyContainerResolveOptions options = null) + where TResolveType : class + { + return CanResolve(typeof(TResolveType), name, options); + } + + /// + /// Attempts to resolve a type using the default options. + /// + /// Type to resolve. + /// Resolved type or default if resolve fails. + /// true if resolved successfully, false otherwise. + public bool TryResolve(Type resolveType, out object resolvedType) + { + try + { + resolvedType = Resolve(resolveType); + return true; + } + catch (DependencyContainerResolutionException) + { + resolvedType = null; + return false; + } + } + + /// + /// Attempts to resolve a type using the given options. + /// + /// Type to resolve. + /// Resolution options. + /// Resolved type or default if resolve fails. + /// true if resolved successfully, false otherwise. + public bool TryResolve(Type resolveType, DependencyContainerResolveOptions options, out object resolvedType) + { + try + { + resolvedType = Resolve(resolveType, options: options); + return true; + } + catch (DependencyContainerResolutionException) + { + resolvedType = null; + return false; + } + } + + /// + /// Attempts to resolve a type using the default options and given name. + /// + /// Type to resolve. + /// Name of registration. + /// Resolved type or default if resolve fails. + /// true if resolved successfully, false otherwise. + public bool TryResolve(Type resolveType, string name, out object resolvedType) + { + try + { + resolvedType = Resolve(resolveType, name); + return true; + } + catch (DependencyContainerResolutionException) + { + resolvedType = null; + return false; + } + } + + /// + /// Attempts to resolve a type using the given options and name. + /// + /// Type to resolve. + /// Name of registration. + /// Resolution options. + /// Resolved type or default if resolve fails. + /// true if resolved successfully, false otherwise. + public bool TryResolve( + Type resolveType, + string name, + DependencyContainerResolveOptions options, + out object resolvedType) + { + try + { + resolvedType = Resolve(resolveType, name, options); + return true; + } + catch (DependencyContainerResolutionException) + { + resolvedType = null; + return false; + } + } + + /// + /// Attempts to resolve a type using the default options. + /// + /// Type to resolve. + /// Resolved type or default if resolve fails. + /// true if resolved successfully, false otherwise. + public bool TryResolve(out TResolveType resolvedType) + where TResolveType : class + { + try + { + resolvedType = Resolve(); + return true; + } + catch (DependencyContainerResolutionException) + { + resolvedType = default; + return false; + } + } + + /// + /// Attempts to resolve a type using the given options. + /// + /// Type to resolve. + /// Resolution options. + /// Resolved type or default if resolve fails. + /// true if resolved successfully, false otherwise. + public bool TryResolve(DependencyContainerResolveOptions options, out TResolveType resolvedType) + where TResolveType : class + { + try + { + resolvedType = Resolve(options: options); + return true; + } + catch (DependencyContainerResolutionException) + { + resolvedType = default; + return false; + } + } + + /// + /// Attempts to resolve a type using the default options and given name. + /// + /// Type to resolve. + /// Name of registration. + /// Resolved type or default if resolve fails. + /// true if resolved successfully, false otherwise. + public bool TryResolve(string name, out TResolveType resolvedType) + where TResolveType : class + { + try + { + resolvedType = Resolve(name); + return true; + } + catch (DependencyContainerResolutionException) + { + resolvedType = default; + return false; + } + } + + /// + /// Attempts to resolve a type using the given options and name. + /// + /// Type to resolve. + /// Name of registration. + /// Resolution options. + /// Resolved type or default if resolve fails. + /// true if resolved successfully, false otherwise. + public bool TryResolve( + string name, + DependencyContainerResolveOptions options, + out TResolveType resolvedType) + where TResolveType : class + { + try + { + resolvedType = Resolve(name, options); + return true; + } + catch (DependencyContainerResolutionException) + { + resolvedType = default; + return false; + } + } + + /// + /// Returns all registrations of a type. + /// + /// Type to resolveAll. + /// Whether to include un-named (default) registrations. + /// IEnumerable. + public IEnumerable ResolveAll(Type resolveType, bool includeUnnamed = false) + => RegisteredTypes.Resolve(resolveType, includeUnnamed); + + /// + /// Returns all registrations of a type. + /// + /// Type to resolveAll. + /// Whether to include un-named (default) registrations. + /// IEnumerable. + public IEnumerable ResolveAll(bool includeUnnamed = true) + where TResolveType : class + { + return ResolveAll(typeof(TResolveType), includeUnnamed).Cast(); + } + + /// + /// Attempts to resolve all public property dependencies on the given object using the given resolve options. + /// + /// Object to "build up". + /// Resolve options to use. + public void BuildUp(object input, DependencyContainerResolveOptions resolveOptions = null) + { + if (resolveOptions == null) + resolveOptions = DependencyContainerResolveOptions.Default; + + var properties = input.GetType() + .GetProperties() + .Where(property => property.GetCacheGetMethod() != null && property.GetCacheSetMethod() != null && + !property.PropertyType.IsValueType()); + + foreach (var property in properties.Where(property => property.GetValue(input, null) == null)) + { + try + { + property.SetValue( + input, + RegisteredTypes.ResolveInternal(new TypeRegistration(property.PropertyType), resolveOptions), + null); + } + catch (DependencyContainerResolutionException) + { + // Catch any resolution errors and ignore them + } + } + } + + #endregion + + #region Internal Methods + + internal static bool IsValidAssignment(Type registerType, Type registerImplementation) + { + if (!registerType.IsGenericTypeDefinition()) + { + if (!registerType.IsAssignableFrom(registerImplementation)) + return false; + } + else + { + if (registerType.IsInterface() && registerImplementation.GetInterfaces().All(t => t.Name != registerType.Name)) + return false; + + if (registerType.IsAbstract() && registerImplementation.BaseType() != registerType) + return false; + } + + return true; + } + +#if !NETSTANDARD1_3 + private static bool IsIgnoredAssembly(Assembly assembly) + { + // TODO - find a better way to remove "system" assemblies from the auto registration + var ignoreChecks = new List> + { + asm => asm.FullName.StartsWith("Microsoft.", StringComparison.Ordinal), + asm => asm.FullName.StartsWith("System.", StringComparison.Ordinal), + asm => asm.FullName.StartsWith("System,", StringComparison.Ordinal), + asm => asm.FullName.StartsWith("CR_ExtUnitTest", StringComparison.Ordinal), + asm => asm.FullName.StartsWith("mscorlib,", StringComparison.Ordinal), + asm => asm.FullName.StartsWith("CR_VSTest", StringComparison.Ordinal), + asm => asm.FullName.StartsWith("DevExpress.CodeRush", StringComparison.Ordinal), + asm => asm.FullName.StartsWith("xunit.", StringComparison.Ordinal), + }; + + return ignoreChecks.Any(check => check(assembly)); + } +#endif + + private static bool IsIgnoredType(Type type, Func registrationPredicate) + { + // TODO - find a better way to remove "system" types from the auto registration + var ignoreChecks = new List>() + { + t => t.FullName?.StartsWith("System.", StringComparison.Ordinal) ?? false, + t => t.FullName?.StartsWith("Microsoft.", StringComparison.Ordinal) ?? false, + t => t.IsPrimitive(), + t => t.IsGenericTypeDefinition(), + t => (t.GetConstructors(BindingFlags.Instance | BindingFlags.Public).Length == 0) && + !(t.IsInterface() || t.IsAbstract()), + }; + + if (registrationPredicate != null) + { + ignoreChecks.Add(t => !registrationPredicate(t)); + } + + return ignoreChecks.Any(check => check(type)); + } + + private static ObjectFactoryBase GetDefaultObjectFactory(Type registerType, Type registerImplementation) => registerType.IsInterface() || registerType.IsAbstract() + ? (ObjectFactoryBase)new SingletonFactory(registerType, registerImplementation) + : new MultiInstanceFactory(registerType, registerImplementation); + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/DependencyContainerResolveOptions.cs b/Unosquare.Swan/Components/DependencyContainerResolveOptions.cs new file mode 100644 index 0000000..4089a8e --- /dev/null +++ b/Unosquare.Swan/Components/DependencyContainerResolveOptions.cs @@ -0,0 +1,114 @@ +namespace Unosquare.Swan.Components +{ + using System.Collections.Generic; + + /// + /// Resolution settings. + /// + public class DependencyContainerResolveOptions + { + /// + /// Gets the default options (attempt resolution of unregistered types, fail on named resolution if name not found). + /// + public static DependencyContainerResolveOptions Default { get; } = new DependencyContainerResolveOptions(); + + /// + /// Gets or sets the unregistered resolution action. + /// + /// + /// The unregistered resolution action. + /// + public DependencyContainerUnregisteredResolutionActions UnregisteredResolutionAction { get; set; } = + DependencyContainerUnregisteredResolutionActions.AttemptResolve; + + /// + /// Gets or sets the named resolution failure action. + /// + /// + /// The named resolution failure action. + /// + public DependencyContainerNamedResolutionFailureActions NamedResolutionFailureAction { get; set; } = + DependencyContainerNamedResolutionFailureActions.Fail; + + /// + /// Gets the constructor parameters. + /// + /// + /// The constructor parameters. + /// + public Dictionary ConstructorParameters { get; } = new Dictionary(); + + /// + /// Clones this instance. + /// + /// + public DependencyContainerResolveOptions Clone() => new DependencyContainerResolveOptions + { + NamedResolutionFailureAction = NamedResolutionFailureAction, + UnregisteredResolutionAction = UnregisteredResolutionAction, + }; + } + + /// + /// Defines Resolution actions. + /// + public enum DependencyContainerUnregisteredResolutionActions + { + /// + /// Attempt to resolve type, even if the type isn't registered. + /// + /// Registered types/options will always take precedence. + /// + AttemptResolve, + + /// + /// Fail resolution if type not explicitly registered + /// + Fail, + + /// + /// Attempt to resolve unregistered type if requested type is generic + /// and no registration exists for the specific generic parameters used. + /// + /// Registered types/options will always take precedence. + /// + GenericsOnly, + } + + /// + /// Enumerates failure actions. + /// + public enum DependencyContainerNamedResolutionFailureActions + { + /// + /// The attempt unnamed resolution + /// + AttemptUnnamedResolution, + + /// + /// The fail + /// + Fail, + } + + /// + /// Enumerates duplicate definition actions. + /// + public enum DependencyContainerDuplicateImplementationActions + { + /// + /// The register single + /// + RegisterSingle, + + /// + /// The register multiple + /// + RegisterMultiple, + + /// + /// The fail + /// + Fail, + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/IMessageHubMessage.cs b/Unosquare.Swan/Components/IMessageHubMessage.cs new file mode 100644 index 0000000..82a8927 --- /dev/null +++ b/Unosquare.Swan/Components/IMessageHubMessage.cs @@ -0,0 +1,13 @@ +namespace Unosquare.Swan.Components +{ + /// + /// A Message to be published/delivered by Messenger. + /// + public interface IMessageHubMessage + { + /// + /// The sender of the message, or null if not supported by the message implementation. + /// + object Sender { get; } + } +} diff --git a/Unosquare.Swan/Components/MessageHub.cs b/Unosquare.Swan/Components/MessageHub.cs new file mode 100644 index 0000000..263c3fe --- /dev/null +++ b/Unosquare.Swan/Components/MessageHub.cs @@ -0,0 +1,466 @@ +// =============================================================================== +// TinyIoC - TinyMessenger +// +// A simple messenger/event aggregator. +// +// https://github.com/grumpydev/TinyIoC/blob/master/src/TinyIoC/TinyMessenger.cs +// =============================================================================== +// Copyright © Steven Robbins. All rights reserved. +// THIS CODE AND INFORMATION IS PROVIDED "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. +// =============================================================================== + +namespace Unosquare.Swan.Components +{ + using System.Threading.Tasks; + using System; + using System.Collections.Generic; + using System.Linq; + + #region Message Types / Interfaces + + /// + /// Represents a message subscription. + /// + public interface IMessageHubSubscription + { + /// + /// Token returned to the subscribed to reference this subscription. + /// + MessageHubSubscriptionToken SubscriptionToken { get; } + + /// + /// Whether delivery should be attempted. + /// + /// Message that may potentially be delivered. + /// true - ok to send, false - should not attempt to send. + bool ShouldAttemptDelivery(IMessageHubMessage message); + + /// + /// Deliver the message. + /// + /// Message to deliver. + void Deliver(IMessageHubMessage message); + } + + /// + /// Message proxy definition. + /// + /// A message proxy can be used to intercept/alter messages and/or + /// marshal delivery actions onto a particular thread. + /// + public interface IMessageHubProxy + { + /// + /// Delivers the specified message. + /// + /// The message. + /// The subscription. + void Deliver(IMessageHubMessage message, IMessageHubSubscription subscription); + } + + /// + /// Default "pass through" proxy. + /// + /// Does nothing other than deliver the message. + /// + public sealed class MessageHubDefaultProxy : IMessageHubProxy + { + private MessageHubDefaultProxy() + { + // placeholder + } + + /// + /// Singleton instance of the proxy. + /// + public static MessageHubDefaultProxy Instance { get; } = new MessageHubDefaultProxy(); + + /// + /// Delivers the specified message. + /// + /// The message. + /// The subscription. + public void Deliver(IMessageHubMessage message, IMessageHubSubscription subscription) + => subscription.Deliver(message); + } + + #endregion + + #region Hub Interface + + /// + /// Messenger hub responsible for taking subscriptions/publications and delivering of messages. + /// + public interface IMessageHub + { + /// + /// Subscribe to a message type with the given destination and delivery action. + /// Messages will be delivered via the specified proxy. + /// + /// All messages of this type will be delivered. + /// + /// Type of message. + /// Action to invoke when message is delivered. + /// Use strong references to destination and deliveryAction. + /// Proxy to use when delivering the messages. + /// MessageSubscription used to unsubscribing. + MessageHubSubscriptionToken Subscribe( + Action deliveryAction, + bool useStrongReferences, + IMessageHubProxy proxy) + where TMessage : class, IMessageHubMessage; + + /// + /// Subscribe to a message type with the given destination and delivery action with the given filter. + /// Messages will be delivered via the specified proxy. + /// All references are held with WeakReferences + /// Only messages that "pass" the filter will be delivered. + /// + /// Type of message. + /// Action to invoke when message is delivered. + /// The message filter. + /// Use strong references to destination and deliveryAction. + /// Proxy to use when delivering the messages. + /// + /// MessageSubscription used to unsubscribing. + /// + MessageHubSubscriptionToken Subscribe( + Action deliveryAction, + Func messageFilter, + bool useStrongReferences, + IMessageHubProxy proxy) + where TMessage : class, IMessageHubMessage; + + /// + /// Unsubscribe from a particular message type. + /// + /// Does not throw an exception if the subscription is not found. + /// + /// Type of message. + /// Subscription token received from Subscribe. + void Unsubscribe(MessageHubSubscriptionToken subscriptionToken) + where TMessage : class, IMessageHubMessage; + + /// + /// Publish a message to any subscribers. + /// + /// Type of message. + /// Message to deliver. + void Publish(TMessage message) + where TMessage : class, IMessageHubMessage; + + /// + /// Publish a message to any subscribers asynchronously. + /// + /// Type of message. + /// Message to deliver. + /// A task from Publish action. + Task PublishAsync(TMessage message) + where TMessage : class, IMessageHubMessage; + } + + #endregion + + #region Hub Implementation + + /// + /// + /// The following code describes how to use a MessageHub. Both the + /// subscription and the message sending are done in the same place but this is only for explanatory purposes. + /// + /// class Example + /// { + /// using Unosquare.Swan; + /// using Unosquare.Swan.Components; + /// + /// static void Main() + /// { + /// // using DependencyContainer to create an instance of MessageHub + /// var messageHub = DependencyContainer + /// .Current + /// .Resolve<IMessageHub>() as MessageHub; + /// + /// // create an instance of the publisher class + /// // which has a string as its content + /// var message = new MessageHubGenericMessage<string>(new object(), "SWAN"); + /// + /// // subscribe to the publisher's event + /// // and just print out the content which is a string + /// // a token is returned which can be used to unsubscribe later on + /// var token = messageHub + /// .Subscribe<MessageHubGenericMessage<string>>(m => m.Content.Info()); + /// + /// // publish the message described above which is + /// // the string 'SWAN' + /// messageHub.Publish(message); + /// + /// // unsuscribe, we will no longer receive any messages + /// messageHub.Unsubscribe<MessageHubGenericMessage<string>>(token); + /// + /// Terminal.Flush(); + /// } + /// + /// } + /// + /// + public sealed class MessageHub : IMessageHub + { + #region Private Types and Interfaces + + private readonly object _subscriptionsPadlock = new object(); + + private readonly Dictionary> _subscriptions = + new Dictionary>(); + + private class WeakMessageSubscription : IMessageHubSubscription + where TMessage : class, IMessageHubMessage + { + private readonly WeakReference _deliveryAction; + private readonly WeakReference _messageFilter; + + /// + /// Initializes a new instance of the class. + /// + /// The subscription token. + /// The delivery action. + /// The message filter. + /// subscriptionToken + /// or + /// deliveryAction + /// or + /// messageFilter. + public WeakMessageSubscription( + MessageHubSubscriptionToken subscriptionToken, + Action deliveryAction, + Func messageFilter) + { + SubscriptionToken = subscriptionToken ?? throw new ArgumentNullException(nameof(subscriptionToken)); + _deliveryAction = new WeakReference(deliveryAction); + _messageFilter = new WeakReference(messageFilter); + } + + public MessageHubSubscriptionToken SubscriptionToken { get; } + + public bool ShouldAttemptDelivery(IMessageHubMessage message) + { + return _deliveryAction.IsAlive && _messageFilter.IsAlive && + ((Func) _messageFilter.Target).Invoke((TMessage) message); + } + + public void Deliver(IMessageHubMessage message) + { + if (_deliveryAction.IsAlive) + { + ((Action) _deliveryAction.Target).Invoke((TMessage) message); + } + } + } + + private class StrongMessageSubscription : IMessageHubSubscription + where TMessage : class, IMessageHubMessage + { + private readonly Action _deliveryAction; + private readonly Func _messageFilter; + + /// + /// Initializes a new instance of the class. + /// + /// The subscription token. + /// The delivery action. + /// The message filter. + /// subscriptionToken + /// or + /// deliveryAction + /// or + /// messageFilter. + public StrongMessageSubscription( + MessageHubSubscriptionToken subscriptionToken, + Action deliveryAction, + Func messageFilter) + { + SubscriptionToken = subscriptionToken ?? throw new ArgumentNullException(nameof(subscriptionToken)); + _deliveryAction = deliveryAction; + _messageFilter = messageFilter; + } + + public MessageHubSubscriptionToken SubscriptionToken { get; } + + public bool ShouldAttemptDelivery(IMessageHubMessage message) => _messageFilter.Invoke((TMessage) message); + + public void Deliver(IMessageHubMessage message) => _deliveryAction.Invoke((TMessage) message); + } + + #endregion + + #region Subscription dictionary + + private class SubscriptionItem + { + public SubscriptionItem(IMessageHubProxy proxy, IMessageHubSubscription subscription) + { + Proxy = proxy; + Subscription = subscription; + } + + public IMessageHubProxy Proxy { get; } + public IMessageHubSubscription Subscription { get; } + } + + #endregion + + #region Public API + + /// + /// Subscribe to a message type with the given destination and delivery action. + /// Messages will be delivered via the specified proxy. + /// + /// All messages of this type will be delivered. + /// + /// Type of message. + /// Action to invoke when message is delivered. + /// Use strong references to destination and deliveryAction. + /// Proxy to use when delivering the messages. + /// MessageSubscription used to unsubscribing. + public MessageHubSubscriptionToken Subscribe( + Action deliveryAction, + bool useStrongReferences = true, + IMessageHubProxy proxy = null) + where TMessage : class, IMessageHubMessage + { + return Subscribe(deliveryAction, m => true, useStrongReferences, proxy); + } + + /// + /// Subscribe to a message type with the given destination and delivery action with the given filter. + /// Messages will be delivered via the specified proxy. + /// All references are held with WeakReferences + /// Only messages that "pass" the filter will be delivered. + /// + /// Type of message. + /// Action to invoke when message is delivered. + /// The message filter. + /// Use strong references to destination and deliveryAction. + /// Proxy to use when delivering the messages. + /// + /// MessageSubscription used to unsubscribing. + /// + public MessageHubSubscriptionToken Subscribe( + Action deliveryAction, + Func messageFilter, + bool useStrongReferences = true, + IMessageHubProxy proxy = null) + where TMessage : class, IMessageHubMessage + { + if (deliveryAction == null) + throw new ArgumentNullException(nameof(deliveryAction)); + + if (messageFilter == null) + throw new ArgumentNullException(nameof(messageFilter)); + + lock (_subscriptionsPadlock) + { + if (!_subscriptions.TryGetValue(typeof(TMessage), out var currentSubscriptions)) + { + currentSubscriptions = new List(); + _subscriptions[typeof(TMessage)] = currentSubscriptions; + } + + var subscriptionToken = new MessageHubSubscriptionToken(this, typeof(TMessage)); + + IMessageHubSubscription subscription; + if (useStrongReferences) + { + subscription = new StrongMessageSubscription( + subscriptionToken, + deliveryAction, + messageFilter); + } + else + { + subscription = new WeakMessageSubscription( + subscriptionToken, + deliveryAction, + messageFilter); + } + + currentSubscriptions.Add(new SubscriptionItem(proxy ?? MessageHubDefaultProxy.Instance, subscription)); + + return subscriptionToken; + } + } + + /// + public void Unsubscribe(MessageHubSubscriptionToken subscriptionToken) + where TMessage : class, IMessageHubMessage + { + if (subscriptionToken == null) + throw new ArgumentNullException(nameof(subscriptionToken)); + + lock (_subscriptionsPadlock) + { + if (!_subscriptions.TryGetValue(typeof(TMessage), out var currentSubscriptions)) + return; + + var currentlySubscribed = currentSubscriptions + .Where(sub => ReferenceEquals(sub.Subscription.SubscriptionToken, subscriptionToken)) + .ToList(); + + currentlySubscribed.ForEach(sub => currentSubscriptions.Remove(sub)); + } + } + + /// + /// Publish a message to any subscribers. + /// + /// Type of message. + /// Message to deliver. + public void Publish(TMessage message) + where TMessage : class, IMessageHubMessage + { + if (message == null) + throw new ArgumentNullException(nameof(message)); + + List currentlySubscribed; + lock (_subscriptionsPadlock) + { + if (!_subscriptions.TryGetValue(typeof(TMessage), out var currentSubscriptions)) + return; + + currentlySubscribed = currentSubscriptions + .Where(sub => sub.Subscription.ShouldAttemptDelivery(message)) + .ToList(); + } + + currentlySubscribed.ForEach(sub => + { + try + { + sub.Proxy.Deliver(message, sub.Subscription); + } + catch + { + // Ignore any errors and carry on + } + }); + } + + /// + /// Publish a message to any subscribers asynchronously. + /// + /// Type of message. + /// Message to deliver. + /// A task with the publish. + public Task PublishAsync(TMessage message) + where TMessage : class, IMessageHubMessage + { + return Task.Run(() => Publish(message)); + } + + #endregion + } + + #endregion +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/MessageHubMessageBase.cs b/Unosquare.Swan/Components/MessageHubMessageBase.cs new file mode 100644 index 0000000..5c8c7ea --- /dev/null +++ b/Unosquare.Swan/Components/MessageHubMessageBase.cs @@ -0,0 +1,59 @@ +namespace Unosquare.Swan.Components +{ + using System; + + /// + /// Base class for messages that provides weak reference storage of the sender. + /// + public abstract class MessageHubMessageBase + : IMessageHubMessage + { + /// + /// Store a WeakReference to the sender just in case anyone is daft enough to + /// keep the message around and prevent the sender from being collected. + /// + private readonly WeakReference _sender; + + /// + /// Initializes a new instance of the class. + /// + /// The sender. + /// sender. + protected MessageHubMessageBase(object sender) + { + if (sender == null) + throw new ArgumentNullException(nameof(sender)); + + _sender = new WeakReference(sender); + } + + /// + /// The sender of the message, or null if not supported by the message implementation. + /// + public object Sender => _sender?.Target; + } + + /// + /// Generic message with user specified content. + /// + /// Content type to store. + public class MessageHubGenericMessage + : MessageHubMessageBase + { + /// + /// Initializes a new instance of the class. + /// + /// The sender. + /// The content. + public MessageHubGenericMessage(object sender, TContent content) + : base(sender) + { + Content = content; + } + + /// + /// Contents of the message. + /// + public TContent Content { get; protected set; } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/MessageHubSubscriptionToken.cs b/Unosquare.Swan/Components/MessageHubSubscriptionToken.cs new file mode 100644 index 0000000..bcec34e --- /dev/null +++ b/Unosquare.Swan/Components/MessageHubSubscriptionToken.cs @@ -0,0 +1,54 @@ +namespace Unosquare.Swan.Components +{ + using System; +#if NETSTANDARD1_3 + using System.Reflection; +#endif + + /// + /// Represents an active subscription to a message. + /// + public sealed class MessageHubSubscriptionToken + : IDisposable + { + private readonly WeakReference _hub; + private readonly Type _messageType; + + /// + /// Initializes a new instance of the class. + /// + /// The hub. + /// Type of the message. + /// hub. + /// messageType. + public MessageHubSubscriptionToken(IMessageHub hub, Type messageType) + { + if (hub == null) + { + throw new ArgumentNullException(nameof(hub)); + } + + if (!typeof(IMessageHubMessage).IsAssignableFrom(messageType)) + { + throw new ArgumentOutOfRangeException(nameof(messageType)); + } + + _hub = new WeakReference(hub); + _messageType = messageType; + } + + /// + public void Dispose() + { + if (_hub.IsAlive && _hub.Target is IMessageHub hub) + { + var unsubscribeMethod = typeof(IMessageHub).GetMethod(nameof(IMessageHub.Unsubscribe), + new[] {typeof(MessageHubSubscriptionToken)}); + unsubscribeMethod = unsubscribeMethod.MakeGenericMethod(_messageType); + unsubscribeMethod.Invoke(hub, new object[] {this}); + } + + GC.SuppressFinalize(this); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/ObjectFactoryBase.cs b/Unosquare.Swan/Components/ObjectFactoryBase.cs new file mode 100644 index 0000000..2771c29 --- /dev/null +++ b/Unosquare.Swan/Components/ObjectFactoryBase.cs @@ -0,0 +1,424 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Collections.Generic; + using System.Reflection; + using Exceptions; + + /// + /// Represents an abstract class for Object Factory. + /// + public abstract class ObjectFactoryBase + { + /// + /// Whether to assume this factory successfully constructs its objects + /// + /// Generally set to true for delegate style factories as CanResolve cannot delve + /// into the delegates they contain. + /// + public virtual bool AssumeConstruction => false; + + /// + /// The type the factory instantiates. + /// + public abstract Type CreatesType { get; } + + /// + /// Constructor to use, if specified. + /// + public ConstructorInfo Constructor { get; private set; } + + /// + /// Gets the singleton variant. + /// + /// + /// The singleton variant. + /// + /// singleton. + public virtual ObjectFactoryBase SingletonVariant => + throw new DependencyContainerRegistrationException(GetType(), "singleton"); + + /// + /// Gets the multi instance variant. + /// + /// + /// The multi instance variant. + /// + /// multi-instance. + public virtual ObjectFactoryBase MultiInstanceVariant => + throw new DependencyContainerRegistrationException(GetType(), "multi-instance"); + + /// + /// Gets the strong reference variant. + /// + /// + /// The strong reference variant. + /// + /// strong reference. + public virtual ObjectFactoryBase StrongReferenceVariant => + throw new DependencyContainerRegistrationException(GetType(), "strong reference"); + + /// + /// Gets the weak reference variant. + /// + /// + /// The weak reference variant. + /// + /// weak reference. + public virtual ObjectFactoryBase WeakReferenceVariant => + throw new DependencyContainerRegistrationException(GetType(), "weak reference"); + + /// + /// Create the type. + /// + /// Type user requested to be resolved. + /// Container that requested the creation. + /// The options. + /// Instance of type. + public abstract object GetObject( + Type requestedType, + DependencyContainer container, + DependencyContainerResolveOptions options); + + /// + /// Gets the factory for child container. + /// + /// The type. + /// The parent. + /// The child. + /// + public virtual ObjectFactoryBase GetFactoryForChildContainer( + Type type, + DependencyContainer parent, + DependencyContainer child) + { + return this; + } + } + + /// + /// + /// IObjectFactory that creates new instances of types for each resolution. + /// + internal class MultiInstanceFactory : ObjectFactoryBase + { + private readonly Type _registerType; + private readonly Type _registerImplementation; + + public MultiInstanceFactory(Type registerType, Type registerImplementation) + { + if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) + { + throw new DependencyContainerRegistrationException(registerImplementation, + "MultiInstanceFactory", + true); + } + + if (!DependencyContainer.IsValidAssignment(registerType, registerImplementation)) + { + throw new DependencyContainerRegistrationException(registerImplementation, + "MultiInstanceFactory", + true); + } + + _registerType = registerType; + _registerImplementation = registerImplementation; + } + + public override Type CreatesType => _registerImplementation; + + public override ObjectFactoryBase SingletonVariant => + new SingletonFactory(_registerType, _registerImplementation); + + public override ObjectFactoryBase MultiInstanceVariant => this; + + public override object GetObject( + Type requestedType, + DependencyContainer container, + DependencyContainerResolveOptions options) + { + try + { + return container.RegisteredTypes.ConstructType(_registerImplementation, Constructor, options); + } + catch (DependencyContainerResolutionException ex) + { + throw new DependencyContainerResolutionException(_registerType, ex); + } + } + } + + /// + /// + /// IObjectFactory that invokes a specified delegate to construct the object. + /// + internal class DelegateFactory : ObjectFactoryBase + { + private readonly Type _registerType; + + private readonly Func, object> _factory; + + public DelegateFactory( + Type registerType, + Func, object> factory) + { + _factory = factory ?? throw new ArgumentNullException(nameof(factory)); + + _registerType = registerType; + } + + public override bool AssumeConstruction => true; + + public override Type CreatesType => _registerType; + + public override ObjectFactoryBase WeakReferenceVariant => new WeakDelegateFactory(_registerType, _factory); + + public override ObjectFactoryBase StrongReferenceVariant => this; + + public override object GetObject( + Type requestedType, + DependencyContainer container, + DependencyContainerResolveOptions options) + { + try + { + return _factory.Invoke(container, options.ConstructorParameters); + } + catch (Exception ex) + { + throw new DependencyContainerResolutionException(_registerType, ex); + } + } + } + + /// + /// + /// IObjectFactory that invokes a specified delegate to construct the object + /// Holds the delegate using a weak reference. + /// + internal class WeakDelegateFactory : ObjectFactoryBase + { + private readonly Type _registerType; + + private readonly WeakReference _factory; + + public WeakDelegateFactory(Type registerType, + Func, object> factory) + { + if (factory == null) + throw new ArgumentNullException(nameof(factory)); + + _factory = new WeakReference(factory); + + _registerType = registerType; + } + + public override bool AssumeConstruction => true; + + public override Type CreatesType => _registerType; + + public override ObjectFactoryBase StrongReferenceVariant + { + get + { + if (!(_factory.Target is Func, object> factory)) + throw new DependencyContainerWeakReferenceException(_registerType); + + return new DelegateFactory(_registerType, factory); + } + } + + public override ObjectFactoryBase WeakReferenceVariant => this; + + public override object GetObject( + Type requestedType, + DependencyContainer container, + DependencyContainerResolveOptions options) + { + if (!(_factory.Target is Func, object> factory)) + throw new DependencyContainerWeakReferenceException(_registerType); + + try + { + return factory.Invoke(container, options.ConstructorParameters); + } + catch (Exception ex) + { + throw new DependencyContainerResolutionException(_registerType, ex); + } + } + } + + /// + /// Stores an particular instance to return for a type. + /// + internal class InstanceFactory : ObjectFactoryBase, IDisposable + { + private readonly Type _registerType; + private readonly Type _registerImplementation; + private readonly object _instance; + + public InstanceFactory(Type registerType, Type registerImplementation, object instance) + { + if (!DependencyContainer.IsValidAssignment(registerType, registerImplementation)) + throw new DependencyContainerRegistrationException(registerImplementation, "InstanceFactory", true); + + _registerType = registerType; + _registerImplementation = registerImplementation; + _instance = instance; + } + + public override bool AssumeConstruction => true; + + public override Type CreatesType => _registerImplementation; + + public override ObjectFactoryBase MultiInstanceVariant => + new MultiInstanceFactory(_registerType, _registerImplementation); + + public override ObjectFactoryBase WeakReferenceVariant => + new WeakInstanceFactory(_registerType, _registerImplementation, _instance); + + public override ObjectFactoryBase StrongReferenceVariant => this; + + public override object GetObject( + Type requestedType, + DependencyContainer container, + DependencyContainerResolveOptions options) + { + return _instance; + } + + public void Dispose() + { + var disposable = _instance as IDisposable; + + disposable?.Dispose(); + } + } + + /// + /// Stores the instance with a weak reference. + /// + internal class WeakInstanceFactory : ObjectFactoryBase, IDisposable + { + private readonly Type _registerType; + private readonly Type _registerImplementation; + private readonly WeakReference _instance; + + public WeakInstanceFactory(Type registerType, Type registerImplementation, object instance) + { + if (!DependencyContainer.IsValidAssignment(registerType, registerImplementation)) + { + throw new DependencyContainerRegistrationException( + registerImplementation, + "WeakInstanceFactory", + true); + } + + _registerType = registerType; + _registerImplementation = registerImplementation; + _instance = new WeakReference(instance); + } + + public override Type CreatesType => _registerImplementation; + + public override ObjectFactoryBase MultiInstanceVariant => + new MultiInstanceFactory(_registerType, _registerImplementation); + + public override ObjectFactoryBase WeakReferenceVariant => this; + + public override ObjectFactoryBase StrongReferenceVariant + { + get + { + var instance = _instance.Target; + + if (instance == null) + throw new DependencyContainerWeakReferenceException(_registerType); + + return new InstanceFactory(_registerType, _registerImplementation, instance); + } + } + + public override object GetObject( + Type requestedType, + DependencyContainer container, + DependencyContainerResolveOptions options) + { + var instance = _instance.Target; + + if (instance == null) + throw new DependencyContainerWeakReferenceException(_registerType); + + return instance; + } + + public void Dispose() => (_instance.Target as IDisposable)?.Dispose(); + } + + /// + /// A factory that lazy instantiates a type and always returns the same instance. + /// + internal class SingletonFactory : ObjectFactoryBase, IDisposable + { + private readonly Type _registerType; + private readonly Type _registerImplementation; + private readonly object _singletonLock = new object(); + private object _current; + + public SingletonFactory(Type registerType, Type registerImplementation) + { + if (registerImplementation.IsAbstract() || registerImplementation.IsInterface()) + { + throw new DependencyContainerRegistrationException(registerImplementation, nameof(SingletonFactory), true); + } + + if (!DependencyContainer.IsValidAssignment(registerType, registerImplementation)) + { + throw new DependencyContainerRegistrationException(registerImplementation, nameof(SingletonFactory), true); + } + + _registerType = registerType; + _registerImplementation = registerImplementation; + } + + public override Type CreatesType => _registerImplementation; + + public override ObjectFactoryBase SingletonVariant => this; + + public override ObjectFactoryBase MultiInstanceVariant => + new MultiInstanceFactory(_registerType, _registerImplementation); + + public override object GetObject( + Type requestedType, + DependencyContainer container, + DependencyContainerResolveOptions options) + { + if (options.ConstructorParameters.Count != 0) + throw new ArgumentException("Cannot specify parameters for singleton types"); + + lock (_singletonLock) + { + if (_current == null) + _current = container.RegisteredTypes.ConstructType(_registerImplementation, Constructor, options); + } + + return _current; + } + + public override ObjectFactoryBase GetFactoryForChildContainer( + Type type, + DependencyContainer parent, + DependencyContainer child) + { + // We make sure that the singleton is constructed before the child container takes the factory. + // Otherwise the results would vary depending on whether or not the parent container had resolved + // the type before the child container does. + GetObject(type, parent, DependencyContainerResolveOptions.Default); + return this; + } + + public void Dispose() => (_current as IDisposable)?.Dispose(); + } +} diff --git a/Unosquare.Swan/Components/ProcessResult.cs b/Unosquare.Swan/Components/ProcessResult.cs new file mode 100644 index 0000000..f5c9e64 --- /dev/null +++ b/Unosquare.Swan/Components/ProcessResult.cs @@ -0,0 +1,46 @@ +namespace Unosquare.Swan.Components +{ + /// + /// Represents the text of the standard output and standard error + /// of a process, including its exit code. + /// + public class ProcessResult + { + /// + /// Initializes a new instance of the class. + /// + /// The exit code. + /// The standard output. + /// The standard error. + public ProcessResult(int exitCode, string standardOutput, string standardError) + { + ExitCode = exitCode; + StandardOutput = standardOutput; + StandardError = standardError; + } + + /// + /// Gets the exit code. + /// + /// + /// The exit code. + /// + public int ExitCode { get; } + + /// + /// Gets the text of the standard output. + /// + /// + /// The standard output. + /// + public string StandardOutput { get; } + + /// + /// Gets the text of the standard error. + /// + /// + /// The standard error. + /// + public string StandardError { get; } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/ProcessRunner.cs b/Unosquare.Swan/Components/ProcessRunner.cs new file mode 100644 index 0000000..1a7d33e --- /dev/null +++ b/Unosquare.Swan/Components/ProcessRunner.cs @@ -0,0 +1,474 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Diagnostics; + using System.IO; + using System.Linq; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Provides methods to help create external processes, and efficiently capture the + /// standard error and standard output streams. + /// + public static class ProcessRunner + { + /// + /// Defines a delegate to handle binary data reception from the standard + /// output or standard error streams from a process. + /// + /// The process data. + /// The process. + public delegate void ProcessDataReceivedCallback(byte[] processData, Process process); + + /// + /// Runs the process asynchronously and if the exit code is 0, + /// returns all of the standard output text. If the exit code is something other than 0 + /// it returns the contents of standard error. + /// This method is meant to be used for programs that output a relatively small amount of text. + /// + /// The filename. + /// The cancellation token. + /// The type of the result produced by this Task. + public static Task GetProcessOutputAsync(string filename, CancellationToken ct = default) => + GetProcessOutputAsync(filename, string.Empty, ct); + + /// + /// Runs the process asynchronously and if the exit code is 0, + /// returns all of the standard output text. If the exit code is something other than 0 + /// it returns the contents of standard error. + /// This method is meant to be used for programs that output a relatively small amount of text. + /// + /// The filename. + /// The arguments. + /// The cancellation token. + /// The type of the result produced by this Task. + /// + /// The following code explains how to run an external process using the + /// method. + /// + /// class Example + /// { + /// using System.Threading.Tasks; + /// using Unosquare.Swan.Components; + /// + /// static async Task Main() + /// { + /// // execute a process and save its output + /// var data = await ProcessRunner. + /// GetProcessOutputAsync("dotnet", "--help"); + /// + /// // print the output + /// data.WriteLine(); + /// } + /// } + /// + /// + public static async Task GetProcessOutputAsync( + string filename, + string arguments, + CancellationToken ct = default) + { + var result = await GetProcessResultAsync(filename, arguments, ct).ConfigureAwait(false); + return result.ExitCode == 0 ? result.StandardOutput : result.StandardError; + } + + /// + /// Gets the process output asynchronous. + /// + /// The filename. + /// The arguments. + /// The working directory. + /// The cancellation token. + /// + /// The type of the result produced by this Task. + /// + public static async Task GetProcessOutputAsync( + string filename, + string arguments, + string workingDirectory, + CancellationToken ct = default) + { + var result = await GetProcessResultAsync(filename, arguments, workingDirectory, ct: ct).ConfigureAwait(false); + return result.ExitCode == 0 ? result.StandardOutput : result.StandardError; + } + + /// + /// Runs the process asynchronously and if the exit code is 0, + /// returns all of the standard output text. If the exit code is something other than 0 + /// it returns the contents of standard error. + /// This method is meant to be used for programs that output a relatively small amount + /// of text using a different encoder. + /// + /// The filename. + /// The arguments. + /// The encoding. + /// The cancellation token. + /// + /// The type of the result produced by this Task. + /// + public static async Task GetProcessEncodedOutputAsync( + string filename, + string arguments = "", + Encoding encoding = null, + CancellationToken ct = default) + { + var result = await GetProcessResultAsync(filename, arguments, null, encoding, ct).ConfigureAwait(false); + return result.ExitCode == 0 ? result.StandardOutput : result.StandardError; + } + + /// + /// Executes a process asynchronously and returns the text of the standard output and standard error streams + /// along with the exit code. This method is meant to be used for programs that output a relatively small + /// amount of text. + /// + /// The filename. + /// The arguments. + /// The cancellation token. + /// + /// Text of the standard output and standard error streams along with the exit code as a instance. + /// + /// filename. + public static Task GetProcessResultAsync( + string filename, + string arguments = "", + CancellationToken ct = default) => + GetProcessResultAsync(filename, arguments, null, Definitions.CurrentAnsiEncoding, ct); + + /// + /// Executes a process asynchronously and returns the text of the standard output and standard error streams + /// along with the exit code. This method is meant to be used for programs that output a relatively small + /// amount of text. + /// + /// The filename. + /// The arguments. + /// The working directory. + /// The encoding. + /// The cancellation token. + /// + /// Text of the standard output and standard error streams along with the exit code as a instance. + /// + /// filename. + /// + /// The following code describes how to run an external process using the method. + /// + /// class Example + /// { + /// using System.Threading.Tasks; + /// using Unosquare.Swan.Components; + /// static async Task Main() + /// { + /// // Execute a process asynchronously + /// var data = await ProcessRunner.GetProcessResultAsync("dotnet", "--help"); + /// // print out the exit code + /// $"{data.ExitCode}".WriteLine(); + /// // print out the output + /// data.StandardOutput.WriteLine(); + /// // and the error if exists + /// data.StandardError.Error(); + /// } + /// } + /// + public static async Task GetProcessResultAsync( + string filename, + string arguments, + string workingDirectory, + Encoding encoding = null, + CancellationToken ct = default) + { + if (filename == null) + throw new ArgumentNullException(nameof(filename)); + + if (encoding == null) + encoding = Definitions.CurrentAnsiEncoding; + + var standardOutputBuilder = new StringBuilder(); + var standardErrorBuilder = new StringBuilder(); + + var processReturn = await RunProcessAsync( + filename, + arguments, + workingDirectory, + (data, proc) => { standardOutputBuilder.Append(encoding.GetString(data)); }, + (data, proc) => { standardErrorBuilder.Append(encoding.GetString(data)); }, + encoding, + true, + ct) + .ConfigureAwait(false); + + return new ProcessResult(processReturn, standardOutputBuilder.ToString(), standardErrorBuilder.ToString()); + } + + /// + /// Runs an external process asynchronously, providing callbacks to + /// capture binary data from the standard error and standard output streams. + /// The callbacks contain a reference to the process so you can respond to output or + /// error streams by writing to the process' input stream. + /// The exit code (return value) will be -1 for forceful termination of the process. + /// + /// The filename. + /// The arguments. + /// The working directory. + /// The on output data. + /// The on error data. + /// The encoding. + /// if set to true the next data callback will wait until the current one completes. + /// The cancellation token. + /// + /// Value type will be -1 for forceful termination of the process. + /// + public static Task RunProcessAsync( + string filename, + string arguments, + string workingDirectory, + ProcessDataReceivedCallback onOutputData, + ProcessDataReceivedCallback onErrorData, + Encoding encoding, + bool syncEvents = true, + CancellationToken ct = default) + { + if (filename == null) + throw new ArgumentNullException(nameof(filename)); + + return Task.Run(() => + { + // Setup the process and its corresponding start info + var process = new Process + { + EnableRaisingEvents = false, + StartInfo = new ProcessStartInfo + { + Arguments = arguments, + CreateNoWindow = true, + FileName = filename, + RedirectStandardError = true, + StandardErrorEncoding = encoding, + RedirectStandardOutput = true, + StandardOutputEncoding = encoding, + UseShellExecute = false, +#if NET452 + WindowStyle = ProcessWindowStyle.Hidden, +#endif + }, + }; + + if (!string.IsNullOrWhiteSpace(workingDirectory)) + process.StartInfo.WorkingDirectory = workingDirectory; + + // Launch the process and discard any buffered data for standard error and standard output + process.Start(); + process.StandardError.DiscardBufferedData(); + process.StandardOutput.DiscardBufferedData(); + + // Launch the asynchronous stream reading tasks + var readTasks = new Task[2]; + readTasks[0] = CopyStreamAsync( + process, + process.StandardOutput.BaseStream, + onOutputData, + syncEvents, + ct); + readTasks[1] = CopyStreamAsync( + process, + process.StandardError.BaseStream, + onErrorData, + syncEvents, + ct); + + try + { + // Wait for all tasks to complete + Task.WaitAll(readTasks, ct); + } + catch (TaskCanceledException) + { + // ignore + } + finally + { + // Wait for the process to exit + while (ct.IsCancellationRequested == false) + { + if (process.HasExited || process.WaitForExit(5)) + break; + } + + // Forcefully kill the process if it do not exit + try + { + if (process.HasExited == false) + process.Kill(); + } + catch + { + // swallow + } + } + + try + { + // Retrieve and return the exit code. + // -1 signals error + return process.HasExited ? process.ExitCode : -1; + } + catch + { + return -1; + } + }, ct); + } + + /// + /// Runs an external process asynchronously, providing callbacks to + /// capture binary data from the standard error and standard output streams. + /// The callbacks contain a reference to the process so you can respond to output or + /// error streams by writing to the process' input stream. + /// The exit code (return value) will be -1 for forceful termination of the process. + /// + /// The filename. + /// The arguments. + /// The on output data. + /// The on error data. + /// if set to true the next data callback will wait until the current one completes. + /// The cancellation token. + /// Value type will be -1 for forceful termination of the process. + /// + /// The following example illustrates how to run an external process using the + /// + /// method. + /// + /// class Example + /// { + /// using System.Diagnostics; + /// using System.Text; + /// using System.Threading.Tasks; + /// using Unosquare.Swan; + /// using Unosquare.Swan.Components; + /// + /// static async Task Main() + /// { + /// // Execute a process asynchronously + /// var data = await ProcessRunner + /// .RunProcessAsync("dotnet", "--help", Print, Print); + /// + /// // flush all messages + /// Terminal.Flush(); + /// } + /// + /// // a callback to print both output or errors + /// static void Print(byte[] data, Process proc) => + /// Encoding.GetEncoding(0).GetString(data).WriteLine(); + /// } + /// + /// + public static Task RunProcessAsync( + string filename, + string arguments, + ProcessDataReceivedCallback onOutputData, + ProcessDataReceivedCallback onErrorData, + bool syncEvents = true, + CancellationToken ct = default) + => RunProcessAsync( + filename, + arguments, + null, + onOutputData, + onErrorData, + Definitions.CurrentAnsiEncoding, + syncEvents, + ct); + + /// + /// Copies the stream asynchronously. + /// + /// The process. + /// The source stream. + /// The on data callback. + /// if set to true [synchronize events]. + /// The cancellation token. + /// Total copies stream. + private static Task CopyStreamAsync( + Process process, + Stream baseStream, + ProcessDataReceivedCallback onDataCallback, + bool syncEvents, + CancellationToken ct) + { + return Task.Factory.StartNew(async () => + { + // define some state variables + var swapBuffer = new byte[2048]; // the buffer to copy data from one stream to the next + ulong totalCount = 0; // the total amount of bytes read + var hasExited = false; + + while (ct.IsCancellationRequested == false) + { + try + { + // Check if process is no longer valid + // if this condition holds, simply read the last bits of data available. + int readCount; // the bytes read in any given event + if (process.HasExited || process.WaitForExit(1)) + { + while (true) + { + try + { + readCount = await baseStream.ReadAsync(swapBuffer, 0, swapBuffer.Length, ct); + + if (readCount > 0) + { + totalCount += (ulong) readCount; + onDataCallback?.Invoke(swapBuffer.Skip(0).Take(readCount).ToArray(), process); + } + else + { + hasExited = true; + break; + } + } + catch + { + hasExited = true; + break; + } + } + } + + if (hasExited) break; + + // Try reading from the stream. < 0 means no read occurred. + readCount = await baseStream.ReadAsync(swapBuffer, 0, swapBuffer.Length, ct); + + // When no read is done, we need to let is rest for a bit + if (readCount <= 0) + { + await Task.Delay(1, ct); // do not hog CPU cycles doing nothing. + continue; + } + + totalCount += (ulong) readCount; + if (onDataCallback == null) continue; + + // Create the buffer to pass to the callback + var eventBuffer = swapBuffer.Skip(0).Take(readCount).ToArray(); + + // Create the data processing callback invocation + var eventTask = + Task.Factory.StartNew(() => { onDataCallback.Invoke(eventBuffer, process); }, ct); + + // wait for the event to process before the next read occurs + if (syncEvents) eventTask.Wait(ct); + } + catch + { + break; + } + } + + return totalCount; + }, ct).Unwrap(); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/RealtimeClock.cs b/Unosquare.Swan/Components/RealtimeClock.cs new file mode 100644 index 0000000..894934c --- /dev/null +++ b/Unosquare.Swan/Components/RealtimeClock.cs @@ -0,0 +1,143 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Diagnostics; + using Abstractions; + + /// + /// A time measurement artifact. + /// + internal sealed class RealTimeClock : IDisposable + { + private readonly Stopwatch _chrono = new Stopwatch(); + private ISyncLocker _locker = SyncLockerFactory.Create(useSlim: true); + private long _offsetTicks; + private double _speedRatio = 1.0d; + private bool _isDisposed; + + /// + /// Initializes a new instance of the class. + /// The clock starts paused and at the 0 position. + /// + public RealTimeClock() + { + Reset(); + } + + /// + /// Gets or sets the clock position. + /// + public TimeSpan Position + { + get + { + using (_locker.AcquireReaderLock()) + { + return TimeSpan.FromTicks( + _offsetTicks + Convert.ToInt64(_chrono.Elapsed.Ticks * SpeedRatio)); + } + } + } + + /// + /// Gets a value indicating whether the clock is running. + /// + public bool IsRunning + { + get + { + using (_locker.AcquireReaderLock()) + { + return _chrono.IsRunning; + } + } + } + + /// + /// Gets or sets the speed ratio at which the clock runs. + /// + public double SpeedRatio + { + get + { + using (_locker.AcquireReaderLock()) + { + return _speedRatio; + } + } + set + { + using (_locker.AcquireWriterLock()) + { + if (value < 0d) value = 0d; + + // Capture the initial position se we set it even after the speedratio has changed + // this ensures a smooth position transition + var initialPosition = Position; + _speedRatio = value; + Update(initialPosition); + } + } + } + + /// + /// Sets a new position value atomically. + /// + /// The new value that the position porperty will hold. + public void Update(TimeSpan value) + { + using (_locker.AcquireWriterLock()) + { + var resume = _chrono.IsRunning; + _chrono.Reset(); + _offsetTicks = value.Ticks; + if (resume) _chrono.Start(); + } + } + + /// + /// Starts or resumes the clock. + /// + public void Play() + { + using (_locker.AcquireWriterLock()) + { + if (_chrono.IsRunning) return; + _chrono.Start(); + } + } + + /// + /// Pauses the clock. + /// + public void Pause() + { + using (_locker.AcquireWriterLock()) + { + _chrono.Stop(); + } + } + + /// + /// Sets the clock position to 0 and stops it. + /// The speed ratio is not modified. + /// + public void Reset() + { + using (_locker.AcquireWriterLock()) + { + _offsetTicks = 0; + _chrono.Reset(); + } + } + + /// + public void Dispose() + { + if (_isDisposed) return; + _isDisposed = true; + _locker?.Dispose(); + _locker = null; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/RegisterOptions.cs b/Unosquare.Swan/Components/RegisterOptions.cs new file mode 100644 index 0000000..aff98b5 --- /dev/null +++ b/Unosquare.Swan/Components/RegisterOptions.cs @@ -0,0 +1,132 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Collections.Generic; + using System.Linq; + using Exceptions; + + /// + /// Registration options for "fluent" API. + /// + public sealed class RegisterOptions + { + private readonly TypesConcurrentDictionary _registeredTypes; + private readonly DependencyContainer.TypeRegistration _registration; + + /// + /// Initializes a new instance of the class. + /// + /// The registered types. + /// The registration. + public RegisterOptions(TypesConcurrentDictionary registeredTypes, DependencyContainer.TypeRegistration registration) + { + _registeredTypes = registeredTypes; + _registration = registration; + } + + /// + /// Make registration a singleton (single instance) if possible. + /// + /// A registration options for fluent API. + /// Generic constraint registration exception. + public RegisterOptions AsSingleton() + { + var currentFactory = _registeredTypes.GetCurrentFactory(_registration); + + if (currentFactory == null) + throw new DependencyContainerRegistrationException(_registration.Type, "singleton"); + + return _registeredTypes.AddUpdateRegistration(_registration, currentFactory.SingletonVariant); + } + + /// + /// Make registration multi-instance if possible. + /// + /// A registration options for fluent API. + /// Generic constraint registration exception. + public RegisterOptions AsMultiInstance() + { + var currentFactory = _registeredTypes.GetCurrentFactory(_registration); + + if (currentFactory == null) + throw new DependencyContainerRegistrationException(_registration.Type, "multi-instance"); + + return _registeredTypes.AddUpdateRegistration(_registration, currentFactory.MultiInstanceVariant); + } + + /// + /// Make registration hold a weak reference if possible. + /// + /// A registration options for fluent API. + /// Generic constraint registration exception. + public RegisterOptions WithWeakReference() + { + var currentFactory = _registeredTypes.GetCurrentFactory(_registration); + + if (currentFactory == null) + throw new DependencyContainerRegistrationException(_registration.Type, "weak reference"); + + return _registeredTypes.AddUpdateRegistration(_registration, currentFactory.WeakReferenceVariant); + } + + /// + /// Make registration hold a strong reference if possible. + /// + /// A registration options for fluent API. + /// Generic constraint registration exception. + public RegisterOptions WithStrongReference() + { + var currentFactory = _registeredTypes.GetCurrentFactory(_registration); + + if (currentFactory == null) + throw new DependencyContainerRegistrationException(_registration.Type, "strong reference"); + + return _registeredTypes.AddUpdateRegistration(_registration, currentFactory.StrongReferenceVariant); + } + } + + /// + /// Registration options for "fluent" API when registering multiple implementations. + /// + public sealed class MultiRegisterOptions + { + private IEnumerable _registerOptions; + + /// + /// Initializes a new instance of the class. + /// + /// The register options. + public MultiRegisterOptions(IEnumerable registerOptions) + { + _registerOptions = registerOptions; + } + + /// + /// Make registration a singleton (single instance) if possible. + /// + /// A registration multi-instance for fluent API. + /// Generic Constraint Registration Exception. + public MultiRegisterOptions AsSingleton() + { + _registerOptions = ExecuteOnAllRegisterOptions(ro => ro.AsSingleton()); + return this; + } + + /// + /// Make registration multi-instance if possible. + /// + /// A registration multi-instance for fluent API. + /// Generic Constraint Registration Exception. + public MultiRegisterOptions AsMultiInstance() + { + _registerOptions = ExecuteOnAllRegisterOptions(ro => ro.AsMultiInstance()); + return this; + } + + private IEnumerable ExecuteOnAllRegisterOptions( + Func action) + { + return _registerOptions.Select(action).ToList(); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/TypeRegistration.cs b/Unosquare.Swan/Components/TypeRegistration.cs new file mode 100644 index 0000000..0fa4dca --- /dev/null +++ b/Unosquare.Swan/Components/TypeRegistration.cs @@ -0,0 +1,67 @@ +namespace Unosquare.Swan.Components +{ + using System; + + public partial class DependencyContainer + { + /// + /// Represents a Type Registration within the IoC Container. + /// + public sealed class TypeRegistration + { + private readonly int _hashCode; + + /// + /// Initializes a new instance of the class. + /// + /// The type. + /// The name. + public TypeRegistration(Type type, string name = null) + { + Type = type; + Name = name ?? string.Empty; + + _hashCode = string.Concat(Type.FullName, "|", Name).GetHashCode(); + } + + /// + /// Gets the type. + /// + /// + /// The type. + /// + public Type Type { get; } + + /// + /// Gets the name. + /// + /// + /// The name. + /// + public string Name { get; } + + /// + /// Determines whether the specified , is equal to this instance. + /// + /// The to compare with this instance. + /// + /// true if the specified is equal to this instance; otherwise, false. + /// + public override bool Equals(object obj) + { + if (!(obj is TypeRegistration typeRegistration) || typeRegistration.Type != Type) + return false; + + return string.Compare(Name, typeRegistration.Name, StringComparison.Ordinal) == 0; + } + + /// + /// Returns a hash code for this instance. + /// + /// + /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table. + /// + public override int GetHashCode() => _hashCode; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Components/TypesConcurrentDictionary.cs b/Unosquare.Swan/Components/TypesConcurrentDictionary.cs new file mode 100644 index 0000000..114c302 --- /dev/null +++ b/Unosquare.Swan/Components/TypesConcurrentDictionary.cs @@ -0,0 +1,352 @@ +namespace Unosquare.Swan.Components +{ + using System; + using System.Linq.Expressions; + using System.Reflection; + using System.Collections.Generic; + using System.Linq; + using Exceptions; + using System.Collections.Concurrent; + + /// + /// Represents a Concurrent Dictionary for TypeRegistration. + /// + public class TypesConcurrentDictionary : ConcurrentDictionary + { + private static readonly ConcurrentDictionary ObjectConstructorCache = + new ConcurrentDictionary(); + + private readonly DependencyContainer _dependencyContainer; + + internal TypesConcurrentDictionary(DependencyContainer dependencyContainer) + { + _dependencyContainer = dependencyContainer; + } + + /// + /// Represents a delegate to build an object with the parameters. + /// + /// The parameters. + /// The built object. + public delegate object ObjectConstructor(params object[] parameters); + + internal IEnumerable Resolve(Type resolveType, bool includeUnnamed) + { + var registrations = Keys.Where(tr => tr.Type == resolveType) + .Concat(GetParentRegistrationsForType(resolveType)).Distinct(); + + if (!includeUnnamed) + registrations = registrations.Where(tr => tr.Name != string.Empty); + + return registrations.Select(registration => + ResolveInternal(registration, DependencyContainerResolveOptions.Default)); + } + + internal ObjectFactoryBase GetCurrentFactory(DependencyContainer.TypeRegistration registration) + { + TryGetValue(registration, out var current); + + return current; + } + + internal RegisterOptions Register(Type registerType, string name, ObjectFactoryBase factory) + => AddUpdateRegistration(new DependencyContainer.TypeRegistration(registerType, name), factory); + + internal RegisterOptions AddUpdateRegistration(DependencyContainer.TypeRegistration typeRegistration, ObjectFactoryBase factory) + { + this[typeRegistration] = factory; + + return new RegisterOptions(this, typeRegistration); + } + + internal bool RemoveRegistration(DependencyContainer.TypeRegistration typeRegistration) + => TryRemove(typeRegistration, out _); + + internal object ResolveInternal( + DependencyContainer.TypeRegistration registration, + DependencyContainerResolveOptions options = null) + { + if (options == null) + options = DependencyContainerResolveOptions.Default; + + // Attempt container resolution + if (TryGetValue(registration, out var factory)) + { + try + { + return factory.GetObject(registration.Type, _dependencyContainer, options); + } + catch (DependencyContainerResolutionException) + { + throw; + } + catch (Exception ex) + { + throw new DependencyContainerResolutionException(registration.Type, ex); + } + } + + // Attempt to get a factory from parent if we can + var bubbledObjectFactory = GetParentObjectFactory(registration); + if (bubbledObjectFactory != null) + { + try + { + return bubbledObjectFactory.GetObject(registration.Type, _dependencyContainer, options); + } + catch (DependencyContainerResolutionException) + { + throw; + } + catch (Exception ex) + { + throw new DependencyContainerResolutionException(registration.Type, ex); + } + } + + // Fail if requesting named resolution and settings set to fail if unresolved + if (!string.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction == + DependencyContainerNamedResolutionFailureActions.Fail) + throw new DependencyContainerResolutionException(registration.Type); + + // Attempted unnamed fallback container resolution if relevant and requested + if (!string.IsNullOrEmpty(registration.Name) && options.NamedResolutionFailureAction == + DependencyContainerNamedResolutionFailureActions.AttemptUnnamedResolution) + { + if (TryGetValue(new DependencyContainer.TypeRegistration(registration.Type, string.Empty), out factory)) + { + try + { + return factory.GetObject(registration.Type, _dependencyContainer, options); + } + catch (DependencyContainerResolutionException) + { + throw; + } + catch (Exception ex) + { + throw new DependencyContainerResolutionException(registration.Type, ex); + } + } + } + + // Attempt unregistered construction if possible and requested + var isValid = (options.UnregisteredResolutionAction == + DependencyContainerUnregisteredResolutionActions.AttemptResolve) || + (registration.Type.IsGenericType() && options.UnregisteredResolutionAction == + DependencyContainerUnregisteredResolutionActions.GenericsOnly); + + return isValid && !registration.Type.IsAbstract() && !registration.Type.IsInterface() + ? ConstructType(registration.Type, null, options) + : throw new DependencyContainerResolutionException(registration.Type); + } + + internal bool CanResolve( + DependencyContainer.TypeRegistration registration, + DependencyContainerResolveOptions options = null) + { + if (options == null) + options = DependencyContainerResolveOptions.Default; + + var checkType = registration.Type; + var name = registration.Name; + + if (TryGetValue(new DependencyContainer.TypeRegistration(checkType, name), out var factory)) + { + if (factory.AssumeConstruction) + return true; + + if (factory.Constructor == null) + return GetBestConstructor(factory.CreatesType, options) != null; + + return CanConstruct(factory.Constructor, options); + } + + // Fail if requesting named resolution and settings set to fail if unresolved + // Or bubble up if we have a parent + if (!string.IsNullOrEmpty(name) && options.NamedResolutionFailureAction == + DependencyContainerNamedResolutionFailureActions.Fail) + return _dependencyContainer.Parent?.RegisteredTypes.CanResolve(registration, options.Clone()) ?? false; + + // Attempted unnamed fallback container resolution if relevant and requested + if (!string.IsNullOrEmpty(name) && options.NamedResolutionFailureAction == + DependencyContainerNamedResolutionFailureActions.AttemptUnnamedResolution) + { + if (TryGetValue(new DependencyContainer.TypeRegistration(checkType), out factory)) + { + if (factory.AssumeConstruction) + return true; + + return GetBestConstructor(factory.CreatesType, options) != null; + } + } + + // Check if type is an automatic lazy factory request or an IEnumerable + if (IsAutomaticLazyFactoryRequest(checkType) || registration.Type.IsIEnumerable()) + return true; + + // Attempt unregistered construction if possible and requested + // If we cant', bubble if we have a parent + if ((options.UnregisteredResolutionAction == + DependencyContainerUnregisteredResolutionActions.AttemptResolve) || + (checkType.IsGenericType() && options.UnregisteredResolutionAction == + DependencyContainerUnregisteredResolutionActions.GenericsOnly)) + { + return (GetBestConstructor(checkType, options) != null) || + (_dependencyContainer.Parent?.RegisteredTypes.CanResolve(registration, options.Clone()) ?? false); + } + + // Bubble resolution up the container tree if we have a parent + return _dependencyContainer.Parent != null && _dependencyContainer.Parent.RegisteredTypes.CanResolve(registration, options.Clone()); + } + + internal object ConstructType( + Type implementationType, + ConstructorInfo constructor, + DependencyContainerResolveOptions options = null) + { + var typeToConstruct = implementationType; + + if (constructor == null) + { + // Try and get the best constructor that we can construct + // if we can't construct any then get the constructor + // with the least number of parameters so we can throw a meaningful + // resolve exception + constructor = GetBestConstructor(typeToConstruct, options) ?? + GetTypeConstructors(typeToConstruct).LastOrDefault(); + } + + if (constructor == null) + throw new DependencyContainerResolutionException(typeToConstruct); + + var ctorParams = constructor.GetParameters(); + var args = new object[ctorParams.Length]; + + for (var parameterIndex = 0; parameterIndex < ctorParams.Length; parameterIndex++) + { + var currentParam = ctorParams[parameterIndex]; + + try + { + args[parameterIndex] = options?.ConstructorParameters.GetValueOrDefault(currentParam.Name, ResolveInternal(new DependencyContainer.TypeRegistration(currentParam.ParameterType), options.Clone())); + } + catch (DependencyContainerResolutionException ex) + { + // If a constructor parameter can't be resolved + // it will throw, so wrap it and throw that this can't + // be resolved. + throw new DependencyContainerResolutionException(typeToConstruct, ex); + } + catch (Exception ex) + { + throw new DependencyContainerResolutionException(typeToConstruct, ex); + } + } + + try + { + return CreateObjectConstructionDelegateWithCache(constructor).Invoke(args); + } + catch (Exception ex) + { + throw new DependencyContainerResolutionException(typeToConstruct, ex); + } + } + + private static ObjectConstructor CreateObjectConstructionDelegateWithCache(ConstructorInfo constructor) + { + if (ObjectConstructorCache.TryGetValue(constructor, out var objectConstructor)) + return objectConstructor; + + // We could lock the cache here, but there's no real side + // effect to two threads creating the same ObjectConstructor + // at the same time, compared to the cost of a lock for + // every creation. + var constructorParams = constructor.GetParameters(); + var lambdaParams = Expression.Parameter(typeof(object[]), "parameters"); + var newParams = new Expression[constructorParams.Length]; + + for (var i = 0; i < constructorParams.Length; i++) + { + var paramsParameter = Expression.ArrayIndex(lambdaParams, Expression.Constant(i)); + + newParams[i] = Expression.Convert(paramsParameter, constructorParams[i].ParameterType); + } + + var newExpression = Expression.New(constructor, newParams); + + var constructionLambda = Expression.Lambda(typeof(ObjectConstructor), newExpression, lambdaParams); + + objectConstructor = (ObjectConstructor)constructionLambda.Compile(); + + ObjectConstructorCache[constructor] = objectConstructor; + return objectConstructor; + } + + private static IEnumerable GetTypeConstructors(Type type) + => type.GetConstructors().OrderByDescending(ctor => ctor.GetParameters().Length); + + private static bool IsAutomaticLazyFactoryRequest(Type type) + { + if (!type.IsGenericType()) + return false; + + var genericType = type.GetGenericTypeDefinition(); + + // Just a func + if (genericType == typeof(Func<>)) + return true; + + // 2 parameter func with string as first parameter (name) + if (genericType == typeof(Func<,>) && type.GetGenericArguments()[0] == typeof(string)) + return true; + + // 3 parameter func with string as first parameter (name) and IDictionary as second (parameters) + return genericType == typeof(Func<,,>) && type.GetGenericArguments()[0] == typeof(string) && + type.GetGenericArguments()[1] == typeof(IDictionary); + } + + private ObjectFactoryBase GetParentObjectFactory(DependencyContainer.TypeRegistration registration) + { + if (_dependencyContainer.Parent == null) + return null; + + return _dependencyContainer.Parent.RegisteredTypes.TryGetValue(registration, out var factory) + ? factory.GetFactoryForChildContainer(registration.Type, _dependencyContainer.Parent, _dependencyContainer) + : _dependencyContainer.Parent.RegisteredTypes.GetParentObjectFactory(registration); + } + + private ConstructorInfo GetBestConstructor( + Type type, + DependencyContainerResolveOptions options) + => type.IsValueType() ? null : GetTypeConstructors(type).FirstOrDefault(ctor => CanConstruct(ctor, options)); + + private bool CanConstruct( + ConstructorInfo ctor, + DependencyContainerResolveOptions options) + { + foreach (var parameter in ctor.GetParameters()) + { + if (string.IsNullOrEmpty(parameter.Name)) + return false; + + var isParameterOverload = options.ConstructorParameters.ContainsKey(parameter.Name); + + if (parameter.ParameterType.IsPrimitive() && !isParameterOverload) + return false; + + if (!isParameterOverload && + !CanResolve(new DependencyContainer.TypeRegistration(parameter.ParameterType), options.Clone())) + return false; + } + + return true; + } + + private IEnumerable GetParentRegistrationsForType(Type resolveType) + => _dependencyContainer.Parent == null + ? new DependencyContainer.TypeRegistration[] { } + : _dependencyContainer.Parent.RegisteredTypes.Keys.Where(tr => tr.Type == resolveType).Concat(_dependencyContainer.Parent.RegisteredTypes.GetParentRegistrationsForType(resolveType)); + } +} diff --git a/Unosquare.Swan/Enums.cs b/Unosquare.Swan/Enums.cs new file mode 100644 index 0000000..6cb034f --- /dev/null +++ b/Unosquare.Swan/Enums.cs @@ -0,0 +1,28 @@ +namespace Unosquare.Swan +{ + /// + /// Enumerates the possible causes of the DataReceived event occurring. + /// + public enum ConnectionDataReceivedTrigger + { + /// + /// The trigger was a forceful flush of the buffer + /// + Flush, + + /// + /// The new line sequence bytes were received + /// + NewLineSequenceEncountered, + + /// + /// The buffer was full + /// + BufferFull, + + /// + /// The block size reached + /// + BlockSizeReached, + } +} diff --git a/Unosquare.Swan/Eventing.ConnectionListener.cs b/Unosquare.Swan/Eventing.ConnectionListener.cs new file mode 100644 index 0000000..d7e8b96 --- /dev/null +++ b/Unosquare.Swan/Eventing.ConnectionListener.cs @@ -0,0 +1,158 @@ +namespace Unosquare.Swan +{ + using System; + using System.Net; + using System.Net.Sockets; + + /// + /// The event arguments for when connections are accepted. + /// + /// + public class ConnectionAcceptedEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The client. + /// client. + public ConnectionAcceptedEventArgs(TcpClient client) + { + Client = client ?? throw new ArgumentNullException(nameof(client)); + } + + /// + /// Gets the client. + /// + /// + /// The client. + /// + public TcpClient Client { get; } + } + + /// + /// Occurs before a connection is accepted. Set the Cancel property to true to prevent the connection from being accepted. + /// + /// + public class ConnectionAcceptingEventArgs : ConnectionAcceptedEventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The client. + public ConnectionAcceptingEventArgs(TcpClient client) + : base(client) + { + } + + /// + /// Setting Cancel to true rejects the new TcpClient. + /// + /// + /// true if cancel; otherwise, false. + /// + public bool Cancel { get; set; } + } + + /// + /// Event arguments for when a server listener is started. + /// + /// + public class ConnectionListenerStartedEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The listener end point. + /// listenerEndPoint. + public ConnectionListenerStartedEventArgs(IPEndPoint listenerEndPoint) + { + EndPoint = listenerEndPoint ?? throw new ArgumentNullException(nameof(listenerEndPoint)); + } + + /// + /// Gets the end point. + /// + /// + /// The end point. + /// + public IPEndPoint EndPoint { get; } + } + + /// + /// Event arguments for when a server listener fails to start. + /// + /// + public class ConnectionListenerFailedEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The listener end point. + /// The ex. + /// + /// listenerEndPoint + /// or + /// ex. + /// + public ConnectionListenerFailedEventArgs(IPEndPoint listenerEndPoint, Exception ex) + { + EndPoint = listenerEndPoint ?? throw new ArgumentNullException(nameof(listenerEndPoint)); + Error = ex ?? throw new ArgumentNullException(nameof(ex)); + } + + /// + /// Gets the end point. + /// + /// + /// The end point. + /// + public IPEndPoint EndPoint { get; } + + /// + /// Gets the error. + /// + /// + /// The error. + /// + public Exception Error { get; } + } + + /// + /// Event arguments for when a server listener stopped. + /// + /// + public class ConnectionListenerStoppedEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The listener end point. + /// The ex. + /// + /// listenerEndPoint + /// or + /// ex. + /// + public ConnectionListenerStoppedEventArgs(IPEndPoint listenerEndPoint, Exception ex = null) + { + EndPoint = listenerEndPoint ?? throw new ArgumentNullException(nameof(listenerEndPoint)); + Error = ex; + } + + /// + /// Gets the end point. + /// + /// + /// The end point. + /// + public IPEndPoint EndPoint { get; } + + /// + /// Gets the error. + /// + /// + /// The error. + /// + public Exception Error { get; } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Eventing.cs b/Unosquare.Swan/Eventing.cs new file mode 100644 index 0000000..a460255 --- /dev/null +++ b/Unosquare.Swan/Eventing.cs @@ -0,0 +1,90 @@ +namespace Unosquare.Swan +{ + using System; + using System.Text; + + /// + /// The event arguments for connection failure events. + /// + /// + public class ConnectionFailureEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The ex. + public ConnectionFailureEventArgs(Exception ex) + { + Error = ex; + } + + /// + /// Gets the error. + /// + /// + /// The error. + /// + public Exception Error { get; } + } + + /// + /// Event arguments for when data is received. + /// + /// + public class ConnectionDataReceivedEventArgs : EventArgs + { + /// + /// Initializes a new instance of the class. + /// + /// The buffer. + /// The trigger. + /// if set to true [more available]. + public ConnectionDataReceivedEventArgs(byte[] buffer, ConnectionDataReceivedTrigger trigger, bool moreAvailable) + { + Buffer = buffer ?? throw new ArgumentNullException(nameof(buffer)); + Trigger = trigger; + HasMoreAvailable = moreAvailable; + } + + /// + /// Gets the buffer. + /// + /// + /// The buffer. + /// + public byte[] Buffer { get; } + + /// + /// Gets the cause as to why this event was thrown. + /// + /// + /// The trigger. + /// + public ConnectionDataReceivedTrigger Trigger { get; } + + /// + /// Gets a value indicating whether the receive buffer has more bytes available. + /// + /// + /// true if this instance has more available; otherwise, false. + /// + public bool HasMoreAvailable { get; } + + /// + /// Gets the string from the given buffer. + /// + /// The buffer. + /// The encoding. + /// A that contains the results of decoding the specified sequence of bytes. + public static string GetStringFromBuffer(byte[] buffer, Encoding encoding) + => encoding.GetString(buffer).TrimEnd('\r', '\n'); + + /// + /// Gets the string from buffer. + /// + /// The encoding. + /// A that contains the results of decoding the specified sequence of bytes. + public string GetStringFromBuffer(Encoding encoding) + => GetStringFromBuffer(Buffer, encoding); + } +} diff --git a/Unosquare.Swan/Exceptions/DependencyContainerRegistrationException.cs b/Unosquare.Swan/Exceptions/DependencyContainerRegistrationException.cs new file mode 100644 index 0000000..5d13d2c --- /dev/null +++ b/Unosquare.Swan/Exceptions/DependencyContainerRegistrationException.cs @@ -0,0 +1,46 @@ +namespace Unosquare.Swan.Exceptions +{ + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// Generic Constraint Registration Exception. + /// + /// + public class DependencyContainerRegistrationException : Exception + { + private const string ConvertErrorText = "Cannot convert current registration of {0} to {1}"; + private const string RegisterErrorText = + "Cannot register type {0} - abstract classes or interfaces are not valid implementation types for {1}."; + private const string ErrorText = "Duplicate implementation of type {0} found ({1})."; + + /// + /// Initializes a new instance of the class. + /// + /// Type of the register. + /// The types. + public DependencyContainerRegistrationException(Type registerType, IEnumerable types) + : base(string.Format(ErrorText, registerType, GetTypesString(types))) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The type. + /// The method. + /// if set to true [is type factory]. + public DependencyContainerRegistrationException(Type type, string method, bool isTypeFactory = false) + : base(isTypeFactory + ? string.Format(RegisterErrorText, type.FullName, method) + : string.Format(ConvertErrorText, type.FullName, method)) + { + } + + private static string GetTypesString(IEnumerable types) + { + return string.Join(",", types.Select(type => type.FullName)); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Exceptions/DependencyContainerResolutionException.cs b/Unosquare.Swan/Exceptions/DependencyContainerResolutionException.cs new file mode 100644 index 0000000..b74bd8e --- /dev/null +++ b/Unosquare.Swan/Exceptions/DependencyContainerResolutionException.cs @@ -0,0 +1,32 @@ +namespace Unosquare.Swan.Exceptions +{ + using System; + + /// + /// An exception for dependency resolutions. + /// + /// + public class DependencyContainerResolutionException : Exception + { + private const string ErrorText = "Unable to resolve type: {0}"; + + /// + /// Initializes a new instance of the class. + /// + /// The type. + public DependencyContainerResolutionException(Type type) + : base(string.Format(ErrorText, type.FullName)) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The type. + /// The inner exception. + public DependencyContainerResolutionException(Type type, Exception innerException) + : base(string.Format(ErrorText, type.FullName), innerException) + { + } + } +} diff --git a/Unosquare.Swan/Exceptions/DependencyContainerWeakReferenceException.cs b/Unosquare.Swan/Exceptions/DependencyContainerWeakReferenceException.cs new file mode 100644 index 0000000..52a2974 --- /dev/null +++ b/Unosquare.Swan/Exceptions/DependencyContainerWeakReferenceException.cs @@ -0,0 +1,22 @@ +namespace Unosquare.Swan.Exceptions +{ + using System; + + /// + /// Weak Reference Exception. + /// + /// + public class DependencyContainerWeakReferenceException : Exception + { + private const string ErrorText = "Unable to instantiate {0} - referenced object has been reclaimed"; + + /// + /// Initializes a new instance of the class. + /// + /// The type. + public DependencyContainerWeakReferenceException(Type type) + : base(string.Format(ErrorText, type.FullName)) + { + } + } +} diff --git a/Unosquare.Swan/Exceptions/DnsQueryException.cs b/Unosquare.Swan/Exceptions/DnsQueryException.cs new file mode 100644 index 0000000..5ee5264 --- /dev/null +++ b/Unosquare.Swan/Exceptions/DnsQueryException.cs @@ -0,0 +1,40 @@ +namespace Unosquare.Swan.Exceptions +{ + using System; + using Networking; + + /// + /// An exception thrown when the DNS query fails. + /// + /// + public class DnsQueryException : Exception + { + internal DnsQueryException(string message) + : base(message) + { + } + + internal DnsQueryException(string message, Exception e) + : base(message, e) + { + } + + internal DnsQueryException(DnsClient.IDnsResponse response) + : this(response, Format(response)) + { + } + + internal DnsQueryException(DnsClient.IDnsResponse response, string message) + : base(message) + { + Response = response; + } + + internal DnsClient.IDnsResponse Response { get; } + + private static string Format(DnsClient.IDnsResponse response) + { + return $"Invalid response received with code {response.ResponseCode}"; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Exceptions/JsonRequestException.cs b/Unosquare.Swan/Exceptions/JsonRequestException.cs new file mode 100644 index 0000000..0ae0949 --- /dev/null +++ b/Unosquare.Swan/Exceptions/JsonRequestException.cs @@ -0,0 +1,48 @@ +namespace Unosquare.Swan.Exceptions +{ + using System; + + /// + /// Represents errors that occurs requesting a JSON file through HTTP. + /// + /// +#if !NETSTANDARD1_3 + [Serializable] +#endif + public class JsonRequestException + : Exception + { + /// + /// + /// Initializes a new instance of the class. + /// + /// The message. + /// The HTTP error code. + /// Content of the error. + public JsonRequestException(string message, int httpErrorCode = 500, string errorContent = null) + : base(message) + { + HttpErrorCode = httpErrorCode; + HttpErrorContent = errorContent; + } + + /// + /// Gets the HTTP error code. + /// + /// + /// The HTTP error code. + /// + public int HttpErrorCode { get; } + + /// + /// Gets the content of the HTTP error. + /// + /// + /// The content of the HTTP error. + /// + public string HttpErrorContent { get; } + + /// + public override string ToString() => string.IsNullOrEmpty(HttpErrorContent) ? $"HTTP Response Status Code {HttpErrorCode} Error Message: {HttpErrorContent}" : base.ToString(); + } +} diff --git a/Unosquare.Swan/Exceptions/LdapException.cs b/Unosquare.Swan/Exceptions/LdapException.cs new file mode 100644 index 0000000..7575818 --- /dev/null +++ b/Unosquare.Swan/Exceptions/LdapException.cs @@ -0,0 +1,134 @@ +namespace Unosquare.Swan.Exceptions +{ + using System; + using Networking.Ldap; + + /// + /// Thrown to indicate that an Ldap exception has occurred. This is a general + /// exception which includes a message and an Ldap result code. + /// An LdapException can result from physical problems (such as + /// network errors) as well as problems with Ldap operations detected + /// by the server. For example, if an Ldap add operation fails because of a + /// duplicate entry, the server returns a result code. + /// + /// + public class LdapException + : Exception + { + internal const string UnexpectedEnd = "Unexpected end of filter"; + internal const string MissingLeftParen = "Unmatched parentheses, left parenthesis missing"; + internal const string MissingRightParen = "Unmatched parentheses, right parenthesis missing"; + internal const string ExpectingRightParen = "Expecting right parenthesis, found \"{0}\""; + internal const string ExpectingLeftParen = "Expecting left parenthesis, found \"{0}\""; + + private readonly string _serverMessage; + + /// + /// Initializes a new instance of the class. + /// Constructs an exception with a detailed message obtained from the + /// specified MessageOrKey String. + /// Additional parameters specify the result code, the message returned + /// from the server, and a matchedDN returned from the server. + /// The String is used either as a message key to obtain a localized + /// message from ExceptionMessages, or if there is no key in the + /// resource matching the text, it is used as the detailed message itself. + /// + /// The message. + /// The result code returned. + /// Error message specifying additional information + /// from the server. + /// The maximal subset of a specified DN which could + /// be matched by the server on a search operation. + /// The root exception. + public LdapException( + string message, + LdapStatusCode resultCode, + string serverMsg = null, + string matchedDN = null, + Exception rootException = null) + : base(message) + { + ResultCode = resultCode; + Cause = rootException; + MatchedDN = matchedDN; + _serverMessage = serverMsg; + } + + /// + /// Returns the error message from the Ldap server, if this message is + /// available (that is, if this message was set). If the message was not set, + /// this method returns null. + /// + /// + /// The error message or null if the message was not set. + /// + public string LdapErrorMessage => + _serverMessage != null && _serverMessage.Length == 0 ? null : _serverMessage; + + /// + /// Returns the lower level Exception which caused the failure, if any. + /// For example, an IOException with additional information may be returned + /// on a CONNECT_ERROR failure. + /// + /// + /// The cause. + /// + public Exception Cause { get; } + + /// + /// Returns the result code from the exception. + /// The codes are defined as public final static int members + /// of the Ldap Exception class. If the exception is a + /// result of error information returned from a directory operation, the + /// code will be one of those defined for the class. Otherwise, a local error + /// code is returned. + /// + /// + /// The result code. + /// + public LdapStatusCode ResultCode { get; } + + /// + /// Returns the part of a submitted distinguished name which could be + /// matched by the server. + /// If the exception was caused by a local error, such as no server + /// available, the return value is null. If the exception resulted from + /// an operation being executed on a server, the value is an empty string + /// except when the result of the operation was one of the following:. + ///
  • NO_SUCH_OBJECT
  • ALIAS_PROBLEM
  • INVALID_DN_SYNTAX
  • ALIAS_DEREFERENCING_PROBLEM
+ ///
+ /// + /// The matched dn. + /// + public string MatchedDN { get; } + + /// + public override string Message => ResultCode.ToString().Humanize(); + + /// + public override string ToString() + { + // Craft a string from the resource file + var msg = $"{nameof(LdapException)}: {base.Message} ({ResultCode}) {ResultCode.ToString().Humanize()}"; + + // Add server message + if (!string.IsNullOrEmpty(_serverMessage)) + { + msg += $"\r\nServer Message: {_serverMessage}"; + } + + // Add Matched DN message + if (MatchedDN != null) + { + msg += $"\r\nMatched DN: {MatchedDN}"; + } + + if (Cause != null) + { + msg += $"\r\n{Cause}"; + } + + return msg; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Exceptions/SmtpException.cs b/Unosquare.Swan/Exceptions/SmtpException.cs new file mode 100644 index 0000000..37b54b5 --- /dev/null +++ b/Unosquare.Swan/Exceptions/SmtpException.cs @@ -0,0 +1,31 @@ +#if NETSTANDARD1_3 +namespace Unosquare.Swan.Exceptions +{ + using Networking; + + /// + /// Defines an SMTP Exceptions class. + /// + public class SmtpException : System.Exception + { + /// + /// Initializes a new instance of the class with a message. + /// + /// The message. + public SmtpException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The SmtpStatusCode reply. + /// The exception message. + public SmtpException(SmtpStatusCode replyCode, string message) + : base($"{message} ReplyCode: {replyCode}") + { + } + } +} +#endif \ No newline at end of file diff --git a/Unosquare.Swan/Extensions.MimeMessage.cs b/Unosquare.Swan/Extensions.MimeMessage.cs new file mode 100644 index 0000000..e480531 --- /dev/null +++ b/Unosquare.Swan/Extensions.MimeMessage.cs @@ -0,0 +1,55 @@ +#if NET452 || NETSTANDARD2_0 +namespace Unosquare.Swan +{ + using System; + using System.IO; + using System.Net.Mail; + using System.Reflection; + + /// + /// Extension methods. + /// + public static class SmtpExtensions + { + /// + /// The raw contents of this MailMessage as a MemoryStream. + /// + /// The caller. + /// A MemoryStream with the raw contents of this MailMessage. + public static MemoryStream ToMimeMessage(this MailMessage self) + { + if (self == null) + throw new ArgumentNullException(nameof(self)); + + var result = new MemoryStream(); + var mailWriter = MimeMessageConstants.MailWriterConstructor.Invoke(new object[] { result }); + MimeMessageConstants.SendMethod.Invoke( + self, + MimeMessageConstants.PrivateInstanceFlags, + null, + MimeMessageConstants.IsRunningInDotNetFourPointFive ? new[] { mailWriter, true, true } : new[] { mailWriter, true }, + null); + + result = new MemoryStream(result.ToArray()); + MimeMessageConstants.CloseMethod.Invoke( + mailWriter, + MimeMessageConstants.PrivateInstanceFlags, + null, + new object[] { }, + null); + result.Position = 0; + return result; + } + + internal static class MimeMessageConstants + { + public static readonly BindingFlags PrivateInstanceFlags = BindingFlags.Instance | BindingFlags.NonPublic; + public static readonly Type MailWriter = typeof(SmtpClient).Assembly.GetType("System.Net.Mail.MailWriter"); + public static readonly ConstructorInfo MailWriterConstructor = MailWriter.GetConstructor(PrivateInstanceFlags, null, new[] { typeof(Stream) }, null); + public static readonly MethodInfo CloseMethod = MailWriter.GetMethod("Close", PrivateInstanceFlags); + public static readonly MethodInfo SendMethod = typeof(MailMessage).GetMethod("Send", PrivateInstanceFlags); + public static readonly bool IsRunningInDotNetFourPointFive = SendMethod.GetParameters().Length == 3; + } + } +} +#endif diff --git a/Unosquare.Swan/Extensions.Network.cs b/Unosquare.Swan/Extensions.Network.cs new file mode 100644 index 0000000..225a4f4 --- /dev/null +++ b/Unosquare.Swan/Extensions.Network.cs @@ -0,0 +1,58 @@ +namespace Unosquare.Swan +{ + using System; + using System.Linq; + using System.Net; + using System.Net.Sockets; + + /// + /// Provides various extension methods for networking-related tasks. + /// + public static class NetworkExtensions + { + /// + /// Determines whether the IP address is private. + /// + /// The IP address. + /// + /// True if the IP Address is private; otherwise, false. + /// + /// address. + public static bool IsPrivateAddress(this IPAddress address) + { + if (address == null) + throw new ArgumentNullException(nameof(address)); + + var octets = address.ToString().Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries).Select(byte.Parse).ToArray(); + var is24Bit = octets[0] == 10; + var is20Bit = octets[0] == 172 && (octets[1] >= 16 && octets[1] <= 31); + var is16Bit = octets[0] == 192 && octets[1] == 168; + + return is24Bit || is20Bit || is16Bit; + } + + /// + /// Converts an IPv4 Address to its Unsigned, 32-bit integer representation. + /// + /// The address. + /// + /// A 32-bit unsigned integer converted from four bytes at a specified position in a byte array. + /// + /// address. + /// InterNetwork - address. + public static uint ToUInt32(this IPAddress address) + { + if (address == null) + throw new ArgumentNullException(nameof(address)); + + if (address.AddressFamily != AddressFamily.InterNetwork) + throw new ArgumentException($"Address has to be of family '{nameof(AddressFamily.InterNetwork)}'", nameof(address)); + + var addressBytes = address.GetAddressBytes(); + if (BitConverter.IsLittleEndian) + Array.Reverse(addressBytes); + + return BitConverter.ToUInt32(addressBytes, 0); + } + } +} diff --git a/Unosquare.Swan/Extensions.WindowsServices.cs b/Unosquare.Swan/Extensions.WindowsServices.cs new file mode 100644 index 0000000..9fb0fdb --- /dev/null +++ b/Unosquare.Swan/Extensions.WindowsServices.cs @@ -0,0 +1,80 @@ +#if !NETSTANDARD1_3 +namespace Unosquare.Swan +{ + using System; + using System.Collections.Generic; + using System.Reflection; + using System.Threading; +#if NET452 + using System.ServiceProcess; +#else + using Abstractions; +#endif + + /// + /// Extension methods. + /// + public static class WindowsServicesExtensions + { + /// + /// Runs a service in console mode. + /// + /// The service to run. + public static void RunInConsoleMode(this ServiceBase serviceToRun) + { + if (serviceToRun == null) + throw new ArgumentNullException(nameof(serviceToRun)); + + RunInConsoleMode(new[] { serviceToRun }); + } + + /// + /// Runs a set of services in console mode. + /// + /// The services to run. + public static void RunInConsoleMode(this ServiceBase[] servicesToRun) + { + if (servicesToRun == null) + throw new ArgumentNullException(nameof(servicesToRun)); + + const string onStartMethodName = "OnStart"; + const string onStopMethodName = "OnStop"; + + var onStartMethod = typeof(ServiceBase).GetMethod(onStartMethodName, + BindingFlags.Instance | BindingFlags.NonPublic); + var onStopMethod = typeof(ServiceBase).GetMethod(onStopMethodName, + BindingFlags.Instance | BindingFlags.NonPublic); + + var serviceThreads = new List(); + "Starting services . . .".Info(Runtime.EntryAssemblyName.Name); + + foreach (var service in servicesToRun) + { + var thread = new Thread(() => + { + onStartMethod.Invoke(service, new object[] { new string[] { } }); + $"Started service '{service.GetType().Name}'".Info(service.GetType()); + }); + + serviceThreads.Add(thread); + thread.Start(); + } + + "Press any key to stop all services.".Info(Runtime.EntryAssemblyName.Name); + Terminal.ReadKey(true, true); + "Stopping services . . .".Info(Runtime.EntryAssemblyName.Name); + + foreach (var service in servicesToRun) + { + onStopMethod.Invoke(service, null); + $"Stopped service '{service.GetType().Name}'".Info(service.GetType()); + } + + foreach (var thread in serviceThreads) + thread.Join(); + + "Stopped all services.".Info(Runtime.EntryAssemblyName.Name); + } + } +} +#endif \ No newline at end of file diff --git a/Unosquare.Swan/Formatters/BitmapBuffer.cs b/Unosquare.Swan/Formatters/BitmapBuffer.cs new file mode 100644 index 0000000..180a127 --- /dev/null +++ b/Unosquare.Swan/Formatters/BitmapBuffer.cs @@ -0,0 +1,179 @@ +#if NET452 +namespace Unosquare.Swan.Formatters +{ + using System; + using System.Drawing; + using System.Drawing.Imaging; + using System.Runtime.InteropServices; + using System.Threading.Tasks; + + /// + /// Represents a buffer of bytes containing pixels in BGRA byte order + /// loaded from an image that is passed on to the constructor. + /// Data contains all the raw bytes (without scanline left-over bytes) + /// where they can be quickly changed and then a new bitmap + /// can be created from the byte data. + /// + public class BitmapBuffer + { + /// + /// A constant representing the number of + /// bytes per pixel in the pixel data. This is + /// always 4 but it is kept here for readability. + /// + public const int BytesPerPixel = 4; + + /// + /// The blue byte offset within a pixel offset. This is 0. + /// + public const int BOffset = 0; + + /// + /// The green byte offset within a pixel offset. This is 1. + /// + public const int GOffset = 1; + + /// + /// The red byte offset within a pixel offset. This is 2. + /// + public const int ROffset = 2; + + /// + /// The alpha byte offset within a pixel offset. This is 3. + /// + public const int AOffset = 3; + + /// + /// Initializes a new instance of the class. + /// Data will not contain left-over stride bytes + /// + /// The source image. + public BitmapBuffer(Image sourceImage) + { + // Acquire or create the source bitmap in a manageable format + var disposeSourceBitmap = false; + if (!(sourceImage is Bitmap sourceBitmap) || sourceBitmap.PixelFormat != PixelFormat) + { + sourceBitmap = new Bitmap(sourceImage.Width, sourceImage.Height, PixelFormat); + using (var g = Graphics.FromImage(sourceBitmap)) + { + g.DrawImage(sourceImage, 0, 0); + } + + // We created this bitmap. Make sure we clear it from memory + disposeSourceBitmap = true; + } + + // Lock the bits + var sourceDataLocker = sourceBitmap.LockBits( + new Rectangle(0, 0, sourceBitmap.Width, sourceBitmap.Height), + ImageLockMode.ReadOnly, + sourceBitmap.PixelFormat); + + // Set basic properties + ImageWidth = sourceBitmap.Width; + ImageHeight = sourceBitmap.Height; + LineStride = sourceDataLocker.Stride; + + // State variables + LineLength = sourceBitmap.Width * BytesPerPixel; // may or may not be equal to the Stride + Data = new byte[LineLength * sourceBitmap.Height]; + + // copy line by line in order to ignore the useless left-over stride + Parallel.For(0, sourceBitmap.Height, y => + { + var sourceAddress = sourceDataLocker.Scan0 + (sourceDataLocker.Stride * y); + var targetAddress = y * LineLength; + Marshal.Copy(sourceAddress, Data, targetAddress, LineLength); + }); + + // finally unlock the bitmap + sourceBitmap.UnlockBits(sourceDataLocker); + + // dispose the source bitmap if we had to create it + if (disposeSourceBitmap) + { + sourceBitmap.Dispose(); + } + } + + /// + /// Contains all the bytes of the pixel data + /// Each horizontal scanline is represented by LineLength + /// rather than by LinceStride. The left-over stride bytes + /// are removed. + /// + public byte[] Data { get; } + + /// + /// Gets the width of the image. + /// + public int ImageWidth { get; } + + /// + /// Gets the height of the image. + /// + public int ImageHeight { get; } + + /// + /// Gets the pixel format. This will always be Format32bppArgb. + /// + public PixelFormat PixelFormat { get; } = PixelFormat.Format32bppArgb; + + /// + /// Gets the length in bytes of a line of pixel data. + /// Basically the same as Line Length except Stride might be a little larger as + /// some bitmaps might be DWORD-algned. + /// + public int LineStride { get; } + + /// + /// Gets the length in bytes of a line of pixel data. + /// Basically the same as Stride except Stride might be a little larger as + /// some bitmaps might be DWORD-algned. + /// + public int LineLength { get; } + + /// + /// Gets the index of the first byte in the BGRA pixel data for the given image coordinates. + /// + /// The x. + /// The y. + /// Index of the first byte in the BGRA pixel. + /// + /// x + /// or + /// y. + /// + public int GetPixelOffset(int x, int y) + { + if (x < 0 || x > ImageWidth) throw new ArgumentOutOfRangeException(nameof(x)); + if (y < 0 || y > ImageHeight) throw new ArgumentOutOfRangeException(nameof(y)); + + return (y * LineLength) + (x * BytesPerPixel); + } + + /// + /// Converts the pixel data bytes held in the buffer + /// to a 32-bit RGBA bitmap. + /// + /// Pixel data for a graphics image and its attribute. + public Bitmap ToBitmap() + { + var bitmap = new Bitmap(ImageWidth, ImageHeight, PixelFormat); + var bitLocker = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, bitmap.PixelFormat); + + Parallel.For(0, bitmap.Height, y => + { + var sourceOffset = GetPixelOffset(0, y); + var targetOffset = bitLocker.Scan0 + (y * bitLocker.Stride); + Marshal.Copy(Data, sourceOffset, targetOffset, bitLocker.Width); + }); + + bitmap.UnlockBits(bitLocker); + + return bitmap; + } + } +} +#endif \ No newline at end of file diff --git a/Unosquare.Swan/Models/OkOrError.cs b/Unosquare.Swan/Models/OkOrError.cs new file mode 100644 index 0000000..dbc1cac --- /dev/null +++ b/Unosquare.Swan/Models/OkOrError.cs @@ -0,0 +1,48 @@ +namespace Unosquare.Swan.Models +{ + /// + /// Represents a Ok value or Error value. + /// + /// The type of OK value. + /// The type of the error. + public class OkOrError + { + /// + /// Gets or sets a value indicating whether this instance is Ok. + /// + /// + /// true if this instance is ok; otherwise, false. + /// + public bool IsOk => !Equals(Ok, default(T)); + + /// + /// Gets or sets the ok. + /// + /// + /// The ok. + /// + public T Ok { get; set; } + + /// + /// Gets or sets the error. + /// + /// + /// The error. + /// + public TError Error { get; set; } + + /// + /// Creates a new OkOrError from the specified Ok object. + /// + /// The ok. + /// OkOrError instance. + public static OkOrError FromOk(T ok) => new OkOrError { Ok = ok }; + + /// + /// Creates a new OkOrError from the specified Error object. + /// + /// The error. + /// OkOrError instance. + public static OkOrError FromError(TError error) => new OkOrError { Error = error }; + } +} diff --git a/Unosquare.Swan/Network.cs b/Unosquare.Swan/Network.cs new file mode 100644 index 0000000..945e114 --- /dev/null +++ b/Unosquare.Swan/Network.cs @@ -0,0 +1,450 @@ +namespace Unosquare.Swan +{ + using Networking; + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using System.Net.Http; + using System.Net.NetworkInformation; + using System.Net.Sockets; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Provides miscellaneous network utilities such as a Public IP finder, + /// a DNS client to query DNS records of any kind, and an NTP client. + /// + public static class Network + { + /// + /// The DNS default port. + /// + public const int DnsDefaultPort = 53; + + /// + /// The NTP default port. + /// + public const int NtpDefaultPort = 123; + + /// + /// Gets the name of the host. + /// + /// + /// The name of the host. + /// + public static string HostName => IPGlobalProperties.GetIPGlobalProperties().HostName; + + /// + /// Gets the name of the network domain. + /// + /// + /// The name of the network domain. + /// + public static string DomainName => IPGlobalProperties.GetIPGlobalProperties().DomainName; + + #region IP Addresses and Adapters Information Methods + + /// + /// Gets the active IPv4 interfaces. + /// Only those interfaces with a valid unicast address and a valid gateway will be returned in the collection. + /// + /// + /// A collection of NetworkInterface/IPInterfaceProperties pairs + /// that represents the active IPv4 interfaces. + /// + public static Dictionary GetIPv4Interfaces() + { + // zero conf ip address + var zeroConf = new IPAddress(0); + + var adapters = NetworkInterface.GetAllNetworkInterfaces() + .Where(network => + network.OperationalStatus == OperationalStatus.Up + && network.NetworkInterfaceType != NetworkInterfaceType.Unknown + && network.NetworkInterfaceType != NetworkInterfaceType.Loopback) + .ToArray(); + + var result = new Dictionary(); + + foreach (var adapter in adapters) + { + var properties = adapter.GetIPProperties(); + if (properties == null + || properties.GatewayAddresses.Count == 0 + || properties.GatewayAddresses.All(gateway => Equals(gateway.Address, zeroConf)) + || properties.UnicastAddresses.Count == 0 + || properties.GatewayAddresses.All(address => Equals(address.Address, zeroConf)) + || properties.UnicastAddresses.Any(a => a.Address.AddressFamily == AddressFamily.InterNetwork) == + false) + continue; + + result[adapter] = properties; + } + + return result; + } + + /// + /// Retrieves the local ip addresses. + /// + /// if set to true [include loopback]. + /// An array of local ip addresses. + public static IPAddress[] GetIPv4Addresses(bool includeLoopback = true) => + GetIPv4Addresses(NetworkInterfaceType.Unknown, true, includeLoopback); + + /// + /// Retrieves the local ip addresses. + /// + /// Type of the interface. + /// if set to true [skip type filter]. + /// if set to true [include loopback]. + /// An array of local ip addresses. + public static IPAddress[] GetIPv4Addresses( + NetworkInterfaceType interfaceType, + bool skipTypeFilter = false, + bool includeLoopback = false) + { + var addressList = new List(); + var interfaces = NetworkInterface.GetAllNetworkInterfaces() + .Where(ni => +#if NET452 + ni.IsReceiveOnly == false && +#endif + (skipTypeFilter || ni.NetworkInterfaceType == interfaceType) && + ni.OperationalStatus == OperationalStatus.Up) + .ToArray(); + + foreach (var networkInterface in interfaces) + { + var properties = networkInterface.GetIPProperties(); + + if (properties.GatewayAddresses.All(g => g.Address.AddressFamily != AddressFamily.InterNetwork)) + continue; + + addressList.AddRange(properties.UnicastAddresses + .Where(i => i.Address.AddressFamily == AddressFamily.InterNetwork) + .Select(i => i.Address)); + } + + if (includeLoopback || interfaceType == NetworkInterfaceType.Loopback) + addressList.Add(IPAddress.Loopback); + + return addressList.ToArray(); + } + + /// + /// Gets the public IP address using ipify.org. + /// + /// The cancellation token. + /// A public IP address of the result produced by this Task. + public static async Task GetPublicIPAddressAsync(CancellationToken ct = default) + { + using (var client = new HttpClient()) + { + var response = await client.GetAsync("https://api.ipify.org", ct).ConfigureAwait(false); + return IPAddress.Parse(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); + } + } + + /// + /// Gets the public IP address using ipify.org. + /// + /// A public ip address. + public static IPAddress GetPublicIPAddress() => GetPublicIPAddressAsync().GetAwaiter().GetResult(); + + /// + /// Gets the configured IPv4 DNS servers for the active network interfaces. + /// + /// + /// A collection of NetworkInterface/IPInterfaceProperties pairs + /// that represents the active IPv4 interfaces. + /// + public static IPAddress[] GetIPv4DnsServers() + => GetIPv4Interfaces() + .Select(a => a.Value.DnsAddresses.Where(d => d.AddressFamily == AddressFamily.InterNetwork)) + .SelectMany(d => d) + .ToArray(); + + #endregion + + #region DNS and NTP Clients + + /// + /// Gets the DNS host entry (a list of IP addresses) for the domain name. + /// + /// The FQDN. + /// An array of local ip addresses. + public static IPAddress[] GetDnsHostEntry(string fqdn) + { + var dnsServer = GetIPv4DnsServers().FirstOrDefault() ?? IPAddress.Parse("8.8.8.8"); + return GetDnsHostEntry(fqdn, dnsServer, DnsDefaultPort); + } + + /// + /// Gets the DNS host entry (a list of IP addresses) for the domain name. + /// + /// The FQDN. + /// The cancellation token. + /// An array of local ip addresses of the result produced by this task. + public static Task GetDnsHostEntryAsync(string fqdn, + CancellationToken ct = default) + { + return Task.Run(() => GetDnsHostEntry(fqdn), ct); + } + + /// + /// Gets the DNS host entry (a list of IP addresses) for the domain name. + /// + /// The FQDN. + /// The DNS server. + /// The port. + /// + /// An array of local ip addresses. + /// + /// fqdn. + public static IPAddress[] GetDnsHostEntry(string fqdn, IPAddress dnsServer, int port) + { + if (fqdn == null) + throw new ArgumentNullException(nameof(fqdn)); + + if (fqdn.IndexOf(".", StringComparison.Ordinal) == -1) + { + fqdn += "." + IPGlobalProperties.GetIPGlobalProperties().DomainName; + } + + while (true) + { + if (fqdn.EndsWith(".") == false) break; + + fqdn = fqdn.Substring(0, fqdn.Length - 1); + } + + var client = new DnsClient(dnsServer, port); + var result = client.Lookup(fqdn); + return result.ToArray(); + } + + /// + /// Gets the DNS host entry (a list of IP addresses) for the domain name. + /// + /// The FQDN. + /// The DNS server. + /// The port. + /// The cancellation token. + /// An array of local ip addresses of the result produced by this task. + public static Task GetDnsHostEntryAsync( + string fqdn, + IPAddress dnsServer, + int port, + CancellationToken ct = default) + { + return Task.Run(() => GetDnsHostEntry(fqdn, dnsServer, port), ct); + } + + /// + /// Gets the reverse lookup FQDN of the given IP Address. + /// + /// The query. + /// The DNS server. + /// The port. + /// A that represents the current object. + public static string GetDnsPointerEntry(IPAddress query, IPAddress dnsServer, int port) => new DnsClient(dnsServer, port).Reverse(query); + + /// + /// Gets the reverse lookup FQDN of the given IP Address. + /// + /// The query. + /// The DNS server. + /// The port. + /// The cancellation token. + /// A that represents the current object. + public static Task GetDnsPointerEntryAsync( + IPAddress query, + IPAddress dnsServer, + int port, + CancellationToken ct = default) + { + return Task.Run(() => GetDnsPointerEntry(query, dnsServer, port), ct); + } + + /// + /// Gets the reverse lookup FQDN of the given IP Address. + /// + /// The query. + /// A that represents the current object. + public static string GetDnsPointerEntry(IPAddress query) => new DnsClient(GetIPv4DnsServers().FirstOrDefault()).Reverse(query); + + /// + /// Gets the reverse lookup FQDN of the given IP Address. + /// + /// The query. + /// The cancellation token. + /// A that represents the current object. + public static Task GetDnsPointerEntryAsync( + IPAddress query, + CancellationToken ct = default) + { + return Task.Run(() => GetDnsPointerEntry(query), ct); + } + + /// + /// Queries the DNS server for the specified record type. + /// + /// The query. + /// Type of the record. + /// The DNS server. + /// The port. + /// + /// Appropriate DNS server for the specified record type. + /// + public static DnsQueryResult QueryDns(string query, DnsRecordType recordType, IPAddress dnsServer, int port) + { + if (query == null) + throw new ArgumentNullException(nameof(query)); + + var response = new DnsClient(dnsServer, port).Resolve(query, recordType); + return new DnsQueryResult(response); + } + + /// + /// Queries the DNS server for the specified record type. + /// + /// The query. + /// Type of the record. + /// The DNS server. + /// The port. + /// The cancellation token. + /// Queries the DNS server for the specified record type of the result produced by this Task. + public static Task QueryDnsAsync( + string query, + DnsRecordType recordType, + IPAddress dnsServer, + int port, + CancellationToken ct = default) + { + return Task.Run(() => QueryDns(query, recordType, dnsServer, port), ct); + } + + /// + /// Queries the DNS server for the specified record type. + /// + /// The query. + /// Type of the record. + /// Appropriate DNS server for the specified record type. + public static DnsQueryResult QueryDns(string query, DnsRecordType recordType) => QueryDns(query, recordType, GetIPv4DnsServers().FirstOrDefault(), DnsDefaultPort); + + /// + /// Queries the DNS server for the specified record type. + /// + /// The query. + /// Type of the record. + /// The cancellation token. + /// Queries the DNS server for the specified record type of the result produced by this Task. + public static Task QueryDnsAsync( + string query, + DnsRecordType recordType, + CancellationToken ct = default) + { + return Task.Run(() => QueryDns(query, recordType), ct); + } + + /// + /// Gets the UTC time by querying from an NTP server. + /// + /// The NTP server address. + /// The port. + /// + /// A new instance of the DateTime structure to + /// the specified year, month, day, hour, minute and second. + /// + public static DateTime GetNetworkTimeUtc(IPAddress ntpServerAddress, int port = NtpDefaultPort) + { + if (ntpServerAddress == null) + throw new ArgumentNullException(nameof(ntpServerAddress)); + + // NTP message size - 16 bytes of the digest (RFC 2030) + var ntpData = new byte[48]; + + // Setting the Leap Indicator, Version Number and Mode values + ntpData[0] = 0x1B; // LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode) + + // The UDP port number assigned to NTP is 123 + var endPoint = new IPEndPoint(ntpServerAddress, port); + var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); + + socket.Connect(endPoint); + socket.ReceiveTimeout = 3000; // Stops code hang if NTP is blocked + socket.Send(ntpData); + socket.Receive(ntpData); + socket.Dispose(); + + // Offset to get to the "Transmit Timestamp" field (time at which the reply + // departed the server for the client, in 64-bit timestamp format." + const byte serverReplyTime = 40; + + // Get the seconds part + ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime); + + // Get the seconds fraction + ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4); + + // Convert From big-endian to little-endian to match the platform + if (BitConverter.IsLittleEndian) + { + intPart = intPart.SwapEndianness(); + fractPart = intPart.SwapEndianness(); + } + + var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L); + + // The time is given in UTC + return new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddMilliseconds((long) milliseconds); + } + + /// + /// Gets the UTC time by querying from an NTP server. + /// + /// The NTP server, by default pool.ntp.org. + /// The port, by default NTP 123. + /// The UTC time by querying from an NTP server. + public static DateTime GetNetworkTimeUtc(string ntpServerName = "pool.ntp.org", + int port = NtpDefaultPort) + { + var addresses = GetDnsHostEntry(ntpServerName); + return GetNetworkTimeUtc(addresses.First(), port); + } + + /// + /// Gets the UTC time by querying from an NTP server. + /// + /// The NTP server address. + /// The port. + /// The cancellation token. + /// The UTC time by querying from an NTP server of the result produced by this Task. + public static Task GetNetworkTimeUtcAsync( + IPAddress ntpServerAddress, + int port = NtpDefaultPort, + CancellationToken ct = default) + { + return Task.Run(() => GetNetworkTimeUtc(ntpServerAddress, port), ct); + } + + /// + /// Gets the UTC time by querying from an NTP server. + /// + /// Name of the NTP server. + /// The port. + /// The cancellation token. + /// The UTC time by querying from an NTP server of the result produced by this Task. + public static Task GetNetworkTimeUtcAsync( + string ntpServerName = "pool.ntp.org", + int port = NtpDefaultPort, + CancellationToken ct = default) + { + return Task.Run(() => GetNetworkTimeUtc(ntpServerName, port), ct); + } + + #endregion + } +} diff --git a/Unosquare.Swan/Networking/Connection.cs b/Unosquare.Swan/Networking/Connection.cs new file mode 100644 index 0000000..f30b42e --- /dev/null +++ b/Unosquare.Swan/Networking/Connection.cs @@ -0,0 +1,892 @@ +namespace Unosquare.Swan.Networking +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Security; + using System.Net.Sockets; + using System.Security.Cryptography.X509Certificates; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Represents a network connection either on the server or on the client. It wraps a TcpClient + /// and its corresponding network streams. It is capable of working in 2 modes. Typically on the server side + /// you will need to enable continuous reading and events. On the client side you may want to disable continuous reading + /// and use the Read methods available. In continuous reading mode Read methods are not available and will throw + /// an invalid operation exceptions if they are used. + /// Continuous Reading Mode: Subscribe to data reception events, it runs a background thread, don't use Read methods + /// Manual Reading Mode: Data reception events are NEVER fired. No background threads are used. Use Read methods to receive data. + /// + /// + /// + /// The following code explains how to create a TCP server. + /// + /// using System.Text; + /// using Unosquare.Swan.Networking; + /// + /// class Example + /// { + /// static void Main() + /// { + /// // create a new connection listener on a specific port + /// var connectionListener = new ConnectionListener(1337); + /// + /// // handle the OnConnectionAccepting event + /// connectionListener.OnConnectionAccepted += (s, e) => + /// { + /// // create a new connection + /// using (var con = new Connection(e.Client)) + /// { + /// con.WriteLineAsync("Hello world!").Wait(); + /// } + /// }; + /// + /// connectionListener.Start(); + /// } + /// } + /// + /// The following code describes how to create a TCP client. + /// + /// using System.Net.Sockets; + /// using System.Text; + /// using System.Threading.Tasks; + /// using Unosquare.Swan.Networking; + /// + /// class Example + /// { + /// static async Task Main() + /// { + /// // create a new TcpClient object + /// var client = new TcpClient(); + /// + /// // connect to a specific address and port + /// client.Connect("localhost", 1337); + /// + /// //create a new connection with specific encoding, + /// //new line sequence and continuous reading disabled + /// using (var cn = new Connection(client, Encoding.UTF8, "\r\n", true, 0)) + /// { + /// var response = await cn.ReadTextAsync(); + /// } + /// } + /// } + /// + /// + public sealed class Connection : IDisposable + { + // New Line definitions for reading. This applies to both, events and read methods + private readonly string _newLineSequence; + + private readonly byte[] _newLineSequenceBytes; + private readonly char[] _newLineSequenceChars; + private readonly string[] _newLineSequenceLineSplitter; + private readonly byte[] _receiveBuffer; + private readonly TimeSpan _continuousReadingInterval = TimeSpan.FromMilliseconds(5); + private readonly Queue _readLineBuffer = new Queue(); + private readonly ManualResetEvent _writeDone = new ManualResetEvent(true); + + // Disconnect and Dispose + private bool _hasDisposed; + + private int _disconnectCalls; + + // Continuous Reading + private Thread _continuousReadingThread; + + private int _receiveBufferPointer; + + // Reading and writing + private Task _readTask; + + /// + /// Initializes a new instance of the class. + /// + /// The client. + /// The text encoding. + /// The new line sequence used for read and write operations. + /// if set to true [disable continuous reading]. + /// Size of the block. -- set to 0 or less to disable. + public Connection( + TcpClient client, + Encoding textEncoding, + string newLineSequence, + bool disableContinuousReading, + int blockSize) + { + // Setup basic properties + Id = Guid.NewGuid(); + TextEncoding = textEncoding; + + // Setup new line sequence + if (string.IsNullOrEmpty(newLineSequence)) + throw new ArgumentException("Argument cannot be null", nameof(newLineSequence)); + + _newLineSequence = newLineSequence; + _newLineSequenceBytes = TextEncoding.GetBytes(_newLineSequence); + _newLineSequenceChars = _newLineSequence.ToCharArray(); + _newLineSequenceLineSplitter = new[] { _newLineSequence }; + + // Setup Connection timers + ConnectionStartTimeUtc = DateTime.UtcNow; + DataReceivedLastTimeUtc = ConnectionStartTimeUtc; + DataSentLastTimeUtc = ConnectionStartTimeUtc; + + // Setup connection properties + RemoteClient = client; + LocalEndPoint = client.Client.LocalEndPoint as IPEndPoint; + NetworkStream = RemoteClient.GetStream(); + RemoteEndPoint = RemoteClient.Client.RemoteEndPoint as IPEndPoint; + + // Setup buffers + _receiveBuffer = new byte[RemoteClient.ReceiveBufferSize * 2]; + ProtocolBlockSize = blockSize; + _receiveBufferPointer = 0; + + // Setup continuous reading mode if enabled + if (disableContinuousReading) return; + +#if NETSTANDARD1_3 + ThreadPool.QueueUserWorkItem(PerformContinuousReading, this); +#else + ThreadPool.GetAvailableThreads(out var availableWorkerThreads, out _); + ThreadPool.GetMaxThreads(out var maxWorkerThreads, out var _); + + var activeThreadPoolTreads = maxWorkerThreads - availableWorkerThreads; + + if (activeThreadPoolTreads < Environment.ProcessorCount / 4) + { + ThreadPool.QueueUserWorkItem(PerformContinuousReading, this); + } + else + { + new Thread(PerformContinuousReading) { IsBackground = true }.Start(); + } +#endif + } + + /// + /// Initializes a new instance of the class in continuous reading mode. + /// It uses UTF8 encoding, CRLF as a new line sequence and disables a protocol block size. + /// + /// The client. + public Connection(TcpClient client) + : this(client, Encoding.UTF8, "\r\n", false, 0) + { + // placeholder + } + + /// + /// Initializes a new instance of the class in continuous reading mode. + /// It uses UTF8 encoding, disables line sequences, and uses a protocol block size instead. + /// + /// The client. + /// Size of the block. + public Connection(TcpClient client, int blockSize) + : this(client, Encoding.UTF8, new string('\n', blockSize + 1), false, blockSize) + { + // placeholder + } + + #region Events + + /// + /// Occurs when the receive buffer has encounters a new line sequence, the buffer is flushed or the buffer is full. + /// + public event EventHandler DataReceived = (s, e) => { }; + + /// + /// Occurs when an error occurs while upgrading, sending, or receiving data in this client + /// + public event EventHandler ConnectionFailure = (s, e) => { }; + + /// + /// Occurs when a client is disconnected + /// + public event EventHandler ClientDisconnected = (s, e) => { }; + + #endregion + + #region Properties + + /// + /// Gets the unique identifier of this connection. + /// This field is filled out upon instantiation of this class. + /// + /// + /// The identifier. + /// + public Guid Id { get; } + + /// + /// Gets the active stream. Returns an SSL stream if the connection is secure, otherwise returns + /// the underlying NetworkStream. + /// + /// + /// The active stream. + /// + public Stream ActiveStream => SecureStream ?? NetworkStream as Stream; + + /// + /// Gets a value indicating whether the current connection stream is an SSL stream. + /// + /// + /// true if this instance is active stream secure; otherwise, false. + /// + public bool IsActiveStreamSecure => SecureStream != null; + + /// + /// Gets the text encoding for send and receive operations. + /// + /// + /// The text encoding. + /// + public Encoding TextEncoding { get; } + + /// + /// Gets the remote end point of this TCP connection. + /// + /// + /// The remote end point. + /// + public IPEndPoint RemoteEndPoint { get; } + + /// + /// Gets the local end point of this TCP connection. + /// + /// + /// The local end point. + /// + public IPEndPoint LocalEndPoint { get; } + + /// + /// Gets the remote client of this TCP connection. + /// + /// + /// The remote client. + /// + public TcpClient RemoteClient { get; private set; } + + /// + /// When in continuous reading mode, and if set to greater than 0, + /// a Data reception event will be fired whenever the amount of bytes + /// determined by this property has been received. Useful for fixed-length message protocols. + /// + /// + /// The size of the protocol block. + /// + public int ProtocolBlockSize { get; } + + /// + /// Gets a value indicating whether this connection is in continuous reading mode. + /// Remark: Whenever a disconnect event occurs, the background thread is terminated + /// and this property will return false whenever the reading thread is not active. + /// Therefore, even if continuous reading was not disabled in the constructor, this property + /// might return false. + /// + /// + /// true if this instance is continuous reading enabled; otherwise, false. + /// + public bool IsContinuousReadingEnabled => _continuousReadingThread != null; + + /// + /// Gets the start time at which the connection was started in UTC. + /// + /// + /// The connection start time UTC. + /// + public DateTime ConnectionStartTimeUtc { get; } + + /// + /// Gets the start time at which the connection was started in local time. + /// + /// + /// The connection start time. + /// + public DateTime ConnectionStartTime => ConnectionStartTimeUtc.ToLocalTime(); + + /// + /// Gets the duration of the connection. + /// + /// + /// The duration of the connection. + /// + public TimeSpan ConnectionDuration => DateTime.UtcNow.Subtract(ConnectionStartTimeUtc); + + /// + /// Gets the last time data was received at in UTC. + /// + /// + /// The data received last time UTC. + /// + public DateTime DataReceivedLastTimeUtc { get; private set; } + + /// + /// Gets how long has elapsed since data was last received. + /// + public TimeSpan DataReceivedIdleDuration => DateTime.UtcNow.Subtract(DataReceivedLastTimeUtc); + + /// + /// Gets the last time at which data was sent in UTC. + /// + /// + /// The data sent last time UTC. + /// + public DateTime DataSentLastTimeUtc { get; private set; } + + /// + /// Gets how long has elapsed since data was last sent. + /// + /// + /// The duration of the data sent idle. + /// + public TimeSpan DataSentIdleDuration => DateTime.UtcNow.Subtract(DataSentLastTimeUtc); + + /// + /// Gets a value indicating whether this connection is connected. + /// Remarks: This property polls the socket internally and checks if it is available to read data from it. + /// If disconnect has been called, then this property will return false. + /// + /// + /// true if this instance is connected; otherwise, false. + /// + public bool IsConnected + { + get + { + if (_disconnectCalls > 0) + return false; + + try + { + var socket = RemoteClient.Client; + var pollResult = !((socket.Poll(1000, SelectMode.SelectRead) + && (NetworkStream.DataAvailable == false)) || !socket.Connected); + + if (pollResult == false) + Disconnect(); + + return pollResult; + } + catch + { + Disconnect(); + return false; + } + } + } + + private NetworkStream NetworkStream { get; set; } + + private SslStream SecureStream { get; set; } + + #endregion + + #region Read Methods + + /// + /// Reads data from the remote client asynchronously and with the given timeout. + /// + /// The timeout. + /// The cancellation token. + /// A byte array containing the results of encoding the specified set of characters. + /// Read methods have been disabled because continuous reading is enabled. + /// Reading data from {ActiveStream} timed out in {timeout.TotalMilliseconds} m. + public async Task ReadDataAsync(TimeSpan timeout, CancellationToken ct = default) + { + if (IsContinuousReadingEnabled) + { + throw new InvalidOperationException( + "Read methods have been disabled because continuous reading is enabled."); + } + + if (RemoteClient == null) + { + throw new InvalidOperationException("An open connection is required"); + } + + var receiveBuffer = new byte[RemoteClient.ReceiveBufferSize * 2]; + var receiveBuilder = new List(receiveBuffer.Length); + + try + { + var startTime = DateTime.UtcNow; + + while (receiveBuilder.Count <= 0) + { + if (DateTime.UtcNow.Subtract(startTime) >= timeout) + { + throw new TimeoutException( + $"Reading data from {ActiveStream} timed out in {timeout.TotalMilliseconds} ms"); + } + + if (_readTask == null) + _readTask = ActiveStream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length, ct); + + if (_readTask.Wait(_continuousReadingInterval)) + { + var bytesReceivedCount = _readTask.Result; + if (bytesReceivedCount > 0) + { + DataReceivedLastTimeUtc = DateTime.UtcNow; + var buffer = new byte[bytesReceivedCount]; + Array.Copy(receiveBuffer, 0, buffer, 0, bytesReceivedCount); + receiveBuilder.AddRange(buffer); + } + + _readTask = null; + } + else + { + await Task.Delay(_continuousReadingInterval, ct).ConfigureAwait(false); + } + } + } + catch (Exception ex) + { + ex.Error(typeof(Connection).FullName, "Error while reading network stream data asynchronously."); + throw; + } + + return receiveBuilder.ToArray(); + } + + /// + /// Reads data asynchronously from the remote stream with a 5000 millisecond timeout. + /// + /// The cancellation token. + /// A byte array containing the results the specified sequence of bytes. + public Task ReadDataAsync(CancellationToken ct = default) + => ReadDataAsync(TimeSpan.FromSeconds(5), ct); + + /// + /// Asynchronously reads data as text with the given timeout. + /// + /// The timeout. + /// The cancellation token. + /// A that contains the results of decoding the specified sequence of bytes. + public async Task ReadTextAsync(TimeSpan timeout, CancellationToken ct = default) + { + var buffer = await ReadDataAsync(timeout, ct).ConfigureAwait(false); + return buffer == null ? null : TextEncoding.GetString(buffer); + } + + /// + /// Asynchronously reads data as text with a 5000 millisecond timeout. + /// + /// The cancellation token. + /// When this method completes successfully, it returns the contents of the file as a text string. + public Task ReadTextAsync(CancellationToken ct = default) + => ReadTextAsync(TimeSpan.FromSeconds(5), ct); + + /// + /// Performs the same task as this method's overload but it defaults to a read timeout of 30 seconds. + /// + /// The cancellation token. + /// + /// A task that represents the asynchronous read operation. The value of the TResult parameter + /// contains the next line from the stream, or is null if all the characters have been read. + /// + public Task ReadLineAsync(CancellationToken ct = default) + => ReadLineAsync(TimeSpan.FromSeconds(30), ct); + + /// + /// Reads the next available line of text in queue. Return null when no text is read. + /// This method differs from the rest of the read methods because it keeps an internal + /// queue of lines that are read from the stream and only returns the one line next in the queue. + /// It is only recommended to use this method when you are working with text-based protocols + /// and the rest of the read methods are not called. + /// + /// The timeout. + /// The cancellation token. + /// A task with a string line from the queue. + /// Read methods have been disabled because continuous reading is enabled. + public async Task ReadLineAsync(TimeSpan timeout, CancellationToken ct = default) + { + if (IsContinuousReadingEnabled) + { + throw new InvalidOperationException( + "Read methods have been disabled because continuous reading is enabled."); + } + + if (_readLineBuffer.Count > 0) + return _readLineBuffer.Dequeue(); + + var builder = new StringBuilder(); + + while (true) + { + var text = await ReadTextAsync(timeout, ct).ConfigureAwait(false); + if (text.Length == 0) + break; + + builder.Append(text); + + if (text.EndsWith(_newLineSequence) == false) continue; + + var lines = builder.ToString().TrimEnd(_newLineSequenceChars) + .Split(_newLineSequenceLineSplitter, StringSplitOptions.None); + foreach (var item in lines) + _readLineBuffer.Enqueue(item); + + break; + } + + return _readLineBuffer.Count > 0 ? _readLineBuffer.Dequeue() : null; + } + + #endregion + + #region Write Methods + + /// + /// Writes data asynchronously. + /// + /// The buffer. + /// if set to true [force flush]. + /// The cancellation token. + /// A task that represents the asynchronous write operation. + public async Task WriteDataAsync(byte[] buffer, bool forceFlush, CancellationToken ct = default) + { + try + { + _writeDone.WaitOne(); + _writeDone.Reset(); + await ActiveStream.WriteAsync(buffer, 0, buffer.Length, ct).ConfigureAwait(false); + if (forceFlush) + await ActiveStream.FlushAsync(ct).ConfigureAwait(false); + + DataSentLastTimeUtc = DateTime.UtcNow; + } + finally + { + _writeDone.Set(); + } + } + + /// + /// Writes text asynchronously. + /// + /// The text. + /// The cancellation token. + /// A task that represents the asynchronous write operation. + public Task WriteTextAsync(string text, CancellationToken ct = default) + => WriteTextAsync(text, TextEncoding, ct); + + /// + /// Writes text asynchronously. + /// + /// The text. + /// The encoding. + /// The cancellation token. + /// A task that represents the asynchronous write operation. + public Task WriteTextAsync(string text, Encoding encoding, CancellationToken ct = default) + => WriteDataAsync(encoding.GetBytes(text), true, ct); + + /// + /// Writes a line of text asynchronously. + /// The new line sequence is added automatically at the end of the line. + /// + /// The line. + /// The encoding. + /// The cancellation token. + /// A task that represents the asynchronous write operation. + public Task WriteLineAsync(string line, Encoding encoding, CancellationToken ct = default) + => WriteDataAsync(encoding.GetBytes($"{line}{_newLineSequence}"), true, ct); + + /// + /// Writes a line of text asynchronously. + /// The new line sequence is added automatically at the end of the line. + /// + /// The line. + /// The cancellation token. + /// A task that represents the asynchronous write operation. + public Task WriteLineAsync(string line, CancellationToken ct = default) + => WriteLineAsync(line, TextEncoding, ct); + + #endregion + + #region Socket Methods + + /// + /// Upgrades the active stream to an SSL stream if this connection object is hosted in the server. + /// + /// The server certificate. + /// true if the object is hosted in the server; otherwise, false. + public async Task UpgradeToSecureAsServerAsync(X509Certificate2 serverCertificate) + { + if (IsActiveStreamSecure) + return true; + + _writeDone.WaitOne(); + + SslStream secureStream = null; + + try + { + secureStream = new SslStream(NetworkStream, true); + await secureStream.AuthenticateAsServerAsync(serverCertificate).ConfigureAwait(false); + SecureStream = secureStream; + return true; + } + catch (Exception ex) + { + ConnectionFailure(this, new ConnectionFailureEventArgs(ex)); + secureStream?.Dispose(); + + return false; + } + } + + /// + /// Upgrades the active stream to an SSL stream if this connection object is hosted in the client. + /// + /// The hostname. + /// The callback. + /// A tasks with true if the upgrade to SSL was successful; otherwise, false. + public async Task UpgradeToSecureAsClientAsync( + string hostname = null, + RemoteCertificateValidationCallback callback = null) + { + if (IsActiveStreamSecure) + return true; + + var secureStream = callback == null + ? new SslStream(NetworkStream, true) + : new SslStream(NetworkStream, true, callback); + + try + { + await secureStream.AuthenticateAsClientAsync(hostname ?? Network.HostName.ToLowerInvariant()).ConfigureAwait(false); + SecureStream = secureStream; + } + catch (Exception ex) + { + secureStream.Dispose(); + ConnectionFailure(this, new ConnectionFailureEventArgs(ex)); + return false; + } + + return true; + } + + /// + /// Disconnects this connection. + /// + public void Disconnect() + { + if (_disconnectCalls > 0) + return; + + _disconnectCalls++; + _writeDone.WaitOne(); + + try + { + ClientDisconnected(this, EventArgs.Empty); + } + catch + { + // ignore + } + + try + { +#if !NET452 + RemoteClient.Dispose(); + SecureStream?.Dispose(); + NetworkStream?.Dispose(); +#else + RemoteClient.Close(); + SecureStream?.Close(); + NetworkStream?.Close(); +#endif + } + catch + { + // ignored + } + finally + { + NetworkStream = null; + SecureStream = null; + RemoteClient = null; + _continuousReadingThread = null; + } + } + + #endregion + + #region Dispose + + /// + /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. + /// + public void Dispose() + { + if (_hasDisposed) + return; + + // Release managed resources + Disconnect(); + _continuousReadingThread = null; + _writeDone.Dispose(); + + _hasDisposed = true; + } + + #endregion + + #region Continuous Read Methods + + /// + /// Raises the receive buffer events. + /// + /// The received data. + /// Split function failed! This is terribly wrong. + private void RaiseReceiveBufferEvents(byte[] receivedData) + { + var moreAvailable = RemoteClient.Available > 0; + + foreach (var data in receivedData) + { + ProcessReceivedBlock(data, moreAvailable); + } + + // Check if we are left with some more stuff to handle + if (_receiveBufferPointer <= 0) + return; + + // Extract the segments split by newline terminated bytes + var sequences = _receiveBuffer.Skip(0).Take(_receiveBufferPointer).ToArray() + .Split(0, _newLineSequenceBytes); + + // Something really wrong happened + if (sequences.Count == 0) + throw new InvalidOperationException("Split function failed! This is terribly wrong!"); + + // We only have one sequence and it is not newline-terminated + // we don't have to do anything. + if (sequences.Count == 1 && sequences[0].EndsWith(_newLineSequenceBytes) == false) + return; + + // Process the events for each sequence + for (var i = 0; i < sequences.Count; i++) + { + var sequenceBytes = sequences[i]; + var isNewLineTerminated = sequences[i].EndsWith(_newLineSequenceBytes); + var isLast = i == sequences.Count - 1; + + if (isNewLineTerminated) + { + var eventArgs = new ConnectionDataReceivedEventArgs( + sequenceBytes, + ConnectionDataReceivedTrigger.NewLineSequenceEncountered, + isLast == false); + DataReceived(this, eventArgs); + } + + // Depending on the last segment determine what to do with the receive buffer + if (!isLast) continue; + + if (isNewLineTerminated) + { + // Simply reset the buffer pointer if the last segment was also terminated + _receiveBufferPointer = 0; + } + else + { + // If we have not received the termination sequence, then just shift the receive buffer to the left + // and adjust the pointer + Array.Copy(sequenceBytes, _receiveBuffer, sequenceBytes.Length); + _receiveBufferPointer = sequenceBytes.Length; + } + } + } + + private void ProcessReceivedBlock(byte data, bool moreAvailable) + { + _receiveBuffer[_receiveBufferPointer] = data; + _receiveBufferPointer++; + + // Block size reached + if (ProtocolBlockSize > 0 && _receiveBufferPointer >= ProtocolBlockSize) + { + SendBuffer(moreAvailable, ConnectionDataReceivedTrigger.BlockSizeReached); + return; + } + + // The receive buffer is full. Time to flush + if (_receiveBufferPointer >= _receiveBuffer.Length) + { + SendBuffer(moreAvailable, ConnectionDataReceivedTrigger.BufferFull); + } + } + + private void SendBuffer(bool moreAvailable, ConnectionDataReceivedTrigger trigger) + { + var eventBuffer = new byte[_receiveBuffer.Length]; + Array.Copy(_receiveBuffer, eventBuffer, eventBuffer.Length); + + DataReceived(this, + new ConnectionDataReceivedEventArgs( + eventBuffer, + trigger, + moreAvailable)); + _receiveBufferPointer = 0; + } + + private void PerformContinuousReading(object threadContext) + { + _continuousReadingThread = Thread.CurrentThread; + + // Check if the RemoteClient is still there + if (RemoteClient == null) return; + + var receiveBuffer = new byte[RemoteClient.ReceiveBufferSize * 2]; + + while (IsConnected && _disconnectCalls <= 0) + { + var doThreadSleep = false; + + try + { + if (_readTask == null) + _readTask = ActiveStream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length); + + if (_readTask.Wait(_continuousReadingInterval)) + { + var bytesReceivedCount = _readTask.Result; + if (bytesReceivedCount > 0) + { + DataReceivedLastTimeUtc = DateTime.UtcNow; + var buffer = new byte[bytesReceivedCount]; + Array.Copy(receiveBuffer, 0, buffer, 0, bytesReceivedCount); + RaiseReceiveBufferEvents(buffer); + } + + _readTask = null; + } + else + { + doThreadSleep = _disconnectCalls <= 0; + } + } + catch (Exception ex) + { + ex.Log(nameof(Connection), "Continuous Read operation errored"); + } + finally + { + if (doThreadSleep) + Thread.Sleep(_continuousReadingInterval); + } + } + } + + #endregion + } +} diff --git a/Unosquare.Swan/Networking/ConnectionListener.cs b/Unosquare.Swan/Networking/ConnectionListener.cs new file mode 100644 index 0000000..15dc5f4 --- /dev/null +++ b/Unosquare.Swan/Networking/ConnectionListener.cs @@ -0,0 +1,258 @@ +namespace Unosquare.Swan.Networking +{ + using Swan; + using System; + using System.Net; + using System.Net.Sockets; + using System.Threading; + using System.Threading.Tasks; + + /// + /// TCP Listener manager with built-in events and asynchronous functionality. + /// This networking component is typically used when writing server software. + /// + /// + public sealed class ConnectionListener : IDisposable + { + #region Private Declarations + + private readonly object _stateLock = new object(); + private TcpListener _listenerSocket; + private bool _cancellationPending; + private CancellationTokenSource _cancelListening; + private Task _backgroundWorkerTask; + private bool _hasDisposed; + + #endregion + + #region Events + + /// + /// Occurs when a new connection requests a socket from the listener. + /// Set Cancel = true to prevent the TCP client from being accepted. + /// + public event EventHandler OnConnectionAccepting = (s, e) => { }; + + /// + /// Occurs when a new connection is accepted. + /// + public event EventHandler OnConnectionAccepted = (s, e) => { }; + + /// + /// Occurs when a connection fails to get accepted + /// + public event EventHandler OnConnectionFailure = (s, e) => { }; + + /// + /// Occurs when the listener stops. + /// + public event EventHandler OnListenerStopped = (s, e) => { }; + + #endregion + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The listen end point. + public ConnectionListener(IPEndPoint listenEndPoint) + { + Id = Guid.NewGuid(); + LocalEndPoint = listenEndPoint ?? throw new ArgumentNullException(nameof(listenEndPoint)); + } + + /// + /// Initializes a new instance of the class. + /// It uses the loopback address for listening. + /// + /// The listen port. + public ConnectionListener(int listenPort) + : this(new IPEndPoint(IPAddress.Loopback, listenPort)) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The listen address. + /// The listen port. + public ConnectionListener(IPAddress listenAddress, int listenPort) + : this(new IPEndPoint(listenAddress, listenPort)) + { + } + + /// + /// Finalizes an instance of the class. + /// + ~ConnectionListener() + { + Dispose(false); + } + + #endregion + + #region Public Properties + + /// + /// Gets the local end point on which we are listening. + /// + /// + /// The local end point. + /// + public IPEndPoint LocalEndPoint { get; } + + /// + /// Gets a value indicating whether this listener is active. + /// + /// + /// true if this instance is listening; otherwise, false. + /// + public bool IsListening => _backgroundWorkerTask != null; + + /// + /// Gets a unique identifier that gets automatically assigned upon instantiation of this class. + /// + /// + /// The unique identifier. + /// + public Guid Id { get; } + + #endregion + + #region Start and Stop + + /// + /// Starts the listener in an asynchronous, non-blocking fashion. + /// Subscribe to the events of this class to gain access to connected client sockets. + /// + /// Cancellation has already been requested. This listener is not reusable. + public void Start() + { + lock (_stateLock) + { + if (_backgroundWorkerTask != null) + { + return; + } + + if (_cancellationPending) + { + throw new InvalidOperationException( + "Cancellation has already been requested. This listener is not reusable."); + } + + _backgroundWorkerTask = DoWorkAsync(); + } + } + + /// + /// Stops the listener from receiving new connections. + /// This does not prevent the listener from . + /// + public void Stop() + { + lock (_stateLock) + { + _cancellationPending = true; + _listenerSocket?.Stop(); + _cancelListening?.Cancel(); + _backgroundWorkerTask?.Wait(); + _backgroundWorkerTask = null; + _cancellationPending = false; + } + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() => LocalEndPoint.ToString(); + + /// + public void Dispose() + { + Dispose(true); + GC.SuppressFinalize(this); + } + + /// + /// Releases unmanaged and - optionally - managed resources. + /// + /// true to release both managed and unmanaged resources; false to release only unmanaged resources. + private void Dispose(bool disposing) + { + if (_hasDisposed) + return; + + if (disposing) + { + // Release managed resources + Stop(); + } + + _hasDisposed = true; + } + + /// + /// Continuously checks for client connections until the Close method has been called. + /// + /// A task that represents the asynchronous connection operation. + private async Task DoWorkAsync() + { + _cancellationPending = false; + _listenerSocket = new TcpListener(LocalEndPoint); + _listenerSocket.Start(); + _cancelListening = new CancellationTokenSource(); + + try + { + while (_cancellationPending == false) + { + try + { + var client = await Task.Run(() => _listenerSocket.AcceptTcpClientAsync(), _cancelListening.Token).ConfigureAwait(false); + var acceptingArgs = new ConnectionAcceptingEventArgs(client); + OnConnectionAccepting(this, acceptingArgs); + + if (acceptingArgs.Cancel) + { +#if !NET452 + client.Dispose(); +#else + client.Close(); +#endif + continue; + } + + OnConnectionAccepted(this, new ConnectionAcceptedEventArgs(client)); + } + catch (Exception ex) + { + OnConnectionFailure(this, new ConnectionFailureEventArgs(ex)); + } + } + + OnListenerStopped(this, new ConnectionListenerStoppedEventArgs(LocalEndPoint)); + } + catch (ObjectDisposedException) + { + OnListenerStopped(this, new ConnectionListenerStoppedEventArgs(LocalEndPoint)); + } + catch (Exception ex) + { + OnListenerStopped(this, + new ConnectionListenerStoppedEventArgs(LocalEndPoint, _cancellationPending ? null : ex)); + } + finally + { + _backgroundWorkerTask = null; + _cancellationPending = false; + } + } + + #endregion + } +} diff --git a/Unosquare.Swan/Networking/DnsClient.Interfaces.cs b/Unosquare.Swan/Networking/DnsClient.Interfaces.cs new file mode 100644 index 0000000..ae7fe78 --- /dev/null +++ b/Unosquare.Swan/Networking/DnsClient.Interfaces.cs @@ -0,0 +1,61 @@ +namespace Unosquare.Swan.Networking +{ + using System; + using System.Collections.Generic; + + /// + /// DnsClient public interfaces. + /// + internal partial class DnsClient + { + public interface IDnsMessage + { + IList Questions { get; } + + int Size { get; } + byte[] ToArray(); + } + + public interface IDnsMessageEntry + { + DnsDomain Name { get; } + DnsRecordType Type { get; } + DnsRecordClass Class { get; } + + int Size { get; } + byte[] ToArray(); + } + + public interface IDnsResourceRecord : IDnsMessageEntry + { + TimeSpan TimeToLive { get; } + int DataLength { get; } + byte[] Data { get; } + } + + public interface IDnsRequest : IDnsMessage + { + int Id { get; set; } + DnsOperationCode OperationCode { get; set; } + bool RecursionDesired { get; set; } + } + + public interface IDnsResponse : IDnsMessage + { + int Id { get; set; } + IList AnswerRecords { get; } + IList AuthorityRecords { get; } + IList AdditionalRecords { get; } + bool IsRecursionAvailable { get; set; } + bool IsAuthorativeServer { get; set; } + bool IsTruncated { get; set; } + DnsOperationCode OperationCode { get; set; } + DnsResponseCode ResponseCode { get; set; } + } + + public interface IDnsRequestResolver + { + DnsClientResponse Request(DnsClientRequest request); + } + } +} diff --git a/Unosquare.Swan/Networking/DnsClient.Request.cs b/Unosquare.Swan/Networking/DnsClient.Request.cs new file mode 100644 index 0000000..d129c24 --- /dev/null +++ b/Unosquare.Swan/Networking/DnsClient.Request.cs @@ -0,0 +1,683 @@ +namespace Unosquare.Swan.Networking +{ + using Formatters; + using System; + using System.Collections.Generic; + using System.IO; + using System.Linq; + using System.Net; + using System.Net.Sockets; + using System.Runtime.InteropServices; + using System.Text; + using Exceptions; + using Attributes; + + /// + /// DnsClient Request inner class. + /// + internal partial class DnsClient + { + public class DnsClientRequest : IDnsRequest + { + private readonly IDnsRequestResolver _resolver; + private readonly IDnsRequest _request; + + public DnsClientRequest(IPEndPoint dns, IDnsRequest request = null, IDnsRequestResolver resolver = null) + { + Dns = dns; + _request = request == null ? new DnsRequest() : new DnsRequest(request); + _resolver = resolver ?? new DnsUdpRequestResolver(); + } + + public int Id + { + get => _request.Id; + set => _request.Id = value; + } + + public DnsOperationCode OperationCode + { + get => _request.OperationCode; + set => _request.OperationCode = value; + } + + public bool RecursionDesired + { + get => _request.RecursionDesired; + set => _request.RecursionDesired = value; + } + + public IList Questions => _request.Questions; + + public int Size => _request.Size; + + public IPEndPoint Dns { get; set; } + + public byte[] ToArray() => _request.ToArray(); + + public override string ToString() => _request.ToString(); + + /// + /// Resolves this request into a response using the provided DNS information. The given + /// request strategy is used to retrieve the response. + /// + /// Throw if a malformed response is received from the server. + /// Thrown if a IO error occurs. + /// Thrown if a the reading or writing to the socket fails. + /// The response received from server. + public DnsClientResponse Resolve() + { + try + { + var response = _resolver.Request(this); + + if (response.Id != Id) + { + throw new DnsQueryException(response, "Mismatching request/response IDs"); + } + + if (response.ResponseCode != DnsResponseCode.NoError) + { + throw new DnsQueryException(response); + } + + return response; + } + catch (ArgumentException e) + { + throw new DnsQueryException("Invalid response", e); + } + } + } + + public class DnsRequest : IDnsRequest + { + private static readonly Random Random = new Random(); + + private readonly IList questions; + private DnsHeader header; + + public DnsRequest() + { + questions = new List(); + header = new DnsHeader + { + OperationCode = DnsOperationCode.Query, + Response = false, + Id = Random.Next(UInt16.MaxValue), + }; + } + + public DnsRequest(IDnsRequest request) + { + header = new DnsHeader(); + questions = new List(request.Questions); + + header.Response = false; + + Id = request.Id; + OperationCode = request.OperationCode; + RecursionDesired = request.RecursionDesired; + } + + public IList Questions => questions; + + public int Size => header.Size + questions.Sum(q => q.Size); + + public int Id + { + get => header.Id; + set => header.Id = value; + } + + public DnsOperationCode OperationCode + { + get => header.OperationCode; + set => header.OperationCode = value; + } + + public bool RecursionDesired + { + get => header.RecursionDesired; + set => header.RecursionDesired = value; + } + + public byte[] ToArray() + { + UpdateHeader(); + var result = new MemoryStream(Size); + + result + .Append(header.ToArray()) + .Append(questions.Select(q => q.ToArray())); + + return result.ToArray(); + } + + public override string ToString() + { + UpdateHeader(); + + return Json.Serialize(this, true); + } + + private void UpdateHeader() + { + header.QuestionCount = questions.Count; + } + } + + public class DnsTcpRequestResolver : IDnsRequestResolver + { + public DnsClientResponse Request(DnsClientRequest request) + { + var tcp = new TcpClient(); + + try + { + tcp.Client.Connect(request.Dns); + + var stream = tcp.GetStream(); + var buffer = request.ToArray(); + var length = BitConverter.GetBytes((ushort) buffer.Length); + + if (BitConverter.IsLittleEndian) + Array.Reverse(length); + + stream.Write(length, 0, length.Length); + stream.Write(buffer, 0, buffer.Length); + + buffer = new byte[2]; + Read(stream, buffer); + + if (BitConverter.IsLittleEndian) + Array.Reverse(buffer); + + buffer = new byte[BitConverter.ToUInt16(buffer, 0)]; + Read(stream, buffer); + + var response = DnsResponse.FromArray(buffer); + + return new DnsClientResponse(request, response, buffer); + } + finally + { +#if NET452 + tcp.Close(); +#else + tcp.Dispose(); +#endif + } + } + + private static void Read(Stream stream, byte[] buffer) + { + var length = buffer.Length; + var offset = 0; + int size; + + while (length > 0 && (size = stream.Read(buffer, offset, length)) > 0) + { + offset += size; + length -= size; + } + + if (length > 0) + { + throw new IOException("Unexpected end of stream"); + } + } + } + + public class DnsUdpRequestResolver : IDnsRequestResolver + { + private readonly IDnsRequestResolver _fallback; + + public DnsUdpRequestResolver(IDnsRequestResolver fallback) + { + _fallback = fallback; + } + + public DnsUdpRequestResolver() + { + _fallback = new DnsNullRequestResolver(); + } + + public DnsClientResponse Request(DnsClientRequest request) + { + var udp = new UdpClient(); + var dns = request.Dns; + + try + { + udp.Client.SendTimeout = 7000; + udp.Client.ReceiveTimeout = 7000; + udp.Client.Connect(dns); + udp.Client.Send(request.ToArray()); + + var bufferList = new List(); + + do + { + var tempBuffer = new byte[1024]; + var receiveCount = udp.Client.Receive(tempBuffer); + bufferList.AddRange(tempBuffer.Skip(0).Take(receiveCount)); + } while (udp.Client.Available > 0 || bufferList.Count == 0); + + var buffer = bufferList.ToArray(); + var response = DnsResponse.FromArray(buffer); + + return response.IsTruncated + ? _fallback.Request(request) + : new DnsClientResponse(request, response, buffer); + } + finally + { +#if NET452 + udp.Close(); +#else + udp.Dispose(); +#endif + } + } + } + + public class DnsNullRequestResolver : IDnsRequestResolver + { + public DnsClientResponse Request(DnsClientRequest request) + { + throw new DnsQueryException("Request failed"); + } + } + + // 12 bytes message header + [StructEndianness(Endianness.Big)] + [StructLayout(LayoutKind.Sequential, Pack = 1)] + public struct DnsHeader + { + public const int SIZE = 12; + + public static DnsHeader FromArray(byte[] header) + { + if (header.Length < SIZE) + { + throw new ArgumentException("Header length too small"); + } + + return header.ToStruct(0, SIZE); + } + + private ushort id; + + private byte flag0; + private byte flag1; + + // Question count: number of questions in the Question section + private ushort questionCount; + + // Answer record count: number of records in the Answer section + private ushort answerCount; + + // Authority record count: number of records in the Authority section + private ushort authorityCount; + + // Additional record count: number of records in the Additional section + private ushort addtionalCount; + + public int Id + { + get => id; + set => id = (ushort) value; + } + + public int QuestionCount + { + get => questionCount; + set => questionCount = (ushort) value; + } + + public int AnswerRecordCount + { + get => answerCount; + set => answerCount = (ushort) value; + } + + public int AuthorityRecordCount + { + get => authorityCount; + set => authorityCount = (ushort) value; + } + + public int AdditionalRecordCount + { + get => addtionalCount; + set => addtionalCount = (ushort) value; + } + + public bool Response + { + get => Qr == 1; + set => Qr = Convert.ToByte(value); + } + + public DnsOperationCode OperationCode + { + get => (DnsOperationCode) Opcode; + set => Opcode = (byte) value; + } + + public bool AuthorativeServer + { + get => Aa == 1; + set => Aa = Convert.ToByte(value); + } + + public bool Truncated + { + get => Tc == 1; + set => Tc = Convert.ToByte(value); + } + + public bool RecursionDesired + { + get => Rd == 1; + set => Rd = Convert.ToByte(value); + } + + public bool RecursionAvailable + { + get => Ra == 1; + set => Ra = Convert.ToByte(value); + } + + public DnsResponseCode ResponseCode + { + get => (DnsResponseCode) RCode; + set => RCode = (byte) value; + } + + public int Size => SIZE; + + // Query/Response Flag + private byte Qr + { + get => Flag0.GetBitValueAt(7); + set => Flag0 = Flag0.SetBitValueAt(7, 1, value); + } + + // Operation Code + private byte Opcode + { + get => Flag0.GetBitValueAt(3, 4); + set => Flag0 = Flag0.SetBitValueAt(3, 4, value); + } + + // Authorative Answer Flag + private byte Aa + { + get => Flag0.GetBitValueAt(2); + set => Flag0 = Flag0.SetBitValueAt(2, 1, value); + } + + // Truncation Flag + private byte Tc + { + get => Flag0.GetBitValueAt(1); + set => Flag0 = Flag0.SetBitValueAt(1, 1, value); + } + + // Recursion Desired + private byte Rd + { + get => Flag0.GetBitValueAt(0); + set => Flag0 = Flag0.SetBitValueAt(0, 1, value); + } + + // Recursion Available + private byte Ra + { + get => Flag1.GetBitValueAt(7); + set => Flag1 = Flag1.SetBitValueAt(7, 1, value); + } + + // Zero (Reserved) + private byte Z + { + get => Flag1.GetBitValueAt(4, 3); + set { } + } + + // Response Code + private byte RCode + { + get => Flag1.GetBitValueAt(0, 4); + set => Flag1 = Flag1.SetBitValueAt(0, 4, value); + } + + private byte Flag0 + { + get => flag0; + set => flag0 = value; + } + + private byte Flag1 + { + get => flag1; + set => flag1 = value; + } + + public byte[] ToArray() => this.ToBytes(); + + public override string ToString() + => Json.SerializeExcluding(this, true, nameof(Size)); + } + + public class DnsDomain : IComparable + { + private readonly string[] _labels; + + public DnsDomain(string domain) + : this(domain.Split('.')) + { + } + + public DnsDomain(string[] labels) + { + _labels = labels; + } + + public int Size => _labels.Sum(l => l.Length) + _labels.Length + 1; + + public static DnsDomain FromArray(byte[] message, int offset) + => FromArray(message, offset, out offset); + + public static DnsDomain FromArray(byte[] message, int offset, out int endOffset) + { + var labels = new List(); + var endOffsetAssigned = false; + endOffset = 0; + byte lengthOrPointer; + + while ((lengthOrPointer = message[offset++]) > 0) + { + // Two heighest bits are set (pointer) + if (lengthOrPointer.GetBitValueAt(6, 2) == 3) + { + if (!endOffsetAssigned) + { + endOffsetAssigned = true; + endOffset = offset + 1; + } + + ushort pointer = lengthOrPointer.GetBitValueAt(0, 6); + offset = (pointer << 8) | message[offset]; + + continue; + } + + if (lengthOrPointer.GetBitValueAt(6, 2) != 0) + { + throw new ArgumentException("Unexpected bit pattern in label length"); + } + + var length = lengthOrPointer; + var label = new byte[length]; + Array.Copy(message, offset, label, 0, length); + + labels.Add(label); + + offset += length; + } + + if (!endOffsetAssigned) + { + endOffset = offset; + } + + return new DnsDomain(labels.Select(l => l.ToText(Encoding.ASCII)).ToArray()); + } + + public static DnsDomain PointerName(IPAddress ip) + => new DnsDomain(FormatReverseIP(ip)); + + public byte[] ToArray() + { + var result = new byte[Size]; + var offset = 0; + + foreach (var l in _labels.Select(label => Encoding.ASCII.GetBytes(label))) + { + result[offset++] = (byte) l.Length; + l.CopyTo(result, offset); + + offset += l.Length; + } + + result[offset] = 0; + + return result; + } + + public override string ToString() + => string.Join(".", _labels); + + public int CompareTo(DnsDomain other) + => string.Compare(ToString(), other.ToString(), StringComparison.Ordinal); + + public override bool Equals(object obj) + => obj is DnsDomain domain && CompareTo(domain) == 0; + + public override int GetHashCode() => ToString().GetHashCode(); + + private static string FormatReverseIP(IPAddress ip) + { + var address = ip.GetAddressBytes(); + + if (address.Length == 4) + { + return string.Join(".", address.Reverse().Select(b => b.ToString())) + ".in-addr.arpa"; + } + + var nibbles = new byte[address.Length * 2]; + + for (int i = 0, j = 0; i < address.Length; i++, j = 2 * i) + { + var b = address[i]; + + nibbles[j] = b.GetBitValueAt(4, 4); + nibbles[j + 1] = b.GetBitValueAt(0, 4); + } + + return string.Join(".", nibbles.Reverse().Select(b => b.ToString("x"))) + ".ip6.arpa"; + } + } + + public class DnsQuestion : IDnsMessageEntry + { + private readonly DnsDomain _domain; + private readonly DnsRecordType _type; + private readonly DnsRecordClass _klass; + + public static IList GetAllFromArray(byte[] message, int offset, int questionCount) => + GetAllFromArray(message, offset, questionCount, out offset); + + public static IList GetAllFromArray( + byte[] message, + int offset, + int questionCount, + out int endOffset) + { + IList questions = new List(questionCount); + + for (var i = 0; i < questionCount; i++) + { + questions.Add(FromArray(message, offset, out offset)); + } + + endOffset = offset; + return questions; + } + + public static DnsQuestion FromArray(byte[] message, int offset, out int endOffset) + { + var domain = DnsDomain.FromArray(message, offset, out offset); + var tail = message.ToStruct(offset, Tail.SIZE); + + endOffset = offset + Tail.SIZE; + + return new DnsQuestion(domain, tail.Type, tail.Class); + } + + public DnsQuestion( + DnsDomain domain, + DnsRecordType type = DnsRecordType.A, + DnsRecordClass klass = DnsRecordClass.IN) + { + _domain = domain; + _type = type; + _klass = klass; + } + + public DnsDomain Name => _domain; + + public DnsRecordType Type => _type; + + public DnsRecordClass Class => _klass; + + public int Size => _domain.Size + Tail.SIZE; + + public byte[] ToArray() + { + return new MemoryStream(Size) + .Append(_domain.ToArray()) + .Append(new Tail {Type = Type, Class = Class}.ToBytes()) + .ToArray(); + } + + public override string ToString() + => Json.SerializeOnly(this, true, nameof(Name), nameof(Type), nameof(Class)); + + [StructEndianness(Endianness.Big)] + [StructLayout(LayoutKind.Sequential, Pack = 2)] + private struct Tail + { + public const int SIZE = 4; + + private ushort type; + private ushort klass; + + public DnsRecordType Type + { + get => (DnsRecordType) type; + set => type = (ushort) value; + } + + public DnsRecordClass Class + { + get => (DnsRecordClass) klass; + set => klass = (ushort) value; + } + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/DnsClient.ResourceRecords.cs b/Unosquare.Swan/Networking/DnsClient.ResourceRecords.cs new file mode 100644 index 0000000..4a43f30 --- /dev/null +++ b/Unosquare.Swan/Networking/DnsClient.ResourceRecords.cs @@ -0,0 +1,460 @@ +namespace Unosquare.Swan.Networking +{ + using Attributes; + using Formatters; + using System; + using System.Collections.Generic; + using System.IO; + using System.Net; + using System.Runtime.InteropServices; + + /// + /// DnsClient public methods. + /// + internal partial class DnsClient + { + public abstract class DnsResourceRecordBase : IDnsResourceRecord + { + private readonly IDnsResourceRecord _record; + + protected DnsResourceRecordBase(IDnsResourceRecord record) + { + _record = record; + } + + public DnsDomain Name => _record.Name; + + public DnsRecordType Type => _record.Type; + + public DnsRecordClass Class => _record.Class; + + public TimeSpan TimeToLive => _record.TimeToLive; + + public int DataLength => _record.DataLength; + + public byte[] Data => _record.Data; + + public int Size => _record.Size; + + protected virtual string[] IncludedProperties + => new[] {nameof(Name), nameof(Type), nameof(Class), nameof(TimeToLive), nameof(DataLength)}; + + public byte[] ToArray() => _record.ToArray(); + + public override string ToString() + => Json.SerializeOnly(this, true, IncludedProperties); + } + + public class DnsResourceRecord : IDnsResourceRecord + { + public DnsResourceRecord( + DnsDomain domain, + byte[] data, + DnsRecordType type, + DnsRecordClass klass = DnsRecordClass.IN, + TimeSpan ttl = default) + { + Name = domain; + Type = type; + Class = klass; + TimeToLive = ttl; + Data = data; + } + + public DnsDomain Name { get; } + + public DnsRecordType Type { get; } + + public DnsRecordClass Class { get; } + + public TimeSpan TimeToLive { get; } + + public int DataLength => Data.Length; + + public byte[] Data { get; } + + public int Size => Name.Size + Tail.SIZE + Data.Length; + + public static IList GetAllFromArray( + byte[] message, + int offset, + int count, + out int endOffset) + { + IList records = new List(count); + + for (var i = 0; i < count; i++) + { + records.Add(FromArray(message, offset, out offset)); + } + + endOffset = offset; + return records; + } + + public static DnsResourceRecord FromArray(byte[] message, int offset, out int endOffset) + { + var domain = DnsDomain.FromArray(message, offset, out offset); + var tail = message.ToStruct(offset, Tail.SIZE); + + var data = new byte[tail.DataLength]; + + offset += Tail.SIZE; + Array.Copy(message, offset, data, 0, data.Length); + + endOffset = offset + data.Length; + + return new DnsResourceRecord(domain, data, tail.Type, tail.Class, tail.TimeToLive); + } + + public byte[] ToArray() + { + return new MemoryStream(Size) + .Append(Name.ToArray()) + .Append(new Tail() + { + Type = Type, + Class = Class, + TimeToLive = TimeToLive, + DataLength = Data.Length, + }.ToBytes()) + .Append(Data) + .ToArray(); + } + + public override string ToString() + { + return Json.SerializeOnly( + this, + true, + nameof(Name), + nameof(Type), + nameof(Class), + nameof(TimeToLive), + nameof(DataLength)); + } + + [StructEndianness(Endianness.Big)] + [StructLayout(LayoutKind.Sequential, Pack = 2)] + private struct Tail + { + public const int SIZE = 10; + + private ushort type; + private ushort klass; + private uint ttl; + private ushort dataLength; + + public DnsRecordType Type + { + get => (DnsRecordType) type; + set => type = (ushort) value; + } + + public DnsRecordClass Class + { + get => (DnsRecordClass) klass; + set => klass = (ushort) value; + } + + public TimeSpan TimeToLive + { + get => TimeSpan.FromSeconds(ttl); + set => ttl = (uint) value.TotalSeconds; + } + + public int DataLength + { + get => dataLength; + set => dataLength = (ushort) value; + } + } + } + + public class DnsPointerResourceRecord : DnsResourceRecordBase + { + public DnsPointerResourceRecord(IDnsResourceRecord record, byte[] message, int dataOffset) + : base(record) + { + PointerDomainName = DnsDomain.FromArray(message, dataOffset); + } + + public DnsDomain PointerDomainName { get; } + + protected override string[] IncludedProperties + { + get + { + var temp = new List(base.IncludedProperties) {nameof(PointerDomainName)}; + return temp.ToArray(); + } + } + } + + public class DnsIPAddressResourceRecord : DnsResourceRecordBase + { + public DnsIPAddressResourceRecord(IDnsResourceRecord record) + : base(record) + { + IPAddress = new IPAddress(Data); + } + + public IPAddress IPAddress { get; } + + protected override string[] IncludedProperties + { + get + { + var temp = new List(base.IncludedProperties) {nameof(IPAddress)}; + return temp.ToArray(); + } + } + } + + public class DnsNameServerResourceRecord : DnsResourceRecordBase + { + public DnsNameServerResourceRecord(IDnsResourceRecord record, byte[] message, int dataOffset) + : base(record) + { + NSDomainName = DnsDomain.FromArray(message, dataOffset); + } + + public DnsDomain NSDomainName { get; } + + protected override string[] IncludedProperties + { + get + { + var temp = new List(base.IncludedProperties) {nameof(NSDomainName)}; + return temp.ToArray(); + } + } + } + + public class DnsCanonicalNameResourceRecord : DnsResourceRecordBase + { + public DnsCanonicalNameResourceRecord(IDnsResourceRecord record, byte[] message, int dataOffset) + : base(record) + { + CanonicalDomainName = DnsDomain.FromArray(message, dataOffset); + } + + public DnsDomain CanonicalDomainName { get; } + + protected override string[] IncludedProperties => new List(base.IncludedProperties) + { + nameof(CanonicalDomainName), + }.ToArray(); + } + + public class DnsMailExchangeResourceRecord : DnsResourceRecordBase + { + private const int PreferenceSize = 2; + + public DnsMailExchangeResourceRecord( + IDnsResourceRecord record, + byte[] message, + int dataOffset) + : base(record) + { + var preference = new byte[PreferenceSize]; + Array.Copy(message, dataOffset, preference, 0, preference.Length); + + if (BitConverter.IsLittleEndian) + { + Array.Reverse(preference); + } + + dataOffset += PreferenceSize; + + Preference = BitConverter.ToUInt16(preference, 0); + ExchangeDomainName = DnsDomain.FromArray(message, dataOffset); + } + + public int Preference { get; } + + public DnsDomain ExchangeDomainName { get; } + + protected override string[] IncludedProperties => new List(base.IncludedProperties) + { + nameof(Preference), + nameof(ExchangeDomainName), + }.ToArray(); + } + + public class DnsStartOfAuthorityResourceRecord : DnsResourceRecordBase + { + public DnsStartOfAuthorityResourceRecord(IDnsResourceRecord record, byte[] message, int dataOffset) + : base(record) + { + MasterDomainName = DnsDomain.FromArray(message, dataOffset, out dataOffset); + ResponsibleDomainName = DnsDomain.FromArray(message, dataOffset, out dataOffset); + + var tail = message.ToStruct(dataOffset, Options.SIZE); + + SerialNumber = tail.SerialNumber; + RefreshInterval = tail.RefreshInterval; + RetryInterval = tail.RetryInterval; + ExpireInterval = tail.ExpireInterval; + MinimumTimeToLive = tail.MinimumTimeToLive; + } + + public DnsStartOfAuthorityResourceRecord( + DnsDomain domain, + DnsDomain master, + DnsDomain responsible, + long serial, + TimeSpan refresh, + TimeSpan retry, + TimeSpan expire, + TimeSpan minTtl, + TimeSpan ttl = default) + : base(Create(domain, master, responsible, serial, refresh, retry, expire, minTtl, ttl)) + { + MasterDomainName = master; + ResponsibleDomainName = responsible; + + SerialNumber = serial; + RefreshInterval = refresh; + RetryInterval = retry; + ExpireInterval = expire; + MinimumTimeToLive = minTtl; + } + + public DnsDomain MasterDomainName { get; } + + public DnsDomain ResponsibleDomainName { get; } + + public long SerialNumber { get; } + + public TimeSpan RefreshInterval { get; } + + public TimeSpan RetryInterval { get; } + + public TimeSpan ExpireInterval { get; } + + public TimeSpan MinimumTimeToLive { get; } + + protected override string[] IncludedProperties => new List(base.IncludedProperties) + { + nameof(MasterDomainName), + nameof(ResponsibleDomainName), + nameof(SerialNumber), + }.ToArray(); + + private static IDnsResourceRecord Create( + DnsDomain domain, + DnsDomain master, + DnsDomain responsible, + long serial, + TimeSpan refresh, + TimeSpan retry, + TimeSpan expire, + TimeSpan minTtl, + TimeSpan ttl) + { + var data = new MemoryStream(Options.SIZE + master.Size + responsible.Size); + var tail = new Options + { + SerialNumber = serial, + RefreshInterval = refresh, + RetryInterval = retry, + ExpireInterval = expire, + MinimumTimeToLive = minTtl, + }; + + data.Append(master.ToArray()).Append(responsible.ToArray()).Append(tail.ToBytes()); + + return new DnsResourceRecord(domain, data.ToArray(), DnsRecordType.SOA, DnsRecordClass.IN, ttl); + } + + [StructEndianness(Endianness.Big)] + [StructLayout(LayoutKind.Sequential, Pack = 4)] + public struct Options + { + public const int SIZE = 20; + + private uint serialNumber; + private uint refreshInterval; + private uint retryInterval; + private uint expireInterval; + private uint ttl; + + public long SerialNumber + { + get => serialNumber; + set => serialNumber = (uint) value; + } + + public TimeSpan RefreshInterval + { + get => TimeSpan.FromSeconds(refreshInterval); + set => refreshInterval = (uint) value.TotalSeconds; + } + + public TimeSpan RetryInterval + { + get => TimeSpan.FromSeconds(retryInterval); + set => retryInterval = (uint) value.TotalSeconds; + } + + public TimeSpan ExpireInterval + { + get => TimeSpan.FromSeconds(expireInterval); + set => expireInterval = (uint) value.TotalSeconds; + } + + public TimeSpan MinimumTimeToLive + { + get => TimeSpan.FromSeconds(ttl); + set => ttl = (uint) value.TotalSeconds; + } + } + } + + private static class DnsResourceRecordFactory + { + public static IList GetAllFromArray( + byte[] message, + int offset, + int count, + out int endOffset) + { + var result = new List(count); + + for (var i = 0; i < count; i++) + { + result.Add(GetFromArray(message, offset, out offset)); + } + + endOffset = offset; + return result; + } + + private static IDnsResourceRecord GetFromArray(byte[] message, int offset, out int endOffset) + { + var record = DnsResourceRecord.FromArray(message, offset, out endOffset); + var dataOffset = endOffset - record.DataLength; + + switch (record.Type) + { + case DnsRecordType.A: + case DnsRecordType.AAAA: + return new DnsIPAddressResourceRecord(record); + case DnsRecordType.NS: + return new DnsNameServerResourceRecord(record, message, dataOffset); + case DnsRecordType.CNAME: + return new DnsCanonicalNameResourceRecord(record, message, dataOffset); + case DnsRecordType.SOA: + return new DnsStartOfAuthorityResourceRecord(record, message, dataOffset); + case DnsRecordType.PTR: + return new DnsPointerResourceRecord(record, message, dataOffset); + case DnsRecordType.MX: + return new DnsMailExchangeResourceRecord(record, message, dataOffset); + default: + return record; + } + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/DnsClient.Response.cs b/Unosquare.Swan/Networking/DnsClient.Response.cs new file mode 100644 index 0000000..8be8f9b --- /dev/null +++ b/Unosquare.Swan/Networking/DnsClient.Response.cs @@ -0,0 +1,215 @@ +namespace Unosquare.Swan.Networking +{ + using Formatters; + using System; + using System.Collections.Generic; + using System.Collections.ObjectModel; + using System.IO; + using System.Linq; + + /// + /// DnsClient Response inner class. + /// + internal partial class DnsClient + { + public class DnsClientResponse : IDnsResponse + { + private readonly DnsResponse _response; + private readonly byte[] _message; + + internal DnsClientResponse(DnsClientRequest request, DnsResponse response, byte[] message) + { + Request = request; + + _message = message; + _response = response; + } + + public DnsClientRequest Request { get; } + + public int Id + { + get { return _response.Id; } + set { } + } + + public IList AnswerRecords => _response.AnswerRecords; + + public IList AuthorityRecords => + new ReadOnlyCollection(_response.AuthorityRecords); + + public IList AdditionalRecords => + new ReadOnlyCollection(_response.AdditionalRecords); + + public bool IsRecursionAvailable + { + get { return _response.IsRecursionAvailable; } + set { } + } + + public bool IsAuthorativeServer + { + get { return _response.IsAuthorativeServer; } + set { } + } + + public bool IsTruncated + { + get { return _response.IsTruncated; } + set { } + } + + public DnsOperationCode OperationCode + { + get { return _response.OperationCode; } + set { } + } + + public DnsResponseCode ResponseCode + { + get { return _response.ResponseCode; } + set { } + } + + public IList Questions => new ReadOnlyCollection(_response.Questions); + + public int Size => _message.Length; + + public byte[] ToArray() => _message; + + public override string ToString() => _response.ToString(); + } + + public class DnsResponse : IDnsResponse + { + private DnsHeader _header; + + public DnsResponse( + DnsHeader header, + IList questions, + IList answers, + IList authority, + IList additional) + { + _header = header; + Questions = questions; + AnswerRecords = answers; + AuthorityRecords = authority; + AdditionalRecords = additional; + } + + public IList Questions { get; } + + public IList AnswerRecords { get; } + + public IList AuthorityRecords { get; } + + public IList AdditionalRecords { get; } + + public int Id + { + get => _header.Id; + set => _header.Id = value; + } + + public bool IsRecursionAvailable + { + get => _header.RecursionAvailable; + set => _header.RecursionAvailable = value; + } + + public bool IsAuthorativeServer + { + get => _header.AuthorativeServer; + set => _header.AuthorativeServer = value; + } + + public bool IsTruncated + { + get => _header.Truncated; + set => _header.Truncated = value; + } + + public DnsOperationCode OperationCode + { + get => _header.OperationCode; + set => _header.OperationCode = value; + } + + public DnsResponseCode ResponseCode + { + get => _header.ResponseCode; + set => _header.ResponseCode = value; + } + + public int Size + => _header.Size + + Questions.Sum(q => q.Size) + + AnswerRecords.Sum(a => a.Size) + + AuthorityRecords.Sum(a => a.Size) + + AdditionalRecords.Sum(a => a.Size); + + public static DnsResponse FromArray(byte[] message) + { + var header = DnsHeader.FromArray(message); + var offset = header.Size; + + if (!header.Response || header.QuestionCount == 0) + { + throw new ArgumentException("Invalid response message"); + } + + if (header.Truncated) + { + return new DnsResponse(header, + DnsQuestion.GetAllFromArray(message, offset, header.QuestionCount), + new List(), + new List(), + new List()); + } + + return new DnsResponse(header, + DnsQuestion.GetAllFromArray(message, offset, header.QuestionCount, out offset), + DnsResourceRecordFactory.GetAllFromArray(message, offset, header.AnswerRecordCount, out offset), + DnsResourceRecordFactory.GetAllFromArray(message, offset, header.AuthorityRecordCount, out offset), + DnsResourceRecordFactory.GetAllFromArray(message, offset, header.AdditionalRecordCount, out offset)); + } + + public byte[] ToArray() + { + UpdateHeader(); + var result = new MemoryStream(Size); + + result + .Append(_header.ToArray()) + .Append(Questions.Select(q => q.ToArray())) + .Append(AnswerRecords.Select(a => a.ToArray())) + .Append(AuthorityRecords.Select(a => a.ToArray())) + .Append(AdditionalRecords.Select(a => a.ToArray())); + + return result.ToArray(); + } + + public override string ToString() + { + UpdateHeader(); + + return Json.SerializeOnly( + this, + true, + nameof(Questions), + nameof(AnswerRecords), + nameof(AuthorityRecords), + nameof(AdditionalRecords)); + } + + private void UpdateHeader() + { + _header.QuestionCount = Questions.Count; + _header.AnswerRecordCount = AnswerRecords.Count; + _header.AuthorityRecordCount = AuthorityRecords.Count; + _header.AdditionalRecordCount = AdditionalRecords.Count; + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/DnsClient.cs b/Unosquare.Swan/Networking/DnsClient.cs new file mode 100644 index 0000000..70abcd9 --- /dev/null +++ b/Unosquare.Swan/Networking/DnsClient.cs @@ -0,0 +1,88 @@ +namespace Unosquare.Swan.Networking +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Net; + using Exceptions; + + /// + /// DnsClient public methods. + /// + internal partial class DnsClient + { + private readonly IPEndPoint _dns; + private readonly IDnsRequestResolver _resolver; + + public DnsClient(IPEndPoint dns, IDnsRequestResolver resolver = null) + { + _dns = dns; + _resolver = resolver ?? new DnsUdpRequestResolver(new DnsTcpRequestResolver()); + } + + public DnsClient(IPAddress ip, int port = Network.DnsDefaultPort, IDnsRequestResolver resolver = null) + : this(new IPEndPoint(ip, port), resolver) + { + } + + public DnsClientRequest Create(IDnsRequest request = null) + { + return new DnsClientRequest(_dns, request, _resolver); + } + + public IList Lookup(string domain, DnsRecordType type = DnsRecordType.A) + { + if (string.IsNullOrWhiteSpace(domain)) + throw new ArgumentNullException(nameof(domain)); + + if (type != DnsRecordType.A && type != DnsRecordType.AAAA) + { + throw new ArgumentException("Invalid record type " + type); + } + + var response = Resolve(domain, type); + var ips = response.AnswerRecords + .Where(r => r.Type == type) + .Cast() + .Select(r => r.IPAddress) + .ToList(); + + if (ips.Count == 0) + { + throw new DnsQueryException(response, "No matching records"); + } + + return ips; + } + + public string Reverse(IPAddress ip) + { + if (ip == null) + throw new ArgumentNullException(nameof(ip)); + + var response = Resolve(DnsDomain.PointerName(ip), DnsRecordType.PTR); + var ptr = response.AnswerRecords.FirstOrDefault(r => r.Type == DnsRecordType.PTR); + + if (ptr == null) + { + throw new DnsQueryException(response, "No matching records"); + } + + return ((DnsPointerResourceRecord)ptr).PointerDomainName.ToString(); + } + + public DnsClientResponse Resolve(string domain, DnsRecordType type) => Resolve(new DnsDomain(domain), type); + + public DnsClientResponse Resolve(DnsDomain domain, DnsRecordType type) + { + var request = Create(); + var question = new DnsQuestion(domain, type); + + request.Questions.Add(question); + request.OperationCode = DnsOperationCode.Query; + request.RecursionDesired = true; + + return request.Resolve(); + } + } +} diff --git a/Unosquare.Swan/Networking/DnsQueryResult.cs b/Unosquare.Swan/Networking/DnsQueryResult.cs new file mode 100644 index 0000000..fdc4823 --- /dev/null +++ b/Unosquare.Swan/Networking/DnsQueryResult.cs @@ -0,0 +1,123 @@ +namespace Unosquare.Swan.Networking +{ + using System.Collections.Generic; + + /// + /// Represents a response from a DNS server. + /// + public class DnsQueryResult + { + private readonly List m_AnswerRecords = new List(); + private readonly List m_AdditionalRecords = new List(); + private readonly List m_AuthorityRecords = new List(); + + /// + /// Initializes a new instance of the class. + /// + /// The response. + internal DnsQueryResult(DnsClient.DnsClientResponse response) + : this() + { + Id = response.Id; + IsAuthoritativeServer = response.IsAuthorativeServer; + IsRecursionAvailable = response.IsRecursionAvailable; + IsTruncated = response.IsTruncated; + OperationCode = response.OperationCode; + ResponseCode = response.ResponseCode; + + if (response.AnswerRecords != null) + { + foreach (var record in response.AnswerRecords) + AnswerRecords.Add(new DnsRecord(record)); + } + + if (response.AuthorityRecords != null) + { + foreach (var record in response.AuthorityRecords) + AuthorityRecords.Add(new DnsRecord(record)); + } + + if (response.AdditionalRecords != null) + { + foreach (var record in response.AdditionalRecords) + AdditionalRecords.Add(new DnsRecord(record)); + } + } + + private DnsQueryResult() + { + } + + /// + /// Gets the identifier. + /// + /// + /// The identifier. + /// + public int Id { get; } + + /// + /// Gets a value indicating whether this instance is authoritative server. + /// + /// + /// true if this instance is authoritative server; otherwise, false. + /// + public bool IsAuthoritativeServer { get; } + + /// + /// Gets a value indicating whether this instance is truncated. + /// + /// + /// true if this instance is truncated; otherwise, false. + /// + public bool IsTruncated { get; } + + /// + /// Gets a value indicating whether this instance is recursion available. + /// + /// + /// true if this instance is recursion available; otherwise, false. + /// + public bool IsRecursionAvailable { get; } + + /// + /// Gets the operation code. + /// + /// + /// The operation code. + /// + public DnsOperationCode OperationCode { get; } + + /// + /// Gets the response code. + /// + /// + /// The response code. + /// + public DnsResponseCode ResponseCode { get; } + + /// + /// Gets the answer records. + /// + /// + /// The answer records. + /// + public IList AnswerRecords => m_AnswerRecords; + + /// + /// Gets the additional records. + /// + /// + /// The additional records. + /// + public IList AdditionalRecords => m_AdditionalRecords; + + /// + /// Gets the authority records. + /// + /// + /// The authority records. + /// + public IList AuthorityRecords => m_AuthorityRecords; + } +} diff --git a/Unosquare.Swan/Networking/DnsRecord.cs b/Unosquare.Swan/Networking/DnsRecord.cs new file mode 100644 index 0000000..272001e --- /dev/null +++ b/Unosquare.Swan/Networking/DnsRecord.cs @@ -0,0 +1,208 @@ +namespace Unosquare.Swan.Networking +{ + using System; + using System.Net; + using System.Text; + + /// + /// Represents a DNS record entry. + /// + public class DnsRecord + { + /// + /// Initializes a new instance of the class. + /// + /// The record. + internal DnsRecord(DnsClient.IDnsResourceRecord record) + : this() + { + Name = record.Name.ToString(); + Type = record.Type; + Class = record.Class; + TimeToLive = record.TimeToLive; + Data = record.Data; + + // PTR + PointerDomainName = (record as DnsClient.DnsPointerResourceRecord)?.PointerDomainName?.ToString(); + + // A + IPAddress = (record as DnsClient.DnsIPAddressResourceRecord)?.IPAddress; + + // NS + NameServerDomainName = (record as DnsClient.DnsNameServerResourceRecord)?.NSDomainName?.ToString(); + + // CNAME + CanonicalDomainName = (record as DnsClient.DnsCanonicalNameResourceRecord)?.CanonicalDomainName.ToString(); + + // MX + MailExchangerDomainName = (record as DnsClient.DnsMailExchangeResourceRecord)?.ExchangeDomainName.ToString(); + MailExchangerPreference = (record as DnsClient.DnsMailExchangeResourceRecord)?.Preference; + + // SOA + SoaMasterDomainName = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.MasterDomainName.ToString(); + SoaResponsibleDomainName = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.ResponsibleDomainName.ToString(); + SoaSerialNumber = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.SerialNumber; + SoaRefreshInterval = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.RefreshInterval; + SoaRetryInterval = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.RetryInterval; + SoaExpireInterval = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.ExpireInterval; + SoaMinimumTimeToLive = (record as DnsClient.DnsStartOfAuthorityResourceRecord)?.MinimumTimeToLive; + } + + private DnsRecord() + { + // placeholder + } + + /// + /// Gets the name. + /// + /// + /// The name. + /// + public string Name { get; } + + /// + /// Gets the type. + /// + /// + /// The type. + /// + public DnsRecordType Type { get; } + + /// + /// Gets the class. + /// + /// + /// The class. + /// + public DnsRecordClass Class { get; } + + /// + /// Gets the time to live. + /// + /// + /// The time to live. + /// + public TimeSpan TimeToLive { get; } + + /// + /// Gets the raw data of the record. + /// + /// + /// The data. + /// + public byte[] Data { get; } + + /// + /// Gets the data text bytes in ASCII encoding. + /// + /// + /// The data text. + /// + public string DataText => Data == null ? string.Empty : Encoding.ASCII.GetString(Data); + + /// + /// Gets the name of the pointer domain. + /// + /// + /// The name of the pointer domain. + /// + public string PointerDomainName { get; } + + /// + /// Gets the ip address. + /// + /// + /// The ip address. + /// + public IPAddress IPAddress { get; } + + /// + /// Gets the name of the name server domain. + /// + /// + /// The name of the name server domain. + /// + public string NameServerDomainName { get; } + + /// + /// Gets the name of the canonical domain. + /// + /// + /// The name of the canonical domain. + /// + public string CanonicalDomainName { get; } + + /// + /// Gets the mail exchanger preference. + /// + /// + /// The mail exchanger preference. + /// + public int? MailExchangerPreference { get; } + + /// + /// Gets the name of the mail exchanger domain. + /// + /// + /// The name of the mail exchanger domain. + /// + public string MailExchangerDomainName { get; } + + /// + /// Gets the name of the soa master domain. + /// + /// + /// The name of the soa master domain. + /// + public string SoaMasterDomainName { get; } + + /// + /// Gets the name of the soa responsible domain. + /// + /// + /// The name of the soa responsible domain. + /// + public string SoaResponsibleDomainName { get; } + + /// + /// Gets the soa serial number. + /// + /// + /// The soa serial number. + /// + public long? SoaSerialNumber { get; } + + /// + /// Gets the soa refresh interval. + /// + /// + /// The soa refresh interval. + /// + public TimeSpan? SoaRefreshInterval { get; } + + /// + /// Gets the soa retry interval. + /// + /// + /// The soa retry interval. + /// + public TimeSpan? SoaRetryInterval { get; } + + /// + /// Gets the soa expire interval. + /// + /// + /// The soa expire interval. + /// + public TimeSpan? SoaExpireInterval { get; } + + /// + /// Gets the soa minimum time to live. + /// + /// + /// The soa minimum time to live. + /// + public TimeSpan? SoaMinimumTimeToLive { get; } + } +} diff --git a/Unosquare.Swan/Networking/Enums.Dns.cs b/Unosquare.Swan/Networking/Enums.Dns.cs new file mode 100644 index 0000000..7e2fe6b --- /dev/null +++ b/Unosquare.Swan/Networking/Enums.Dns.cs @@ -0,0 +1,177 @@ +// ReSharper disable InconsistentNaming +namespace Unosquare.Swan.Networking +{ + #region DNS + + /// + /// Enumerates the different DNS record types. + /// + public enum DnsRecordType + { + /// + /// A records + /// + A = 1, + + /// + /// Nameserver records + /// + NS = 2, + + /// + /// CNAME records + /// + CNAME = 5, + + /// + /// SOA records + /// + SOA = 6, + + /// + /// WKS records + /// + WKS = 11, + + /// + /// PTR records + /// + PTR = 12, + + /// + /// MX records + /// + MX = 15, + + /// + /// TXT records + /// + TXT = 16, + + /// + /// A records fot IPv6 + /// + AAAA = 28, + + /// + /// SRV records + /// + SRV = 33, + + /// + /// ANY records + /// + ANY = 255, + } + + /// + /// Enumerates the different DNS record classes. + /// + public enum DnsRecordClass + { + /// + /// IN records + /// + IN = 1, + + /// + /// ANY records + /// + ANY = 255, + } + + /// + /// Enumerates the different DNS operation codes. + /// + public enum DnsOperationCode + { + /// + /// Query operation + /// + Query = 0, + + /// + /// IQuery operation + /// + IQuery, + + /// + /// Status operation + /// + Status, + + /// + /// Notify operation + /// + Notify = 4, + + /// + /// Update operation + /// + Update, + } + + /// + /// Enumerates the different DNS query response codes. + /// + public enum DnsResponseCode + { + /// + /// No error + /// + NoError = 0, + + /// + /// No error + /// + FormatError, + + /// + /// Format error + /// + ServerFailure, + + /// + /// Server failure error + /// + NameError, + + /// + /// Name error + /// + NotImplemented, + + /// + /// Not implemented error + /// + Refused, + + /// + /// Refused error + /// + YXDomain, + + /// + /// YXRR error + /// + YXRRSet, + + /// + /// NXRR Set error + /// + NXRRSet, + + /// + /// Not authorized error + /// + NotAuth, + + /// + /// Not zone error + /// + NotZone, + } + + #endregion + +} diff --git a/Unosquare.Swan/Networking/Enums.Smtp.cs b/Unosquare.Swan/Networking/Enums.Smtp.cs new file mode 100644 index 0000000..5d05d02 --- /dev/null +++ b/Unosquare.Swan/Networking/Enums.Smtp.cs @@ -0,0 +1,300 @@ +// ReSharper disable InconsistentNaming +namespace Unosquare.Swan.Networking +{ +#if NETSTANDARD1_3 + + /// + /// Defines the different SMTP status codes + /// + public enum SmtpStatusCode + { + /// + /// System code + /// + SystemStatus = 211, + + /// + /// Help message code + /// + HelpMessage = 214, + + /// + /// Service ready code + /// + ServiceReady = 220, + + /// + /// Service closing channel code + /// + ServiceClosingTransmissionChannel = 221, + + /// + /// OK Code + /// + Ok = 250, + + /// + /// User not local code + /// + UserNotLocalWillForward = 251, + + /// + /// Cannot verify user code + /// + CannotVerifyUserWillAttemptDelivery = 252, + + /// + /// Start Mail Input code + /// + StartMailInput = 354, + + /// + /// Service Not Available code + /// + ServiceNotAvailable = 421, + + /// + /// Mailbox Busy code + /// + MailboxBusy = 450, + + /// + /// Local Error code + /// + LocalErrorInProcessing = 451, + + /// + /// Insufficient storage code + /// + InsufficientStorage = 452, + + /// + /// Client not permitted code + /// + ClientNotPermitted = 454, + + /// + /// Command Unrecognized + /// + CommandUnrecognized = 500, + + /// + /// Syntax error + /// + SyntaxError = 501, + + /// + /// Command Not Implemented + /// + CommandNotImplemented = 502, + + /// + /// Bad Command Sequence + /// + BadCommandSequence = 503, + + /// + /// Must Issue Start Tls First + /// + MustIssueStartTlsFirst = 530, + + /// + /// Command Parameter Not Implemented + /// + CommandParameterNotImplemented = 504, + + /// + /// Mailbox Unavailable + /// + MailboxUnavailable = 550, + + /// + /// User Not Local Try Alternate Path + /// + UserNotLocalTryAlternatePath = 551, + + /// + /// Exceeded Storage Allocation code + /// + ExceededStorageAllocation = 552, + + /// + /// Mailbox name not allowed code + /// + MailboxNameNotAllowed = 553, + + /// + /// Transaction failed code + /// + TransactionFailed = 554, + + /// + /// General Failure code + /// + GeneralFailure = -1, + } +#endif + + /// + /// Enumerates all of the well-known SMTP command names. + /// + public enum SmtpCommandNames + { + /// + /// An unknown command + /// + Unknown, + + /// + /// The helo command + /// + HELO, + + /// + /// The ehlo command + /// + EHLO, + + /// + /// The quit command + /// + QUIT, + + /// + /// The help command + /// + HELP, + + /// + /// The noop command + /// + NOOP, + + /// + /// The rset command + /// + RSET, + + /// + /// The mail command + /// + MAIL, + + /// + /// The data command + /// + DATA, + + /// + /// The send command + /// + SEND, + + /// + /// The soml command + /// + SOML, + + /// + /// The saml command + /// + SAML, + + /// + /// The RCPT command + /// + RCPT, + + /// + /// The vrfy command + /// + VRFY, + + /// + /// The expn command + /// + EXPN, + + /// + /// The starttls command + /// + STARTTLS, + + /// + /// The authentication command + /// + AUTH, + } + + /// + /// Enumerates the reply code severities. + /// + public enum SmtpReplyCodeSeverities + { + /// + /// The unknown severity + /// + Unknown = 0, + + /// + /// The positive completion severity + /// + PositiveCompletion = 200, + + /// + /// The positive intermediate severity + /// + PositiveIntermediate = 300, + + /// + /// The transient negative severity + /// + TransientNegative = 400, + + /// + /// The permanent negative severity + /// + PermanentNegative = 500, + } + + /// + /// Enumerates the reply code categories. + /// + public enum SmtpReplyCodeCategories + { + /// + /// The unknown category + /// + Unknown = -1, + + /// + /// The syntax category + /// + Syntax = 0, + + /// + /// The information category + /// + Information = 1, + + /// + /// The connections category + /// + Connections = 2, + + /// + /// The unspecified a category + /// + UnspecifiedA = 3, + + /// + /// The unspecified b category + /// + UnspecifiedB = 4, + + /// + /// The system category + /// + System = 5, + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/JsonClient.cs b/Unosquare.Swan/Networking/JsonClient.cs new file mode 100644 index 0000000..164a1fa --- /dev/null +++ b/Unosquare.Swan/Networking/JsonClient.cs @@ -0,0 +1,400 @@ +namespace Unosquare.Swan.Networking +{ + using System; + using Exceptions; + using Models; + using Formatters; + using System.Collections.Generic; + using System.Net.Http; + using System.Security; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + + /// + /// Represents a HttpClient with extended methods to use with JSON payloads + /// and bearer tokens authentication. + /// + public static class JsonClient + { + private const string JsonMimeType = "application/json"; + + /// + /// Post a object as JSON with optional authorization token. + /// + /// The type of response object. + /// The URL. + /// The payload. + /// The authorization. + /// The cancellation token. + /// A task with a result of the requested type. + public static async Task Post( + string url, + object payload, + string authorization = null, + CancellationToken ct = default) + { + var jsonString = await PostString(url, payload, authorization, ct).ConfigureAwait(false); + + return !string.IsNullOrEmpty(jsonString) ? Json.Deserialize(jsonString) : default; + } + + /// + /// Posts a object as JSON with optional authorization token and retrieve an object + /// or an error. + /// + /// The type of response object. + /// The type of the error. + /// The URL. + /// The payload. + /// The HTTP status error. + /// The authorization. + /// The cancellation token. + /// A task with a result of the requested type or an error object. + public static async Task> PostOrError( + string url, + object payload, + int httpStatusError = 500, + string authorization = null, + CancellationToken ct = default) + { + using (var httpClient = GetHttpClientWithAuthorizationHeader(authorization)) + { + var payloadJson = new StringContent(Json.Serialize(payload), Encoding.UTF8, JsonMimeType); + + var response = await httpClient.PostAsync(url, payloadJson, ct).ConfigureAwait(false); + + var jsonString = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + + if (response.StatusCode == System.Net.HttpStatusCode.OK) + { + return OkOrError.FromOk(!string.IsNullOrEmpty(jsonString) + ? Json.Deserialize(jsonString) + : default); + } + + if ((int) response.StatusCode == httpStatusError) + { + return OkOrError.FromError(!string.IsNullOrEmpty(jsonString) + ? Json.Deserialize(jsonString) + : default); + } + + return new OkOrError(); + } + } + + /// + /// Posts the specified URL. + /// + /// The URL. + /// The payload. + /// The authorization. + /// The cancellation token. + /// A task with a result as a collection of key/value pairs. + public static async Task> Post( + string url, + object payload, + string authorization = null, + CancellationToken ct = default) + { + var jsonString = await PostString(url, payload, authorization, ct).ConfigureAwait(false); + + return string.IsNullOrWhiteSpace(jsonString) + ? default + : Json.Deserialize(jsonString) as IDictionary; + } + + /// + /// Posts the specified URL. + /// + /// The URL. + /// The payload. + /// The authorization. + /// The cancellation token. + /// + /// A task with a result of the requested string. + /// + /// url. + /// Error POST JSON. + public static Task PostString( + string url, + object payload, + string authorization = null, + CancellationToken ct = default) => SendAsync(HttpMethod.Post, url, payload, authorization, ct); + + /// + /// Puts the specified URL. + /// + /// The type of response object. + /// The URL. + /// The payload. + /// The authorization. + /// The cancellation token. + /// A task with a result of the requested type. + public static async Task Put( + string url, + object payload, + string authorization = null, + CancellationToken ct = default) + { + var jsonString = await PutString(url, payload, authorization, ct).ConfigureAwait(false); + + return !string.IsNullOrEmpty(jsonString) ? Json.Deserialize(jsonString) : default; + } + + /// + /// Puts the specified URL. + /// + /// The URL. + /// The payload. + /// The authorization. + /// The cancellation token. + /// A task with a result of the requested collection of key/value pairs. + public static async Task> Put( + string url, + object payload, + string authorization = null, + CancellationToken ct = default) + { + var response = await Put(url, payload, authorization, ct).ConfigureAwait(false); + + return response as IDictionary; + } + + /// + /// Puts as string. + /// + /// The URL. + /// The payload. + /// The authorization. + /// The cancellation token. + /// + /// A task with a result of the requested string. + /// + /// url. + /// Error PUT JSON. + public static Task PutString( + string url, + object payload, + string authorization = null, + CancellationToken ct = default) => SendAsync(HttpMethod.Put, url, payload, authorization, ct); + + /// + /// Gets as string. + /// + /// The URL. + /// The authorization. + /// The cancellation token. + /// + /// A task with a result of the requested string. + /// + /// url. + /// Error GET JSON. + public static async Task GetString( + string url, + string authorization = null, + CancellationToken ct = default) + { + var response = await GetHttpContent(url, authorization, ct).ConfigureAwait(false); + + return await response.ReadAsStringAsync().ConfigureAwait(false); + } + + /// + /// Gets the specified URL and return the JSON data as object + /// with optional authorization token. + /// + /// The response type. + /// The URL. + /// The authorization. + /// The cancellation token. + /// A task with a result of the requested type. + public static async Task Get( + string url, + string authorization = null, + CancellationToken ct = default) + { + var jsonString = await GetString(url, authorization, ct).ConfigureAwait(false); + + return !string.IsNullOrEmpty(jsonString) ? Json.Deserialize(jsonString) : default; + } + + /// + /// Gets the binary. + /// + /// The URL. + /// The authorization. + /// The cancellation token. + /// + /// A task with a result of the requested byte array. + /// + /// url. + /// Error GET Binary. + public static async Task GetBinary( + string url, + string authorization = null, + CancellationToken ct = default) + { + var response = await GetHttpContent(url, authorization, ct).ConfigureAwait(false); + + return await response.ReadAsByteArrayAsync().ConfigureAwait(false); + } + + /// + /// Authenticate against a web server using Bearer Token. + /// + /// The URL. + /// The username. + /// The password. + /// The cancellation token. + /// + /// A task with a Dictionary with authentication data. + /// + /// + /// url + /// or + /// username. + /// + /// Error Authenticating. + public static async Task> Authenticate( + string url, + string username, + string password, + CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(url)) + throw new ArgumentNullException(nameof(url)); + + if (string.IsNullOrWhiteSpace(username)) + throw new ArgumentNullException(nameof(username)); + + using (var httpClient = new HttpClient()) + { + // ignore empty password for now + var requestContent = new StringContent( + $"grant_type=password&username={username}&password={password}", + Encoding.UTF8, + "application/x-www-form-urlencoded"); + var response = await httpClient.PostAsync(url, requestContent, ct).ConfigureAwait(false); + + if (response.IsSuccessStatusCode == false) + throw new SecurityException($"Error Authenticating. Status code: {response.StatusCode}."); + + var jsonPayload = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + + return Json.Deserialize(jsonPayload) as IDictionary; + } + } + + /// + /// Posts the file. + /// + /// The URL. + /// The buffer. + /// Name of the file. + /// The authorization. + /// The cancellation token. + /// + /// A task with a result of the requested string. + /// + public static Task PostFileString( + string url, + byte[] buffer, + string fileName, + string authorization = null, + CancellationToken ct = default) + { + return PostString(url, new {Filename = fileName, Data = buffer}, authorization, ct); + } + + /// + /// Posts the file. + /// + /// The response type. + /// The URL. + /// The buffer. + /// Name of the file. + /// The authorization. + /// The cancellation token. + /// A task with a result of the requested string. + public static Task PostFile( + string url, + byte[] buffer, + string fileName, + string authorization = null, + CancellationToken ct = default) + { + return Post(url, new {Filename = fileName, Data = buffer}, authorization, ct); + } + + /// + /// Sends the asynchronous request. + /// + /// The method. + /// The URL. + /// The payload. + /// The authorization. + /// The cancellation token. + /// A task with a result of the requested string. + public static async Task SendAsync(HttpMethod method, + string url, + object payload, + string authorization = null, + CancellationToken ct = default) + { + if (string.IsNullOrWhiteSpace(url)) + throw new ArgumentNullException(nameof(url)); + + using (var httpClient = GetHttpClientWithAuthorizationHeader(authorization)) + { + var payloadJson = new StringContent(Json.Serialize(payload), Encoding.UTF8, JsonMimeType); + + var response = await httpClient + .SendAsync(new HttpRequestMessage(method, url) {Content = payloadJson}, ct).ConfigureAwait(false); + + if (response.IsSuccessStatusCode == false) + { + throw new JsonRequestException( + $"Error {method} JSON", + (int) response.StatusCode, + await response.Content.ReadAsStringAsync().ConfigureAwait(false)); + } + + return await response.Content.ReadAsStringAsync().ConfigureAwait(false); + } + } + + private static HttpClient GetHttpClientWithAuthorizationHeader(string authorization) + { + var httpClient = new HttpClient(); + + if (string.IsNullOrWhiteSpace(authorization) == false) + { + httpClient.DefaultRequestHeaders.Authorization = + new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authorization); + } + + return httpClient; + } + + private static async Task GetHttpContent( + string url, + string authorization, + CancellationToken ct) + { + if (string.IsNullOrWhiteSpace(url)) + throw new ArgumentNullException(nameof(url)); + + using (var httpClient = GetHttpClientWithAuthorizationHeader(authorization)) + { + var response = await httpClient.GetAsync(url, ct).ConfigureAwait(false); + + if (response.IsSuccessStatusCode == false) + throw new JsonRequestException("Error GET", (int) response.StatusCode); + + return response.Content; + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/Asn1.cs b/Unosquare.Swan/Networking/Ldap/Asn1.cs new file mode 100644 index 0000000..d2e0bc7 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/Asn1.cs @@ -0,0 +1,621 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System; + using System.IO; + using System.Text; + + /// + /// The Asn1Set class can hold an unordered collection of components with + /// identical type. This class inherits from the Asn1Structured class + /// which already provides functionality to hold multiple Asn1 components. + /// + /// + internal class Asn1SetOf + : Asn1Structured + { + public const int Tag = 0x11; + + public static readonly Asn1Identifier Id = new Asn1Identifier(Asn1IdentifierTag.Universal, true, Tag); + + public Asn1SetOf(int size = 10) + : base(Id, size) + { + } + + public override string ToString() => ToString("SET OF: { "); + } + + /// + /// The Asn1Choice object represents the choice of any Asn1Object. All + /// Asn1Object methods are delegated to the object this Asn1Choice contains. + /// + /// + internal class Asn1Choice + : Asn1Object + { + private Asn1Object _content; + + public Asn1Choice(Asn1Object content = null) + { + _content = content; + } + + protected internal virtual Asn1Object ChoiceValue + { + get => _content; + set => _content = value; + } + + public override Asn1Identifier GetIdentifier() => _content.GetIdentifier(); + + public override void SetIdentifier(Asn1Identifier id) => _content.SetIdentifier(id); + + public override string ToString() => _content.ToString(); + } + + /// + /// This class is used to encapsulate an ASN.1 Identifier. + /// An Asn1Identifier is composed of three parts: + ///
  • a class type,
  • a form, and
  • a tag.
  • + /// The class type is defined as: + ///
    +    /// bit 8 7 TAG CLASS
    +    /// ------- -----------
    +    /// 0 0 UNIVERSAL
    +    /// 0 1 APPLICATION
    +    /// 1 0 CONTEXT
    +    /// 1 1 PRIVATE
    +    /// 
    + /// The form is defined as: + ///
    +    /// bit 6 FORM
    +    /// ----- --------
    +    /// 0 PRIMITIVE
    +    /// 1 CONSTRUCTED
    +    /// 
    + /// Note: CONSTRUCTED types are made up of other CONSTRUCTED or PRIMITIVE + /// types. + /// The tag is defined as:. + ///
    +    /// bit 5 4 3 2 1 TAG
    +    /// ------------- ---------------------------------------------
    +    /// 0 0 0 0 0
    +    /// . . . . .
    +    /// 1 1 1 1 0 (0-30) single octet tag
    +    /// 1 1 1 1 1 (> 30) multiple octet tag, more octets follow
    +    /// 
    + internal sealed class Asn1Identifier + { + public Asn1Identifier(Asn1IdentifierTag tagClass, bool constructed, int tag) + { + Asn1Class = tagClass; + Constructed = constructed; + Tag = tag; + } + + public Asn1Identifier(LdapOperation tag) + : this(Asn1IdentifierTag.Application, true, (int) tag) + { + } + + public Asn1Identifier(int contextTag, bool constructed = false) + : this(Asn1IdentifierTag.Context, constructed, contextTag) + { + } + + public Asn1Identifier(Stream stream) + { + var r = stream.ReadByte(); + EncodedLength++; + + if (r < 0) + throw new EndOfStreamException("BERDecoder: decode: EOF in Identifier"); + + Asn1Class = (Asn1IdentifierTag) (r >> 6); + Constructed = (r & 0x20) != 0; + Tag = r & 0x1F; // if tag < 30 then its a single octet identifier. + + if (Tag == 0x1F) + { + // if true, its a multiple octet identifier. + Tag = DecodeTagNumber(stream); + } + } + + public Asn1IdentifierTag Asn1Class { get; } + + public bool Constructed { get; } + + public int Tag { get; } + + public int EncodedLength { get; private set; } + + public bool Universal => Asn1Class == Asn1IdentifierTag.Universal; + + public object Clone() => MemberwiseClone(); + + private int DecodeTagNumber(Stream stream) + { + var n = 0; + while (true) + { + var r = stream.ReadByte(); + EncodedLength++; + if (r < 0) + throw new EndOfStreamException("BERDecoder: decode: EOF in tag number"); + + n = (n << 7) + (r & 0x7F); + if ((r & 0x80) == 0) break; + } + + return n; + } + } + + /// + /// This is the base class for all other Asn1 types. + /// + internal abstract class Asn1Object + { + private static readonly string[] ClassTypes = {"[UNIVERSAL ", "[APPLICATION ", "[", "[PRIVATE "}; + + private Asn1Identifier _id; + + protected Asn1Object(Asn1Identifier id = null) + { + _id = id; + } + + public virtual Asn1Identifier GetIdentifier() => _id; + + public virtual void SetIdentifier(Asn1Identifier identifier) => _id = identifier; + + public override string ToString() + { + var identifier = GetIdentifier(); + + return $"{ClassTypes[(int) identifier.Asn1Class]}{identifier.Tag}]"; + } + } + + /// + /// This class encapsulates the OCTET STRING type. + /// + /// + internal sealed class Asn1OctetString + : Asn1Object + { + public const int Tag = 0x04; + + private static readonly Asn1Identifier Id = new Asn1Identifier(Asn1IdentifierTag.Universal, false, Tag); + + private readonly sbyte[] _content; + + public Asn1OctetString(sbyte[] content) + : base(Id) + { + _content = content; + } + + public Asn1OctetString(string content) + : base(Id) + { + _content = Encoding.UTF8.GetSBytes(content); + } + + public Asn1OctetString(Stream stream, int len) + : base(Id) + { + _content = len > 0 ? (sbyte[]) LberDecoder.DecodeOctetString(stream, len) : new sbyte[0]; + } + + public sbyte[] ByteValue() => _content; + + public string StringValue() => Encoding.UTF8.GetString(_content); + + public override string ToString() => base.ToString() + "OCTET STRING: " + StringValue(); + } + + /// + /// The Asn1Tagged class can hold a base Asn1Object with a distinctive tag + /// describing the type of that base object. It also maintains a boolean value + /// indicating whether the value should be encoded by EXPLICIT or IMPLICIT + /// means. (Explicit is true by default.) + /// If the type is encoded IMPLICITLY, the base types form, length and content + /// will be encoded as usual along with the class type and tag specified in + /// the constructor of this Asn1Tagged class. + /// If the type is to be encoded EXPLICITLY, the base type will be encoded as + /// usual after the Asn1Tagged identifier has been encoded. + /// + /// + internal class Asn1Tagged : Asn1Object + { + private Asn1Object _content; + + public Asn1Tagged(Asn1Identifier identifier, Asn1Object obj = null, bool isExplicit = true) + : base(identifier) + { + _content = obj; + Explicit = isExplicit; + + if (!isExplicit) + { + // replace object's id with new tag. + _content?.SetIdentifier(identifier); + } + } + + public Asn1Tagged(Asn1Identifier identifier, sbyte[] vals) + : base(identifier) + { + _content = new Asn1OctetString(vals); + Explicit = false; + } + + public Asn1Tagged(Stream stream, int len, Asn1Identifier identifier) + : base(identifier) + { + // If we are decoding an implicit tag, there is no way to know at this + // low level what the base type really is. We can place the content + // into an Asn1OctetString type and pass it back to the application who + // will be able to create the appropriate ASN.1 type for this tag. + _content = new Asn1OctetString(stream, len); + } + + public Asn1Object TaggedValue + { + get => _content; + + set + { + _content = value; + if (!Explicit) + { + // replace object's id with new tag. + value?.SetIdentifier(GetIdentifier()); + } + } + } + + public bool Explicit { get; } + + public override string ToString() => Explicit ? base.ToString() + _content : _content.ToString(); + } + + /// + /// This class serves as the base type for all ASN.1 + /// structured types. + /// + /// + internal abstract class Asn1Structured : Asn1Object + { + private Asn1Object[] _content; + private int _contentIndex; + + protected internal Asn1Structured(Asn1Identifier id, int size = 10) + : base(id) + { + _content = new Asn1Object[size]; + } + + public Asn1Object[] ToArray() + { + var cloneArray = new Asn1Object[_contentIndex]; + Array.Copy(_content, 0, cloneArray, 0, _contentIndex); + return cloneArray; + } + + public void Add(string s) => Add(new Asn1OctetString(s)); + + public void Add(Asn1Object obj) + { + if (_contentIndex == _content.Length) + { + // Array too small, need to expand it, double length + var newArray = new Asn1Object[_contentIndex + _contentIndex]; + Array.Copy(_content, 0, newArray, 0, _contentIndex); + _content = newArray; + } + + _content[_contentIndex++] = obj; + } + + public void Set(int index, Asn1Object value) + { + if (index >= _contentIndex || index < 0) + { + throw new IndexOutOfRangeException($"Asn1Structured: get: index {index}, size {_contentIndex}"); + } + + _content[index] = value; + } + + public Asn1Object Get(int index) + { + if (index >= _contentIndex || index < 0) + { + throw new IndexOutOfRangeException($"Asn1Structured: set: index {index}, size {_contentIndex}"); + } + + return _content[index]; + } + + public int Size() => _contentIndex; + + public string ToString(string type) + { + var sb = new StringBuilder().Append(type); + + for (var i = 0; i < _contentIndex; i++) + { + sb.Append(_content[i]); + if (i != _contentIndex - 1) + sb.Append(", "); + } + + sb.Append(" }"); + + return base.ToString() + sb; + } + + protected internal void DecodeStructured(Stream stream, int len) + { + var componentLen = new int[1]; // collects length of component + + while (len > 0) + { + Add(LberDecoder.Decode(stream, componentLen)); + len -= componentLen[0]; + } + } + } + + /// + /// This class encapsulates the ASN.1 BOOLEAN type. + /// + /// + internal class Asn1Boolean + : Asn1Object + { + public const int Tag = 0x01; + + public static readonly Asn1Identifier Id = new Asn1Identifier(Asn1IdentifierTag.Universal, false, Tag); + + private readonly bool _content; + + public Asn1Boolean(bool content) + : base(Id) + { + _content = content; + } + + public Asn1Boolean(Stream stream, int len) + : base(Id) + { + _content = LberDecoder.DecodeBoolean(stream, len); + } + + public bool BooleanValue() => _content; + + public override string ToString() => $"{base.ToString()}BOOLEAN: {_content}"; + } + + /// + /// This class represents the ASN.1 NULL type. + /// + /// + internal sealed class Asn1Null + : Asn1Object + { + public const int Tag = 0x05; + + public static readonly Asn1Identifier Id = new Asn1Identifier(Asn1IdentifierTag.Universal, false, Tag); + + public Asn1Null() + : base(Id) + { + } + + public override string ToString() => $"{base.ToString()}NULL: \"\""; + } + + /// + /// This abstract class is the base class + /// for all Asn1 numeric (integral) types. These include + /// Asn1Integer and Asn1Enumerated. + /// + /// + internal abstract class Asn1Numeric : Asn1Object + { + private readonly long _content; + + internal Asn1Numeric(Asn1Identifier id, int numericValue) + : base(id) + { + _content = numericValue; + } + + internal Asn1Numeric(Asn1Identifier id, long numericValue) + : base(id) + { + _content = numericValue; + } + + public int IntValue() => (int) _content; + + public long LongValue() => _content; + } + + /// + /// This class provides a means to manipulate ASN.1 Length's. It will + /// be used by Asn1Encoder's and Asn1Decoder's by composition. + /// + internal sealed class Asn1Length + { + public Asn1Length(Stream stream) + { + var r = stream.ReadByte(); + EncodedLength++; + if (r == 0x80) + { + Length = -1; + } + else if (r < 0x80) + { + Length = r; + } + else + { + Length = 0; + for (r = r & 0x7F; r > 0; r--) + { + var part = stream.ReadByte(); + EncodedLength++; + if (part < 0) + throw new EndOfStreamException("BERDecoder: decode: EOF in Asn1Length"); + Length = (Length << 8) + part; + } + } + } + + public int Length { get; } + + public int EncodedLength { get; } + } + + /// + /// The Asn1Sequence class can hold an ordered collection of components with + /// distinct type. + /// This class inherits from the Asn1Structured class which + /// provides functionality to hold multiple Asn1 components. + /// + /// + internal class Asn1Sequence + : Asn1Structured + { + public const int Tag = 0x10; + + private static readonly Asn1Identifier Id = new Asn1Identifier(Asn1IdentifierTag.Universal, true, Tag); + + public Asn1Sequence(int size) + : base(Id, size) + { + } + + public Asn1Sequence(Stream stream, int len) + : base(Id) + { + DecodeStructured(stream, len); + } + + public override string ToString() => ToString("SEQUENCE: { "); + } + + /// + /// The Asn1Set class can hold an unordered collection of components with + /// distinct type. This class inherits from the Asn1Structured class + /// which already provides functionality to hold multiple Asn1 components. + /// + /// + internal sealed class Asn1Set + : Asn1Structured + { + public const int Tag = 0x11; + + public static readonly Asn1Identifier Id = new Asn1Identifier(Asn1IdentifierTag.Universal, true, Tag); + + public Asn1Set(Stream stream, int len) + : base(Id) + { + DecodeStructured(stream, len); + } + + public override string ToString() => ToString("SET: { "); + } + + /// + /// This class encapsulates the ASN.1 INTEGER type. + /// + /// + internal class Asn1Integer + : Asn1Numeric + { + public const int Tag = 0x02; + + public static readonly Asn1Identifier Id = new Asn1Identifier(Asn1IdentifierTag.Universal, false, Tag); + + public Asn1Integer(int content) + : base(Id, content) + { + } + + public Asn1Integer(Stream stream, int len) + : base(Id, LberDecoder.DecodeNumeric(stream, len)) + { + } + + public override string ToString() => base.ToString() + "INTEGER: " + LongValue(); + } + + /// + /// This class encapsulates the ASN.1 ENUMERATED type. + /// + /// + internal sealed class Asn1Enumerated : Asn1Numeric + { + public const int Tag = 0x0a; + + public static readonly Asn1Identifier Id = new Asn1Identifier(Asn1IdentifierTag.Universal, false, Tag); + + public Asn1Enumerated(LdapScope content) + : base(Id, (int) content) + { + } + + public Asn1Enumerated(int content) + : base(Id, content) + { + } + + /// + /// Initializes a new instance of the class. + /// Constructs an Asn1Enumerated object by decoding data from an + /// input stream. + /// + /// The stream. + /// The length. + public Asn1Enumerated(Stream stream, int len) + : base(Id, LberDecoder.DecodeNumeric(stream, len)) + { + } + + public override string ToString() => base.ToString() + "ENUMERATED: " + LongValue(); + } + + /// + /// The Asn1SequenceOf class is used to hold an ordered collection + /// of components with identical type. This class inherits + /// from the Asn1Structured class which already provides + /// functionality to hold multiple Asn1 components. + /// + /// + internal class Asn1SequenceOf : Asn1Structured + { + public const int Tag = 0x10; + + public static readonly Asn1Identifier Id = new Asn1Identifier(Asn1IdentifierTag.Universal, true, Tag); + + public Asn1SequenceOf(int size) + : base(Id, size) + { + } + + public Asn1SequenceOf(Stream stream, int len) + : base(Id) + { + DecodeStructured(stream, len); + } + + public override string ToString() => ToString("SEQUENCE OF: { "); + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LberDecoder.cs b/Unosquare.Swan/Networking/Ldap/LberDecoder.cs new file mode 100644 index 0000000..1b2892b --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LberDecoder.cs @@ -0,0 +1,166 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System.IO; + + /// + /// This class provides LBER decoding routines for ASN.1 Types. LBER is a + /// subset of BER as described in the following taken from 5.1 of RFC 2251: + /// 5.1. Mapping Onto BER-based Transport Services + /// The protocol elements of Ldap are encoded for exchange using the + /// Basic Encoding Rules (BER) [11] of ASN.1 [3]. However, due to the + /// high overhead involved in using certain elements of the BER, the + /// following additional restrictions are placed on BER-encodings of Ldap + /// protocol elements: + ///
  • (1) Only the definite form of length encoding will be used.
  • + ///
  • (2) OCTET STRING values will be encoded in the primitive form only.
  • + /// (3) If the value of a BOOLEAN type is true, the encoding MUST have + /// its contents octets set to hex "FF". + ///
  • + /// (4) If a value of a type is its default value, it MUST be absent. + /// Only some BOOLEAN and INTEGER types have default values in this + /// protocol definition. + /// These restrictions do not apply to ASN.1 types encapsulated inside of + /// OCTET STRING values, such as attribute values, unless otherwise + /// noted. + ///
  • + /// [3] ITU-T Rec. X.680, "Abstract Syntax Notation One (ASN.1) - + /// Specification of Basic Notation", 1994. + /// [11] ITU-T Rec. X.690, "Specification of ASN.1 encoding rules: Basic, + /// Canonical, and Distinguished Encoding Rules", 1994. + ///
    + internal static class LberDecoder + { + /// + /// Decode an LBER encoded value into an Asn1Object from an InputStream. + /// This method also returns the total length of this encoded + /// Asn1Object (length of type + length of length + length of content) + /// in the parameter len. This information is helpful when decoding + /// structured types. + /// + /// The stream. + /// The length. + /// + /// Decoded Asn1Obect. + /// + /// Unknown tag. + public static Asn1Object Decode(Stream stream, int[] len) + { + var asn1Id = new Asn1Identifier(stream); + var asn1Len = new Asn1Length(stream); + + var length = asn1Len.Length; + len[0] = asn1Id.EncodedLength + asn1Len.EncodedLength + length; + + if (asn1Id.Universal == false) + return new Asn1Tagged(stream, length, (Asn1Identifier) asn1Id.Clone()); + + switch (asn1Id.Tag) + { + case Asn1Sequence.Tag: + return new Asn1Sequence(stream, length); + + case Asn1Set.Tag: + return new Asn1Set(stream, length); + + case Asn1Boolean.Tag: + return new Asn1Boolean(stream, length); + + case Asn1Integer.Tag: + return new Asn1Integer(stream, length); + + case Asn1OctetString.Tag: + return new Asn1OctetString(stream, length); + + case Asn1Enumerated.Tag: + return new Asn1Enumerated(stream, length); + + case Asn1Null.Tag: + return new Asn1Null(); // has no content to decode. + + default: + throw new EndOfStreamException("Unknown tag"); + } + } + + /// + /// Decode a boolean directly from a stream. + /// + /// The stream. + /// Length in bytes. + /// + /// Decoded boolean object. + /// + /// LBER: BOOLEAN: decode error: EOF. + public static bool DecodeBoolean(Stream stream, int len) + { + var lber = new sbyte[len]; + + if (stream.ReadInput(ref lber, 0, lber.Length) != len) + throw new EndOfStreamException("LBER: BOOLEAN: decode error: EOF"); + + return lber[0] != 0x00; + } + + /// + /// Decode a Numeric type directly from a stream. Decodes INTEGER + /// and ENUMERATED types. + /// + /// The stream. + /// Length in bytes. + /// + /// Decoded numeric object. + /// + /// + /// LBER: NUMERIC: decode error: EOF + /// or + /// LBER: NUMERIC: decode error: EOF. + /// + public static long DecodeNumeric(Stream stream, int len) + { + long l = 0; + var r = stream.ReadByte(); + + if (r < 0) + throw new EndOfStreamException("LBER: NUMERIC: decode error: EOF"); + + if ((r & 0x80) != 0) + { + // check for negative number + l = -1; + } + + l = (l << 8) | r; + + for (var i = 1; i < len; i++) + { + r = stream.ReadByte(); + if (r < 0) + throw new EndOfStreamException("LBER: NUMERIC: decode error: EOF"); + + l = (l << 8) | r; + } + + return l; + } + + /// + /// Decode an OctetString directly from a stream. + /// + /// The stream. + /// Length in bytes. + /// Decoded octet. + public static object DecodeOctetString(Stream stream, int len) + { + var octets = new sbyte[len]; + var totalLen = 0; + + while (totalLen < len) + { + // Make sure we have read all the data + totalLen += stream.ReadInput(ref octets, totalLen, len - totalLen); + } + + return octets; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LberEncoder.cs b/Unosquare.Swan/Networking/Ldap/LberEncoder.cs new file mode 100644 index 0000000..eb36934 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LberEncoder.cs @@ -0,0 +1,246 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System.IO; + + /// + /// This class provides LBER encoding routines for ASN.1 Types. LBER is a + /// subset of BER as described in the following taken from 5.1 of RFC 2251: + /// 5.1. Mapping Onto BER-based Transport Services + /// The protocol elements of Ldap are encoded for exchange using the + /// Basic Encoding Rules (BER) [11] of ASN.1 [3]. However, due to the + /// high overhead involved in using certain elements of the BER, the + /// following additional restrictions are placed on BER-encodings of Ldap + /// protocol elements: + ///
  • (1) Only the definite form of length encoding will be used.
  • + ///
  • (2) OCTET STRING values will be encoded in the primitive form only.
  • + /// (3) If the value of a BOOLEAN type is true, the encoding MUST have + /// its contents octets set to hex "FF". + ///
  • + /// (4) If a value of a type is its default value, it MUST be absent. + /// Only some BOOLEAN and INTEGER types have default values in this + /// protocol definition. + /// These restrictions do not apply to ASN.1 types encapsulated inside of + /// OCTET STRING values, such as attribute values, unless otherwise + /// noted. + ///
  • + /// [3] ITU-T Rec. X.680, "Abstract Syntax Notation One (ASN.1) - + /// Specification of Basic Notation", 1994. + /// [11] ITU-T Rec. X.690, "Specification of ASN.1 encoding rules: Basic, + /// Canonical, and Distinguished Encoding Rules", 1994. + ///
    + internal static class LberEncoder + { + /// + /// BER Encode an Asn1Boolean directly into the specified output stream. + /// + /// The Asn1Boolean object to encode. + /// The stream. + public static void Encode(Asn1Boolean b, Stream stream) + { + Encode(b.GetIdentifier(), stream); + stream.WriteByte(0x01); + stream.WriteByte((byte) (b.BooleanValue() ? 0xff : 0x00)); + } + + /// + /// Encode an Asn1Numeric directly into the specified outputstream. + /// Use a two's complement representation in the fewest number of octets + /// possible. + /// Can be used to encode INTEGER and ENUMERATED values. + /// + /// The Asn1Numeric object to encode. + /// The stream. + public static void Encode(Asn1Numeric n, Stream stream) + { + var octets = new sbyte[8]; + sbyte len; + var longValue = n.LongValue(); + long endValue = longValue < 0 ? -1 : 0; + var endSign = endValue & 0x80; + + for (len = 0; len == 0 || longValue != endValue || (octets[len - 1] & 0x80) != endSign; len++) + { + octets[len] = (sbyte)(longValue & 0xFF); + longValue >>= 8; + } + + Encode(n.GetIdentifier(), stream); + stream.WriteByte((byte)len); + + for (var i = len - 1; i >= 0; i--) + { + stream.WriteByte((byte) octets[i]); + } + } + + /// + /// Encode an Asn1OctetString directly into the specified outputstream. + /// + /// The Asn1OctetString object to encode. + /// The stream. + public static void Encode(Asn1OctetString os, Stream stream) + { + Encode(os.GetIdentifier(), stream); + EncodeLength(os.ByteValue().Length, stream); + var tempSbyteArray = os.ByteValue(); + stream.Write(tempSbyteArray.ToByteArray(), 0, tempSbyteArray.Length); + } + + public static void Encode(Asn1Object obj, Stream stream) + { + switch (obj) + { + case Asn1Boolean b: + Encode(b, stream); + break; + case Asn1Numeric n: + Encode(n, stream); + break; + case Asn1Null n: + Encode(n.GetIdentifier(), stream); + stream.WriteByte(0x00); // Length (with no Content) + break; + case Asn1OctetString n: + Encode(n, stream); + break; + case Asn1Structured n: + Encode(n, stream); + break; + case Asn1Tagged n: + Encode(n, stream); + break; + case Asn1Choice n: + Encode(n.ChoiceValue, stream); + break; + default: + throw new InvalidDataException(); + } + } + + /// + /// Encode an Asn1Structured into the specified outputstream. This method + /// can be used to encode SET, SET_OF, SEQUENCE, SEQUENCE_OF. + /// + /// The Asn1Structured object to encode. + /// The stream. + public static void Encode(Asn1Structured c, Stream stream) + { + Encode(c.GetIdentifier(), stream); + + var arrayValue = c.ToArray(); + + using (var output = new MemoryStream()) + { + foreach (var obj in arrayValue) + { + Encode(obj, output); + } + + EncodeLength((int) output.Length, stream); + + var tempSbyteArray = output.ToArray(); + stream.Write(tempSbyteArray, 0, tempSbyteArray.Length); + } + } + + /// + /// Encode an Asn1Tagged directly into the specified outputstream. + /// + /// The Asn1Tagged object to encode. + /// The stream. + public static void Encode(Asn1Tagged t, Stream stream) + { + if (!t.Explicit) + { + Encode(t.TaggedValue, stream); + return; + } + + Encode(t.GetIdentifier(), stream); + + // determine the encoded length of the base type. + using (var encodedContent = new MemoryStream()) + { + Encode(t.TaggedValue, encodedContent); + + EncodeLength((int) encodedContent.Length, stream); + var tempSbyteArray = encodedContent.ToArray().ToSByteArray(); + stream.Write(tempSbyteArray.ToByteArray(), 0, tempSbyteArray.Length); + } + } + + /// + /// Encode an Asn1Identifier directly into the specified outputstream. + /// + /// The Asn1Identifier object to encode. + /// The stream. + public static void Encode(Asn1Identifier id, Stream stream) + { + var c = (int) id.Asn1Class; + var t = id.Tag; + var ccf = (sbyte)((c << 6) | (id.Constructed ? 0x20 : 0)); + + if (t < 30) + { + stream.WriteByte((byte)(ccf | t)); + } + else + { + stream.WriteByte((byte)(ccf | 0x1F)); + EncodeTagInteger(t, stream); + } + } + + /// + /// Encodes the length. + /// + /// The length. + /// The stream. + private static void EncodeLength(int length, Stream stream) + { + if (length < 0x80) + { + stream.WriteByte((byte)length); + } + else + { + var octets = new sbyte[4]; // 4 bytes sufficient for 32 bit int. + sbyte n; + for (n = 0; length != 0; n++) + { + octets[n] = (sbyte)(length & 0xFF); + length >>= 8; + } + + stream.WriteByte((byte)(0x80 | n)); + + for (var i = n - 1; i >= 0; i--) + stream.WriteByte((byte)octets[i]); + } + } + + /// + /// Encodes the provided tag into the stream. + /// + /// The value. + /// The stream. + private static void EncodeTagInteger(int val, Stream stream) + { + var octets = new sbyte[5]; + int n; + + for (n = 0; val != 0; n++) + { + octets[n] = (sbyte)(val & 0x7F); + val = val >> 7; + } + + for (var i = n - 1; i > 0; i--) + { + stream.WriteByte((byte)(octets[i] | 0x80)); + } + + stream.WriteByte((byte)octets[0]); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapConnection.cs b/Unosquare.Swan/Networking/Ldap/LdapConnection.cs new file mode 100644 index 0000000..bbba3e5 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapConnection.cs @@ -0,0 +1,402 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.IO; + using System.Net.Sockets; + using System.Text; + using System.Threading; + using System.Threading.Tasks; + using Exceptions; + + /// + /// The central class that encapsulates the connection + /// to a directory server through the Ldap protocol. + /// LdapConnection objects are used to perform common Ldap + /// operations such as search, modify and add. + /// In addition, LdapConnection objects allow you to bind to an + /// Ldap server, set connection and search constraints, and perform + /// several other tasks. + /// An LdapConnection object is not connected on + /// construction and can only be connected to one server at one + /// port. + /// + /// Based on https://github.com/dsbenghe/Novell.Directory.Ldap.NETStandard. + /// + /// + /// The following code describes how to use the LdapConnection class: + /// + /// + /// class Example + /// { + /// using Unosquare.Swan; + /// using Unosquare.Swan.Networking.Ldap; + /// using System.Threading.Tasks; + /// + /// static async Task Main() + /// { + /// // create a LdapConnection object + /// var connection = new LdapConnection(); + /// + /// // connect to a server + /// await connection.Connect("ldap.forumsys.com", 389); + /// + /// // set up the credentials + /// await connection.Bind("cn=read-only-admin,dc=example,dc=com", "password"); + /// + /// // retrieve all entries that have the specified email using ScopeSub + /// // which searches all entries at all levels under + /// // and including the specified base DN + /// var searchResult = await connection + /// .Search("dc=example,dc=com", LdapConnection.ScopeSub, "(cn=Isaac Newton)"); + /// + /// // if there are more entries remaining keep going + /// while (searchResult.HasMore()) + /// { + /// // point to the next entry + /// var entry = searchResult.Next(); + /// + /// // get all attributes + /// var entryAttributes = entry.GetAttributeSet(); + /// + /// // select its name and print it out + /// entryAttributes.GetAttribute("cn").StringValue.Info(); + /// } + /// + /// // modify Tesla and sets its email as tesla@email.com + /// connection.Modify("uid=tesla,dc=example,dc=com", + /// new[] { + /// new LdapModification(LdapModificationOp.Replace, + /// "mail", "tesla@email.com") + /// }); + /// + /// // delete the listed values from the given attribute + /// connection.Modify("uid=tesla,dc=example,dc=com", + /// new[] { + /// new LdapModification(LdapModificationOp.Delete, + /// "mail", "tesla@email.com") + /// }); + /// + /// // add back the recently deleted property + /// connection.Modify("uid=tesla,dc=example,dc=com", + /// new[] { + /// new LdapModification(LdapModificationOp.Add, + /// "mail", "tesla@email.com") + /// }); + /// + /// // disconnect from the LDAP server + /// connection.Disconnect(); + /// + /// Terminal.Flush(); + /// } + /// } + /// + /// + public class LdapConnection : IDisposable + { + private const int LdapV3 = 3; + + private readonly CancellationTokenSource _cts = new CancellationTokenSource(); + + private Connection _conn; + private bool _isDisposing; + + /// + /// Returns the protocol version uses to authenticate. + /// 0 is returned if no authentication has been performed. + /// + /// + /// The protocol version. + /// + public int ProtocolVersion => BindProperties?.ProtocolVersion ?? LdapV3; + + /// + /// Returns the distinguished name (DN) used for as the bind name during + /// the last successful bind operation. null is returned + /// if no authentication has been performed or if the bind resulted in + /// an anonymous connection. + /// + /// + /// The authentication dn. + /// + public string AuthenticationDn => BindProperties == null ? null : (BindProperties.Anonymous ? null : BindProperties.AuthenticationDN); + + /// + /// Returns the method used to authenticate the connection. The return + /// value is one of the following:. + ///
    • "none" indicates the connection is not authenticated.
    • + /// "simple" indicates simple authentication was used or that a null + /// or empty authentication DN was specified. + ///
    • "sasl" indicates that a SASL mechanism was used to authenticate
    + ///
    + /// + /// The authentication method. + /// + public string AuthenticationMethod => BindProperties == null ? "simple" : BindProperties.AuthenticationMethod; + + /// + /// Indicates whether the connection represented by this object is open + /// at this time. + /// + /// + /// True if connection is open; false if the connection is closed. + /// + public bool Connected => _conn?.IsConnected == true; + + internal BindProperties BindProperties { get; set; } + + internal List Messages { get; } = new List(); + + /// + public void Dispose() + { + if (_isDisposing) return; + + _isDisposing = true; + Disconnect(); + _cts?.Dispose(); + } + + /// + /// Synchronously authenticates to the Ldap server (that the object is + /// currently connected to) using the specified name, password, Ldap version, + /// and constraints. + /// If the object has been disconnected from an Ldap server, + /// this method attempts to reconnect to the server. If the object + /// has already authenticated, the old authentication is discarded. + /// + /// If non-null and non-empty, specifies that the + /// connection and all operations through it should + /// be authenticated with dn as the distinguished + /// name. + /// If non-null and non-empty, specifies that the + /// connection and all operations through it should + /// be authenticated with dn as the distinguished + /// name and password. + /// Note: the application should use care in the use + /// of String password objects. These are long lived + /// objects, and may expose a security risk, especially + /// in objects that are serialized. The LdapConnection + /// keeps no long lived instances of these objects. + /// + /// A representing the asynchronous operation. + /// + public Task Bind(string dn, string password) => Bind(LdapV3, dn, password); + + /// + /// Synchronously authenticates to the Ldap server (that the object is + /// currently connected to) using the specified name, password, Ldap version, + /// and constraints. + /// If the object has been disconnected from an Ldap server, + /// this method attempts to reconnect to the server. If the object + /// has already authenticated, the old authentication is discarded. + /// + /// The Ldap protocol version, use Ldap_V3. + /// Ldap_V2 is not supported. + /// If non-null and non-empty, specifies that the + /// connection and all operations through it should + /// be authenticated with dn as the distinguished + /// name. + /// If non-null and non-empty, specifies that the + /// connection and all operations through it should + /// be authenticated with dn as the distinguished + /// name and passwd as password. + /// Note: the application should use care in the use + /// of String password objects. These are long lived + /// objects, and may expose a security risk, especially + /// in objects that are serialized. The LdapConnection + /// keeps no long lived instances of these objects. + /// A representing the asynchronous operation. + public Task Bind(int version, string dn, string password) + { + dn = string.IsNullOrEmpty(dn) ? string.Empty : dn.Trim(); + var passwordData = string.IsNullOrWhiteSpace(password) ? new sbyte[] { } : Encoding.UTF8.GetSBytes(password); + + var anonymous = false; + + if (passwordData.Length == 0) + { + anonymous = true; // anonymous, password length zero with simple bind + dn = string.Empty; // set to null if anonymous + } + + BindProperties = new BindProperties(version, dn, "simple", anonymous); + + return RequestLdapMessage(new LdapBindRequest(version, dn, passwordData)); + } + + /// + /// Connects to the specified host and port. + /// If this LdapConnection object represents an open connection, the + /// connection is closed first before the new connection is opened. + /// At this point, there is no authentication, and any operations are + /// conducted as an anonymous client. + /// + /// A host name or a dotted string representing the IP address + /// of a host running an Ldap server. + /// The TCP or UDP port number to connect to or contact. + /// The default Ldap port is 389. + /// A representing the asynchronous operation. + public async Task Connect(string host, int port) + { + var tcpClient = new TcpClient(); + await tcpClient.ConnectAsync(host, port).ConfigureAwait(false); + _conn = new Connection(tcpClient, Encoding.UTF8, "\r\n", true, 0); + +#pragma warning disable 4014 + Task.Run(() => RetrieveMessages(), _cts.Token); +#pragma warning restore 4014 + } + + /// + /// Synchronously disconnects from the Ldap server. + /// Before the object can perform Ldap operations again, it must + /// reconnect to the server by calling connect. + /// The disconnect method abandons any outstanding requests, issues an + /// unbind request to the server, and then closes the socket. + /// + public void Disconnect() + { + // disconnect from API call + _cts.Cancel(); + _conn.Disconnect(); + } + + /// + /// Synchronously reads the entry for the specified distinguished name (DN), + /// using the specified constraints, and retrieves only the specified + /// attributes from the entry. + /// + /// The distinguished name of the entry to retrieve. + /// The names of the attributes to retrieve. + /// The cancellation token. + /// + /// the LdapEntry read from the server. + /// + /// Read response is ambiguous, multiple entries returned. + public async Task Read(string dn, string[] attrs = null, CancellationToken ct = default) + { + var sr = await Search(dn, LdapScope.ScopeSub, null, attrs, false, ct); + LdapEntry ret = null; + + if (sr.HasMore()) + { + ret = sr.Next(); + if (sr.HasMore()) + { + throw new LdapException("Read response is ambiguous, multiple entries returned", LdapStatusCode.AmbiguousResponse); + } + } + + return ret; + } + + /// + /// Performs the search specified by the parameters, + /// also allowing specification of constraints for the search (such + /// as the maximum number of entries to find or the maximum time to + /// wait for search results). + /// + /// The base distinguished name to search from. + /// The scope of the entries to search. + /// The search filter specifying the search criteria. + /// The names of attributes to retrieve. + /// If true, returns the names but not the values of + /// the attributes found. If false, returns the + /// names and values for attributes found. + /// The cancellation token. + /// + /// A representing the asynchronous operation. + /// + public async Task Search( + string @base, + LdapScope scope, + string filter = "objectClass=*", + string[] attrs = null, + bool typesOnly = false, + CancellationToken ct = default) + { + // TODO: Add Search options + var msg = new LdapSearchRequest(@base, scope, filter, attrs, 0, 1000, 0, typesOnly, null); + + await RequestLdapMessage(msg, ct).ConfigureAwait(false); + + return new LdapSearchResults(Messages, msg.MessageId); + } + + /// + /// Modifies the specified dn. + /// + /// Name of the distinguished. + /// The mods. + /// The cancellation token. + /// + /// A representing the asynchronous operation. + /// + /// distinguishedName. + public Task Modify(string distinguishedName, LdapModification[] mods, CancellationToken ct = default) + { + if (distinguishedName == null) + { + throw new ArgumentNullException(nameof(distinguishedName)); + } + + return RequestLdapMessage(new LdapModifyRequest(distinguishedName, mods, null), ct); + } + + internal async Task RequestLdapMessage(LdapMessage msg, CancellationToken ct = default) + { + using (var stream = new MemoryStream()) + { + LberEncoder.Encode(msg.Asn1Object, stream); + await _conn.WriteDataAsync(stream.ToArray(), true, ct).ConfigureAwait(false); + + try + { + while (new List(Messages).Any(x => x.MessageId == msg.MessageId) == false) + await Task.Delay(100, ct).ConfigureAwait(false); + } + catch (ArgumentException) + { + // expected + } + + var first = new List(Messages).FirstOrDefault(x => x.MessageId == msg.MessageId); + + if (first != null) + { + var response = new LdapResponse(first); + response.ChkResultCode(); + } + } + } + + internal void RetrieveMessages() + { + while (!_cts.IsCancellationRequested) + { + try + { + var asn1Id = new Asn1Identifier(_conn.ActiveStream); + + if (asn1Id.Tag != Asn1Sequence.Tag) + { + continue; // loop looking for an RfcLdapMessage identifier + } + + // Turn the message into an RfcMessage class + var asn1Len = new Asn1Length(_conn.ActiveStream); + + Messages.Add(new RfcLdapMessage(_conn.ActiveStream, asn1Len.Length)); + } + catch (IOException) + { + // ignore + } + } + + // ReSharper disable once FunctionNeverReturns + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapControl.cs b/Unosquare.Swan/Networking/Ldap/LdapControl.cs new file mode 100644 index 0000000..98e7faa --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapControl.cs @@ -0,0 +1,292 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System; + using System.Collections.Generic; + using Exceptions; + + /// + /// Encapsulates optional additional parameters or constraints to be applied to + /// an Ldap operation. + /// When included with LdapConstraints or LdapSearchConstraints + /// on an LdapConnection or with a specific operation request, it is + /// sent to the server along with operation requests. + /// + public class LdapControl + { + /// + /// Initializes a new instance of the class. + /// Constructs a new LdapControl object using the specified values. + /// + /// The OID of the control, as a dotted string. + /// True if the Ldap operation should be discarded if + /// the control is not supported. False if + /// the operation can be processed without the control. + /// The control-specific data. + /// An OID must be specified. + public LdapControl(string oid, bool critical, sbyte[] values) + { + if (oid == null) + { + throw new ArgumentException("An OID must be specified"); + } + + Asn1Object = new RfcControl( + oid, + new Asn1Boolean(critical), + values == null ? null : new Asn1OctetString(values)); + } + + /// + /// Returns the identifier of the control. + /// + /// + /// The identifier. + /// + public string Id => Asn1Object.ControlType.StringValue(); + + /// + /// Returns whether the control is critical for the operation. + /// + /// + /// true if critical; otherwise, false. + /// + public bool Critical => Asn1Object.Criticality.BooleanValue(); + + internal static RespControlVector RegisteredControls { get; } = new RespControlVector(5); + + internal RfcControl Asn1Object { get; } + + /// + /// Registers a class to be instantiated on receipt of a control with the + /// given OID. + /// Any previous registration for the OID is overridden. The + /// controlClass must be an extension of LdapControl. + /// + /// The object identifier of the control. + /// A class which can instantiate an LdapControl. + public static void Register(string oid, Type controlClass) + => RegisteredControls.RegisterResponseControl(oid, controlClass); + + /// + /// Returns the control-specific data of the object. + /// + /// + /// The control-specific data of the object as a byte array, + /// or null if the control has no data. + /// + public sbyte[] GetValue() => Asn1Object.ControlValue?.ByteValue(); + + internal void SetValue(sbyte[] controlValue) + { + Asn1Object.ControlValue = new Asn1OctetString(controlValue); + } + } + + /// + /// Represents a simple bind request. + /// + /// + public class LdapBindRequest : LdapMessage + { + /// + /// Initializes a new instance of the class. + /// Constructs a simple bind request. + /// + /// The Ldap protocol version, use Ldap_V3. + /// Ldap_V2 is not supported. + /// If non-null and non-empty, specifies that the + /// connection and all operations through it should + /// be authenticated with dn as the distinguished + /// name. + /// If non-null and non-empty, specifies that the + /// connection and all operations through it should + /// be authenticated with dn as the distinguished + /// name and passwd as password. + public LdapBindRequest(int version, string dn, sbyte[] password) + : base(LdapOperation.BindRequest, new RfcBindRequest(version, dn, password)) + { + } + + /// + /// Retrieves the Authentication DN for a bind request. + /// + /// + /// The authentication dn. + /// + public string AuthenticationDN => Asn1Object.RequestDn; + + /// + public override string ToString() => Asn1Object.ToString(); + } + + /// + /// Encapsulates a continuation reference from an asynchronous search operation. + /// + /// + internal class LdapSearchResultReference : LdapMessage + { + /// + /// Initializes a new instance of the class. + /// Constructs an LdapSearchResultReference object. + /// + /// The LdapMessage with a search reference. + internal LdapSearchResultReference(RfcLdapMessage message) + : base(message) + { + } + + /// + /// Returns any URLs in the object. + /// + /// + /// The referrals. + /// + public string[] Referrals + { + get + { + var references = ((RfcSearchResultReference)Message.Response).ToArray(); + var srefs = new string[references.Length]; + for (var i = 0; i < references.Length; i++) + { + srefs[i] = ((Asn1OctetString)references[i]).StringValue(); + } + + return srefs; + } + } + } + + internal class LdapResponse : LdapMessage + { + internal LdapResponse(RfcLdapMessage message) + : base(message) + { + } + + public string ErrorMessage => ((IRfcResponse)Message.Response).GetErrorMessage().StringValue(); + + public string MatchedDN => ((IRfcResponse)Message.Response).GetMatchedDN().StringValue(); + + public LdapStatusCode ResultCode => Message.Response is RfcSearchResultEntry || + (IRfcResponse)Message.Response is RfcIntermediateResponse + ? LdapStatusCode.Success + : (LdapStatusCode)((IRfcResponse)Message.Response).GetResultCode().IntValue(); + + internal LdapException Exception { get; set; } + + internal void ChkResultCode() + { + if (Exception != null) + { + throw Exception; + } + + switch (ResultCode) + { + case LdapStatusCode.Success: + case LdapStatusCode.CompareTrue: + case LdapStatusCode.CompareFalse: + break; + case LdapStatusCode.Referral: + throw new LdapException( + "Automatic referral following not enabled", + LdapStatusCode.Referral, + ErrorMessage); + default: + throw new LdapException(ResultCode.ToString().Humanize(), ResultCode, ErrorMessage, MatchedDN); + } + } + } + + /// + /// The RespControlVector class implements extends the + /// existing Vector class so that it can be used to maintain a + /// list of currently registered control responses. + /// + internal class RespControlVector : List + { + private readonly object _syncLock = new object(); + + public RespControlVector(int cap) + : base(cap) + { + } + + public void RegisterResponseControl(string oid, Type controlClass) + { + lock (_syncLock) + { + Add(new RegisteredControl(this, oid, controlClass)); + } + } + + /// + /// Inner class defined to create a temporary object to encapsulate + /// all registration information about a response control. + /// + internal class RegisteredControl + { + public RegisteredControl(RespControlVector enclosingInstance, string oid, Type controlClass) + { + EnclosingInstance = enclosingInstance; + MyOid = oid; + MyClass = controlClass; + } + + internal Type MyClass { get; } + + internal string MyOid { get; } + + private RespControlVector EnclosingInstance { get; } + } + } + + /// + /// Represents and Ldap Bind Request. + ///
    +    /// BindRequest ::= [APPLICATION 0] SEQUENCE {
    +    /// version                 INTEGER (1 .. 127),
    +    /// name                    LdapDN,
    +    /// authentication          AuthenticationChoice }
    +    /// 
    + /// + /// + internal sealed class RfcBindRequest + : Asn1Sequence, IRfcRequest + { + private readonly sbyte[] _password; + private static readonly Asn1Identifier Id = new Asn1Identifier(LdapOperation.BindRequest); + + public RfcBindRequest(int version, string name, sbyte[] password) + : base(3) + { + _password = password; + Add(new Asn1Integer(version)); + Add(name); + Add(new RfcAuthenticationChoice(password)); + } + + public Asn1Integer Version + { + get => (Asn1Integer)Get(0); + set => Set(0, value); + } + + public Asn1OctetString Name + { + get => (Asn1OctetString)Get(1); + set => Set(1, value); + } + + public RfcAuthenticationChoice AuthenticationChoice + { + get => (RfcAuthenticationChoice)Get(2); + set => Set(2, value); + } + + public override Asn1Identifier GetIdentifier() => Id; + + public string GetRequestDN() => ((Asn1OctetString)Get(1)).StringValue(); + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapEntry.cs b/Unosquare.Swan/Networking/Ldap/LdapEntry.cs new file mode 100644 index 0000000..b1d7f34 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapEntry.cs @@ -0,0 +1,794 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System.Linq; + using System; + using System.Collections.Generic; + using System.Text; + + /// + /// Represents a single entry in a directory, consisting of + /// a distinguished name (DN) and zero or more attributes. + /// An instance of + /// LdapEntry is created in order to add an entry to a directory, and + /// instances of LdapEntry are returned on a search by enumerating an + /// LdapSearchResults. + /// + /// + /// + public class LdapEntry + { + private readonly LdapAttributeSet _attrs; + + /// + /// Initializes a new instance of the class. + /// Constructs a new entry with the specified distinguished name and set + /// of attributes. + /// + /// The distinguished name of the new entry. The + /// value is not validated. An invalid distinguished + /// name will cause operations using this entry to fail. + /// The initial set of attributes assigned to the + /// entry. + public LdapEntry(string dn = null, LdapAttributeSet attrs = null) + { + DN = dn ?? string.Empty; + _attrs = attrs ?? new LdapAttributeSet(); + } + + /// + /// Returns the distinguished name of the entry. + /// + /// + /// The dn. + /// + public string DN { get; } + + /// + /// Returns the attributes matching the specified attrName. + /// + /// The name of the attribute or attributes to return. + /// + /// The attribute matching the name. + /// + public LdapAttribute GetAttribute(string attrName) => _attrs[attrName]; + + /// + /// Returns the attribute set of the entry. + /// All base and subtype variants of all attributes are + /// returned. The LdapAttributeSet returned may be + /// empty if there are no attributes in the entry. + /// + /// + /// The attribute set of the entry. + /// + public LdapAttributeSet GetAttributeSet() => _attrs; + + /// + /// Returns an attribute set from the entry, consisting of only those + /// attributes matching the specified subtypes. + /// The getAttributeSet method can be used to extract only + /// a particular language variant subtype of each attribute, + /// if it exists. The "subtype" may be, for example, "lang-ja", "binary", + /// or "lang-ja;phonetic". If more than one subtype is specified, separated + /// with a semicolon, only those attributes with all of the named + /// subtypes will be returned. The LdapAttributeSet returned may be + /// empty if there are no matching attributes in the entry. + /// + /// One or more subtype specification(s), separated + /// with semicolons. The "lang-ja" and + /// "lang-en;phonetic" are valid subtype + /// specifications. + /// + /// An attribute set from the entry with the attributes that + /// match the specified subtypes or an empty set if no attributes + /// match. + /// + public LdapAttributeSet GetAttributeSet(string subtype) => _attrs.GetSubset(subtype); + } + + /// + /// The name and values of one attribute of a directory entry. + /// LdapAttribute objects are used when searching for, adding, + /// modifying, and deleting attributes from the directory. + /// LdapAttributes are often used in conjunction with an + /// LdapAttributeSet when retrieving or adding multiple + /// attributes to an entry. + /// + public class LdapAttribute + { + private readonly string _baseName; // cn of cn;lang-ja;phonetic + private readonly string[] _subTypes; // lang-ja of cn;lang-ja + private object[] _values; // Array of byte[] attribute values + + /// + /// Initializes a new instance of the class. + /// Constructs an attribute with no values. + /// + /// Name of the attribute. + /// Attribute name cannot be null. + public LdapAttribute(string attrName) + { + Name = attrName ?? throw new ArgumentNullException(nameof(attrName)); + _baseName = GetBaseName(attrName); + _subTypes = GetSubtypes(attrName); + } + + /// + /// Initializes a new instance of the class. + /// Constructs an attribute with a single value. + /// + /// Name of the attribute. + /// Value of the attribute as a string. + /// Attribute value cannot be null. + public LdapAttribute(string attrName, string attrString) + : this(attrName) + { + Add(Encoding.UTF8.GetSBytes(attrString)); + } + + /// + /// Returns the values of the attribute as an array of bytes. + /// + /// + /// The byte value array. + /// + public sbyte[][] ByteValueArray + { + get + { + if (_values == null) + return new sbyte[0][]; + + var size = _values.Length; + var bva = new sbyte[size][]; + + // Deep copy so application cannot change values + for (int i = 0, u = size; i < u; i++) + { + bva[i] = new sbyte[((sbyte[])_values[i]).Length]; + Array.Copy((Array)_values[i], 0, bva[i], 0, bva[i].Length); + } + + return bva; + } + } + + /// + /// Returns the values of the attribute as an array of strings. + /// + /// + /// The string value array. + /// + public string[] StringValueArray + { + get + { + if (_values == null) + return new string[0]; + + var size = _values.Length; + var sva = new string[size]; + + for (var j = 0; j < size; j++) + { + sva[j] = Encoding.UTF8.GetString((sbyte[])_values[j]); + } + + return sva; + } + } + + /// + /// Returns the the first value of the attribute as an UTF-8 string. + /// + /// + /// The string value. + /// + public string StringValue => _values == null ? null : Encoding.UTF8.GetString((sbyte[])_values[0]); + + /// + /// Returns the first value of the attribute as a byte array or null. + /// + /// + /// The byte value. + /// + public sbyte[] ByteValue + { + get + { + if (_values == null) return null; + + // Deep copy so app can't change the value + var bva = new sbyte[((sbyte[])_values[0]).Length]; + Array.Copy((Array)_values[0], 0, bva, 0, bva.Length); + + return bva; + } + } + + /// + /// Returns the language subtype of the attribute, if any. + /// For example, if the attribute name is cn;lang-ja;phonetic, + /// this method returns the string, lang-ja. + /// + /// + /// The language subtype. + /// + public string LangSubtype => _subTypes?.FirstOrDefault(t => t.StartsWith("lang-")); + + /// + /// Returns the name of the attribute. + /// + /// + /// The name. + /// + public string Name { get; } + + internal string Value + { + set + { + _values = null; + + Add(Encoding.UTF8.GetSBytes(value)); + } + } + + /// + /// Extracts the subtypes from the specified attribute name. + /// For example, if the attribute name is cn;lang-ja;phonetic, + /// this method returns an array containing lang-ja and phonetic. + /// + /// Name of the attribute from which to extract + /// the subtypes. + /// + /// An array subtypes or null if the attribute has none. + /// + /// Attribute name cannot be null. + public static string[] GetSubtypes(string attrName) + { + if (attrName == null) + { + throw new ArgumentException("Attribute name cannot be null"); + } + + var st = new Tokenizer(attrName, ";"); + string[] subTypes = null; + var cnt = st.Count; + + if (cnt > 0) + { + st.NextToken(); // skip over basename + subTypes = new string[cnt - 1]; + var i = 0; + while (st.HasMoreTokens()) + { + subTypes[i++] = st.NextToken(); + } + } + + return subTypes; + } + + /// + /// Returns the base name of the specified attribute name. + /// For example, if the attribute name is cn;lang-ja;phonetic, + /// this method returns cn. + /// + /// Name of the attribute from which to extract the + /// base name. + /// The base name of the attribute. + /// Attribute name cannot be null. + public static string GetBaseName(string attrName) + { + if (attrName == null) + { + throw new ArgumentException("Attribute name cannot be null"); + } + + var idx = attrName.IndexOf(';'); + return idx == -1 ? attrName : attrName.Substring(0, idx - 0); + } + + /// + /// Clones this instance. + /// + /// A cloned instance. + public LdapAttribute Clone() + { + var newObj = MemberwiseClone(); + if (_values != null) + { + Array.Copy(_values, 0, ((LdapAttribute)newObj)._values, 0, _values.Length); + } + + return (LdapAttribute) newObj; + } + + /// + /// Adds a value to the attribute. + /// + /// Value of the attribute as a String. + /// Attribute value cannot be null. + public void AddValue(string attrString) + { + if (attrString == null) + { + throw new ArgumentException("Attribute value cannot be null"); + } + + Add(Encoding.UTF8.GetSBytes(attrString)); + } + + /// + /// Adds a byte-formatted value to the attribute. + /// + /// Value of the attribute as raw bytes. + /// Note: If attrBytes represents a string it should be UTF-8 encoded. + /// Attribute value cannot be null. + public void AddValue(sbyte[] attrBytes) + { + if (attrBytes == null) + { + throw new ArgumentException("Attribute value cannot be null"); + } + + Add(attrBytes); + } + + /// + /// Adds a base64 encoded value to the attribute. + /// The value will be decoded and stored as bytes. String + /// data encoded as a base64 value must be UTF-8 characters. + /// + /// The base64 value of the attribute as a String. + /// Attribute value cannot be null. + public void AddBase64Value(string attrString) + { + if (attrString == null) + { + throw new ArgumentException("Attribute value cannot be null"); + } + + Add(Convert.FromBase64String(attrString).ToSByteArray()); + } + + /// + /// Adds a base64 encoded value to the attribute. + /// The value will be decoded and stored as bytes. Character + /// data encoded as a base64 value must be UTF-8 characters. + /// + /// The base64 value of the attribute as a StringBuffer. + /// The start index of base64 encoded part, inclusive. + /// The end index of base encoded part, exclusive. + /// attrString. + public void AddBase64Value(StringBuilder attrString, int start, int end) + { + if (attrString == null) + { + throw new ArgumentNullException(nameof(attrString)); + } + + Add(Convert.FromBase64String(attrString.ToString(start, end)).ToSByteArray()); + } + + /// + /// Adds a base64 encoded value to the attribute. + /// The value will be decoded and stored as bytes. Character + /// data encoded as a base64 value must be UTF-8 characters. + /// + /// The base64 value of the attribute as an array of + /// characters. + /// attrChars. + public void AddBase64Value(char[] attrChars) + { + if (attrChars == null) + { + throw new ArgumentNullException(nameof(attrChars)); + } + + Add(Convert.FromBase64CharArray(attrChars, 0, attrChars.Length).ToSByteArray()); + } + + /// + /// Returns the base name of the attribute. + /// For example, if the attribute name is cn;lang-ja;phonetic, + /// this method returns cn. + /// + /// + /// The base name of the attribute. + /// + public string GetBaseName() => _baseName; + + /// + /// Extracts the subtypes from the attribute name. + /// For example, if the attribute name is cn;lang-ja;phonetic, + /// this method returns an array containing lang-ja and phonetic. + /// + /// + /// An array subtypes or null if the attribute has none. + /// + public string[] GetSubtypes() => _subTypes; + + /// + /// Reports if the attribute name contains the specified subtype. + /// For example, if you check for the subtype lang-en and the + /// attribute name is cn;lang-en, this method returns true. + /// + /// + /// The single subtype to check for. + /// + /// + /// True, if the attribute has the specified subtype; + /// false, if it doesn't. + /// + public bool HasSubtype(string subtype) + { + if (subtype == null) + { + throw new ArgumentNullException(nameof(subtype)); + } + + return _subTypes != null && _subTypes.Any(t => string.Equals(t, subtype, StringComparison.OrdinalIgnoreCase)); + } + + /// + /// Reports if the attribute name contains all the specified subtypes. + /// For example, if you check for the subtypes lang-en and phonetic + /// and if the attribute name is cn;lang-en;phonetic, this method + /// returns true. If the attribute name is cn;phonetic or cn;lang-en, + /// this method returns false. + /// + /// + /// An array of subtypes to check for. + /// + /// + /// True, if the attribute has all the specified subtypes; + /// false, if it doesn't have all the subtypes. + /// + public bool HasSubtypes(string[] subtypes) + { + if (subtypes == null) + { + throw new ArgumentNullException(nameof(subtypes)); + } + + for (var i = 0; i < subtypes.Length; i++) + { + foreach (var sub in _subTypes) + { + if (sub == null) + { + throw new ArgumentException($"subtype at array index {i} cannot be null"); + } + + if (string.Equals(sub, subtypes[i], StringComparison.OrdinalIgnoreCase)) + { + return true; + } + } + } + + return false; + } + + /// + /// Removes a string value from the attribute. + /// + /// Value of the attribute as a string. + /// Note: Removing a value which is not present in the attribute has + /// no effect. + /// attrString. + public void RemoveValue(string attrString) + { + if (attrString == null) + { + throw new ArgumentNullException(nameof(attrString)); + } + + RemoveValue(Encoding.UTF8.GetSBytes(attrString)); + } + + /// + /// Removes a byte-formatted value from the attribute. + /// + /// Value of the attribute as raw bytes. + /// Note: If attrBytes represents a string it should be UTF-8 encoded. + /// Note: Removing a value which is not present in the attribute has + /// no effect. + /// + /// attrBytes. + public void RemoveValue(sbyte[] attrBytes) + { + if (attrBytes == null) + { + throw new ArgumentNullException(nameof(attrBytes)); + } + + for (var i = 0; i < _values.Length; i++) + { + if (!Equals(attrBytes, (sbyte[])_values[i])) continue; + + if (i == 0 && _values.Length == 1) + { + // Optimize if first element of a single valued attr + _values = null; + return; + } + + if (_values.Length == 1) + { + _values = null; + } + else + { + var moved = _values.Length - i - 1; + var tmp = new object[_values.Length - 1]; + if (i != 0) + { + Array.Copy(_values, 0, tmp, 0, i); + } + + if (moved != 0) + { + Array.Copy(_values, i + 1, tmp, i, moved); + } + + _values = tmp; + } + + break; + } + } + + /// + /// Returns the number of values in the attribute. + /// + /// + /// The number of values in the attribute. + /// + public int Size() => _values?.Length ?? 0; + + /// + /// Compares this object with the specified object for order. + /// Ordering is determined by comparing attribute names using the method Compare() of the String class. + /// + /// The LdapAttribute to be compared to this object. + /// + /// Returns a negative integer, zero, or a positive + /// integer as this object is less than, equal to, or greater than the + /// specified object. + /// + public int CompareTo(object attribute) + => string.Compare(Name, ((LdapAttribute)attribute).Name, StringComparison.Ordinal); + + /// + /// Returns a string representation of this LdapAttribute. + /// + /// + /// a string representation of this LdapAttribute. + /// + /// NullReferenceException. + public override string ToString() + { + var result = new StringBuilder("LdapAttribute: "); + + result.Append("{type='" + Name + "'"); + + if (_values != null) + { + result + .Append(", ") + .Append(_values.Length == 1 ? "value='" : "values='"); + + for (var i = 0; i < _values.Length; i++) + { + if (i != 0) + { + result.Append("','"); + } + + if (((sbyte[])_values[i]).Length == 0) + { + continue; + } + + var sval = Encoding.UTF8.GetString((sbyte[])_values[i]); + if (sval.Length == 0) + { + // didn't decode well, must be binary + result.Append(" + /// Adds an object to this object's list of attribute values. + /// + /// Ultimately all of this attribute's values are treated + /// as binary data so we simplify the process by requiring + /// that all data added to our list is in binary form. + /// Note: If attrBytes represents a string it should be UTF-8 encoded. + private void Add(sbyte[] bytes) + { + if (_values == null) + { + _values = new object[] { bytes }; + } + else + { + // Duplicate attribute values not allowed + if (_values.Any(t => Equals(bytes, (sbyte[])t))) + { + return; // Duplicate, don't add + } + + var tmp = new object[_values.Length + 1]; + Array.Copy(_values, 0, tmp, 0, _values.Length); + tmp[_values.Length] = bytes; + _values = tmp; + } + } + + private static bool Equals(sbyte[] e1, sbyte[] e2) + { + // If same object, they compare true + if (e1 == e2) + return true; + + // If either but not both are null, they compare false + if (e1 == null || e2 == null) + return false; + + // If arrays have different length, they compare false + var length = e1.Length; + if (e2.Length != length) + return false; + + // If any of the bytes are different, they compare false + for (var i = 0; i < length; i++) + { + if (e1[i] != e2[i]) + return false; + } + + return true; + } + } + + /// + /// A set of LdapAttribute objects. + /// An LdapAttributeSet is a collection of LdapAttribute + /// classes as returned from an LdapEntry on a search or read + /// operation. LdapAttributeSet may be also used to construct an entry + /// to be added to a directory. + /// + /// + /// + public class LdapAttributeSet : Dictionary + { + /// + /// Initializes a new instance of the class. + /// + public LdapAttributeSet() + : base(StringComparer.OrdinalIgnoreCase) + { + // placeholder + } + + /// + /// Creates a new attribute set containing only the attributes that have + /// the specified subtypes. + /// For example, suppose an attribute set contains the following + /// attributes: + ///
    • cn
    • cn;lang-ja
    • sn;phonetic;lang-ja
    • sn;lang-us
    + /// Calling the getSubset method and passing lang-ja as the + /// argument, the method returns an attribute set containing the following + /// attributes:. + ///
    • cn;lang-ja
    • sn;phonetic;lang-ja
    + ///
    + /// Semi-colon delimited list of subtypes to include. For + /// example: + ///
    • "lang-ja" specifies only Japanese language subtypes
    • "binary" specifies only binary subtypes
    • + /// "binary;lang-ja" specifies only Japanese language subtypes + /// which also are binary + ///
    + /// Note: Novell eDirectory does not currently support language subtypes. + /// It does support the "binary" subtype. + /// + /// An attribute set containing the attributes that match the + /// specified subtype. + /// + public LdapAttributeSet GetSubset(string subtype) + { + // Create a new tempAttributeSet + var tempAttributeSet = new LdapAttributeSet(); + + foreach (var kvp in this) + { + if (kvp.Value.HasSubtype(subtype)) + tempAttributeSet.Add(kvp.Value.Clone()); + } + + return tempAttributeSet; + } + + /// + /// Returns true if this set contains an attribute of the same name + /// as the specified attribute. + /// + /// Object of type LdapAttribute. + /// + /// true if this set contains the specified attribute. + /// + public bool Contains(object attr) => ContainsKey(((LdapAttribute)attr).Name); + + /// + /// Adds the specified attribute to this set if it is not already present. + /// If an attribute with the same name already exists in the set then the + /// specified attribute will not be added. + /// + /// Object of type LdapAttribute. + /// + /// true if the attribute was added. + /// + public bool Add(LdapAttribute attr) + { + var name = attr.Name; + + if (ContainsKey(name)) + return false; + + this[name] = attr; + return true; + } + + /// + /// Removes the specified object from this set if it is present. + /// If the specified object is of type LdapAttribute, the + /// specified attribute will be removed. If the specified object is of type + /// string, the attribute with a name that matches the string will + /// be removed. + /// + /// The entry. + /// + /// true if the object was removed. + /// + public bool Remove(LdapAttribute entry) => Remove(entry.Name); + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + var retValue = new StringBuilder("LdapAttributeSet: "); + var first = true; + + foreach (var attr in this) + { + if (!first) + { + retValue.Append(" "); + } + + first = false; + retValue.Append(attr); + } + + return retValue.ToString(); + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapEnums.cs b/Unosquare.Swan/Networking/Ldap/LdapEnums.cs new file mode 100644 index 0000000..ee861a6 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapEnums.cs @@ -0,0 +1,135 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + /// + /// Ldap Modification Operators. + /// + public enum LdapModificationOp + { + /// + /// Adds the listed values to the given attribute, creating + /// the attribute if it does not already exist. + /// + Add = 0, + + /// + /// Deletes the listed values from the given attribute, + /// removing the entire attribute (1) if no values are listed or + /// (2) if all current values of the attribute are listed for + /// deletion. + /// + Delete = 1, + + /// + /// Replaces all existing values of the given attribute + /// with the new values listed, creating the attribute if it + /// does not already exist. + /// A replace with no value deletes the entire attribute if it + /// exists, and is ignored if the attribute does not exist. + /// + Replace = 2, + } + + /// + /// LDAP valid scopes. + /// + public enum LdapScope + { + /// + /// Used with search to specify that the scope of entrys to search is to + /// search only the base object. + /// + ScopeBase = 0, + + /// + /// Used with search to specify that the scope of entrys to search is to + /// search only the immediate subordinates of the base object. + /// + ScopeOne = 1, + + /// + /// Used with search to specify that the scope of entrys to search is to + /// search the base object and all entries within its subtree. + /// + ScopeSub = 2, + } + + /// + /// Substring Operators. + /// + internal enum SubstringOp + { + /// + /// Search Filter Identifier for an INITIAL component of a SUBSTRING. + /// Note: An initial SUBSTRING is represented as "value*". + /// + Initial = 0, + + /// + /// Search Filter Identifier for an ANY component of a SUBSTRING. + /// Note: An ANY SUBSTRING is represented as "*value*". + /// + Any = 1, + + /// + /// Search Filter Identifier for a FINAL component of a SUBSTRING. + /// Note: A FINAL SUBSTRING is represented as "*value". + /// + Final = 2, + } + + /// + /// Filtering Operators. + /// + internal enum FilterOp + { + /// + /// Identifier for AND component. + /// + And = 0, + + /// + /// Identifier for OR component. + /// + Or = 1, + + /// + /// Identifier for NOT component. + /// + Not = 2, + + /// + /// Identifier for EQUALITY_MATCH component. + /// + EqualityMatch = 3, + + /// + /// Identifier for SUBSTRINGS component. + /// + Substrings = 4, + + /// + /// Identifier for GREATER_OR_EQUAL component. + /// + GreaterOrEqual = 5, + + /// + /// Identifier for LESS_OR_EQUAL component. + /// + LessOrEqual = 6, + + /// + /// Identifier for PRESENT component. + /// + Present = 7, + + /// + /// Identifier for APPROX_MATCH component. + /// + ApproxMatch = 8, + + /// + /// Identifier for EXTENSIBLE_MATCH component. + /// + ExtensibleMatch = 9, + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapMessage.cs b/Unosquare.Swan/Networking/Ldap/LdapMessage.cs new file mode 100644 index 0000000..bd3449b --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapMessage.cs @@ -0,0 +1,140 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + /// + /// The base class for Ldap request and response messages. + /// Subclassed by response messages used in asynchronous operations. + /// + public class LdapMessage + { + internal RfcLdapMessage Message; + + private int _imsgNum = -1; // This instance LdapMessage number + + private LdapOperation _messageType = LdapOperation.Unknown; + + private string _stringTag; + + internal LdapMessage() + { + } + + /// + /// Initializes a new instance of the class. + /// Creates an LdapMessage when sending a protocol operation and sends + /// some optional controls with the message. + /// + /// The type. + /// The operation type of message. + /// The controls to use with the operation. + /// + internal LdapMessage(LdapOperation type, IRfcRequest op, LdapControl[] controls = null) + { + // Get a unique number for this request message + _messageType = type; + RfcControls asn1Ctrls = null; + + if (controls != null) + { + // Move LdapControls into an RFC 2251 Controls object. + asn1Ctrls = new RfcControls(); + + foreach (var t in controls) + { + asn1Ctrls.Add(t.Asn1Object); + } + } + + // create RFC 2251 LdapMessage + Message = new RfcLdapMessage(op, asn1Ctrls); + } + + /// + /// Initializes a new instance of the class. + /// Creates an Rfc 2251 LdapMessage when the libraries receive a response + /// from a command. + /// + /// A response message. + internal LdapMessage(RfcLdapMessage message) => Message = message; + + /// + /// Returns the message ID. The message ID is an integer value + /// identifying the Ldap request and its response. + /// + /// + /// The message identifier. + /// + public virtual int MessageId + { + get + { + if (_imsgNum == -1) + { + _imsgNum = Message.MessageId; + } + + return _imsgNum; + } + } + + /// + /// Indicates whether the message is a request or a response. + /// + /// + /// true if request; otherwise, false. + /// + public virtual bool Request => Message.IsRequest(); + + internal LdapOperation Type + { + get + { + if (_messageType == LdapOperation.Unknown) + { + _messageType = Message.Type; + } + + return _messageType; + } + } + + internal virtual RfcLdapMessage Asn1Object => Message; + + internal virtual LdapMessage RequestingMessage => Message.RequestingMessage; + + /// + /// Retrieves the identifier tag for this message. + /// An identifier can be associated with a message with the + /// setTag method. + /// Tags are set by the application and not by the API or the server. + /// If a server response isRequest() == false has no tag, + /// the tag associated with the corresponding server request is used. + /// + /// + /// The tag. + /// + public virtual string Tag + { + get + { + if (_stringTag != null) + { + return _stringTag; + } + + return Request ? null : RequestingMessage?._stringTag; + } + + set => _stringTag = value; + } + + private string Name => Type.ToString(); + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() => $"{Name}({MessageId}): {Message}"; + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapModification.cs b/Unosquare.Swan/Networking/Ldap/LdapModification.cs new file mode 100644 index 0000000..56c6c26 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapModification.cs @@ -0,0 +1,78 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + /// + /// A single add, delete, or replace operation to an LdapAttribute. + /// An LdapModification contains information on the type of modification + /// being performed, the name of the attribute to be replaced, and the new + /// value. Multiple modifications are expressed as an array of modifications, + /// i.e., LdapModification[]. + /// An LdapModification or an LdapModification array enable you to modify + /// an attribute of an Ldap entry. The entire array of modifications must + /// be performed by the server as a single atomic operation in the order they + /// are listed. No changes are made to the directory unless all the operations + /// succeed. If all succeed, a success result is returned to the application. + /// It should be noted that if the connection fails during a modification, + /// it is indeterminate whether the modification occurred or not. + /// There are three types of modification operations: Add, Delete, + /// and Replace. + /// Add: Creates the attribute if it doesn't exist, and adds + /// the specified values. This operation must contain at least one value, and + /// all values of the attribute must be unique. + /// Delete: Deletes specified values from the attribute. If no + /// values are specified, or if all existing values of the attribute are + /// specified, the attribute is removed. Mandatory attributes cannot be + /// removed. + /// Replace: Creates the attribute if necessary, and replaces + /// all existing values of the attribute with the specified values. + /// If you wish to keep any existing values of a multi-valued attribute, + /// you must include these values in the replace operation. + /// A replace operation with no value will remove the entire attribute if it + /// exists, and is ignored if the attribute does not exist. + /// Additional information on Ldap modifications is available in section 4.6 + /// of. rfc2251.txt + /// + /// + /// + public sealed class LdapModification : LdapMessage + { + /// + /// Initializes a new instance of the class. + /// Specifies a modification to be made to an attribute. + /// + /// The op. + /// The attribute to modify. + public LdapModification(LdapModificationOp op, LdapAttribute attr) + { + Op = op; + Attribute = attr; + } + + /// + /// Initializes a new instance of the class. + /// + /// The op. + /// Name of the attribute. + /// The attribute value. + public LdapModification(LdapModificationOp op, string attrName, string attrValue) + : this(op, new LdapAttribute(attrName, attrValue)) + { + // placeholder + } + + /// + /// Returns the attribute to modify, with any existing values. + /// + /// + /// The attribute. + /// + public LdapAttribute Attribute { get; } + + /// + /// Returns the type of modification specified by this object. + /// + /// + /// The op. + /// + public LdapModificationOp Op { get; } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapModifyRequest.cs b/Unosquare.Swan/Networking/Ldap/LdapModifyRequest.cs new file mode 100644 index 0000000..f8a8434 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapModifyRequest.cs @@ -0,0 +1,68 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + /// + /// Represents a LDAP Modification Request Message. + /// + /// + public sealed class LdapModifyRequest : LdapMessage + { + /// + /// Initializes a new instance of the class. + /// + /// The dn. + /// The modifications. + /// The control. + public LdapModifyRequest(string dn, LdapModification[] modifications, LdapControl[] control) + : base(LdapOperation.ModifyRequest, new RfcModifyRequest(dn, EncodeModifications(modifications)), control) + { + } + + /// + /// Gets the dn. + /// + /// + /// The dn. + /// + public string DN => Asn1Object.RequestDn; + + /// + public override string ToString() => Asn1Object.ToString(); + + private static Asn1SequenceOf EncodeModifications(LdapModification[] mods) + { + var rfcMods = new Asn1SequenceOf(mods.Length); + + foreach (var t in mods) + { + var attr = t.Attribute; + + var vals = new Asn1SetOf(attr.Size()); + if (attr.Size() > 0) + { + foreach (var val in attr.ByteValueArray) + { + vals.Add(new Asn1OctetString(val)); + } + } + + var rfcMod = new Asn1Sequence(2); + rfcMod.Add(new Asn1Enumerated((int) t.Op)); + rfcMod.Add(new RfcAttributeTypeAndValues(attr.Name, vals)); + + rfcMods.Add(rfcMod); + } + + return rfcMods; + } + + internal class RfcAttributeTypeAndValues : Asn1Sequence + { + public RfcAttributeTypeAndValues(string type, Asn1Object vals) + : base(2) + { + Add(type); + Add(vals); + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapOperation.cs b/Unosquare.Swan/Networking/Ldap/LdapOperation.cs new file mode 100644 index 0000000..994be58 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapOperation.cs @@ -0,0 +1,117 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + /// + /// LDAP Operation. + /// + internal enum LdapOperation + { + /// + /// The unknown + /// + Unknown = -1, + + /// + /// A bind request operation. + /// BIND_REQUEST = 0 + /// + BindRequest = 0, + + /// + /// A bind response operation. + /// BIND_RESPONSE = 1 + /// + BindResponse = 1, + + /// + /// An unbind request operation. + /// UNBIND_REQUEST = 2 + /// + UnbindRequest = 2, + + /// + /// A search request operation. + /// SEARCH_REQUEST = 3 + /// + SearchRequest = 3, + + /// + /// A search response containing data. + /// SEARCH_RESPONSE = 4 + /// + SearchResponse = 4, + + /// + /// A search result message - contains search status. + /// SEARCH_RESULT = 5 + /// + SearchResult = 5, + + /// + /// A modify request operation. + /// MODIFY_REQUEST = 6 + /// + ModifyRequest = 6, + + /// + /// A modify response operation. + /// MODIFY_RESPONSE = 7 + /// + ModifyResponse = 7, + + /// + /// An abandon request operation. + /// ABANDON_REQUEST = 16 + /// + AbandonRequest = 16, + + /// + /// A search result reference operation. + /// SEARCH_RESULT_REFERENCE = 19 + /// + SearchResultReference = 19, + + /// + /// An extended request operation. + /// EXTENDED_REQUEST = 23 + /// + ExtendedRequest = 23, + + /// + /// An extended response operation. + /// EXTENDED_RESPONSE = 24 + /// + ExtendedResponse = 24, + + /// + /// An intermediate response operation. + /// INTERMEDIATE_RESPONSE = 25 + /// + IntermediateResponse = 25, + } + + /// + /// ASN1 tags. + /// + internal enum Asn1IdentifierTag + { + /// + /// Universal tag class. + /// + Universal = 0, + + /// + /// Application-wide tag class. + /// + Application = 1, + + /// + /// Context-specific tag class. + /// + Context = 2, + + /// + /// Private-use tag class. + /// + Private = 3, + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapSearchRequest.cs b/Unosquare.Swan/Networking/Ldap/LdapSearchRequest.cs new file mode 100644 index 0000000..cb00800 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapSearchRequest.cs @@ -0,0 +1,185 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System.Collections; + + /// + /// Represents an Ldap Search request. + /// + /// + internal sealed class LdapSearchRequest : LdapMessage + { + /// + /// Initializes a new instance of the class. + /// + /// The base distinguished name to search from. + /// The scope of the entries to search. The following + /// are the valid options:. + ///
    • SCOPE_BASE - searches only the base DN
    • SCOPE_ONE - searches only entries under the base DN
    • + /// SCOPE_SUB - searches the base DN and all entries + /// within its subtree + ///
    + /// The search filter specifying the search criteria. + /// The names of attributes to retrieve. + /// operation exceeds the time limit. + /// Specifies when aliases should be dereferenced. + /// Must be one of the constants defined in + /// LdapConstraints, which are DEREF_NEVER, + /// DEREF_FINDING, DEREF_SEARCHING, or DEREF_ALWAYS. + /// The maximum number of search results to return + /// for a search request. + /// The search operation will be terminated by the server + /// with an LdapException.SIZE_LIMIT_EXCEEDED if the + /// number of results exceed the maximum. + /// The maximum time in seconds that the server + /// should spend returning search results. This is a + /// server-enforced limit. A value of 0 means + /// no time limit. + /// If true, returns the names but not the values of + /// the attributes found. If false, returns the + /// names and values for attributes found. + /// Any controls that apply to the search request. + /// or null if none. + /// + public LdapSearchRequest( + string ldapBase, + LdapScope scope, + string filter, + string[] attrs, + int dereference, + int maxResults, + int serverTimeLimit, + bool typesOnly, + LdapControl[] cont) + : base( + LdapOperation.SearchRequest, + new RfcSearchRequest(ldapBase, scope, dereference, maxResults, serverTimeLimit, typesOnly, filter, attrs), + cont) + { + } + + /// + /// Retrieves an Iterator object representing the parsed filter for + /// this search request. + /// The first object returned from the Iterator is an Integer indicating + /// the type of filter component. One or more values follow the component + /// type as subsequent items in the Iterator. The pattern of Integer + /// component type followed by values continues until the end of the + /// filter. + /// Values returned as a byte array may represent UTF-8 characters or may + /// be binary values. The possible Integer components of a search filter + /// and the associated values that follow are:. + ///
    • AND - followed by an Iterator value
    • OR - followed by an Iterator value
    • NOT - followed by an Iterator value
    • + /// EQUALITY_MATCH - followed by the attribute name represented as a + /// String, and by the attribute value represented as a byte array + ///
    • + /// GREATER_OR_EQUAL - followed by the attribute name represented as a + /// String, and by the attribute value represented as a byte array + ///
    • + /// LESS_OR_EQUAL - followed by the attribute name represented as a + /// String, and by the attribute value represented as a byte array + ///
    • + /// APPROX_MATCH - followed by the attribute name represented as a + /// String, and by the attribute value represented as a byte array + ///
    • PRESENT - followed by a attribute name respresented as a String
    • + /// EXTENSIBLE_MATCH - followed by the name of the matching rule + /// represented as a String, by the attribute name represented + /// as a String, and by the attribute value represented as a + /// byte array. + ///
    • + /// SUBSTRINGS - followed by the attribute name represented as a + /// String, by one or more SUBSTRING components (INITIAL, ANY, + /// or FINAL) followed by the SUBSTRING value. + ///
    + ///
    + /// + /// The search filter. + /// + public IEnumerator SearchFilter => RfcFilter.GetFilterIterator(); + + /// + /// Retrieves the Base DN for a search request. + /// + /// + /// the base DN for a search request. + /// + public string DN => Asn1Object.RequestDn; + + /// + /// Retrieves the scope of a search request. + /// + /// + /// The scope. + /// + public int Scope => ((Asn1Enumerated)((RfcSearchRequest)Asn1Object.Get(1)).Get(1)).IntValue(); + + /// + /// Retrieves the behaviour of dereferencing aliases on a search request. + /// + /// + /// The dereference. + /// + public int Dereference => ((Asn1Enumerated)((RfcSearchRequest)Asn1Object.Get(1)).Get(2)).IntValue(); + + /// + /// Retrieves the maximum number of entries to be returned on a search. + /// + /// + /// The maximum results. + /// + public int MaxResults => ((Asn1Integer)((RfcSearchRequest)Asn1Object.Get(1)).Get(3)).IntValue(); + + /// + /// Retrieves the server time limit for a search request. + /// + /// + /// The server time limit. + /// + public int ServerTimeLimit => ((Asn1Integer)((RfcSearchRequest)Asn1Object.Get(1)).Get(4)).IntValue(); + + /// + /// Retrieves whether attribute values or only attribute types(names) should + /// be returned in a search request. + /// + /// + /// true if [types only]; otherwise, false. + /// + public bool TypesOnly => ((Asn1Boolean)((RfcSearchRequest)Asn1Object.Get(1)).Get(5)).BooleanValue(); + + /// + /// Retrieves an array of attribute names to request for in a search. + /// + /// + /// The attributes. + /// + public string[] Attributes + { + get + { + var attrs = (RfcAttributeDescriptionList)((RfcSearchRequest)Asn1Object.Get(1)).Get(7); + var values = new string[attrs.Size()]; + for (var i = 0; i < values.Length; i++) + { + values[i] = ((Asn1OctetString)attrs.Get(i)).StringValue(); + } + + return values; + } + } + + /// + /// Creates a string representation of the filter in this search request. + /// + /// + /// The string filter. + /// + public string StringFilter => RfcFilter.FilterToString(); + + /// + /// Retrieves an SearchFilter object representing a filter for a search request. + /// + /// + /// The RFC filter. + /// + private RfcFilter RfcFilter => (RfcFilter)((RfcSearchRequest)Asn1Object.Get(1)).Get(6); + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapSearchResults.cs b/Unosquare.Swan/Networking/Ldap/LdapSearchResults.cs new file mode 100644 index 0000000..68fbc19 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapSearchResults.cs @@ -0,0 +1,95 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System; + using System.Collections.Generic; + using System.Linq; + + /// + /// An LdapSearchResults object is returned from a synchronous search + /// operation. It provides access to all results received during the + /// operation (entries and exceptions). + /// + /// + public sealed class LdapSearchResults + { + private readonly List _messages; + private readonly int _messageId; + + /// + /// Initializes a new instance of the class. + /// + /// The messages. + /// The message identifier. + internal LdapSearchResults(List messages, int messageId) + { + _messages = messages; + _messageId = messageId; + } + + /// + /// Returns a count of the items in the search result. + /// Returns a count of the entries and exceptions remaining in the object. + /// If the search was submitted with a batch size greater than zero, + /// getCount reports the number of results received so far but not enumerated + /// with next(). If batch size equals zero, getCount reports the number of + /// items received, since the application thread blocks until all results are + /// received. + /// + /// + /// The count. + /// + public int Count => new List(_messages) + .Count(x => x.MessageId == _messageId && GetResponse(x) is LdapSearchResult); + + /// + /// Reports if there are more search results. + /// + /// + /// true if there are more search results. + /// + public bool HasMore() => new List(_messages) + .Any(x => x.MessageId == _messageId && GetResponse(x) is LdapSearchResult); + + /// + /// Returns the next result as an LdapEntry. + /// If automatic referral following is disabled or if a referral + /// was not followed, next() will throw an LdapReferralException + /// when the referral is received. + /// + /// + /// The next search result as an LdapEntry. + /// + /// Next - No more results. + public LdapEntry Next() + { + var list = new List(_messages) + .Where(x => x.MessageId == _messageId); + + foreach (var item in list) + { + _messages.Remove(item); + var response = GetResponse(item); + + if (response is LdapSearchResult result) + { + return result.Entry; + } + } + + throw new ArgumentOutOfRangeException(nameof(Next), "No more results"); + } + + private static LdapMessage GetResponse(RfcLdapMessage item) + { + switch (item.Type) + { + case LdapOperation.SearchResponse: + return new LdapSearchResult(item); + case LdapOperation.SearchResultReference: + return new LdapSearchResultReference(item); + default: + return new LdapResponse(item); + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/LdapStatusCode.cs b/Unosquare.Swan/Networking/Ldap/LdapStatusCode.cs new file mode 100644 index 0000000..897e45c --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/LdapStatusCode.cs @@ -0,0 +1,539 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + /// + /// LDAP Connection Status Code. + /// + public enum LdapStatusCode + { + /// + /// Indicates the requested client operation completed successfully. + /// SUCCESS = 0

    + ///

    + Success = 0, + + /// + /// Indicates an internal error. + /// The server is unable to respond with a more specific error and is + /// also unable to properly respond to a request. It does not indicate + /// that the client has sent an erroneous message. + /// OPERATIONS_ERROR = 1 + /// + OperationsError = 1, + + /// + /// Indicates that the server has received an invalid or malformed request + /// from the client. + /// PROTOCOL_ERROR = 2 + /// + ProtocolError = 2, + + /// + /// Indicates that the operation's time limit specified by either the + /// client or the server has been exceeded. + /// On search operations, incomplete results are returned. + /// TIME_LIMIT_EXCEEDED = 3 + /// + TimeLimitExceeded = 3, + + /// + /// Indicates that in a search operation, the size limit specified by + /// the client or the server has been exceeded. Incomplete results are + /// returned. + /// SIZE_LIMIT_EXCEEDED = 4 + /// + SizeLimitExceeded = 4, + + /// + /// Does not indicate an error condition. Indicates that the results of + /// a compare operation are false. + /// COMPARE_FALSE = 5 + /// + CompareFalse = 5, + + /// + /// Does not indicate an error condition. Indicates that the results of a + /// compare operation are true. + /// COMPARE_TRUE = 6 + /// + CompareTrue = 6, + + /// + /// Indicates that during a bind operation the client requested an + /// authentication method not supported by the Ldap server. + /// AUTH_METHOD_NOT_SUPPORTED = 7 + /// + AuthMethodNotSupported = 7, + + /// + /// Indicates a problem with the level of authentication. + /// One of the following has occurred: + ///
    • + /// In bind requests, the Ldap server accepts only strong + /// authentication. + ///
    • + /// In a client request, the client requested an operation such as delete + /// that requires strong authentication. + ///
    • + /// In an unsolicited notice of disconnection, the Ldap server discovers + /// the security protecting the communication between the client and + /// server has unexpectedly failed or been compromised. + ///
    + /// STRONG_AUTH_REQUIRED = 8 + ///
    + StrongAuthRequired = 8, + + /// + /// Returned by some Ldap servers to Ldapv2 clients to indicate that a referral + /// has been returned in the error string. + /// Ldap_PARTIAL_RESULTS = 9 + /// + LdapPartialResults = 9, + + /// + /// Does not indicate an error condition. In Ldapv3, indicates that the server + /// does not hold the target entry of the request, but that the servers in the + /// referral field may. + /// REFERRAL = 10 + /// + Referral = 10, + + /// + /// Indicates that an Ldap server limit set by an administrative authority + /// has been exceeded. + /// ADMIN_LIMIT_EXCEEDED = 11 + /// + AdminLimitExceeded = 11, + + /// + /// Indicates that the Ldap server was unable to satisfy a request because + /// one or more critical extensions were not available. + /// Either the server does not support the control or the control is not + /// appropriate for the operation type. + /// UNAVAILABLE_CRITICAL_EXTENSION = 12 + /// + UnavailableCriticalExtension = 12, + + /// + /// Indicates that the session is not protected by a protocol such as + /// Transport Layer Security (TLS), which provides session confidentiality. + /// CONFIDENTIALITY_REQUIRED = 13 + /// + ConfidentialityRequired = 13, + + /// + /// Does not indicate an error condition, but indicates that the server is + /// ready for the next step in the process. The client must send the server + /// the same SASL mechanism to continue the process. + /// SASL_BIND_IN_PROGRESS = 14 + /// + SaslBindInProgress = 14, + + /// + /// Indicates that the attribute specified in the modify or compare + /// operation does not exist in the entry. + /// NO_SUCH_ATTRIBUTE = 16 + /// + NoSuchAttribute = 16, + + /// + /// Indicates that the attribute specified in the modify or add operation + /// does not exist in the Ldap server's schema. + /// UNDEFINED_ATTRIBUTE_TYPE = 17 + /// + UndefinedAttributeType = 17, + + /// + /// Indicates that the matching rule specified in the search filter does + /// not match a rule defined for the attribute's syntax. + /// INAPPROPRIATE_MATCHING = 18 + /// + InappropriateMatching = 18, + + /// + /// Indicates that the attribute value specified in a modify, add, or + /// modify DN operation violates constraints placed on the attribute. The + /// constraint can be one of size or content (for example, string only, + /// no binary data). + /// CONSTRAINT_VIOLATION = 19 + /// + ConstraintViolation = 19, + + /// + /// Indicates that the attribute value specified in a modify or add + /// operation already exists as a value for that attribute. + /// ATTRIBUTE_OR_VALUE_EXISTS = 20 + /// + AttributeOrValueExists = 20, + + /// + /// Indicates that the attribute value specified in an add, compare, or + /// modify operation is an unrecognized or invalid syntax for the attribute. + /// INVALID_ATTRIBUTE_SYNTAX = 21 + /// + InvalidAttributeSyntax = 21, + + /// + /// Indicates the target object cannot be found. + /// This code is not returned on the following operations: + ///
      + ///
    • + /// Search operations that find the search base but cannot find any + /// entries that match the search filter. + ///
    • + ///
    • Bind operations.
    • + ///
    + /// NO_SUCH_OBJECT = 32 + ///
    + NoSuchObject = 32, + + /// + /// Indicates that an error occurred when an alias was dereferenced. + /// ALIAS_PROBLEM = 33 + /// + AliasProblem = 33, + + /// + /// Indicates that the syntax of the DN is incorrect. + /// If the DN syntax is correct, but the Ldap server's structure + /// rules do not permit the operation, the server returns + /// Ldap_UNWILLING_TO_PERFORM. + /// INVALID_DN_SYNTAX = 34 + /// + InvalidDnSyntax = 34, + + /// + /// Indicates that the specified operation cannot be performed on a + /// leaf entry. + /// This code is not currently in the Ldap specifications, but is + /// reserved for this constant. + /// IS_LEAF = 35 + /// + IsLeaf = 35, + + /// + /// Indicates that during a search operation, either the client does not + /// have access rights to read the aliased object's name or dereferencing + /// is not allowed. + /// ALIAS_DEREFERENCING_PROBLEM = 36 + /// + AliasDereferencingProblem = 36, + + /// + /// Indicates that during a bind operation, the client is attempting to use + /// an authentication method that the client cannot use correctly. + /// For example, either of the following cause this error: + ///
      + ///
    • + /// The client returns simple credentials when strong credentials are + /// required. + ///
    • + ///
    • + /// The client returns a DN and a password for a simple bind when the + /// entry does not have a password defined. + ///
    • + ///
    + /// INAPPROPRIATE_AUTHENTICATION = 48 + ///
    + InappropriateAuthentication = 48, + + /// + /// Indicates that invalid information was passed during a bind operation. + /// One of the following occurred: + ///
      + ///
    • The client passed either an incorrect DN or password.
    • + ///
    • + /// The password is incorrect because it has expired, intruder detection + /// has locked the account, or some other similar reason. + ///
    • + ///
    + /// INVALID_CREDENTIALS = 49 + ///
    + InvalidCredentials = 49, + + /// + /// Indicates that the caller does not have sufficient rights to perform + /// the requested operation. + /// INSUFFICIENT_ACCESS_RIGHTS = 50 + /// + InsufficientAccessRights = 50, + + /// + /// Indicates that the Ldap server is too busy to process the client request + /// at this time, but if the client waits and resubmits the request, the + /// server may be able to process it then. + /// BUSY = 51 + /// + Busy = 51, + + /// + /// Indicates that the Ldap server cannot process the client's bind + /// request, usually because it is shutting down. + /// UNAVAILABLE = 52 + /// + Unavailable = 52, + + /// + /// Indicates that the Ldap server cannot process the request because of + /// server-defined restrictions. + /// This error is returned for the following reasons: + ///
      + ///
    • The add entry request violates the server's structure rules.
    • + ///
    • + /// The modify attribute request specifies attributes that users + /// cannot modify. + ///
    • + ///
    + /// UNWILLING_TO_PERFORM = 53 + ///
    + UnwillingToPerform = 53, + + /// + /// Indicates that the client discovered an alias or referral loop, + /// and is thus unable to complete this request. + /// LOOP_DETECT = 54 + /// + LoopDetect = 54, + + /// + /// Indicates that the add or modify DN operation violates the schema's + /// structure rules. + /// For example, + ///
      + ///
    • The request places the entry subordinate to an alias.
    • + ///
    • + /// The request places the entry subordinate to a container that + /// is forbidden by the containment rules. + ///
    • + ///
    • The RDN for the entry uses a forbidden attribute type.
    • + ///
    + /// NAMING_VIOLATION = 64 + ///
    + NamingViolation = 64, + + /// + /// Indicates that the add, modify, or modify DN operation violates the + /// object class rules for the entry. + /// For example, the following types of request return this error: + ///
      + ///
    • + /// The add or modify operation tries to add an entry without a value + /// for a required attribute. + ///
    • + ///
    • + /// The add or modify operation tries to add an entry with a value for + /// an attribute which the class definition does not contain. + ///
    • + ///
    • + /// The modify operation tries to remove a required attribute without + /// removing the auxiliary class that defines the attribute as required. + ///
    • + ///
    + /// OBJECT_CLASS_VIOLATION = 65 + ///
    + ObjectClassViolation = 65, + + /// + /// Indicates that the requested operation is permitted only on leaf entries. + /// For example, the following types of requests return this error: + ///
      + ///
    • The client requests a delete operation on a parent entry.
    • + ///
    • The client request a modify DN operation on a parent entry.
    • + ///
    + /// NOT_ALLOWED_ON_NONLEAF = 66 + ///
    + NotAllowedOnNonleaf = 66, + + /// + /// Indicates that the modify operation attempted to remove an attribute + /// value that forms the entry's relative distinguished name. + /// NOT_ALLOWED_ON_RDN = 67 + /// + NotAllowedOnRdn = 67, + + /// + /// Indicates that the add operation attempted to add an entry that already + /// exists, or that the modify operation attempted to rename an entry to the + /// name of an entry that already exists. + /// ENTRY_ALREADY_EXISTS = 68 + /// + EntryAlreadyExists = 68, + + /// + /// Indicates that the modify operation attempted to modify the structure + /// rules of an object class. + /// OBJECT_CLASS_MODS_PROHIBITED = 69 + /// + ObjectClassModsProhibited = 69, + + /// + /// Indicates that the modify DN operation moves the entry from one Ldap + /// server to another and thus requires more than one Ldap server. + /// AFFECTS_MULTIPLE_DSAS = 71 + /// + AffectsMultipleDsas = 71, + + /// + /// Indicates an unknown error condition. + /// OTHER = 80 + /// + Other = 80, + + ///////////////////////////////////////////////////////////////////////////// + // Local Errors, resulting from actions other than an operation on a server + ///////////////////////////////////////////////////////////////////////////// + + /// + /// Indicates that the Ldap libraries cannot establish an initial connection + /// with the Ldap server. Either the Ldap server is down or the specified + /// host name or port number is incorrect. + /// SERVER_DOWN = 81 + /// + ServerDown = 81, + + /// + /// Indicates that the Ldap client has an error. This is usually a failed + /// dynamic memory allocation error. + /// LOCAL_ERROR = 82 + /// + LocalError = 82, + + /// + /// Indicates that the Ldap client encountered errors when encoding an + /// Ldap request intended for the Ldap server. + /// ENCODING_ERROR = 83 + /// + EncodingError = 83, + + /// + /// Indicates that the Ldap client encountered errors when decoding an + /// Ldap response from the Ldap server. + /// DECODING_ERROR = 84 + /// + DecodingError = 84, + + /// + /// Indicates that the time limit of the Ldap client was exceeded while + /// waiting for a result. + /// Ldap_TIMEOUT = 85 + /// + LdapTimeout = 85, + + /// + /// Indicates that a bind method was called with an unknown + /// authentication method. + /// AUTH_UNKNOWN = 86 + /// + AuthUnknown = 86, + + /// + /// Indicates that the search method was called with an invalid + /// search filter. + /// FILTER_ERROR = 87 + /// + FilterError = 87, + + /// + /// Indicates that the user cancelled the Ldap operation. + /// USER_CANCELLED = 88 + /// + UserCancelled = 88, + + /// + /// Indicates that a dynamic memory allocation method failed when calling + /// an Ldap method. + /// NO_MEMORY = 90 + /// + NoMemory = 90, + + /// + /// Indicates that the Ldap client has lost either its connection or + /// cannot establish a connection to the Ldap server. + /// CONNECT_ERROR = 91 + /// + ConnectError = 91, + + /// + /// Indicates that the requested functionality is not supported by the + /// client. For example, if the Ldap client is established as an Ldapv2 + /// client, the libraries set this error code when the client requests + /// Ldapv3 functionality. + /// Ldap_NOT_SUPPORTED = 92 + /// + LdapNotSupported = 92, + + /// + /// Indicates that the client requested a control that the libraries + /// cannot find in the list of supported controls sent by the Ldap server. + /// CONTROL_NOT_FOUND = 93 + /// + ControlNotFound = 93, + + /// + /// Indicates that the Ldap server sent no results. + /// NO_RESULTS_RETURNED = 94 + /// + NoResultsReturned = 94, + + /// + /// Indicates that more results are chained in the result message. + /// MORE_RESULTS_TO_RETURN = 95 + /// + MoreResultsToReturn = 95, + + /// + /// Indicates the Ldap libraries detected a loop. Usually this happens + /// when following referrals. + /// CLIENT_LOOP = 96 + /// + ClientLoop = 96, + + /// + /// Indicates that the referral exceeds the hop limit. The default hop + /// limit is ten. + /// The hop limit determines how many servers the client can hop through + /// to retrieve data. For example, suppose the following conditions: + ///
      + ///
    • Suppose the hop limit is two.
    • + ///
    • + /// If the referral is to server D which can be contacted only through + /// server B (1 hop) which contacts server C (2 hops) which contacts + /// server D (3 hops). + ///
    • + ///
    + /// With these conditions, the hop limit is exceeded and the Ldap + /// libraries set this code. + /// REFERRAL_LIMIT_EXCEEDED = 97 + ///
    + ReferralLimitExceeded = 97, + + /// + /// Indicates that the server response to a request is invalid. + /// INVALID_RESPONSE = 100 + /// + InvalidResponse = 100, + + /// + /// Indicates that the server response to a request is ambiguous. + /// AMBIGUOUS_RESPONSE = 101 + /// + AmbiguousResponse = 101, + + /// + /// Indicates that TLS is not supported on the server. + /// TLS_NOT_SUPPORTED = 112 + /// + TlsNotSupported = 112, + + /// + /// Indicates that SSL Handshake could not succeed. + /// SSL_HANDSHAKE_FAILED = 113 + /// + SslHandshakeFailed = 113, + + /// + /// Indicates that SSL Provider could not be found. + /// SSL_PROVIDER_NOT_FOUND = 114 + /// + SslProviderNotFound = 114, + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/Message.cs b/Unosquare.Swan/Networking/Ldap/Message.cs new file mode 100644 index 0000000..ee19a47 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/Message.cs @@ -0,0 +1,304 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System; + using System.Collections.Generic; + + /// + /// The class performs token processing from strings. + /// + internal class Tokenizer + { + // The tokenizer uses the default delimiter set: the space character, the tab character, the newline character, and the carriage-return character + private readonly string _delimiters = " \t\n\r"; + + private readonly bool _returnDelims; + + private List _elements; + + private string _source; + + /// + /// Initializes a new instance of the class. + /// Initializes a new class instance with a specified string to process + /// and the specified token delimiters to use. + /// + /// String to tokenize. + /// String containing the delimiters. + /// if set to true [ret delete]. + public Tokenizer(string source, string delimiters, bool retDel = false) + { + _elements = new List(); + _delimiters = delimiters ?? _delimiters; + _source = source; + _returnDelims = retDel; + if (_returnDelims) + Tokenize(); + else + _elements.AddRange(source.Split(_delimiters.ToCharArray())); + RemoveEmptyStrings(); + } + + public int Count => _elements.Count; + + public bool HasMoreTokens() => _elements.Count > 0; + + public string NextToken() + { + if (_source == string.Empty) throw new InvalidOperationException(); + + string result; + if (_returnDelims) + { + RemoveEmptyStrings(); + result = _elements[0]; + _elements.RemoveAt(0); + return result; + } + + _elements = new List(); + _elements.AddRange(_source.Split(_delimiters.ToCharArray())); + RemoveEmptyStrings(); + result = _elements[0]; + _elements.RemoveAt(0); + _source = _source.Remove(_source.IndexOf(result, StringComparison.Ordinal), result.Length); + _source = _source.TrimStart(_delimiters.ToCharArray()); + return result; + } + + private void RemoveEmptyStrings() + { + for (var index = 0; index < _elements.Count; index++) + { + if (_elements[index] != string.Empty) continue; + + _elements.RemoveAt(index); + index--; + } + } + + private void Tokenize() + { + var tempstr = _source; + if (tempstr.IndexOfAny(_delimiters.ToCharArray()) < 0 && tempstr.Length > 0) + { + _elements.Add(tempstr); + } + else if (tempstr.IndexOfAny(_delimiters.ToCharArray()) < 0 && tempstr.Length <= 0) + { + return; + } + + while (tempstr.IndexOfAny(_delimiters.ToCharArray()) >= 0) + { + if (tempstr.IndexOfAny(_delimiters.ToCharArray()) == 0) + { + if (tempstr.Length > 1) + { + _elements.Add(tempstr.Substring(0, 1)); + tempstr = tempstr.Substring(1); + } + else + { + tempstr = string.Empty; + } + } + else + { + var toks = tempstr.Substring(0, tempstr.IndexOfAny(_delimiters.ToCharArray())); + _elements.Add(toks); + _elements.Add(tempstr.Substring(toks.Length, 1)); + + tempstr = tempstr.Length > toks.Length + 1 ? tempstr.Substring(toks.Length + 1) : string.Empty; + } + } + + if (tempstr.Length > 0) + { + _elements.Add(tempstr); + } + } + } + + /// + /// Represents an Ldap Matching Rule Assertion. + ///
    +    /// MatchingRuleAssertion ::= SEQUENCE {
    +    /// matchingRule    [1] MatchingRuleId OPTIONAL,
    +    /// type            [2] AttributeDescription OPTIONAL,
    +    /// matchValue      [3] AssertionValue,
    +    /// dnAttributes    [4] BOOLEAN DEFAULT FALSE }
    +    /// 
    + /// + internal class RfcMatchingRuleAssertion : Asn1Sequence + { + public RfcMatchingRuleAssertion( + string matchingRule, + string type, + sbyte[] matchValue, + Asn1Boolean dnAttributes = null) + : base(4) + { + if (matchingRule != null) + Add(new Asn1Tagged(new Asn1Identifier(1), new Asn1OctetString(matchingRule), false)); + if (type != null) + Add(new Asn1Tagged(new Asn1Identifier(2), new Asn1OctetString(type), false)); + + Add(new Asn1Tagged(new Asn1Identifier(3), new Asn1OctetString(matchValue), false)); + + // if dnAttributes if false, that is the default value and we must not + // encode it. (See RFC 2251 5.1 number 4) + if (dnAttributes != null && dnAttributes.BooleanValue()) + Add(new Asn1Tagged(new Asn1Identifier(4), dnAttributes, false)); + } + } + + /// + /// The AttributeDescriptionList is used to list attributes to be returned in + /// a search request. + ///
    +    /// AttributeDescriptionList ::= SEQUENCE OF
    +    /// AttributeDescription
    +    /// 
    + /// + internal class RfcAttributeDescriptionList : Asn1SequenceOf + { + public RfcAttributeDescriptionList(string[] attrs) + : base(attrs?.Length ?? 0) + { + if (attrs == null) return; + + foreach (var attr in attrs) + { + Add(attr); + } + } + } + + /// + /// Represents an Ldap Search Request. + ///
    +    /// SearchRequest ::= [APPLICATION 3] SEQUENCE {
    +    /// baseObject      LdapDN,
    +    /// scope           ENUMERATED {
    +    /// baseObject              (0),
    +    /// singleLevel             (1),
    +    /// wholeSubtree            (2) },
    +    /// derefAliases    ENUMERATED {
    +    /// neverDerefAliases       (0),
    +    /// derefInSearching        (1),
    +    /// derefFindingBaseObj     (2),
    +    /// derefAlways             (3) },
    +    /// sizeLimit       INTEGER (0 .. maxInt),
    +    /// timeLimit       INTEGER (0 .. maxInt),
    +    /// typesOnly       BOOLEAN,
    +    /// filter          Filter,
    +    /// attributes      AttributeDescriptionList }
    +    /// 
    + ///
    + /// + /// + internal class RfcSearchRequest : Asn1Sequence, IRfcRequest + { + public RfcSearchRequest( + string basePath, + LdapScope scope, + int derefAliases, + int sizeLimit, + int timeLimit, + bool typesOnly, + string filter, + string[] attributes) + : base(8) + { + Add(basePath); + Add(new Asn1Enumerated(scope)); + Add(new Asn1Enumerated(derefAliases)); + Add(new Asn1Integer(sizeLimit)); + Add(new Asn1Integer(timeLimit)); + Add(new Asn1Boolean(typesOnly)); + Add(new RfcFilter(filter)); + Add(new RfcAttributeDescriptionList(attributes)); + } + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.SearchRequest); + + public string GetRequestDN() => ((Asn1OctetString) Get(0)).StringValue(); + } + + /// + /// Represents an Ldap Substring Filter. + ///
    +    /// SubstringFilter ::= SEQUENCE {
    +    /// type            AttributeDescription,
    +    /// -- at least one must be present
    +    /// substrings      SEQUENCE OF CHOICE {
    +    /// initial [0] LdapString,
    +    /// any     [1] LdapString,
    +    /// final   [2] LdapString } }
    +    /// 
    + ///
    + /// + internal class RfcSubstringFilter : Asn1Sequence + { + public RfcSubstringFilter(string type, Asn1Object substrings) + : base(2) + { + Add(type); + Add(substrings); + } + } + + /// + /// Represents an Ldap Attribute Value Assertion. + ///
    +    /// AttributeValueAssertion ::= SEQUENCE {
    +    /// attributeDesc   AttributeDescription,
    +    /// assertionValue  AssertionValue }
    +    /// 
    + ///
    + /// + internal class RfcAttributeValueAssertion : Asn1Sequence + { + public RfcAttributeValueAssertion(string ad, sbyte[] av) + : base(2) + { + Add(ad); + Add(new Asn1OctetString(av)); + } + + public string AttributeDescription => ((Asn1OctetString) Get(0)).StringValue(); + + public sbyte[] AssertionValue => ((Asn1OctetString) Get(1)).ByteValue(); + } + + /// Encapsulates an Ldap Bind properties. + internal class BindProperties + { + /// + /// Initializes a new instance of the class. + /// + /// The version. + /// The dn. + /// The method. + /// if set to true [anonymous]. + public BindProperties( + int version, + string dn, + string method, + bool anonymous) + { + ProtocolVersion = version; + AuthenticationDN = dn; + AuthenticationMethod = method; + Anonymous = anonymous; + } + + public int ProtocolVersion { get; } + + public string AuthenticationDN { get; } + + public string AuthenticationMethod { get; } + + public bool Anonymous { get; } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/RfcControl.cs b/Unosquare.Swan/Networking/Ldap/RfcControl.cs new file mode 100644 index 0000000..d7eec36 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/RfcControl.cs @@ -0,0 +1,131 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + /// + /// Represents an Ldap Control. + ///
    +    /// Control ::= SEQUENCE {
    +    /// controlType             LdapOID,
    +    /// criticality             BOOLEAN DEFAULT FALSE,
    +    /// controlValue            OCTET STRING OPTIONAL }
    +    /// 
    + ///
    + /// + internal class RfcControl : Asn1Sequence + { + /// + /// Initializes a new instance of the class. + /// Note: criticality is only added if true, as per RFC 2251 sec 5.1 part + /// (4): If a value of a type is its default value, it MUST be + /// absent. + /// + /// Type of the control. + /// The criticality. + /// The control value. + public RfcControl(string controlType, Asn1Boolean criticality = null, Asn1Object controlValue = null) + : base(3) + { + Add(controlType); + Add(criticality ?? new Asn1Boolean(false)); + + if (controlValue != null) + Add(controlValue); + } + + public RfcControl(Asn1Structured seqObj) + : base(3) + { + for (var i = 0; i < seqObj.Size(); i++) + Add(seqObj.Get(i)); + } + + public Asn1OctetString ControlType => (Asn1OctetString)Get(0); + + public Asn1Boolean Criticality => Size() > 1 && Get(1) is Asn1Boolean boolean ? boolean : new Asn1Boolean(false); + + public Asn1OctetString ControlValue + { + get + { + if (Size() > 2) + { + // MUST be a control value + return (Asn1OctetString)Get(2); + } + + return Size() > 1 && Get(1) is Asn1OctetString s ? s : null; + } + set + { + if (value == null) + return; + + if (Size() == 3) + { + // We already have a control value, replace it + Set(2, value); + return; + } + + if (Size() == 2) + { + // Get the second element + var obj = Get(1); + + // Is this a control value + if (obj is Asn1OctetString) + { + // replace this one + Set(1, value); + } + else + { + // add a new one at the end + Add(value); + } + } + } + } + } + + /// + /// Represents Ldap Sasl Credentials. + ///
    +    /// SaslCredentials ::= SEQUENCE {
    +    /// mechanism               LdapString,
    +    /// credentials             OCTET STRING OPTIONAL }
    +    /// 
    + /// + internal class RfcSaslCredentials : Asn1Sequence + { + public RfcSaslCredentials(string mechanism, sbyte[] credentials = null) + : base(2) + { + Add(mechanism); + if (credentials != null) + Add(new Asn1OctetString(credentials)); + } + } + + /// + /// Represents an Ldap Authentication Choice. + ///
    +    /// AuthenticationChoice ::= CHOICE {
    +    /// simple                  [0] OCTET STRING,
    +    /// -- 1 and 2 reserved
    +    /// sasl                    [3] SaslCredentials }
    +    /// 
    + /// + internal class RfcAuthenticationChoice : Asn1Choice + { + public RfcAuthenticationChoice(sbyte[] passwd) + : base(new Asn1Tagged(new Asn1Identifier(0), new Asn1OctetString(passwd), false)) + { + } + + public RfcAuthenticationChoice(string mechanism, sbyte[] credentials) + : base(new Asn1Tagged(new Asn1Identifier(3, true), new RfcSaslCredentials(mechanism, credentials), false)) + { + // implicit tagging + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/RfcFilter.cs b/Unosquare.Swan/Networking/Ldap/RfcFilter.cs new file mode 100644 index 0000000..2bb81e2 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/RfcFilter.cs @@ -0,0 +1,1134 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System; + using System.Collections; + using System.Collections.Generic; + using System.Text; + using Exceptions; + + /// + /// Represents an Ldap Filter by parsing an RFC 2254 Search Filter String. + /// This filter object can be created from a String or can be built up + /// programatically by adding filter components one at a time. Existing filter + /// components can be iterated though. + /// Each filter component has an integer identifier defined in this class. + /// The following are basic filter components: {EQUALITY_MATCH}, + /// {GREATER_OR_EQUAL}, {LESS_OR_EQUAL}, {SUBSTRINGS}, + /// {PRESENT}, {APPROX_MATCH}, {EXTENSIBLE_MATCH}. + /// More filters can be nested together into more complex filters with the + /// following filter components: {AND}, {OR}, {NOT} + /// Substrings can have three components:. + /// + ///
    +    /// Filter ::= CHOICE {
    +    /// and             [0] SET OF Filter,
    +    /// or              [1] SET OF Filter,
    +    /// not             [2] Filter,
    +    /// equalityMatch   [3] AttributeValueAssertion,
    +    /// substrings      [4] SubstringFilter,
    +    /// greaterOrEqual  [5] AttributeValueAssertion,
    +    /// lessOrEqual     [6] AttributeValueAssertion,
    +    /// present         [7] AttributeDescription,
    +    /// approxMatch     [8] AttributeValueAssertion,
    +    /// extensibleMatch [9] MatchingRuleAssertion }
    +    /// 
    + ///
    + /// + internal class RfcFilter : Asn1Choice + { + private FilterTokenizer _ft; + + private Stack _filterStack; + private bool _finalFound; + + public RfcFilter(string filter) + { + ChoiceValue = Parse(filter); + } + + /// + /// Creates and adds a substrings filter component. + /// startSubstrings must be immediately followed by at least one + /// AddSubstring method and one EndSubstrings method. + /// + /// Name of the attribute. + public void StartSubstrings(string attrName) + { + _finalFound = false; + var seq = new Asn1SequenceOf(5); + + AddObject(new Asn1Tagged(new Asn1Identifier((int)FilterOp.Substrings, true), + new RfcSubstringFilter(attrName, seq), + false)); + _filterStack.Push(seq); + } + + /// + /// Adds a Substring component of initial, any or final substring matching. + /// This method can be invoked only if startSubString was the last filter- + /// building method called. A substring is not required to have an 'INITIAL' + /// substring. However, when a filter contains an 'INITIAL' substring only + /// one can be added, and it must be the first substring added. Any number of + /// 'ANY' substrings can be added. A substring is not required to have a + /// 'FINAL' substrings either. However, when a filter does contain a 'FINAL' + /// substring only one can be added, and it must be the last substring added. + /// + /// Substring type: INITIAL | ANY | FINAL]. + /// The value renamed. + /// + /// Attempt to add an invalid " + "substring type + /// or + /// Attempt to add an initial " + "substring match after the first substring + /// or + /// Attempt to add a substring " + "match after a final substring match + /// or + /// A call to addSubstring occured " + "without calling startSubstring. + /// + public void AddSubstring(SubstringOp type, sbyte[] values) + { + try + { + var substringSeq = (Asn1SequenceOf)_filterStack.Peek(); + if (type != SubstringOp.Initial && type != SubstringOp.Any && type != SubstringOp.Final) + { + throw new LdapException("Attempt to add an invalid substring type", + LdapStatusCode.FilterError); + } + + if (type == SubstringOp.Initial && substringSeq.Size() != 0) + { + throw new LdapException( + "Attempt to add an initial substring match after the first substring", + LdapStatusCode.FilterError); + } + + if (_finalFound) + { + throw new LdapException("Attempt to add a substring match after a final substring match", + LdapStatusCode.FilterError); + } + + if (type == SubstringOp.Final) + { + _finalFound = true; + } + + substringSeq.Add(new Asn1Tagged(new Asn1Identifier((int)type), values)); + } + catch (InvalidCastException) + { + throw new LdapException("A call to addSubstring occured without calling startSubstring", + LdapStatusCode.FilterError); + } + } + + /// + /// Completes a SubString filter component. + /// + /// + /// Empty substring filter + /// or + /// Mismatched ending of substrings. + /// + public void EndSubstrings() + { + try + { + _finalFound = false; + var substringSeq = (Asn1SequenceOf)_filterStack.Peek(); + + if (substringSeq.Size() == 0) + { + throw new LdapException("Empty substring filter", LdapStatusCode.FilterError); + } + } + catch (InvalidCastException) + { + throw new LdapException("Mismatched ending of substrings", LdapStatusCode.FilterError); + } + + _filterStack.Pop(); + } + + /// + /// Creates and adds an AttributeValueAssertion to the filter. + /// + /// Filter type: EQUALITY_MATCH | GREATER_OR_EQUAL + /// | LESS_OR_EQUAL | APPROX_MATCH ]. + /// Name of the attribute to be asserted. + /// Value of the attribute to be asserted. + /// + /// Cannot insert an attribute assertion in a substring + /// or + /// Invalid filter type for AttributeValueAssertion. + /// + public void AddAttributeValueAssertion(FilterOp rfcType, string attrName, sbyte[] valueArray) + { + if (_filterStack != null && _filterStack.Count != 0 && _filterStack.Peek() is Asn1SequenceOf) + { + throw new LdapException("Cannot insert an attribute assertion in a substring", + LdapStatusCode.FilterError); + } + + if (rfcType != FilterOp.EqualityMatch && rfcType != FilterOp.GreaterOrEqual && + rfcType != FilterOp.LessOrEqual && + rfcType != FilterOp.ApproxMatch) + { + throw new LdapException("Invalid filter type for AttributeValueAssertion", + LdapStatusCode.FilterError); + } + + Asn1Object current = new Asn1Tagged( + new Asn1Identifier((int)rfcType, true), + new RfcAttributeValueAssertion(attrName, valueArray), + false); + AddObject(current); + } + + /// + /// Creates and adds a present matching to the filter. + /// + /// Name of the attribute to check for presence. + public void AddPresent(string attrName) + { + Asn1Object current = new Asn1Tagged( + new Asn1Identifier((int)FilterOp.Present), + new Asn1OctetString(attrName), + false); + AddObject(current); + } + + /// + /// Creates and adds the Asn1Tagged value for a nestedFilter: AND, OR, or + /// NOT. + /// Note that a Not nested filter can only have one filter, where AND + /// and OR do not. + /// + /// Filter type: + /// [AND | OR | NOT]. + /// Attempt to create a nested filter other than AND, OR or NOT. + public void StartNestedFilter(FilterOp rfcType) + { + Asn1Object current; + + switch (rfcType) + { + case FilterOp.And: + case FilterOp.Or: + current = new Asn1Tagged(new Asn1Identifier((int)rfcType, true), new Asn1SetOf(), false); + break; + case FilterOp.Not: + current = new Asn1Tagged(new Asn1Identifier((int)rfcType, true)); + break; + default: + throw new LdapException("Attempt to create a nested filter other than AND, OR or NOT", + LdapStatusCode.FilterError); + } + + AddObject(current); + } + + /// + /// Completes a nested filter and checks for the valid filter type. + /// + /// Type of filter to complete. + /// Mismatched ending of nested filter. + public void EndNestedFilter(FilterOp rfcType) + { + if (rfcType == FilterOp.Not) + { + // if this is a Not than Not should be the second thing on the stack + _filterStack.Pop(); + } + + var topOfStackType = _filterStack.Peek().GetIdentifier().Tag; + if (topOfStackType != (int)rfcType) + { + throw new LdapException("Mismatched ending of nested filter", LdapStatusCode.FilterError); + } + + _filterStack.Pop(); + } + + public IEnumerator GetFilterIterator() => new FilterIterator(this, (Asn1Tagged)ChoiceValue); + + /// + /// Creates and returns a String representation of this filter. + /// + /// Filtered string. + public string FilterToString() + { + var filter = new StringBuilder(); + StringFilter(GetFilterIterator(), filter); + return filter.ToString(); + } + + private static void StringFilter(IEnumerator itr, StringBuilder filter) + { + filter.Append('('); + while (itr.MoveNext()) + { + var filterpart = itr.Current; + + if (filterpart is int i) + { + var op = (FilterOp)i; + switch (op) + { + case FilterOp.And: + filter.Append('&'); + break; + case FilterOp.Or: + filter.Append('|'); + break; + case FilterOp.Not: + filter.Append('!'); + break; + case FilterOp.EqualityMatch: + { + filter.Append((string)itr.Current); + filter.Append('='); + filter.Append(Encoding.UTF8.GetString((sbyte[])itr.Current)); + break; + } + + case FilterOp.GreaterOrEqual: + { + filter + .Append((string)itr.Current) + .Append(">=") + .Append(Encoding.UTF8.GetString((sbyte[])itr.Current)); + break; + } + + case FilterOp.LessOrEqual: + { + filter.Append((string)itr.Current); + filter.Append("<="); + filter.Append(Encoding.UTF8.GetString((sbyte[])itr.Current)); + break; + } + + case FilterOp.Present: + filter.Append((string)itr.Current); + filter.Append("=*"); + break; + case FilterOp.ApproxMatch: + filter.Append((string)itr.Current); + filter.Append("~="); + filter.Append(Encoding.UTF8.GetString((sbyte[])itr.Current)); + break; + case FilterOp.ExtensibleMatch: + var oid = (string)itr.Current; + filter.Append((string)itr.Current); + filter.Append(':'); + filter.Append(oid); + filter.Append(":="); + filter.Append((string)itr.Current); + break; + case FilterOp.Substrings: + { + filter.Append((string)itr.Current); + filter.Append('='); + + while (itr.MoveNext()) + { + switch ((SubstringOp)(int)itr.Current) + { + case SubstringOp.Any: + case SubstringOp.Initial: + filter.Append(itr.Current as string); + filter.Append('*'); + break; + case SubstringOp.Final: + filter.Append((string)itr.Current); + break; + } + } + + break; + } + } + } + else if (filterpart is IEnumerator enumerator) + { + StringFilter(enumerator, filter); + } + } + + filter.Append(')'); + } + + private Asn1Tagged Parse(string expression) + { + var filterExpr = string.IsNullOrWhiteSpace(expression) ? "(objectclass=*)" : expression; + + int idx; + if ((idx = filterExpr.IndexOf('\\')) != -1) + { + var sb = new StringBuilder(filterExpr); + var i = idx; + while (i < sb.Length - 1) + { + var c = sb[i++]; + + if (c != '\\') continue; + + // found '\' (backslash) + // If V2 escape, turn to a V3 escape + c = sb[i]; + if (c != '*' && c != '(' && c != ')' && c != '\\') continue; + + // Ldap v2 filter, convert them into hex chars + sb.Remove(i, i + 1 - i); + sb.Insert(i, Convert.ToString(c, 16)); + i += 2; + } + + filterExpr = sb.ToString(); + } + + // missing opening and closing parentheses, must be V2, add parentheses + if (filterExpr[0] != '(' && filterExpr[filterExpr.Length - 1] != ')') + { + filterExpr = "(" + filterExpr + ")"; + } + + var ch = filterExpr[0]; + var len = filterExpr.Length; + + // missing opening parenthesis ? + if (ch != '(') + { + throw new LdapException(LdapException.MissingLeftParen, LdapStatusCode.FilterError); + } + + // missing closing parenthesis ? + if (filterExpr[len - 1] != ')') + { + throw new LdapException(LdapException.MissingRightParen, LdapStatusCode.FilterError); + } + + // unmatched parentheses ? + var parenCount = 0; + for (var i = 0; i < len; i++) + { + switch (filterExpr[i]) + { + case '(': + parenCount++; + break; + case ')': + parenCount--; + break; + } + } + + if (parenCount > 0) + { + throw new LdapException(LdapException.MissingRightParen, LdapStatusCode.FilterError); + } + + if (parenCount < 0) + { + throw new LdapException(LdapException.MissingLeftParen, LdapStatusCode.FilterError); + } + + _ft = new FilterTokenizer(this, filterExpr); + return ParseFilter(); + } + + private Asn1Tagged ParseFilter() + { + _ft.GetLeftParen(); + var filter = ParseFilterComp(); + _ft.GetRightParen(); + return filter; + } + + private Asn1Tagged ParseFilterComp() + { + Asn1Tagged tag = null; + var filterComp = (FilterOp)_ft.OpOrAttr; + + switch (filterComp) + { + case FilterOp.And: + case FilterOp.Or: + tag = new Asn1Tagged(new Asn1Identifier((int)filterComp, true), + ParseFilterList(), + false); + break; + case FilterOp.Not: + tag = new Asn1Tagged(new Asn1Identifier((int)filterComp, true), + ParseFilter()); + break; + default: + var filterType = _ft.FilterType; + var valueRenamed = _ft.Value; + + switch (filterType) + { + case FilterOp.GreaterOrEqual: + case FilterOp.LessOrEqual: + case FilterOp.ApproxMatch: + tag = new Asn1Tagged(new Asn1Identifier((int)filterType, true), + new RfcAttributeValueAssertion(_ft.Attr, UnescapeString(valueRenamed)), + false); + break; + case FilterOp.EqualityMatch: + if (valueRenamed.Equals("*")) + { + // present + tag = new Asn1Tagged( + new Asn1Identifier((int)FilterOp.Present), + new Asn1OctetString(_ft.Attr), + false); + } + else if (valueRenamed.IndexOf('*') != -1) + { + var sub = new Tokenizer(valueRenamed, "*", true); + var seq = new Asn1SequenceOf(5); + var tokCnt = sub.Count; + var cnt = 0; + var lastTok = new StringBuilder(string.Empty).ToString(); + while (sub.HasMoreTokens()) + { + var subTok = sub.NextToken(); + cnt++; + if (subTok.Equals("*")) + { + // if previous token was '*', and since the current + // token is a '*', we need to insert 'any' + if (lastTok.Equals(subTok)) + { + // '**' + seq.Add(new Asn1Tagged( + new Asn1Identifier((int)SubstringOp.Any), + UnescapeString(string.Empty))); + } + } + else + { + // value (RfcLdapString) + if (cnt == 1) + { + // initial + seq.Add(new Asn1Tagged( + new Asn1Identifier((int)SubstringOp.Initial), + UnescapeString(subTok))); + } + else if (cnt < tokCnt) + { + // any + seq.Add(new Asn1Tagged( + new Asn1Identifier((int)SubstringOp.Any), + UnescapeString(subTok))); + } + else + { + // final + seq.Add(new Asn1Tagged( + new Asn1Identifier((int)SubstringOp.Final), + UnescapeString(subTok))); + } + } + + lastTok = subTok; + } + + tag = new Asn1Tagged( + new Asn1Identifier((int)FilterOp.Substrings, true), + new RfcSubstringFilter(_ft.Attr, seq), + false); + } + else + { + tag = new Asn1Tagged( + new Asn1Identifier((int)FilterOp.EqualityMatch, true), + new RfcAttributeValueAssertion(_ft.Attr, UnescapeString(valueRenamed)), + false); + } + + break; + case FilterOp.ExtensibleMatch: + string type = null, matchingRule = null; + var attr = false; + var st = new Tokenizer(_ft.Attr, ":"); + var first = true; + + while (st.HasMoreTokens()) + { + var s = st.NextToken().Trim(); + if (first && !s.Equals(":")) + { + type = s; + } + else if (s.Equals("dn")) + { + attr = true; + } + else if (!s.Equals(":")) + { + matchingRule = s; + } + + first = false; + } + + tag = new Asn1Tagged( + new Asn1Identifier((int)FilterOp.ExtensibleMatch, true), + new RfcMatchingRuleAssertion(matchingRule, type, UnescapeString(valueRenamed), attr == false ? null : new Asn1Boolean(true)), + false); + + break; + } + + break; + } + + return tag; + } + + private Asn1SetOf ParseFilterList() + { + var setOf = new Asn1SetOf(); + setOf.Add(ParseFilter()); // must have at least 1 filter + while (_ft.PeekChar() == '(') + { + // check for more filters + setOf.Add(ParseFilter()); + } + + return setOf; + } + + /// + /// Replace escaped hex digits with the equivalent binary representation. + /// Assume either V2 or V3 escape mechanisms: + /// V2: \*, \(, \), \\. + /// V3: \2A, \28, \29, \5C, \00. + /// + /// The string renamed. + /// + /// octet-string encoding of the specified string. + /// + /// Invalid Escape. + private static sbyte[] UnescapeString(string value) + { + var octets = new sbyte[value.Length * 3]; + var octs = 0; + var escape = false; + var escStart = false; + var length = value.Length; + var ca = new char[1]; // used while converting multibyte UTF-8 char + var temp = (char)0; // holds the value of the escaped sequence + + // loop through each character of the string and copy them into octets + // converting escaped sequences when needed + for (var str = 0; str < length; str++) + { + var ch = value[str]; // Character we are adding to the octet string + + if (escape) + { + var ival = ch.Hex2Int(); + + if (ival < 0) + { + throw new LdapException($"Invalid value in escape sequence \"{ch}\"", + LdapStatusCode.FilterError); + } + + // V3 escaped: \\** + if (escStart) + { + temp = (char)(ival << 4); // high bits of escaped char + escStart = false; + } + else + { + temp |= (char)ival; // all bits of escaped char + octets[octs++] = (sbyte)temp; + } + } + else if (ch == '\\') + { + escStart = escape = true; + } + else + { + // place the character into octets. + if ((ch >= 0x01 && ch <= 0x27) || (ch >= 0x2B && ch <= 0x5B) || ch >= 0x5D) + { + // found valid char + if (ch <= 0x7f) + { + // char = %x01-27 / %x2b-5b / %x5d-7f + octets[octs++] = (sbyte)ch; + } + else + { + // char > 0x7f, could be encoded in 2 or 3 bytes + ca[0] = ch; + var utf8Bytes = Encoding.UTF8.GetSBytes(new string(ca)); + + // copy utf8 encoded character into octets + Array.Copy(utf8Bytes, 0, octets, octs, utf8Bytes.Length); + octs = octs + utf8Bytes.Length; + } + } + else + { + // found invalid character + var escString = new StringBuilder(); + ca[0] = ch; + + foreach (var u in Encoding.UTF8.GetSBytes(new string(ca))) + { + escString.Append("\\"); + + if (u >= 0 && u < 0x10) escString.Append("0"); + + escString.Append(Convert.ToString(u & 0xff, 16)); + } + + throw new LdapException( + $"The invalid character \"{ch}\" needs to be escaped as \"{escString}\"", + LdapStatusCode.FilterError); + } + } + } + + // Verify that any escape sequence completed + if (escStart || escape) + { + throw new LdapException("Incomplete escape sequence", LdapStatusCode.FilterError); + } + + var toReturn = new sbyte[octs]; + Array.Copy(octets, 0, toReturn, 0, octs); + + return toReturn; + } + + private void AddObject(Asn1Object current) + { + if (_filterStack == null) + { + _filterStack = new Stack(); + } + + if (ChoiceValue == null) + { + // ChoiceValue is the root Asn1 node + ChoiceValue = current; + } + else + { + var topOfStack = (Asn1Tagged)_filterStack.Peek(); + var value = topOfStack.TaggedValue; + + switch (value) + { + case null: + topOfStack.TaggedValue = current; + _filterStack.Push(current); + break; + case Asn1SetOf _: + ((Asn1SetOf)value).Add(current); + break; + case Asn1Set _: + ((Asn1Set)value).Add(current); + break; + default: + if (value.GetIdentifier().Tag == (int)FilterOp.Not) + { + throw new LdapException("Attempt to create more than one 'not' sub-filter", + LdapStatusCode.FilterError); + } + + break; + } + } + + var type = (FilterOp)current.GetIdentifier().Tag; + if (type == FilterOp.And || type == FilterOp.Or || type == FilterOp.Not) + { + _filterStack.Push(current); + } + } + + internal class FilterTokenizer + { + private readonly string _filter; // The filter string to parse + private readonly int _filterLength; // Length of the filter string to parse + private int _offset; // Offset pointer into the filter string + + public FilterTokenizer(RfcFilter enclosingInstance, string filter) + { + EnclosingInstance = enclosingInstance; + _filter = filter; + _offset = 0; + _filterLength = filter.Length; + } + + /// + /// Reads either an operator, or an attribute, whichever is + /// next in the filter string. + /// If the next component is an attribute, it is read and stored in the + /// attr field of this class which may be retrieved with getAttr() + /// and a -1 is returned. Otherwise, the int value of the operator read is + /// returned. + /// + /// + /// The op or attribute. + /// + /// Unexpected end. + public int OpOrAttr + { + get + { + if (_offset >= _filterLength) + { + throw new LdapException(LdapException.UnexpectedEnd, LdapStatusCode.FilterError); + } + + int ret; + int testChar = _filter[_offset]; + + switch (testChar) + { + case '&': + _offset++; + ret = (int)FilterOp.And; + break; + case '|': + _offset++; + ret = (int)FilterOp.Or; + break; + case '!': + _offset++; + ret = (int)FilterOp.Not; + break; + default: + if (_filter.Substring(_offset).StartsWith(":=")) + { + throw new LdapException("Missing matching rule", LdapStatusCode.FilterError); + } + + if (_filter.Substring(_offset).StartsWith("::=") || + _filter.Substring(_offset).StartsWith(":::=")) + { + throw new LdapException("DN and matching rule not specified", LdapStatusCode.FilterError); + } + + // get first component of 'item' (attr or :dn or :matchingrule) + const string delims = "=~<>()"; + var sb = new StringBuilder(); + while (delims.IndexOf(_filter[_offset]) == -1 && + _filter.Substring(_offset).StartsWith(":=") == false) + { + sb.Append(_filter[_offset++]); + } + + Attr = sb.ToString().Trim(); + + // is there an attribute name specified in the filter ? + if (Attr.Length == 0 || Attr[0] == ';') + { + throw new LdapException("Missing attribute description", LdapStatusCode.FilterError); + } + + int index; + for (index = 0; index < Attr.Length; index++) + { + var atIndex = Attr[index]; + if (char.IsLetterOrDigit(atIndex) || atIndex == '-' || atIndex == '.' || + atIndex == ';' || + atIndex == ':') continue; + + if (atIndex == '\\') + { + throw new LdapException("Escape sequence not allowed in attribute description", + LdapStatusCode.FilterError); + } + + throw new LdapException($"Invalid character \"{atIndex}\" in attribute description", + LdapStatusCode.FilterError); + } + + // is there an option specified in the filter ? + index = Attr.IndexOf(';'); + if (index != -1 && index == Attr.Length - 1) + { + throw new LdapException("Semicolon present, but no option specified", + LdapStatusCode.FilterError); + } + + ret = -1; + break; + } + + return ret; + } + } + + public FilterOp FilterType + { + get + { + if (_offset >= _filterLength) + { + throw new LdapException(LdapException.UnexpectedEnd, LdapStatusCode.FilterError); + } + + if (_filter.Substring(_offset).StartsWith(">=")) + { + _offset += 2; + return FilterOp.GreaterOrEqual; + } + + if (_filter.Substring(_offset).StartsWith("<=")) + { + _offset += 2; + return FilterOp.LessOrEqual; + } + + if (_filter.Substring(_offset).StartsWith("~=")) + { + _offset += 2; + return FilterOp.ApproxMatch; + } + + if (_filter.Substring(_offset).StartsWith(":=")) + { + _offset += 2; + return FilterOp.ExtensibleMatch; + } + + if (_filter[_offset] == '=') + { + _offset++; + return FilterOp.EqualityMatch; + } + + throw new LdapException("Invalid comparison operator", LdapStatusCode.FilterError); + } + } + + public string Value + { + get + { + if (_offset >= _filterLength) + { + throw new LdapException(LdapException.UnexpectedEnd, LdapStatusCode.FilterError); + } + + var idx = _filter.IndexOf(')', _offset); + if (idx == -1) + { + idx = _filterLength; + } + + var ret = _filter.Substring(_offset, idx - _offset); + _offset = idx; + return ret; + } + } + + public string Attr { get; private set; } + + public RfcFilter EnclosingInstance { get; } + + public void GetLeftParen() + { + if (_offset >= _filterLength) + { + throw new LdapException(LdapException.UnexpectedEnd, LdapStatusCode.FilterError); + } + + if (_filter[_offset++] != '(') + { + throw new LdapException(string.Format(LdapException.ExpectingLeftParen, _filter[_offset -= 1]), + LdapStatusCode.FilterError); + } + } + + public void GetRightParen() + { + if (_offset >= _filterLength) + { + throw new LdapException(LdapException.UnexpectedEnd, LdapStatusCode.FilterError); + } + + if (_filter[_offset++] != ')') + { + throw new LdapException(string.Format(LdapException.ExpectingRightParen, _filter[_offset - 1]), + LdapStatusCode.FilterError); + } + } + + public char PeekChar() + { + if (_offset >= _filterLength) + { + throw new LdapException(LdapException.UnexpectedEnd, LdapStatusCode.FilterError); + } + + return _filter[_offset]; + } + } + + /// + /// This inner class wrappers the Search Filter with an iterator. + /// This iterator will give access to all the individual components + /// pre-parsed. The first call to next will return an Integer identifying + /// the type of filter component. Then the component values will be returned + /// AND, NOT, and OR components values will be returned as Iterators. + /// + /// + private sealed class FilterIterator + : IEnumerator + { + private readonly Asn1Tagged _root; + + private readonly RfcFilter _enclosingInstance; + + private bool _tagReturned; + + private int _index = -1; + + private bool _hasMore = true; + + public FilterIterator(RfcFilter enclosingInstance, Asn1Tagged root) + { + _enclosingInstance = enclosingInstance; + _root = root; + } + + public object Current + { + get + { + object toReturn = null; + + if (!_tagReturned) + { + _tagReturned = true; + toReturn = _root.GetIdentifier().Tag; + } + else + { + var asn1 = _root.TaggedValue; + + switch (asn1) + { + case Asn1OctetString s: + + // one value to iterate + _hasMore = false; + toReturn = s.StringValue(); + break; + case RfcSubstringFilter sub: + if (_index == -1) + { + // return attribute name + _index = 0; + var attr = (Asn1OctetString)sub.Get(0); + toReturn = attr.StringValue(); + } + else if (_index % 2 == 0) + { + // return substring identifier + var substrs = (Asn1SequenceOf)sub.Get(1); + toReturn = ((Asn1Tagged)substrs.Get(_index / 2)).GetIdentifier().Tag; + _index++; + } + else + { + // return substring value + var substrs = (Asn1SequenceOf)sub.Get(1); + var tag = (Asn1Tagged)substrs.Get(_index / 2); + toReturn = ((Asn1OctetString)tag.TaggedValue).StringValue(); + _index++; + } + + if (_index / 2 >= ((Asn1SequenceOf)sub.Get(1)).Size()) + { + _hasMore = false; + } + + break; + case RfcAttributeValueAssertion assertion: + + // components: =,>=,<=,~= + if (_index == -1) + { + toReturn = assertion.AttributeDescription; + _index = 1; + } + else if (_index == 1) + { + toReturn = assertion.AssertionValue; + _index = 2; + _hasMore = false; + } + + break; + case RfcMatchingRuleAssertion exMatch: + + // Extensible match + if (_index == -1) + { + _index = 0; + } + + toReturn = + ((Asn1OctetString)((Asn1Tagged)exMatch.Get(_index++)).TaggedValue) + .StringValue(); + if (_index > 2) + { + _hasMore = false; + } + + break; + case Asn1SetOf setRenamed: + + // AND and OR nested components + if (_index == -1) + { + _index = 0; + } + + toReturn = new FilterIterator(_enclosingInstance, + (Asn1Tagged)setRenamed.Get(_index++)); + if (_index >= setRenamed.Size()) + { + _hasMore = false; + } + + break; + case Asn1Tagged _: + + // NOT nested component. + toReturn = new FilterIterator(_enclosingInstance, (Asn1Tagged)asn1); + _hasMore = false; + break; + } + } + + return toReturn; + } + } + + public void Reset() + { + // do nothing + } + + public bool MoveNext() => _hasMore; + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/RfcLdap.cs b/Unosquare.Swan/Networking/Ldap/RfcLdap.cs new file mode 100644 index 0000000..8d1f9e5 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/RfcLdap.cs @@ -0,0 +1,246 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System.IO; + + /// + /// Encapsulates a single search result that is in response to an asynchronous + /// search operation. + /// + /// + internal class LdapSearchResult : LdapMessage + { + private LdapEntry _entry; + + internal LdapSearchResult(RfcLdapMessage message) + : base(message) + { + } + + public LdapEntry Entry + { + get + { + if (_entry != null) return _entry; + + var attrs = new LdapAttributeSet(); + var entry = (RfcSearchResultEntry) Message.Response; + + foreach (var o in entry.Attributes.ToArray()) + { + var seq = (Asn1Sequence) o; + var attr = new LdapAttribute(((Asn1OctetString)seq.Get(0)).StringValue()); + var set = (Asn1Set)seq.Get(1); + + foreach (var t in set.ToArray()) + { + attr.AddValue(((Asn1OctetString)t).ByteValue()); + } + + attrs.Add(attr); + } + + _entry = new LdapEntry(entry.ObjectName, attrs); + + return _entry; + } + } + + public override string ToString() => _entry?.ToString() ?? base.ToString(); + } + + /// + /// Represents an Ldap Search Result Reference. + ///
    +    /// SearchResultReference ::= [APPLICATION 19] SEQUENCE OF LdapURL
    +    /// 
    + ///
    + /// + internal class RfcSearchResultReference : Asn1SequenceOf + { + /// + /// Initializes a new instance of the class. + /// The only time a client will create a SearchResultReference is when it is + /// decoding it from an Stream. + /// + /// The streab. + /// The length. + public RfcSearchResultReference(Stream stream, int len) + : base(stream, len) + { + } + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.SearchResultReference); + } + + /// + /// Represents an Ldap Extended Response. + ///
    +    /// ExtendedResponse ::= [APPLICATION 24] SEQUENCE {
    +    /// COMPONENTS OF LdapResult,
    +    /// responseName     [10] LdapOID OPTIONAL,
    +    /// response         [11] OCTET STRING OPTIONAL }
    +    /// 
    + ///
    + /// + /// + internal class RfcExtendedResponse : Asn1Sequence, IRfcResponse + { + public const int ResponseNameCode = 10; + + public const int ResponseCode = 11; + + private readonly int _referralIndex; + private readonly int _responseNameIndex; + private readonly int _responseIndex; + + /// + /// Initializes a new instance of the class. + /// The only time a client will create a ExtendedResponse is when it is + /// decoding it from an stream. + /// + /// The stream. + /// The length. + public RfcExtendedResponse(Stream stream, int len) + : base(stream, len) + { + if (Size() <= 3) return; + + for (var i = 3; i < Size(); i++) + { + var obj = (Asn1Tagged) Get(i); + var id = obj.GetIdentifier(); + + switch (id.Tag) + { + case RfcLdapResult.Referral: + var content = ((Asn1OctetString) obj.TaggedValue).ByteValue(); + + using (var bais = new MemoryStream(content.ToByteArray())) + Set(i, new Asn1SequenceOf(bais, content.Length)); + + _referralIndex = i; + break; + case ResponseNameCode: + Set(i, new Asn1OctetString(((Asn1OctetString) obj.TaggedValue).ByteValue())); + _responseNameIndex = i; + break; + case ResponseCode: + Set(i, obj.TaggedValue); + _responseIndex = i; + break; + } + } + } + + public Asn1OctetString ResponseName => _responseNameIndex != 0 ? (Asn1OctetString) Get(_responseNameIndex) : null; + + public Asn1OctetString Response => _responseIndex != 0 ? (Asn1OctetString) Get(_responseIndex) : null; + + public Asn1Enumerated GetResultCode() => (Asn1Enumerated) Get(0); + + public Asn1OctetString GetMatchedDN() => new Asn1OctetString(((Asn1OctetString) Get(1)).ByteValue()); + + public Asn1OctetString GetErrorMessage() => new Asn1OctetString(((Asn1OctetString) Get(2)).ByteValue()); + + public Asn1SequenceOf GetReferral() + => _referralIndex != 0 ? (Asn1SequenceOf) Get(_referralIndex) : null; + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.ExtendedResponse); + } + + /// + /// Represents and Ldap Bind Response. + ///
    +    /// BindResponse ::= [APPLICATION 1] SEQUENCE {
    +    /// COMPONENTS OF LdapResult,
    +    /// serverSaslCreds    [7] OCTET STRING OPTIONAL }
    +    /// 
    + ///
    + /// + /// + internal class RfcBindResponse : Asn1Sequence, IRfcResponse + { + /// + /// Initializes a new instance of the class. + /// The only time a client will create a BindResponse is when it is + /// decoding it from an InputStream + /// Note: If serverSaslCreds is included in the BindResponse, it does not + /// need to be decoded since it is already an OCTET STRING. + /// + /// The in renamed. + /// The length. + public RfcBindResponse(Stream stream, int len) + : base(stream, len) + { + // Decode optional referral from Asn1OctetString to Referral. + if (Size() <= 3) return; + + var obj = (Asn1Tagged) Get(3); + + if (obj.GetIdentifier().Tag != RfcLdapResult.Referral) return; + + var content = ((Asn1OctetString) obj.TaggedValue).ByteValue(); + + using (var bais = new MemoryStream(content.ToByteArray())) + Set(3, new Asn1SequenceOf(bais, content.Length)); + } + + public Asn1Enumerated GetResultCode() => (Asn1Enumerated) Get(0); + + public Asn1OctetString GetMatchedDN() => new Asn1OctetString(((Asn1OctetString) Get(1)).ByteValue()); + + public Asn1OctetString GetErrorMessage() => new Asn1OctetString(((Asn1OctetString) Get(2)).ByteValue()); + + public Asn1SequenceOf GetReferral() => Size() > 3 && Get(3) is Asn1SequenceOf ? (Asn1SequenceOf) Get(3) : null; + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.BindResponse); + } + + /// + /// Represents an LDAP Intermediate Response. + /// IntermediateResponse ::= [APPLICATION 25] SEQUENCE { + /// COMPONENTS OF LDAPResult, note: only present on incorrectly + /// encoded response from pre Falcon-sp1 server + /// responseName [10] LDAPOID OPTIONAL, + /// responseValue [11] OCTET STRING OPTIONAL }. + /// + /// + /// + internal class RfcIntermediateResponse : Asn1Sequence, IRfcResponse + { + public const int TagResponseName = 0; + public const int TagResponse = 1; + + public RfcIntermediateResponse(Stream stream, int len) + : base(stream, len) + { + var i = Size() >= 3 ? 3 : 0; + + for (; i < Size(); i++) + { + var obj = (Asn1Tagged) Get(i); + + switch (obj.GetIdentifier().Tag) + { + case TagResponseName: + Set(i, new Asn1OctetString(((Asn1OctetString) obj.TaggedValue).ByteValue())); + break; + case TagResponse: + Set(i, obj.TaggedValue); + break; + } + } + } + + public Asn1Enumerated GetResultCode() => Size() > 3 ? (Asn1Enumerated) Get(0) : null; + + public Asn1OctetString GetMatchedDN() => Size() > 3 ? new Asn1OctetString(((Asn1OctetString) Get(1)).ByteValue()) : null; + + public Asn1OctetString GetErrorMessage() => + Size() > 3 ? new Asn1OctetString(((Asn1OctetString) Get(2)).ByteValue()) : null; + + public Asn1SequenceOf GetReferral() => Size() > 3 ? (Asn1SequenceOf) Get(3) : null; + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.IntermediateResponse); + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/RfcLdapMessage.cs b/Unosquare.Swan/Networking/Ldap/RfcLdapMessage.cs new file mode 100644 index 0000000..891b4d8 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/RfcLdapMessage.cs @@ -0,0 +1,390 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System; + using System.IO; + + /// + /// Represents an Ldap Message. + ///
    +    /// LdapMessage ::= SEQUENCE {
    +    /// messageID       MessageID,
    +    /// protocolOp      CHOICE {
    +    /// bindRequest     BindRequest,
    +    /// bindResponse    BindResponse,
    +    /// unbindRequest   UnbindRequest,
    +    /// searchRequest   SearchRequest,
    +    /// searchResEntry  SearchResultEntry,
    +    /// searchResDone   SearchResultDone,
    +    /// searchResRef    SearchResultReference,
    +    /// modifyRequest   ModifyRequest,
    +    /// modifyResponse  ModifyResponse,
    +    /// addRequest      AddRequest,
    +    /// addResponse     AddResponse,
    +    /// delRequest      DelRequest,
    +    /// delResponse     DelResponse,
    +    /// modDNRequest    ModifyDNRequest,
    +    /// modDNResponse   ModifyDNResponse,
    +    /// compareRequest  CompareRequest,
    +    /// compareResponse CompareResponse,
    +    /// abandonRequest  AbandonRequest,
    +    /// extendedReq     ExtendedRequest,
    +    /// extendedResp    ExtendedResponse },
    +    /// controls       [0] Controls OPTIONAL }
    +    /// 
    + /// Note: The creation of a MessageID should be hidden within the creation of + /// an RfcLdapMessage. The MessageID needs to be in sequence, and has an + /// upper and lower limit. There is never a case when a user should be + /// able to specify the MessageID for an RfcLdapMessage. The MessageID() + /// constructor should be package protected. (So the MessageID value + /// isn't arbitrarily run up.). + ///
    + /// + internal sealed class RfcLdapMessage : Asn1Sequence + { + private readonly Asn1Object _op; + + /// + /// Initializes a new instance of the class. + /// Create an RfcLdapMessage request from input parameters. + /// + /// The op. + /// The controls. + public RfcLdapMessage(IRfcRequest op, RfcControls controls) + : base(3) + { + _op = (Asn1Object) op; + + Add(new RfcMessageID()); // MessageID has static counter + Add((Asn1Object) op); + if (controls != null) + { + Add(controls); + } + } + + /// + /// Initializes a new instance of the class. + /// Will decode an RfcLdapMessage directly from an InputStream. + /// + /// The stream. + /// The length. + /// RfcLdapMessage: Invalid tag: " + protocolOpId.Tag. + public RfcLdapMessage(Stream stream, int len) + : base(stream, len) + { + // Decode implicitly tagged protocol operation from an Asn1Tagged type + // to its appropriate application type. + var protocolOp = (Asn1Tagged) Get(1); + var protocolOpId = protocolOp.GetIdentifier(); + var content = ((Asn1OctetString) protocolOp.TaggedValue).ByteValue(); + var bais = new MemoryStream(content.ToByteArray()); + + switch ((LdapOperation) protocolOpId.Tag) + { + case LdapOperation.SearchResponse: + Set(1, new RfcSearchResultEntry(bais, content.Length)); + break; + + case LdapOperation.SearchResult: + Set(1, new RfcSearchResultDone(bais, content.Length)); + break; + + case LdapOperation.SearchResultReference: + Set(1, new RfcSearchResultReference(bais, content.Length)); + break; + + case LdapOperation.BindResponse: + Set(1, new RfcBindResponse(bais, content.Length)); + break; + + case LdapOperation.ExtendedResponse: + Set(1, new RfcExtendedResponse(bais, content.Length)); + break; + + case LdapOperation.IntermediateResponse: + Set(1, new RfcIntermediateResponse(bais, content.Length)); + break; + case LdapOperation.ModifyResponse: + Set(1, new RfcModifyResponse(bais, content.Length)); + break; + + default: + throw new InvalidOperationException($"RfcLdapMessage: Invalid tag: {protocolOpId.Tag}"); + } + + // decode optional implicitly tagged controls from Asn1Tagged type to + // to RFC 2251 types. + if (Size() <= 2) return; + + var controls = (Asn1Tagged) Get(2); + content = ((Asn1OctetString) controls.TaggedValue).ByteValue(); + + using (var ms = new MemoryStream(content.ToByteArray())) + Set(2, new RfcControls(ms, content.Length)); + } + + public int MessageId => ((Asn1Integer) Get(0)).IntValue(); + + /// Returns this RfcLdapMessage's message type. + public LdapOperation Type => (LdapOperation) Get(1).GetIdentifier().Tag; + + public Asn1Object Response => Get(1); + + public string RequestDn => ((IRfcRequest) _op).GetRequestDN(); + + public LdapMessage RequestingMessage { get; set; } + + public IRfcRequest GetRequest() => (IRfcRequest) Get(1); + + public bool IsRequest() => Get(1) is IRfcRequest; + } + + /// + /// Represents Ldap Controls. + ///
    +    /// Controls ::= SEQUENCE OF Control
    +    /// 
    + ///
    + /// + internal class RfcControls : Asn1SequenceOf + { + public const int Controls = 0; + + public RfcControls() + : base(5) + { + } + + public RfcControls(Stream stream, int len) + : base(stream, len) + { + // Convert each SEQUENCE element to a Control + for (var i = 0; i < Size(); i++) + { + var tempControl = new RfcControl((Asn1Sequence) Get(i)); + Set(i, tempControl); + } + } + + public void Add(RfcControl control) => base.Add(control); + + public void Set(int index, RfcControl control) => base.Set(index, control); + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(Controls, true); + } + + /// + /// This interface represents RfcLdapMessages that contain a response from a + /// server. + /// If the protocol operation of the RfcLdapMessage is of this type, + /// it contains at least an RfcLdapResult. + /// + internal interface IRfcResponse + { + /// + /// Gets the result code. + /// + /// Asn1Enumerated. + Asn1Enumerated GetResultCode(); + + /// + /// Gets the matched dn. + /// + /// RfcLdapDN. + Asn1OctetString GetMatchedDN(); + + /// + /// Gets the error message. + /// + /// RfcLdapString. + Asn1OctetString GetErrorMessage(); + + /// + /// Gets the referral. + /// + /// Asn1SequenceOf. + Asn1SequenceOf GetReferral(); + } + + /// + /// This interface represents Protocol Operations that are requests from a + /// client. + /// + internal interface IRfcRequest + { + /// + /// Builds a new request using the data from the this object. + /// + /// A . + string GetRequestDN(); + } + + /// + /// Represents an LdapResult. + ///
    +    /// LdapResult ::= SEQUENCE {
    +    /// resultCode      ENUMERATED {
    +    /// success                      (0),
    +    /// operationsError              (1),
    +    /// protocolError                (2),
    +    /// timeLimitExceeded            (3),
    +    /// sizeLimitExceeded            (4),
    +    /// compareFalse                 (5),
    +    /// compareTrue                  (6),
    +    /// authMethodNotSupported       (7),
    +    /// strongAuthRequired           (8),
    +    /// -- 9 reserved --
    +    /// referral                     (10),  -- new
    +    /// adminLimitExceeded           (11),  -- new
    +    /// unavailableCriticalExtension (12),  -- new
    +    /// confidentialityRequired      (13),  -- new
    +    /// saslBindInProgress           (14),  -- new
    +    /// noSuchAttribute              (16),
    +    /// undefinedAttributeType       (17),
    +    /// inappropriateMatching        (18),
    +    /// constraintViolation          (19),
    +    /// attributeOrValueExists       (20),
    +    /// invalidAttributeSyntax       (21),
    +    /// -- 22-31 unused --
    +    /// noSuchObject                 (32),
    +    /// aliasProblem                 (33),
    +    /// invalidDNSyntax              (34),
    +    /// -- 35 reserved for undefined isLeaf --
    +    /// aliasDereferencingProblem    (36),
    +    /// -- 37-47 unused --
    +    /// inappropriateAuthentication  (48),
    +    /// invalidCredentials           (49),
    +    /// insufficientAccessRights     (50),
    +    /// busy                         (51),
    +    /// unavailable                  (52),
    +    /// unwillingToPerform           (53),
    +    /// loopDetect                   (54),
    +    /// -- 55-63 unused --
    +    /// namingViolation              (64),
    +    /// objectClassViolation         (65),
    +    /// notAllowedOnNonLeaf          (66),
    +    /// notAllowedOnRDN              (67),
    +    /// entryAlreadyExists           (68),
    +    /// objectClassModsProhibited    (69),
    +    /// -- 70 reserved for CLdap --
    +    /// affectsMultipleDSAs          (71), -- new
    +    /// -- 72-79 unused --
    +    /// other                        (80) },
    +    /// -- 81-90 reserved for APIs --
    +    /// matchedDN       LdapDN,
    +    /// errorMessage    LdapString,
    +    /// referral        [3] Referral OPTIONAL }
    +    /// 
    + ///
    + /// + /// + internal class RfcLdapResult : Asn1Sequence, IRfcResponse + { + public const int Referral = 3; + + public RfcLdapResult(Stream stream, int len) + : base(stream, len) + { + // Decode optional referral from Asn1OctetString to Referral. + if (Size() <= 3) return; + + var obj = (Asn1Tagged) Get(3); + var id = obj.GetIdentifier(); + + if (id.Tag != Referral) return; + + var content = ((Asn1OctetString) obj.TaggedValue).ByteValue(); + Set(3, new Asn1SequenceOf(new MemoryStream(content.ToByteArray()), content.Length)); + } + + public Asn1Enumerated GetResultCode() => (Asn1Enumerated) Get(0); + + public Asn1OctetString GetMatchedDN() => new Asn1OctetString(((Asn1OctetString) Get(1)).ByteValue()); + + public Asn1OctetString GetErrorMessage() => new Asn1OctetString(((Asn1OctetString) Get(2)).ByteValue()); + + public Asn1SequenceOf GetReferral() => Size() > 3 ? (Asn1SequenceOf) Get(3) : null; + } + + /// + /// Represents an Ldap Search Result Done Response. + ///
    +    /// SearchResultDone ::= [APPLICATION 5] LdapResult
    +    /// 
    + ///
    + /// + internal class RfcSearchResultDone : RfcLdapResult + { + public RfcSearchResultDone(Stream stream, int len) + : base(stream, len) + { + } + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.SearchResult); + } + + /// + /// Represents an Ldap Search Result Entry. + ///
    +    /// SearchResultEntry ::= [APPLICATION 4] SEQUENCE {
    +    /// objectName      LdapDN,
    +    /// attributes      PartialAttributeList }
    +    /// 
    + ///
    + /// + internal sealed class RfcSearchResultEntry : Asn1Sequence + { + public RfcSearchResultEntry(Stream stream, int len) + : base(stream, len) + { + } + + public string ObjectName => ((Asn1OctetString) Get(0)).StringValue(); + + public Asn1Sequence Attributes => (Asn1Sequence) Get(1); + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.SearchResponse); + } + + /// + /// Represents an Ldap Message ID. + ///
    +    /// MessageID ::= INTEGER (0 .. maxInt)
    +    /// maxInt INTEGER ::= 2147483647 -- (2^^31 - 1) --
    +    /// Note: The creation of a MessageID should be hidden within the creation of
    +    /// an RfcLdapMessage. The MessageID needs to be in sequence, and has an
    +    /// upper and lower limit. There is never a case when a user should be
    +    /// able to specify the MessageID for an RfcLdapMessage. The MessageID()
    +    /// class should be package protected. (So the MessageID value isn't
    +    /// arbitrarily run up.)
    +    /// 
    + /// + internal class RfcMessageID : Asn1Integer + { + private static int _messageId; + private static readonly object SyncRoot = new object(); + + /// + /// Initializes a new instance of the class. + /// Creates a MessageID with an auto incremented Asn1Integer value. + /// Bounds: (0 .. 2,147,483,647) (2^^31 - 1 or Integer.MAX_VALUE) + /// MessageID zero is never used in this implementation. Always + /// start the messages with one. + /// + protected internal RfcMessageID() + : base(MessageId) + { + } + + private static int MessageId + { + get + { + lock (SyncRoot) + { + return _messageId < int.MaxValue ? ++_messageId : (_messageId = 1); + } + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/Ldap/RfcModifyRequest.cs b/Unosquare.Swan/Networking/Ldap/RfcModifyRequest.cs new file mode 100644 index 0000000..8f68497 --- /dev/null +++ b/Unosquare.Swan/Networking/Ldap/RfcModifyRequest.cs @@ -0,0 +1,46 @@ +namespace Unosquare.Swan.Networking.Ldap +{ + using System.IO; + + /// + /// Represents an Ldap Modify Request. + ///
    +    /// ModifyRequest ::= [APPLICATION 6] SEQUENCE {
    +    /// object          LdapDN,
    +    /// modification    SEQUENCE OF SEQUENCE {
    +    /// operation       ENUMERATED {
    +    /// add     (0),
    +    /// delete  (1),
    +    /// replace (2) },
    +    /// modification    AttributeTypeAndValues } }
    +    /// 
    + ///
    + /// + /// + internal sealed class RfcModifyRequest + : Asn1Sequence, IRfcRequest + { + public RfcModifyRequest(string obj, Asn1SequenceOf modification) + : base(2) + { + Add(obj); + Add(modification); + } + + public Asn1SequenceOf Modifications => (Asn1SequenceOf)Get(1); + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.ModifyRequest); + + public string GetRequestDN() => ((Asn1OctetString)Get(0)).StringValue(); + } + + internal class RfcModifyResponse : RfcLdapResult + { + public RfcModifyResponse(Stream stream, int len) + : base(stream, len) + { + } + + public override Asn1Identifier GetIdentifier() => new Asn1Identifier(LdapOperation.ModifyResponse); + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/SmtpClient.cs b/Unosquare.Swan/Networking/SmtpClient.cs new file mode 100644 index 0000000..592c614 --- /dev/null +++ b/Unosquare.Swan/Networking/SmtpClient.cs @@ -0,0 +1,397 @@ +namespace Unosquare.Swan.Networking +{ + using System.Threading; + using System; + using System.Linq; + using System.Net; + using System.Net.Sockets; + using System.Security; + using System.Text; + using System.Net.Security; + using System.Threading.Tasks; + using System.Collections.Generic; +#if !NETSTANDARD1_3 + using System.Net.Mail; +#else + using Exceptions; +#endif + + /// + /// Represents a basic SMTP client that is capable of submitting messages to an SMTP server. + /// + /// + /// The following code explains how to send a simple e-mail. + /// + /// using System.Net.Mail; + /// + /// class Example + /// { + /// static void Main() + /// { + /// // create a new smtp client using google's smtp server + /// var client = new SmtpClient("smtp.gmail.com", 587); + /// + /// // send an email + /// client.SendMailAsync( + /// new MailMessage("sender@test.com", "recipient@test.cm", "Subject", "Body")); + /// } + /// } + /// + /// + /// The following code demonstrates how to sent an e-mail using a SmtpSessionState: + /// + /// class Example + /// { + /// static void Main() + /// { + /// // create a new smtp client using google's smtp server + /// var client = new SmtpClient("smtp.gmail.com", 587); + /// + /// // create a new session state with a sender address + /// var session = new SmtpSessionState { SenderAddress = "sender@test.com" }; + /// + /// // add a recipient + /// session.Recipients.Add("recipient@test.cm"); + /// + /// // send + /// client.SendMailAsync(session); + /// } + /// } + /// + /// + /// The following code shows how to send an e-mail with an attachment: + /// + /// using System.Net.Mail; + /// + /// class Example + /// { + /// static void Main() + /// { + /// // create a new smtp client using google's smtp server + /// var client = new SmtpClient("smtp.gmail.com", 587); + /// + /// // create a new session state with a sender address + /// var session = new SmtpSessionState { SenderAddress = "sender@test.com" }; + /// + /// // add a recipient + /// session.Recipients.Add("recipient@test.cm"); + /// + /// // load a file as an attachment + /// var attachment = new MimePart("image", "gif") + /// { + /// Content = new + /// MimeContent(File.OpenRead("meme.gif"), ContentEncoding.Default), + /// ContentDisposition = + /// new ContentDisposition(ContentDisposition.Attachment), + /// ContentTransferEncoding = ContentEncoding.Base64, + /// FileName = Path.GetFileName("meme.gif") + /// }; + /// + /// // send + /// client.SendMailAsync(session); + /// } + /// } + /// + /// + public class SmtpClient + { + /// + /// Initializes a new instance of the class. + /// + /// The host. + /// The port. + /// host. + public SmtpClient(string host, int port) + { + Host = host ?? throw new ArgumentNullException(nameof(host)); + Port = port; + ClientHostname = Network.HostName; + } + + /// + /// Gets or sets the credentials. No credentials will be used if set to null. + /// + /// + /// The credentials. + /// + public NetworkCredential Credentials { get; set; } + + /// + /// Gets the host. + /// + /// + /// The host. + /// + public string Host { get; } + + /// + /// Gets the port. + /// + /// + /// The port. + /// + public int Port { get; } + + /// + /// Gets or sets a value indicating whether the SSL is enabled. + /// If set to false, communication between client and server will not be secured. + /// + /// + /// true if [enable SSL]; otherwise, false. + /// + public bool EnableSsl { get; set; } + + /// + /// Gets or sets the name of the client that gets announced to the server. + /// + /// + /// The client hostname. + /// + public string ClientHostname { get; set; } + +#if !NETSTANDARD1_3 + /// + /// Sends an email message asynchronously. + /// + /// The message. + /// The session identifier. + /// The cancellation token. + /// The callback. + /// + /// A task that represents the asynchronous of send email operation. + /// + /// message. + public Task SendMailAsync( + MailMessage message, + string sessionId = null, + CancellationToken ct = default, + RemoteCertificateValidationCallback callback = null) + { + if (message == null) + throw new ArgumentNullException(nameof(message)); + + var state = new SmtpSessionState + { + AuthMode = Credentials == null ? string.Empty : SmtpDefinitions.SmtpAuthMethods.Login, + ClientHostname = ClientHostname, + IsChannelSecure = EnableSsl, + SenderAddress = message.From.Address, + }; + + if (Credentials != null) + { + state.Username = Credentials.UserName; + state.Password = Credentials.Password; + } + + foreach (var recipient in message.To) + { + state.Recipients.Add(recipient.Address); + } + + state.DataBuffer.AddRange(message.ToMimeMessage().ToArray()); + + return SendMailAsync(state, sessionId, ct, callback); + } +#endif + + /// + /// Sends an email message using a session state object. + /// Credentials, Enable SSL and Client Hostname are NOT taken from the state object but + /// rather from the properties of this class. + /// + /// The state. + /// The session identifier. + /// The cancellation token. + /// The callback. + /// + /// A task that represents the asynchronous of send email operation. + /// + /// sessionState. + public Task SendMailAsync( + SmtpSessionState sessionState, + string sessionId = null, + CancellationToken ct = default, + RemoteCertificateValidationCallback callback = null) + { + if (sessionState == null) + throw new ArgumentNullException(nameof(sessionState)); + + return SendMailAsync(new[] { sessionState }, sessionId, ct, callback); + } + + /// + /// Sends an array of email messages using a session state object. + /// Credentials, Enable SSL and Client Hostname are NOT taken from the state object but + /// rather from the properties of this class. + /// + /// The session states. + /// The session identifier. + /// The cancellation token. + /// The callback. + /// + /// A task that represents the asynchronous of send email operation. + /// + /// sessionStates. + /// Could not upgrade the channel to SSL. + /// Defines an SMTP Exceptions class. + public async Task SendMailAsync( + IEnumerable sessionStates, + string sessionId = null, + CancellationToken ct = default, + RemoteCertificateValidationCallback callback = null) + { + if (sessionStates == null) + throw new ArgumentNullException(nameof(sessionStates)); + + using (var tcpClient = new TcpClient()) + { + await tcpClient.ConnectAsync(Host, Port).ConfigureAwait(false); + + using (var connection = new Connection(tcpClient, Encoding.UTF8, "\r\n", true, 1000)) + { + var sender = new SmtpSender(sessionId); + + try + { + // Read the greeting message + sender.ReplyText = await connection.ReadLineAsync(ct).ConfigureAwait(false); + + // EHLO 1 + await SendEhlo(ct, sender, connection).ConfigureAwait(false); + + // STARTTLS + if (EnableSsl) + { + sender.RequestText = $"{SmtpCommandNames.STARTTLS}"; + + await connection.WriteLineAsync(sender.RequestText, ct).ConfigureAwait(false); + sender.ReplyText = await connection.ReadLineAsync(ct).ConfigureAwait(false); + sender.ValidateReply(); + + if (await connection.UpgradeToSecureAsClientAsync(callback: callback).ConfigureAwait(false) == false) + throw new SecurityException("Could not upgrade the channel to SSL."); + } + + // EHLO 2 + await SendEhlo(ct, sender, connection).ConfigureAwait(false); + + // AUTH + if (Credentials != null) + { + var auth = new ConnectionAuth(connection, sender, Credentials); + await auth.AuthenticateAsync(ct).ConfigureAwait(false); + } + + foreach (var sessionState in sessionStates) + { + { + // MAIL FROM + sender.RequestText = $"{SmtpCommandNames.MAIL} FROM:<{sessionState.SenderAddress}>"; + + await connection.WriteLineAsync(sender.RequestText, ct).ConfigureAwait(false); + sender.ReplyText = await connection.ReadLineAsync(ct).ConfigureAwait(false); + sender.ValidateReply(); + } + + // RCPT TO + foreach (var recipient in sessionState.Recipients) + { + sender.RequestText = $"{SmtpCommandNames.RCPT} TO:<{recipient}>"; + + await connection.WriteLineAsync(sender.RequestText, ct).ConfigureAwait(false); + sender.ReplyText = await connection.ReadLineAsync(ct).ConfigureAwait(false); + sender.ValidateReply(); + } + + { + // DATA + sender.RequestText = $"{SmtpCommandNames.DATA}"; + + await connection.WriteLineAsync(sender.RequestText, ct).ConfigureAwait(false); + sender.ReplyText = await connection.ReadLineAsync(ct).ConfigureAwait(false); + sender.ValidateReply(); + } + + { + // CONTENT + var dataTerminator = sessionState.DataBuffer + .Skip(sessionState.DataBuffer.Count - 5) + .ToText(); + + sender.RequestText = $"Buffer ({sessionState.DataBuffer.Count} bytes)"; + + await connection.WriteDataAsync(sessionState.DataBuffer.ToArray(), true, ct).ConfigureAwait(false); + if (dataTerminator.EndsWith(SmtpDefinitions.SmtpDataCommandTerminator) == false) + await connection.WriteTextAsync(SmtpDefinitions.SmtpDataCommandTerminator, ct).ConfigureAwait(false); + + sender.ReplyText = await connection.ReadLineAsync(ct).ConfigureAwait(false); + sender.ValidateReply(); + } + } + + { + // QUIT + sender.RequestText = $"{SmtpCommandNames.QUIT}"; + + await connection.WriteLineAsync(sender.RequestText, ct).ConfigureAwait(false); + sender.ReplyText = await connection.ReadLineAsync(ct).ConfigureAwait(false); + sender.ValidateReply(); + } + } + catch (Exception ex) + { + var errorMessage = + $"Could not send email. {ex.Message}\r\n Last Request: {sender.RequestText}\r\n Last Reply: {sender.ReplyText}"; + errorMessage.Error(typeof(SmtpClient).FullName, sessionId); + + throw new SmtpException(errorMessage); + } + } + } + } + + private async Task SendEhlo(CancellationToken ct, SmtpSender sender, Connection connection) + { + sender.RequestText = $"{SmtpCommandNames.EHLO} {ClientHostname}"; + + await connection.WriteLineAsync(sender.RequestText, ct).ConfigureAwait(false); + + do + { + sender.ReplyText = await connection.ReadLineAsync(ct).ConfigureAwait(false); + } while (!sender.IsReplyOk); + + sender.ValidateReply(); + } + + private class ConnectionAuth + { + private readonly SmtpSender _sender; + private readonly Connection _connection; + private readonly NetworkCredential _credentials; + + public ConnectionAuth(Connection connection, SmtpSender sender, NetworkCredential credentials) + { + _connection = connection; + _sender = sender; + _credentials = credentials; + } + + public async Task AuthenticateAsync(CancellationToken ct) + { + _sender.RequestText = + $"{SmtpCommandNames.AUTH} {SmtpDefinitions.SmtpAuthMethods.Login} {Convert.ToBase64String(Encoding.UTF8.GetBytes(_credentials.UserName))}"; + + await _connection.WriteLineAsync(_sender.RequestText, ct).ConfigureAwait(false); + _sender.ReplyText = await _connection.ReadLineAsync(ct).ConfigureAwait(false); + _sender.ValidateReply(); + _sender.RequestText = Convert.ToBase64String(Encoding.UTF8.GetBytes(_credentials.Password)); + + await _connection.WriteLineAsync(_sender.RequestText, ct).ConfigureAwait(false); + _sender.ReplyText = await _connection.ReadLineAsync(ct).ConfigureAwait(false); + _sender.ValidateReply(); + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/SmtpDefinitions.cs b/Unosquare.Swan/Networking/SmtpDefinitions.cs new file mode 100644 index 0000000..dff0951 --- /dev/null +++ b/Unosquare.Swan/Networking/SmtpDefinitions.cs @@ -0,0 +1,29 @@ +namespace Unosquare.Swan.Networking +{ + /// + /// Contains useful constants and definitions. + /// + public static class SmtpDefinitions + { + /// + /// The string sequence that delimits the end of the DATA command. + /// + public const string SmtpDataCommandTerminator = "\r\n.\r\n"; + + /// + /// Lists the AUTH methods supported by default. + /// + public static class SmtpAuthMethods + { + /// + /// The plain method. + /// + public const string Plain = "PLAIN"; + + /// + /// The login method. + /// + public const string Login = "LOGIN"; + } + } +} diff --git a/Unosquare.Swan/Networking/SmtpSender.cs b/Unosquare.Swan/Networking/SmtpSender.cs new file mode 100644 index 0000000..0273081 --- /dev/null +++ b/Unosquare.Swan/Networking/SmtpSender.cs @@ -0,0 +1,60 @@ +namespace Unosquare.Swan.Networking +{ +#if !NETSTANDARD1_3 + using System.Net.Mail; +#else + using Exceptions; +#endif + + /// + /// Use this class to store the sender session data. + /// + internal class SmtpSender + { + private readonly string _sessionId; + private string _requestText; + + public SmtpSender(string sessionId) + { + _sessionId = sessionId; + } + + public string RequestText + { + get => _requestText; + set + { + _requestText = value; + $" TX {_requestText}".Debug(typeof(SmtpClient), _sessionId); + } + } + + public string ReplyText { get; set; } + + public bool IsReplyOk => ReplyText.StartsWith("250 "); + + public void ValidateReply() + { + if (ReplyText == null) + throw new SmtpException("There was no response from the server"); + + try + { + var response = SmtpServerReply.Parse(ReplyText); + $" RX {ReplyText} - {response.IsPositive}".Debug(typeof(SmtpClient), _sessionId); + + if (response.IsPositive) return; + + var responseContent = string.Empty; + if (response.Content.Count > 0) + responseContent = string.Join(";", response.Content.ToArray()); + + throw new SmtpException((SmtpStatusCode)response.ReplyCode, responseContent); + } + catch + { + throw new SmtpException($"Could not parse server response: {ReplyText}"); + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/SmtpServerReply.cs b/Unosquare.Swan/Networking/SmtpServerReply.cs new file mode 100644 index 0000000..d62b3b5 --- /dev/null +++ b/Unosquare.Swan/Networking/SmtpServerReply.cs @@ -0,0 +1,243 @@ +namespace Unosquare.Swan.Networking +{ + using System; + using System.Collections.Generic; + using System.Globalization; + using System.Linq; + using System.Text; + + /// + /// Represents an SMTP server response object. + /// + public class SmtpServerReply + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// The response code. + /// The status code. + /// The content. + public SmtpServerReply(int responseCode, string statusCode, params string[] content) + { + Content = new List(); + ReplyCode = responseCode; + EnhancedStatusCode = statusCode; + Content.AddRange(content); + IsValid = responseCode >= 200 && responseCode < 600; + ReplyCodeSeverity = SmtpReplyCodeSeverities.Unknown; + ReplyCodeCategory = SmtpReplyCodeCategories.Unknown; + + if (!IsValid) return; + if (responseCode >= 200) ReplyCodeSeverity = SmtpReplyCodeSeverities.PositiveCompletion; + if (responseCode >= 300) ReplyCodeSeverity = SmtpReplyCodeSeverities.PositiveIntermediate; + if (responseCode >= 400) ReplyCodeSeverity = SmtpReplyCodeSeverities.TransientNegative; + if (responseCode >= 500) ReplyCodeSeverity = SmtpReplyCodeSeverities.PermanentNegative; + if (responseCode >= 600) ReplyCodeSeverity = SmtpReplyCodeSeverities.Unknown; + + if (int.TryParse(responseCode.ToString(CultureInfo.InvariantCulture).Substring(1, 1), out var middleDigit)) + { + if (middleDigit >= 0 && middleDigit <= 5) + ReplyCodeCategory = (SmtpReplyCodeCategories) middleDigit; + } + } + + /// + /// Initializes a new instance of the class. + /// + public SmtpServerReply() + : this(0, string.Empty, string.Empty) + { + // placeholder + } + + /// + /// Initializes a new instance of the class. + /// + /// The response code. + /// The status code. + /// The content. + public SmtpServerReply(int responseCode, string statusCode, string content) + : this(responseCode, statusCode, new[] {content}) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// The response code. + /// The content. + public SmtpServerReply(int responseCode, string content) + : this(responseCode, string.Empty, content) + { + } + + #endregion + + #region Pre-built responses (https://tools.ietf.org/html/rfc5321#section-4.2.2) + + /// + /// Gets the command unrecognized reply. + /// + public static SmtpServerReply CommandUnrecognized => + new SmtpServerReply(500, "Syntax error, command unrecognized"); + + /// + /// Gets the syntax error arguments reply. + /// + public static SmtpServerReply SyntaxErrorArguments => + new SmtpServerReply(501, "Syntax error in parameters or arguments"); + + /// + /// Gets the command not implemented reply. + /// + public static SmtpServerReply CommandNotImplemented => new SmtpServerReply(502, "Command not implemented"); + + /// + /// Gets the bad sequence of commands reply. + /// + public static SmtpServerReply BadSequenceOfCommands => new SmtpServerReply(503, "Bad sequence of commands"); + + /// + /// Gets the protocol violation reply. + /// = + public static SmtpServerReply ProtocolViolation => + new SmtpServerReply(451, "Requested action aborted: error in processing"); + + /// + /// Gets the system status bye reply. + /// + public static SmtpServerReply SystemStatusBye => + new SmtpServerReply(221, "Service closing transmission channel"); + + /// + /// Gets the system status help reply. + /// = + public static SmtpServerReply SystemStatusHelp => new SmtpServerReply(221, "Refer to RFC 5321"); + + /// + /// Gets the bad syntax command empty reply. + /// + public static SmtpServerReply BadSyntaxCommandEmpty => new SmtpServerReply(400, "Error: bad syntax"); + + /// + /// Gets the OK reply. + /// + public static SmtpServerReply Ok => new SmtpServerReply(250, "OK"); + + /// + /// Gets the authorization required reply. + /// + public static SmtpServerReply AuthorizationRequired => new SmtpServerReply(530, "Authorization Required"); + + #endregion + + #region Properties + + /// + /// Gets the response severity. + /// + public SmtpReplyCodeSeverities ReplyCodeSeverity { get; } + + /// + /// Gets the response category. + /// + public SmtpReplyCodeCategories ReplyCodeCategory { get; } + + /// + /// Gets the numeric response code. + /// + public int ReplyCode { get; } + + /// + /// Gets the enhanced status code. + /// + public string EnhancedStatusCode { get; } + + /// + /// Gets the content. + /// + public List Content { get; } + + /// + /// Returns true if the response code is between 200 and 599. + /// + public bool IsValid { get; } + + /// + /// Gets a value indicating whether this instance is positive. + /// + public bool IsPositive => ReplyCode >= 200 && ReplyCode <= 399; + + #endregion + + #region Methods + + /// + /// Parses the specified text into a Server Reply for thorough analysis. + /// + /// The text. + /// A new instance of SMTP server response object. + public static SmtpServerReply Parse(string text) + { + var lines = text.Split(new[] {"\r\n"}, StringSplitOptions.RemoveEmptyEntries); + if (lines.Length == 0) return new SmtpServerReply(); + + var lastLineParts = lines.Last().Split(new[] {" "}, StringSplitOptions.RemoveEmptyEntries); + var enhancedStatusCode = string.Empty; + int.TryParse(lastLineParts[0], out var responseCode); + if (lastLineParts.Length > 1) + { + if (lastLineParts[1].Split('.').Length == 3) + enhancedStatusCode = lastLineParts[1]; + } + + var content = new List(); + + for (var i = 0; i < lines.Length; i++) + { + var splitChar = i == lines.Length - 1 ? " " : "-"; + + var lineParts = lines[i].Split(new[] {splitChar}, 2, StringSplitOptions.None); + var lineContent = lineParts.Last(); + if (string.IsNullOrWhiteSpace(enhancedStatusCode) == false) + lineContent = lineContent.Replace(enhancedStatusCode, string.Empty).Trim(); + + content.Add(lineContent); + } + + return new SmtpServerReply(responseCode, enhancedStatusCode, content.ToArray()); + } + + /// + /// Returns a that represents this instance. + /// + /// + /// A that represents this instance. + /// + public override string ToString() + { + var responseCodeText = ReplyCode.ToString(CultureInfo.InvariantCulture); + var statusCodeText = string.IsNullOrWhiteSpace(EnhancedStatusCode) + ? string.Empty + : $" {EnhancedStatusCode.Trim()}"; + if (Content.Count == 0) return $"{responseCodeText}{statusCodeText}"; + + var builder = new StringBuilder(); + + for (var i = 0; i < Content.Count; i++) + { + var isLastLine = i == Content.Count - 1; + + builder.Append(isLastLine + ? $"{responseCodeText}{statusCodeText} {Content[i]}" + : $"{responseCodeText}-{Content[i]}\r\n"); + } + + return builder.ToString(); + } + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/SmtpSessionState.cs b/Unosquare.Swan/Networking/SmtpSessionState.cs new file mode 100644 index 0000000..2a506c9 --- /dev/null +++ b/Unosquare.Swan/Networking/SmtpSessionState.cs @@ -0,0 +1,162 @@ +namespace Unosquare.Swan.Networking +{ + using System.Collections.Generic; + + /// + /// Represents the state of an SMTP session associated with a client. + /// + public class SmtpSessionState + { + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + public SmtpSessionState() + { + DataBuffer = new List(); + Reset(true); + ResetAuthentication(); + } + + #endregion + + #region Properties + + /// + /// Gets the contents of the data buffer. + /// + public List DataBuffer { get; protected set; } + + /// + /// Gets or sets a value indicating whether this instance has initiated. + /// + public bool HasInitiated { get; set; } + + /// + /// Gets or sets a value indicating whether the current session supports extensions. + /// + public bool SupportsExtensions { get; set; } + + /// + /// Gets or sets the client hostname. + /// + public string ClientHostname { get; set; } + + /// + /// Gets or sets a value indicating whether the session is currently receiving DATA. + /// + public bool IsInDataMode { get; set; } + + /// + /// Gets or sets the sender address. + /// + public string SenderAddress { get; set; } + + /// + /// Gets the recipients. + /// + public List Recipients { get; } = new List(); + + /// + /// Gets or sets the extended data supporting any additional field for storage by a responder implementation. + /// + public object ExtendedData { get; set; } + + #endregion + + #region AUTH State + + /// + /// Gets or sets a value indicating whether this instance is in authentication mode. + /// + public bool IsInAuthMode { get; set; } + + /// + /// Gets or sets the username. + /// + public string Username { get; set; } + + /// + /// Gets or sets the password. + /// + public string Password { get; set; } + + /// + /// Gets a value indicating whether this instance has provided username. + /// + public bool HasProvidedUsername => string.IsNullOrWhiteSpace(Username) == false; + + /// + /// Gets or sets a value indicating whether this instance is authenticated. + /// + public bool IsAuthenticated { get; set; } + + /// + /// Gets or sets the authentication mode. + /// + public string AuthMode { get; set; } + + /// + /// Gets or sets a value indicating whether this instance is channel secure. + /// + public bool IsChannelSecure { get; set; } + + /// + /// Resets the authentication state. + /// + public void ResetAuthentication() + { + Username = string.Empty; + Password = string.Empty; + AuthMode = string.Empty; + IsInAuthMode = false; + IsAuthenticated = false; + } + + #endregion + + #region Methods + + /// + /// Resets the data mode to false, clears the recipients, the sender address and the data buffer. + /// + public void ResetEmail() + { + IsInDataMode = false; + Recipients.Clear(); + SenderAddress = string.Empty; + DataBuffer.Clear(); + } + + /// + /// Resets the state table entirely. + /// + /// if set to true [clear extension data]. + public void Reset(bool clearExtensionData) + { + HasInitiated = false; + SupportsExtensions = false; + ClientHostname = string.Empty; + ResetEmail(); + + if (clearExtensionData) + ExtendedData = null; + } + + /// + /// Creates a new object that is a copy of the current instance. + /// + /// A clone. + public virtual SmtpSessionState Clone() + { + var clonedState = this.CopyPropertiesToNew(new[] {nameof(DataBuffer)}); + clonedState.DataBuffer.AddRange(DataBuffer); + clonedState.Recipients.AddRange(Recipients); + + return clonedState; + } + + #endregion + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Networking/SnmpClient.cs b/Unosquare.Swan/Networking/SnmpClient.cs new file mode 100644 index 0000000..51d6173 --- /dev/null +++ b/Unosquare.Swan/Networking/SnmpClient.cs @@ -0,0 +1,280 @@ +namespace Unosquare.Swan.Networking +{ + using System; + using System.Collections.Generic; + using System.Net; + using System.Net.Sockets; + using System.Text; + using System.Threading.Tasks; + + /// + /// Represents a little SNMP client based on http://www.java2s.com/Code/CSharp/Network/SimpleSNMP.htm. + /// + public static class SnmpClient + { + private static readonly byte[] DiscoverMessage = + { + 48, 41, 2, 1, 1, 4, 6, 112, 117, 98, 108, 105, 99, 160, 28, 2, 4, 111, 81, 45, 144, 2, 1, 0, 2, 1, 0, 48, + 14, 48, 12, 6, 8, 43, 6, 1, 2, 1, 1, 1, 0, 5, 0, + }; + + /// + /// Discovers the specified SNMP time out. + /// + /// The SNMP time out. + /// An array of network endpoint as an IP address and a port number. + public static IPEndPoint[] Discover(int snmpTimeOut = 6000) + { + var endpoints = new List(); + + Task[] tasks = + { + Task.Run(async () => + { + using (var udp = new UdpClient(IPAddress.Broadcast.AddressFamily)) + { + udp.EnableBroadcast = true; + await udp.SendAsync( + DiscoverMessage, + DiscoverMessage.Length, + new IPEndPoint(IPAddress.Broadcast, 161)); + + while (true) + { + try + { + var buffer = new byte[udp.Client.ReceiveBufferSize]; + EndPoint remote = new IPEndPoint(IPAddress.Any, 0); + udp.Client.ReceiveFrom(buffer, ref remote); + endpoints.Add(remote as IPEndPoint); + } + catch + { + break; + } + } +#if NET452 + udp.Close(); +#endif + } + }), + Task.Delay(snmpTimeOut), + }; + + Task.WaitAny(tasks); + + return endpoints.ToArray(); + } + + /// + /// Gets the name of the public. + /// + /// The host. + /// + /// A string that contains the results of decoding the specified sequence + /// of bytes ref=GetString". + /// + public static string GetPublicName(IPEndPoint host) => GetString(host, "1.3.6.1.2.1.1.5.0"); + + /// + /// Gets the up-time. + /// + /// The host. + /// The mibString. + /// + /// A time interval that represents a specified number of seconds, + /// where the specification is accurate to the nearest millisecond. + /// + public static TimeSpan GetUptime(IPEndPoint host, string mibString = "1.3.6.1.2.1.1.3.0") + { + var response = Get(host, mibString); + if (response[0] == 0xff) return TimeSpan.Zero; + + // If response, get the community name and MIB lengths + var commlength = Convert.ToInt16(response[6]); + var miblength = Convert.ToInt16(response[23 + commlength]); + + // Extract the MIB data from the SNMP response + var datalength = Convert.ToInt16(response[25 + commlength + miblength]); + var datastart = 26 + commlength + miblength; + + var uptime = 0; + + while (datalength > 0) + { + uptime = (uptime << 8) + response[datastart++]; + datalength--; + } + + return TimeSpan.FromSeconds(uptime); + } + + /// + /// Gets the string. + /// + /// The host. + /// The mibString. + /// A that contains the results of decoding the specified sequence of bytes. + public static string GetString(IPEndPoint host, string mibString) + { + var response = Get(host, mibString); + if (response[0] == 0xff) return string.Empty; + + // If response, get the community name and MIB lengths + var commlength = Convert.ToInt16(response[6]); + var miblength = Convert.ToInt16(response[23 + commlength]); + + // Extract the MIB data from the SNMP response + var datalength = Convert.ToInt16(response[25 + commlength + miblength]); + var datastart = 26 + commlength + miblength; + + return Encoding.ASCII.GetString(response, datastart, datalength); + } + + /// + /// Gets the specified host. + /// + /// The host. + /// The mibString. + /// A byte array containing the results of encoding the specified set of characters. + public static byte[] Get(IPEndPoint host, string mibString) => Get("get", host, "public", mibString); + + /// + /// Gets the specified request. + /// + /// The request. + /// The host. + /// The community. + /// The mibString. + /// A byte array containing the results of encoding the specified set of characters. + public static byte[] Get(string request, IPEndPoint host, string community, string mibString) + { + var packet = new byte[1024]; + var mib = new byte[1024]; + var comlen = community.Length; + var mibvals = mibString.Split('.'); + var miblen = mibvals.Length; + var cnt = 0; + var orgmiblen = miblen; + var pos = 0; + + // Convert the string MIB into a byte array of integer values + // Unfortunately, values over 128 require multiple bytes + // which also increases the MIB length + for (var i = 0; i < orgmiblen; i++) + { + int temp = Convert.ToInt16(mibvals[i]); + if (temp > 127) + { + mib[cnt] = Convert.ToByte(128 + (temp / 128)); + mib[cnt + 1] = Convert.ToByte(temp - ((temp / 128) * 128)); + cnt += 2; + miblen++; + } + else + { + mib[cnt] = Convert.ToByte(temp); + cnt++; + } + } + + var snmplen = 29 + comlen + miblen - 1; + + // The SNMP sequence start + packet[pos++] = 0x30; // Sequence start + packet[pos++] = Convert.ToByte(snmplen - 2); // sequence size + + // SNMP version + packet[pos++] = 0x02; // Integer type + packet[pos++] = 0x01; // length + packet[pos++] = 0x00; // SNMP version 1 + + // Community name + packet[pos++] = 0x04; // String type + packet[pos++] = Convert.ToByte(comlen); // length + + // Convert community name to byte array + var data = Encoding.ASCII.GetBytes(community); + + foreach (var t in data) + { + packet[pos++] = t; + } + + // Add GetRequest or GetNextRequest value + if (request == "get") + packet[pos++] = 0xA0; + else + packet[pos++] = 0xA1; + + packet[pos++] = Convert.ToByte(20 + miblen - 1); // Size of total MIB + + // Request ID + packet[pos++] = 0x02; // Integer type + packet[pos++] = 0x04; // length + packet[pos++] = 0x00; // SNMP request ID + packet[pos++] = 0x00; + packet[pos++] = 0x00; + packet[pos++] = 0x01; + + // Error status + packet[pos++] = 0x02; // Integer type + packet[pos++] = 0x01; // length + packet[pos++] = 0x00; // SNMP error status + + // Error index + packet[pos++] = 0x02; // Integer type + packet[pos++] = 0x01; // length + packet[pos++] = 0x00; // SNMP error index + + // Start of variable bindings + packet[pos++] = 0x30; // Start of variable bindings sequence + + packet[pos++] = Convert.ToByte(6 + miblen - 1); // Size of variable binding + + packet[pos++] = 0x30; // Start of first variable bindings sequence + packet[pos++] = Convert.ToByte(6 + miblen - 1 - 2); // size + packet[pos++] = 0x06; // Object type + packet[pos++] = Convert.ToByte(miblen - 1); // length + + // Start of MIB + packet[pos++] = 0x2b; + + // Place MIB array in packet + for (var i = 2; i < miblen; i++) + packet[pos++] = Convert.ToByte(mib[i]); + + packet[pos++] = 0x05; // Null object value + packet[pos] = 0x00; // Null + + // Send packet to destination + SendPacket(host, packet, snmplen); + + return packet; + } + + private static void SendPacket(IPEndPoint host, byte[] packet, int length) + { + var sock = new Socket( + AddressFamily.InterNetwork, + SocketType.Dgram, + ProtocolType.Udp); + sock.SetSocketOption( + SocketOptionLevel.Socket, + SocketOptionName.ReceiveTimeout, + 5000); + var ep = (EndPoint) host; + sock.SendTo(packet, length, SocketFlags.None, host); + + // Receive response from packet + try + { + sock.ReceiveFrom(packet, ref ep); + } + catch (SocketException) + { + packet[0] = 0xff; + } + } + } +} \ No newline at end of file diff --git a/Unosquare.Swan/Properties/AssemblyInfo.cs b/Unosquare.Swan/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..48360ce --- /dev/null +++ b/Unosquare.Swan/Properties/AssemblyInfo.cs @@ -0,0 +1,36 @@ +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// Allgemeine Informationen über eine Assembly werden über die folgenden +// Attribute gesteuert. Ändern Sie diese Attributwerte, um die Informationen zu ändern, +// die einer Assembly zugeordnet sind. +[assembly: AssemblyTitle("Unosquare SWAN")] +[assembly: AssemblyDescription("Repeating code and reinventing the wheel is generally considered bad practice. At Unosquare we are committed to beautiful code and great software. Swan is a collection of classes and extension methods that we and other good developers have developed and evolved over the years. We found ourselves copying and pasting the same code for every project every time we started it. We decide to kill that cycle once and for all. This is the result of that idea. Our philosophy is that SWAN should have no external dependencies, it should be cross-platform, and it should be useful.")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("Unosquare")] +[assembly: AssemblyProduct("Unosquare.Swan")] +[assembly: AssemblyCopyright("Copyright (c) 2016-2019 - Unosquare")] +[assembly: AssemblyTrademark("https://github.com/unosquare/swan")] +[assembly: AssemblyCulture("")] + +// Durch Festlegen von ComVisible auf FALSE werden die Typen in dieser Assembly +// für COM-Komponenten unsichtbar. Wenn Sie auf einen Typ in dieser Assembly von +// COM aus zugreifen müssen, sollten Sie das ComVisible-Attribut für diesen Typ auf "True" festlegen. +[assembly: ComVisible(false)] + +// Die folgende GUID bestimmt die ID der Typbibliothek, wenn dieses Projekt für COM verfügbar gemacht wird +[assembly: Guid("2ea5e3e4-f8c8-4742-8c78-4b070afcfb73")] + +// Versionsinformationen für eine Assembly bestehen aus den folgenden vier Werten: +// +// Hauptversion +// Nebenversion +// Buildnummer +// Revision +// +// Sie können alle Werte angeben oder Standardwerte für die Build- und Revisionsnummern verwenden, +// indem Sie "*" wie unten gezeigt eingeben: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0")] +[assembly: AssemblyFileVersion("1.0.0")] diff --git a/Unosquare.Swan/Unosquare.Swan.csproj b/Unosquare.Swan/Unosquare.Swan.csproj new file mode 100644 index 0000000..93ff031 --- /dev/null +++ b/Unosquare.Swan/Unosquare.Swan.csproj @@ -0,0 +1,130 @@ + + + + + Debug + AnyCPU + {2EA5E3E4-F8C8-4742-8C78-4B070AFCFB73} + Library + Properties + Unosquare.Swan + Unosquare.Swan + v4.7.1 + 512 + + + true + full + false + bin\Debug\ + TRACE;DEBUG;NET452 + prompt + 4 + 7.1 + + + pdbonly + true + bin\Release\ + TRACE;NET452 + prompt + 4 + 7.1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + {ab015683-62e5-47f1-861f-6d037f9c6433} + Unosquare.Swan.Lite + + + + \ No newline at end of file