### Exclude Setup Time from Measurement Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Demonstrates how to exclude setup time, such as data preparation, from the performance measurement. The timer is started only after the data is ready. ```csharp // Create data outside timer var data = Enumerable.Range(0, 100000).ToList(); var timer = HiPerfTimer.StartNew(); var sorted = data.OrderBy(x => x).ToList(); timer.Stop(); ``` -------------------------------- ### Install Masuit.Tools.Abstraction for .NET Standard Source: https://github.com/ldqk/masuit.tools/wiki/Home Install the Masuit.Tools.Abstraction package for .NET Standard 2.1 or for projects that only require basic functionalities. This is the recommended package for general use. ```shell PM> Install-Package Masuit.Tools.Abstraction ``` -------------------------------- ### Install Masuit.Tools via NuGet Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/README.md Provides NuGet package manager commands for installing Masuit.Tools.Abstractions, Masuit.Tools.Core, Masuit.Tools.AspNetCore, Masuit.Tools.Excel, and Masuit.Tools.Net. ```powershell # For .NET Standard/Core (recommended) Install-Package Masuit.Tools.Abstractions # For .NET Core (full features) Install-Package Masuit.Tools.Core # For ASP.NET Core Install-Package Masuit.Tools.AspNetCore # For Excel operations Install-Package Masuit.Tools.Excel # For .NET Framework Install-Package Masuit.Tools.Net ``` -------------------------------- ### Extension Method Syntax Examples Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/README.md Shows examples of using extension methods for string manipulation, email matching, HTML tag removal, number base conversion, collection deduplication, and pagination. ```csharp // String extensions "test@example.com".MatchEmail(); "..."..RemoveHtmlTag(); 255.ToBase(16); // Collection extensions users.DistinctBy(u => u.Email); items.ToPagedList(1, 10); ``` -------------------------------- ### Install Masuit.Tools.Core for .NET Core Source: https://github.com/ldqk/masuit.tools/wiki/Home Install the Masuit.Tools.Core package for .NET Core 2.1 and above. This is the recommended package for .NET Core projects. ```shell PM> Install-Package Masuit.Tools.Core ``` -------------------------------- ### Example: Binary Conversion Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/number-formater.md Shows how to create a NumberFormater for base-2 (binary) and convert a decimal number to its binary string representation. ```csharp var nfBin = new NumberFormater(2); string binary = nfBin.ToString(255); // "11111111" ``` -------------------------------- ### Install Masuit.Tools.DigitalWatermarker via NuGet Source: https://github.com/ldqk/masuit.tools/blob/master/Masuit.Tools.DigtalWatermarker/README.md Install the Masuit.Tools.DigitalWatermarker package and its OpenCV runtime dependency using the NuGet Package Manager. ```bash Install-Package Masuit.Tools.DigitalWatermarker Install-Package OpenCvSharp4.runtime.win ``` -------------------------------- ### Example: Decimal Formatting Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/number-formater.md Demonstrates creating a default NumberFormater for decimal (base-10) and converting a number to its string representation. ```csharp var nf = new NumberFormater(); string result = nf.ToString(12345); // "12345" ``` -------------------------------- ### Install Masuit.Tools.Net for .NET Framework Source: https://github.com/ldqk/masuit.tools/wiki/Home Install the Masuit.Tools.Net package for .NET Framework versions 4.6.1 and above. This package provides a broad set of functionalities. ```shell PM> Install-Package Masuit.Tools.Net ``` -------------------------------- ### Create and Start New HiPerfTimer Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Creates and starts a new HiPerfTimer instance in a single call. This is equivalent to creating a new instance and then calling Start(). ```csharp var timer = HiPerfTimer.StartNew(); for (int i = 0; i < 100000; i++) { Math.Sqrt(i); } timer.Stop(); Console.WriteLine($"Duration: {timer.Duration}s"); ``` -------------------------------- ### RsaKey Usage Example Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/types.md Demonstrates generating RSA keys using RsaCrypt and highlights the importance of securely managing the private key. ```csharp RsaKey keys = RsaCrypt.GenerateRsaKeys(); // Share keys.PublicKey with clients // Keep keys.PrivateKey secure ``` -------------------------------- ### EmailAddress Usage Example Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/types.md Demonstrates how to instantiate and populate an EmailAddress object for use in email sending operations. ```csharp var email = new EmailAddress { Address = "user@example.com", DisplayName = "John Doe" }; ``` -------------------------------- ### Install Masuit.Tools.Net45 for .NET Framework 4.5 Source: https://github.com/ldqk/masuit.tools/wiki/Home Install the Masuit.Tools.Net45 package for .NET Framework 4.5. Note that this version has reduced functionality compared to other packages, omitting features like Redis, HTML, file compression, and ASP.NET extensions. ```shell PM> Install-Package Masuit.Tools.Net45 ``` -------------------------------- ### Property-Based Configuration Example Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/README.md Shows how to configure an Email object using property assignments for SMTP server, subject, and body. ```csharp var email = new Email { SmtpServer = "smtp.example.com", Subject = "Test", Body = "Content" }; ``` -------------------------------- ### Fluent API Chaining Example Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/README.md Illustrates the use of fluent API chaining for setting properties and rendering a template. ```csharp var result = new Template("{{a}} {{b}} {{c}}") .Set("a", "value1") .Set("b", "value2") .Set("c", "value3") .Render(); ``` -------------------------------- ### Example: Base-36 Conversion Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/number-formater.md Shows how to create a NumberFormater for base-36 and convert a decimal number to its base-36 string representation. ```csharp var nf36 = new NumberFormater(36); string hex = nf36.ToString(12345678); // "7clzi" in base-36 ``` -------------------------------- ### Example: Obfuscation with Custom Characters Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/number-formater.md Shows how to use a custom character set with NumberFormater for simple obfuscation of numbers. ```csharp // Custom characters for obfuscation var nf2 = new NumberFormater("zyxwvutsrqponmlkjihgfedcba"); string obfuscated = nf2.ToString(12345); ``` -------------------------------- ### Start HiPerfTimer Instance Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Starts an existing HiPerfTimer instance. Calls Thread.Sleep(0) internally to yield to other threads before starting. ```csharp var timer = new HiPerfTimer(); timer.Start(); Thread.Sleep(100); timer.Stop(); ``` -------------------------------- ### Install Masuit.Tools.DigitalWatermarker via .NET CLI Source: https://github.com/ldqk/masuit.tools/blob/master/Masuit.Tools.DigtalWatermarker/README.md Add the Masuit.Tools.DigitalWatermarker package and its OpenCV runtime dependency to your project using the .NET CLI. ```bash dotnet add package Masuit.Tools.DigitalWatermarker dotnet add package OpenCvSharp4.runtime.win ``` -------------------------------- ### Example: Base-10 Formatting with Byte Array Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/number-formater.md Demonstrates creating a base-10 formatter using a byte array of UTF-8 encoded characters and converting a number to its string representation. ```csharp byte[] chars = Encoding.UTF8.GetBytes("0123456789"); var nf = new NumberFormater(chars); ``` -------------------------------- ### RsaKey Generation Example Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/cryptography.md Demonstrates how to generate RSA keys using the RsaCrypt utility. The public key can be shared, while the private key must be kept secret. ```csharp RsaKey keys = RsaCrypt.GenerateRsaKeys(); // keys.PublicKey - share with clients // keys.PrivateKey - keep secret ``` -------------------------------- ### Example: Base-8 Formatting with Char Array Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/number-formater.md Illustrates creating a base-8 formatter using a character array and converting a number to its base-8 string representation. ```csharp var chars = new[] { '0', '1', 'a', 'b', 'c', 'd', 'e', 'f' }; // Base-8 var nf = new NumberFormater(chars); ``` -------------------------------- ### Getting Enum Dictionaries and Descriptions Source: https://github.com/ldqk/masuit.tools/wiki/Home Shows how to retrieve dictionary mappings for enum values and their string representations, as well as getting specific descriptions or display names from enum members. Useful for data binding and UI display. ```csharp Dictionary dic1 = typeof(MyEnum).GetDictionary();// 获取枚举值和字符串表示的字典映射 var dic2 = typeof(MyEnum).GetDescriptionAndValue();// 获取字符串表示和枚举值的字典映射 string desc = MyEnum.Read.GetDescription();// 获取Description标签 string display = MyEnum.Read.GetDisplay();// 获取Display标签的Name属性 var value = typeof(MyEnum).GetValue("Read");//获取字符串表示值对应的枚举值 string enumString = 0.ToEnumString(typeof(MyEnum));// 获取枚举值对应的字符串表示 ``` -------------------------------- ### Instantiate and Use SnowFlakeNew Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/snowflake-distributed-id.md Demonstrates how to get an instance of SnowFlakeNew and generate unique IDs. Also shows the usage of the static NewId property. ```csharp public class SnowFlakeNew { public static string NewId { get; } public static SnowFlakeNew GetInstance() public long GetLongId() public string GetUniqueId() public string GetUniqueShortId(int maxLength = 8) public static void SetMachienId(long machineId) public static void SetNumberFormater(NumberFormater nf) public static void SetInitialOffset(long offset) } ``` ```csharp var sfn = SnowFlakeNew.GetInstance(); string id = sfn.GetUniqueId(); // Example: "vmbq8q3s3zul" // Or use static property string newId = SnowFlakeNew.NewId; ``` -------------------------------- ### HiPerfTimer.StartNew() Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md A convenience static method that creates a new HiPerfTimer instance and immediately starts it. Returns the newly created and running timer. ```APIDOC ## StartNew() ### Description Creates and starts a new timer in one call. ### Signature ```csharp public static HiPerfTimer StartNew() ``` ### Returns - **HiPerfTimer**: A new timer that is already running ### Usage ```csharp var timer = HiPerfTimer.StartNew(); for (int i = 0; i < 100000; i++) { Math.Sqrt(i); } timer.Stop(); Console.WriteLine($"Duration: {timer.Duration}s"); ``` ### Equivalent to ```csharp var timer = new HiPerfTimer(); timer.Start(); ``` ``` -------------------------------- ### Asynchronous Email Sending Source: https://github.com/ldqk/masuit.tools/blob/master/README.md Provides an example of how to send emails asynchronously using the Email class, configuring SMTP server details, credentials, and recipients. ```csharp new Email() { SmtpServer = "smtp.masuit.com",// SMTP服务器 SmtpPort = 25, // SMTP服务器端口 EnableSsl = true,//使用SSL Username = "admin@masuit.com",// 邮箱用户名 Password = "123456",// 邮箱密码 Tos = "10000@qq.com,10001@qq.com", //收件人 Subject = "测试邮件",//邮件标题 Body = "你好啊",//邮件内容 }.SendAsync(s => { Console.WriteLine(s);// 发送成功后的回调 });// 异步发送邮件 ``` -------------------------------- ### Example: Hexadecimal Formatting with Custom String Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/number-formater.md Demonstrates creating a hexadecimal formatter (base-16) using a custom string of characters and converting a number to its hexadecimal representation. ```csharp var nf = new NumberFormater("0123456789abcdef"); // Hexadecimal formatter string hex = nf.ToString(255); // "ff" ``` -------------------------------- ### HiPerfTimer.Start() Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Starts the timer. This method internally calls Thread.Sleep(0) to yield to other threads before beginning the timing. ```APIDOC ## Start() ### Description Starts the timer. ### Signature ```csharp public void Start() ``` ### Usage ```csharp var timer = new HiPerfTimer(); timer.Start(); Thread.Sleep(100); timer.Stop(); ``` ### Note Calls `Thread.Sleep(0)` internally to yield to other threads before starting. ``` -------------------------------- ### Reflection Operations on Objects Source: https://github.com/ldqk/masuit.tools/blob/master/README.md Demonstrates common reflection-based operations like getting properties, setting values, deep cloning, and converting objects to dictionaries or dynamic types. ```csharp MyClass myClass = new MyClass(); PropertyInfo[] properties = myClass.GetProperties();// 获取属性列表 myClass.SetProperty("Email","1@1.cn");//给对象设置值 myClass.DeepClone(); // 对象深拷贝,带嵌套层级的 myClass.ToDictionary(); // 对象转字典 myClass.ToDynamic(); // 对象转换成动态可扩展类型 ``` -------------------------------- ### DateTime Operations and Ranges Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/README.md Provides examples for timestamp conversions, defining and intersecting time ranges, and retrieving current time periods. ```csharp // Timestamp conversions double timestamp = DateTime.Now.GetTotalSeconds(); double ms = DateTime.Now.GetTotalMilliseconds(); // Time ranges var range = new DateTimeRange(start, end); var (hasOverlap, overlap) = range.Intersect(start2, end2); bool contains = range.Contains(start3, end3); // Get current period var thisWeek = DateTime.Now.GetCurrentWeek(); var thisMonth = DateTime.Now.GetCurrentMonth(); var thisYear = DateTime.Now.GetCurrentYear(); ``` -------------------------------- ### Custom SMTP Server Configuration Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/email-sender.md Example configuration for sending emails via a custom or internal SMTP server. Authentication may not be required. ```csharp var email = new Email { SmtpServer = "mail.company.local", SmtpPort = 25, EnableSsl = false, Username = "noreply@company.com", Password = "", // May not require authentication on internal server Tos = "user@company.com", Subject = "Internal Notification", Body = "Your account has been activated" }; email.Send(); ``` -------------------------------- ### HTML Form Generation with Placeholders Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/template-engine.md Shows how to generate HTML form elements dynamically. This example uses the template engine to set form attributes and input placeholders. ```csharp var formHtml = Template.Create( "
" + "" + "" + "
" ) .Set("action", "/login") .Set("token", csrfToken) .Set("placeholder", "Enter username") .Render(); ``` -------------------------------- ### Image Similarity Comparison Source: https://github.com/ldqk/masuit.tools/blob/master/README.md Demonstrates how to compare image similarity using different hashing algorithms (DifferenceHash256, AverageHash64, DctHash, MedianHash64) and get a similarity score. ```csharp // 图像相似度对比 var hasher = new ImageHasher(); var hash1 = hasher.DifferenceHash256("图片1"); // 使用差分哈希算法计算图像的256位哈希 var hash2 = hasher.DifferenceHash256("图片2"); // 使用差分哈希算法计算图像的256位哈希 //var hash1 = hasher.AverageHash64("图片1"); // 使用平均值算法计算图像的64位哈希 //var hash2 = hasher.AverageHash64("图片2"); // 使用平均值算法计算图像的64位哈希 //var hash1 = hasher.DctHash("图片1"); // 使用DCT算法计算图像的64位哈希 //var hash2 = hasher.DctHash("图片2"); // 使用DCT算法计算图像的64位哈希 //var hash1 = hasher.MedianHash64("图片1"); // 使用中值算法计算给定图像的64位哈希 //var hash2 = hasher.MedianHash64("图片2"); // 使用中值算法计算给定图像的64位哈希 var sim=ImageHasher.Compare(hash1,hash2); // 图片的相似度,范围:[0,1] ``` -------------------------------- ### Email Body Templating with Fluent API Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/template-engine.md Illustrates generating an email body using the template engine. This example sets user-specific and dynamic data like verification links. ```csharp var emailBody = Template.Create( "

Hello {{userName}}!

" + "

Thank you for registering on {{siteName}}.

" + "

Verify your email

" ) .Set("userName", user.Name) .Set("siteName", "MyApp") .Set("verifyLink", $"https://myapp.com/verify?code={verifyCode}") .Render(); ``` -------------------------------- ### DateTimeRange Usage Example Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/types.md Demonstrates how to create a DateTimeRange object and check for overlaps with another time period using the Intersect method. ```csharp var range = new DateTimeRange(startDate, endDate); var (hasOverlap, overlap) = range.Intersect(start2, end2); if (hasOverlap) { // Handle overlapping period } ``` -------------------------------- ### Example: Base-62 Conversion Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/number-formater.md Illustrates creating a NumberFormater for base-62 and converting a decimal number to its base-62 string representation, which uses alphanumeric characters plus two symbols. ```csharp var nf62 = new NumberFormater(62); string b62 = nf62.ToString(9999999); // Uses alphanumeric + 2 symbols ``` -------------------------------- ### Microsoft 365 / Outlook SMTP Configuration Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/email-sender.md Example configuration for sending emails via Microsoft 365 or Outlook SMTP servers. ```csharp var email = new Email { SmtpServer = "smtp.office365.com", SmtpPort = 587, EnableSsl = true, Username = "your-email@company.com", Password = "your-password", Tos = "recipient@company.com", Subject = "Corporate Email", Body = "

Important Notice

" }; email.Send(); ``` -------------------------------- ### Register Masuit.Tools Configuration in Startup Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/README.md Demonstrates how to add Masuit.Tools configuration to the application's services in the Startup class for .NET Core. ```csharp public Startup(IConfiguration configuration) { configuration.AddToMasuitTools(); } ``` -------------------------------- ### Instantiate and Use HiPerfTimer Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Creates a new HiPerfTimer instance, starts it, performs an operation, stops it, and prints the elapsed time in seconds. Requires Windows system with QueryPerformanceCounter support. ```csharp var timer = new HiPerfTimer(); timer.Start(); // ... code to measure timer.Stop(); Console.WriteLine($"Elapsed: {timer.Duration} seconds"); ``` -------------------------------- ### Factory Method for Template Creation Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/template-engine.md Use the static Create method as a factory to get a new Template instance. This is an alternative to direct instantiation. ```csharp public static Template Create(string content) ``` ```csharp var template = Template.Create("Welcome {{username}}!"); ``` -------------------------------- ### Get Elapsed Nanoseconds Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Retrieves the current elapsed time from the timer's start point in nanoseconds. This property is read-only. ```csharp public double ElapsedNanoseconds { get; } ``` -------------------------------- ### Gmail SMTP Configuration Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/email-sender.md Example configuration for sending emails via Gmail's SMTP server. Requires an App Password if 2FA is enabled. ```csharp var email = new Email { SmtpServer = "smtp.gmail.com", SmtpPort = 587, EnableSsl = true, Username = "your-email@gmail.com", Password = "your-app-specific-password", // Not your regular password Tos = "recipient@example.com", Subject = "Hello from C#", Body = "

Email body goes here

" }; email.Send(); ``` -------------------------------- ### Benchmark a Loop's Duration Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Starts a timer, performs a loop, stops the timer, and reports the duration in seconds. This is suitable for measuring longer-running operations. ```csharp var timer = HiPerfTimer.StartNew(); var result = 0; for (int i = 0; i < 1000000; i++) { result += i * i; } timer.Stop(); Console.WriteLine($"1 million iterations: {timer.Duration}s"); ``` -------------------------------- ### DateTimeRange Properties Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/datetime-extensions.md Demonstrates how to create and access properties of a DateTimeRange object. Use this to get the start, end, and duration of a defined period. ```csharp var range = new DateTimeRange(start, end); DateTime start = range.Start; // Period start DateTime end = range.End; // Period end TimeSpan duration = range.Duration; // Period length ``` -------------------------------- ### Get Elapsed Time in Nanoseconds Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Retrieves the elapsed time in nanoseconds between the Start() and Stop() calls. Useful for measuring very short operations. ```csharp var timer = HiPerfTimer.StartNew(); int x = 5 + 3; // Very fast operation timer.Stop(); double nanoseconds = timer.DurationNanoseconds; ``` -------------------------------- ### HiPerfTimer.DurationNanoseconds Property Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Gets the total time elapsed between the Start() and Stop() calls in nanoseconds. This property provides a more granular measurement for very short durations. ```APIDOC ## DurationNanoseconds { get; } ### Description Gets the time elapsed between Start() and Stop() in nanoseconds. ### Signature ```csharp public double DurationNanoseconds { get; } ``` ### Returns - **double**: Elapsed time in nanoseconds ### Usage ```csharp var timer = HiPerfTimer.StartNew(); int x = 5 + 3; // Very fast operation timer.Stop(); double nanoseconds = timer.DurationNanoseconds; ``` ``` -------------------------------- ### HiPerfTimer.Duration Property Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Gets the total time elapsed between the Start() and Stop() calls in seconds. This property reflects the duration of the last completed timing interval. ```APIDOC ## Duration { get; } ### Description Gets the time elapsed between Start() and Stop() in seconds. ### Signature ```csharp public double Duration { get; } ``` ### Returns - **double**: Elapsed time in seconds ### Usage ```csharp var timer = HiPerfTimer.StartNew(); Thread.Sleep(100); timer.Stop(); double seconds = timer.Duration; // ~0.1 ``` ``` -------------------------------- ### High-Performance Timer (Nanosecond Precision) Source: https://github.com/ldqk/masuit.tools/wiki/Home Measure execution time with nanosecond precision. Supports starting a timer and stopping it manually, or using a static method to execute a block of code and get its duration. ```csharp HiPerfTimer timer = HiPerfTimer.StartNew(); for (int i = 0; i < 100000; i++) { //todo } timer.Stop(); Console.WriteLine("执行for循环100000次耗时"+timer.Duration+"s"); ``` ```csharp double time = HiPerfTimer.Execute(() => { for (int i = 0; i < 100000; i++) { //todo } }); Console.WriteLine("执行for循环100000次耗时"+time+"s"); ``` -------------------------------- ### Get Elapsed Time in Seconds Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Retrieves the current elapsed time in seconds since the timer was started without stopping the timer. Each access to Elapsed internally calls Stop(), advancing the stop time. ```csharp var timer = HiPerfTimer.StartNew(); Thread.Sleep(50); double midway = timer.Elapsed; // Get elapsed without stopping Thread.Sleep(50); double total = timer.Elapsed; // Now stopped ``` -------------------------------- ### HiPerfTimer.Elapsed Property Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Gets the current elapsed time from Start() up to the moment this property is accessed, in seconds. Accessing this property internally calls Stop(), effectively advancing the stop time. Use with caution if precise interval measurements are needed. ```APIDOC ## Elapsed { get; } ### Description Gets the current elapsed time from Start() to now in seconds. Calls Stop() internally. ### Signature ```csharp public double Elapsed { get; } ``` ### Returns - **double**: Current elapsed time in seconds ### Usage ```csharp var timer = HiPerfTimer.StartNew(); Thread.Sleep(50); double midway = timer.Elapsed; // Get elapsed without stopping Thread.Sleep(50); double total = timer.Elapsed; // Now stopped ``` ### Note Each access to Elapsed calls Stop(), advancing the stop time. ``` -------------------------------- ### Warm Up Code Before Measurement Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Includes a warm-up phase to allow for JIT compilation and cache warming before starting the actual performance measurement. This ensures more accurate results for the timed operations. ```csharp // Warm up (JIT compilation, cache warming) for (int i = 0; i < 100; i++) { TestMethod(); } // Actual measurement var timer = HiPerfTimer.StartNew(); for (int i = 0; i < 1000000; i++) { TestMethod(); } timer.Stop(); ``` -------------------------------- ### Get Category Tree and Filter by Active Status and Depth Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/tree-structures.md Retrieves all categories and converts them into a tree structure. It then filters this tree to get active categories within a specified maximum depth. ```csharp public class CategoryService { public IList GetCategoryTree() { var all = _db.Categories.ToList(); return all.ToTree(); } public IList GetActiveCategories(int maxDepth = 3) { var tree = GetCategoryTree(); return tree.Filter(c => c.IsActive && c.Level() < maxDepth).ToList(); } public IList GetSubcategories(int parentId, bool includeInactive = false) { var tree = GetCategoryTree(); var parent = tree.Flatten().FirstOrDefault(c => c.Id == parentId); if (parent == null) return new List(); var children = parent.AllChildren(); if (!includeInactive) { children = children.Where(c => c.IsActive).ToList(); } return children; } public bool IsAncestor(int potentialAncestorId, int descendantId) { var tree = GetCategoryTree(); var descendant = tree.Flatten().FirstOrDefault(c => c.Id == descendantId); if (descendant == null) return false; var ancestors = descendant.AllParent().Select(c => c.Id).ToList(); return ancestors.Contains(potentialAncestorId); } } ``` -------------------------------- ### SnowFlakeNew.GetLongId Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/snowflake-distributed-id.md Gets the unique ID as a long integer. ```APIDOC ## SnowFlakeNew.GetLongId() ### Description Gets the unique ID as a long integer. ### Method `public long GetLongId()` ### Usage Example ```csharp var sfn = SnowFlakeNew.GetInstance(); long id = sfn.GetLongId(); ``` ``` -------------------------------- ### Image Transformations (Grayscale, Crop, Resize, Mirror) Source: https://github.com/ldqk/masuit.tools/wiki/Home Illustrates various image manipulation techniques including converting to grayscale, cropping and resizing, and applying horizontal and vertical mirroring. ```csharp Bitmap bmp = new Bitmap(@"D:\1.jpg"); Bitmap newBmp = bmp.BWPic(bmp.Width, bmp.Height);//转换成黑白 Bitmap newBmp = bmp.CutAndResize(new Rectangle(0, 0, 1600, 900), 160, 90);//裁剪并缩放mp.RevPicLR(bmp.Width, bmp.Height);//左右镜像 bmp.RevPicUD(bmp.Width, bmp.Height);//上下镜像 ``` -------------------------------- ### SnowFlakeNew.GetUniqueShortId Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/snowflake-distributed-id.md Gets a unique ID as a string, with an optional maximum length. ```APIDOC ## SnowFlakeNew.GetUniqueShortId(int maxLength = 8) ### Description Gets a unique ID as a string, with an optional maximum length. Defaults to 8 characters. ### Method `public string GetUniqueShortId(int maxLength = 8)` ### Parameters #### Path Parameters - **maxLength** (int) - Optional - The maximum length of the generated ID. Defaults to 8. ``` -------------------------------- ### Restart HiPerfTimer Instance Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Stops and resets the timer, then starts it again for a new measurement cycle. ```csharp var timer = HiPerfTimer.StartNew(); // ... first measurement timer.Restart(); // ... second measurement timer.Stop(); ``` -------------------------------- ### Create Template Instance Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/template-engine.md Instantiates a new Template object with the provided content string. Use this for direct initialization. ```csharp public Template(string content) ``` ```csharp var template = new Template("Hello {{name}}, you are {{age}} years old"); ``` -------------------------------- ### HiPerfTimer.Restart() Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/hiperftimer.md Stops the current timing, resets the timer, and then starts it again. This is useful for measuring consecutive time intervals. ```APIDOC ## Restart() ### Description Stops and resets the timer, then starts it again. ### Signature ```csharp public void Restart() ``` ### Usage ```csharp var timer = HiPerfTimer.StartNew(); // ... first measurement timer.Restart(); // ... second measurement timer.Stop(); ``` ``` -------------------------------- ### Dynamic Object Creation with Clay Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/types.md Allows for dynamic object creation, similar to JavaScript, enabling property assignment at runtime. Use Clay.Create() to instantiate. ```csharp public class Clay : DynamicObject { public static Clay Create() public static Clay Create(object instance) public static Clay Create(Type type) } ``` ```csharp dynamic obj = Clay.Create(); obj.Name = "John"; obj.Age = 30; obj.Email = "john@example.com"; ``` -------------------------------- ### Fluent API for Template Rendering Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/template-engine.md Demonstrates using the fluent API to create a template, set variables, and render the final HTML string. This is useful for dynamically generating content with placeholders. ```csharp string html = new Template( "

{{title}}

" + "

Author: {{author}}

" + "

Published: {{date}}

" ) .Set("title", "Getting Started with Masuit.Tools") .Set("author", "John Developer") .Set("date", DateTime.Now.ToString("yyyy-MM-dd")) .Render(); ``` -------------------------------- ### Create a DateTimeRange Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/datetime-extensions.md Instantiate a DateTimeRange object representing a contiguous time period between a start and end DateTime. ```csharp var range1 = new DateTimeRange( DateTime.Parse("2020-08-03"), DateTime.Parse("2020-08-05") ); ``` -------------------------------- ### Check if a DateTime is within a Range Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/datetime-extensions.md Determine if a target DateTime falls between a specified start and end date. ```csharp DateTime target = DateTime.Parse("2020-08-03"); DateTime start = DateTime.Parse("2020-08-02"); DateTime end = DateTime.Parse("2020-08-04"); bool inRange = target.In(start, end); // true ``` -------------------------------- ### Enum Extensions with Descriptions Source: https://github.com/ldqk/masuit.tools/blob/master/README.md Demonstrates how to use custom attributes for multi-language descriptions and retrieving enum values. ```csharp [Flags] public enum MyEnum { [Display(Name = "读")] [Description("读")] [EnumDescription("读取操作","读","zh-CN")] [EnumDescription("Read","Read","en-US")] Read=1, [Display(Name = "写")] [Description("写")] Write=2, Delete=4, All=8 } ``` ```csharp Dictionary dic1 = typeof(MyEnum).GetDictionary();// 获取枚举值和字符串表示的字典映射 var dic2 = typeof(MyEnum).GetDescriptionAndValue();// 获取字符串表示和枚举值的字典映射 string desc = MyEnum.Read.GetDescription();// 获取Description标签 string display = MyEnum.Read.GetDisplay();// 获取Display标签的Name属性 var value = typeof(MyEnum).GetValue("Read");//获取字符串表示值对应的枚举值 ``` ```csharp var op=MyEnum.Read|MyEnum.Write|MyEnum.Delete; var enums=op.Split(); // 拆分枚举值,得到枚举数组,这个函数建议使用在按位定值的枚举 ``` -------------------------------- ### SnowFlakeNew.GetUniqueId Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/snowflake-distributed-id.md Gets a unique ID as a string. This method generates a unique identifier suitable for various applications. ```APIDOC ## SnowFlakeNew.GetUniqueId() ### Description Gets a unique ID as a string. This method generates a unique identifier suitable for various applications. ### Method `public string GetUniqueId()` ### Usage Example ```csharp var sfn = SnowFlakeNew.GetInstance(); string id = sfn.GetUniqueId(); ``` ``` -------------------------------- ### Static Factory Method Usage Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/README.md Demonstrates the use of static factory methods to create instances of Timer, SnowFlake, and Template. ```csharp var timer = HiPerfTimer.StartNew(); var sf = SnowFlake.GetInstance(); var template = Template.Create("..."); ``` -------------------------------- ### Configure Masuit.Tools in appsettings.json Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/README.md Shows how to configure email domain whitelists and blocklists in appsettings.json for .NET Core applications. ```json { "EmailDomainWhiteList": [ "^\\w{1,10}@company\\.com$", "^\\w{1,10}@partner\\.org$" ], "EmailDomainBlockList": [ "^\\w{1,5}@tempmail\\.com$" ] } ``` -------------------------------- ### Get Timestamp in Various Units Source: https://github.com/ldqk/masuit.tools/blob/master/README.md Obtain the total milliseconds, microseconds, nanoseconds, seconds, or minutes since the epoch. ```csharp double milliseconds = DateTime.Now.GetTotalMilliseconds();// 获取毫秒级时间戳 double microseconds = DateTime.Now.GetTotalMicroseconds();// 获取微秒级时间戳 double nanoseconds = DateTime.Now.GetTotalNanoseconds();// 获取纳秒级时间戳 double seconds = DateTime.Now.GetTotalSeconds();// 获取秒级时间戳 double minutes = DateTime.Now.GetTotalMinutes();// 获取分钟级时间戳 ``` -------------------------------- ### Get NumberFormater Base Length Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/number-formater.md Retrieves the base of the NumberFormater, which corresponds to the number of unique characters in its character set. ```csharp public int Length { get; } ``` -------------------------------- ### Asp.Net Core Controller Examples for ResumeFileResults Source: https://github.com/ldqk/masuit.tools/blob/master/README.md Demonstrates various ways to use ResumeFileResults in an Asp.Net Core controller, including returning file content, streams, physical files, and virtual files. Supports options for filename, ETag, and LastModified headers. ```csharp using Masuit.Tools.AspNetCore.ResumeFileResults.Extensions; private const string EntityTag = "\"TestFile\""; private readonly IHostingEnvironment _hostingEnvironment; private readonly DateTimeOffset _lastModified = new DateTimeOffset(2016, 1, 1, 0, 0, 0, TimeSpan.Zero); /// /// /// /// public TestController(IHostingEnvironment hostingEnvironment) { _hostingEnvironment = hostingEnvironment; } [HttpGet("content/{fileName}/{etag}")] public IActionResult FileContent(bool fileName, bool etag) { string webRoot = _hostingEnvironment.WebRootPath; var content = System.IO.File.ReadAllBytes(Path.Combine(webRoot, "TestFile.txt")); ResumeFileContentResult result = this.ResumeFile(content, "text/plain", fileName ? "TestFile.txt" : null, etag ? EntityTag : null); result.LastModified = _lastModified; return result; } [HttpGet("content/{fileName}")] public IActionResult FileContent(bool fileName) { string webRoot = _hostingEnvironment.WebRootPath; var content = System.IO.File.ReadAllBytes(Path.Combine(webRoot, "TestFile.txt")); var result = new ResumeFileContentResult(content, "text/plain") { FileInlineName = "TestFile.txt", LastModified = _lastModified }; return result; } [HttpHead("file")] public IActionResult FileHead() { ResumeVirtualFileResult result = this.ResumeFile("TestFile.txt", "text/plain", "TestFile.txt", EntityTag); result.LastModified = _lastModified; return result; } [HttpPut("file")] public IActionResult FilePut() { ResumeVirtualFileResult result = this.ResumeFile("TestFile.txt", "text/plain", "TestFile.txt", EntityTag); result.LastModified = _lastModified; return result; } [HttpGet("stream/{fileName}/{etag}")] public IActionResult FileStream(bool fileName, bool etag) { string webRoot = _hostingEnvironment.WebRootPath; FileStream stream = System.IO.File.OpenRead(Path.Combine(webRoot, "TestFile.txt")); ResumeFileStreamResult result = this.ResumeFile(stream, "text/plain", fileName ? "TestFile.txt" : null, etag ? EntityTag : null); result.LastModified = _lastModified; return result; } [HttpGet("stream/{fileName}")] public IActionResult FileStream(bool fileName) { string webRoot = _hostingEnvironment.WebRootPath; FileStream stream = System.IO.File.OpenRead(Path.Combine(webRoot, "TestFile.txt")); var result = new ResumeFileStreamResult(stream, "text/plain") { FileInlineName = "TestFile.txt", LastModified = _lastModified }; return result; } [HttpGet("physical/{fileName}/{etag}")] public IActionResult PhysicalFile(bool fileName, bool etag) { string webRoot = _hostingEnvironment.WebRootPath; ResumePhysicalFileResult result = this.ResumePhysicalFile(Path.Combine(webRoot, "TestFile.txt"), "text/plain", fileName ? "TestFile.txt" : null, etag ? EntityTag : null); result.LastModified = _lastModified; return result; } [HttpGet("physical/{fileName}")] public IActionResult PhysicalFile(bool fileName) { string webRoot = _hostingEnvironment.WebRootPath; var result = new ResumePhysicalFileResult(Path.Combine(webRoot, "TestFile.txt"), "text/plain") { FileInlineName = "TestFile.txt", LastModified = _lastModified }; return result; } [HttpGet("virtual/{fileName}/{etag}")] public IActionResult VirtualFile(bool fileName, bool etag) { ResumeVirtualFileResult result = this.ResumeFile("TestFile.txt", "text/plain", fileName ? "TestFile.txt" : null, etag ? EntityTag : null); result.LastModified = _lastModified; return result; } ``` ```csharp [HttpGet("virtual/{fileName}")] public IActionResult VirtualFile(bool fileName) { var result = new ResumeVirtualFileResult("TestFile.txt", "text/plain") { FileInlineName = "TestFile.txt", LastModified = _lastModified }; return result; } ``` -------------------------------- ### Asynchronous Email Sending Source: https://github.com/ldqk/masuit.tools/wiki/Home Provides an example of how to send an email asynchronously using the Email class. Configuration includes SMTP server details, SSL, credentials, recipients, subject, and body. ```csharp new Email() { SmtpServer = "smtp.masuit.com",// SMTP服务器 SmtpPort = 25, // SMTP服务器端口 EnableSsl = true,//使用SSL Username = "admin@masuit.com",// 邮箱用户名 Password = "123456",// 邮箱密码 Tos = "10000@qq.com,10001@qq.com", //收件人 Subject = "测试邮件",//邮件标题 Body = "你好啊",//邮件内容 }.SendAsync(s = { Console.WriteLine(s);// 发送成功后的回调 });// 异步发送邮件 ``` -------------------------------- ### Generate and Verify IDs in a Distributed System Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/snowflake-distributed-id.md Demonstrates initializing Snowflake with a machine ID based on CPU count and generating a large number of unique IDs. It also includes a verification step to confirm uniqueness. ```csharp // Initialization SnowFlake.SetMachienId(Environment.ProcessorCount); // Use CPU count as machine ID // Generate IDs for (int i = 0; i < 1000000; i++) { string id = SnowFlake.NewId; // Use ID in application } // Verify uniqueness var set = new HashSet(); for (int i = 0; i < 1000000; i++) { set.Add(SnowFlake.NewId); } Console.WriteLine(set.Count == 1000000); // True - all IDs are unique ``` -------------------------------- ### Embed Copyright Watermark Source: https://github.com/ldqk/masuit.tools/blob/master/Masuit.Tools.DigtalWatermarker/README.md Example of embedding a text-based copyright notice as a watermark onto a photograph. Requires logo.png and photo.jpg. ```csharp // 为摄影作品添加版权水印 var photographer = "© 2024 Photographer Name"; var logo = Cv2.ImRead("logo.png"); var photo = Cv2.ImRead("photo.jpg"); using var protected_photo = DigitalWatermarker.EmbedWatermark(photo, logo); Cv2.ImWrite("protected_photo.jpg", protected_photo); ``` -------------------------------- ### Check if a DateTimeRange is within Specific Dates Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/datetime-extensions.md Confirm if the entire duration of a DateTimeRange falls within a specified start and end date. ```csharp bool inRange = range.In( DateTime.Parse("2020-08-03"), DateTime.Parse("2020-08-06") ); // true - entire range is within dates ``` -------------------------------- ### Register Masuit.Tools Configuration in .NET Core Source: https://github.com/ldqk/masuit.tools/wiki/Home Configure Masuit.Tools by adding the configuration to your appsettings.json file. This example shows how to add email domain whitelists and blacklists. The AddToMasuitTools() method automatically loads configurations from appsettings.json if not explicitly called. ```csharp public Startup(IConfiguration configuration) { configuration.AddToMasuitTools(); // 若未调用,则默认自动尝试加载appsettings.json } ``` -------------------------------- ### MD5 Hashing Variations Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/cryptography.md Demonstrates different MD5 hashing methods including simple hashing, salting, double hashing, and triple hashing. Useful for password storage and data integrity checks. ```csharp // Simple MD5 string hash = "123456".MDString(); // 32-char hex string // MD5 with salt string salted = "123456".MDString("salt_value"); // Double MD5 string double = "123456".MDString2(); // Double MD5 with salt string doubleSalt = "123456".MDString2("salt"); // Triple MD5 string triple = "123456".MDString3(); // Triple MD5 with salt string tripleSalt = "123456".MDString3("salt"); ``` ```csharp public class UserService { public void RegisterUser(string username, string password) { string hashedPassword = password.MDString("salt_" + username); userRepository.Save(username, hashedPassword); } } ``` -------------------------------- ### Using PooledMemoryStream for Performance Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/specialized-collections.md Demonstrates the use of PooledMemoryStream, which leverages memory pooling for improved allocation performance, recommended for frequent temporary stream usage. ```csharp // Recommended for many temporary streams using var stream = new PooledMemoryStream(); // Use like normal MemoryStream but with pooled memory ``` -------------------------------- ### SnowFlakeNew.GetInstance Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/snowflake-distributed-id.md Gets an instance of the SnowFlakeNew class. This class provides an improved variant of Snowflake that is less sensitive to time clock callbacks. ```APIDOC ## SnowFlakeNew.GetInstance() ### Description Gets an instance of the SnowFlakeNew class. This class provides an improved variant of Snowflake that is less sensitive to time clock callbacks. ### Method `public static SnowFlakeNew GetInstance()` ### Usage Example ```csharp var sfn = SnowFlakeNew.GetInstance(); string id = sfn.GetUniqueId(); ``` ``` -------------------------------- ### Get Singleton SnowFlake Instance Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/snowflake-distributed-id.md Retrieve the singleton instance of the SnowFlake class. This method ensures that only one instance is created and managed. ```csharp public static SnowFlake GetInstance() ``` ```csharp var sf = SnowFlake.GetInstance(); string id = sf.GetUniqueId(); ``` -------------------------------- ### Get Unix Timestamps in Various Precisions Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/datetime-extensions.md Obtain Unix timestamps in seconds, milliseconds, microseconds, nanoseconds, and minutes from a DateTime object. ```csharp DateTime now = DateTime.Now; // Seconds since Unix epoch double seconds = now.GetTotalSeconds(); // Milliseconds double milliseconds = now.GetTotalMilliseconds(); // Microseconds double microseconds = now.GetTotalMicroseconds(); // Nanoseconds double nanoseconds = now.GetTotalNanoseconds(); // Minutes double minutes = now.GetTotalMinutes(); ``` -------------------------------- ### Collection Processing Utilities Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/README.md Demonstrates deduplication, pagination, comparing changes between collections, and asynchronous processing of collection items. ```csharp // Deduplication var unique = users.DistinctBy(u => u.Email).ToList(); // Pagination var page = items.ToPagedList(pageNumber: 1, pageSize: 10); // Compare changes var (added, removed, updated) = oldList.CompareChanges(newList, x => x.Id); // Async operations var results = await items.SelectAsync(async i => await ProcessAsync(i)); ``` -------------------------------- ### Fixed-Size and Concurrent Queues Source: https://github.com/ldqk/masuit.tools/blob/master/README.md Shows how to declare and use fixed-size queues and their thread-safe concurrent versions. ```csharp LimitedQueue queue = new LimitedQueue(32);// 声明一个容量为32个元素的定长队列 ConcurrentLimitedQueue queue = new ConcurrentLimitedQueue(32);// 声明一个容量为32个元素的线程安全的定长队列 ``` -------------------------------- ### Image Transformations Source: https://github.com/ldqk/masuit.tools/blob/master/README.md Demonstrates various image manipulation techniques including converting to black and white, cropping, resizing, mirroring, adjusting brightness, inverting colors, and applying relief effects. ```csharp var newBmp = image.BWPic(image.Width, image.Height);//转换成黑白 var newBmp = image.CutImage(new Rectangle(0, 0, 1600, 900));//裁剪 var newBmp = image.CutAndResize(new Rectangle(0, 0, 1600, 900), 160, 90);//裁剪并缩放 var newBmp = image.ResizeImage(160, 90);//改变大小 var newBmp = image.RevPicLR();//左右镜像 var newBmp = image.RevPicUD();//上下镜像 var newBmp =image.LDPic(10); //调整光暗 var newBmp =image.RePic(); //反色处理 var newBmp =image.Relief(); //浮雕处理 ``` -------------------------------- ### Email SMTP Server Configuration Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/email-sender.md Specify the SMTP server address. Examples include smtp.gmail.com for Gmail and smtp.office365.com for Microsoft 365. ```csharp var email = new Email { SmtpServer = "smtp.gmail.com" }; ``` -------------------------------- ### Check if a Range is Contained within Another Source: https://github.com/ldqk/masuit.tools/blob/master/_autodocs/datetime-extensions.md Verify if a sub-range, defined by start and end dates, is entirely contained within a larger DateTimeRange. ```csharp bool contains = range.Contains( DateTime.Parse("2020-08-03"), DateTime.Parse("2020-08-04") ); // true - sub-range is contained ```