مطالب
حذف فضاهای خالی در خروجی صفحات ASP.NET MVC
صفحات خروجی وب سایت زمانی که رندر شده و در مرورگر نشان داده می‌شود شامل فواصل اضافی است که تاثیری در نمایش سایت نداشته و صرفا این کاراکترها فضای اضافی اشغال می‌کنند. با حذف این کاراکترهای اضافی می‌توان تا حد زیادی صفحه را کم حجم کرد. برای این کار در ASP.NET Webform کارهایی (^ ) انجام شده است.
روال کار به این صورت بوده که قبل از رندر شدن صفحه در سمت سرور خروجی نهایی بررسی شده و با استفاده از عبارات با قاعده الگوهای مورد نظر لیست شده و سپس حذف می‌شوند و در نهایت خروجی مورد نظر حاصل خواهد شد. برای راحتی کار و عدم نوشتن این روال در تمامی صفحات می‌تواند در مستر پیج این عمل را انجام داد. مثلا:
private static readonly Regex RegexBetweenTags = new Regex(@">\s+<", RegexOptions.Compiled);
        private static readonly Regex RegexLineBreaks = new Regex(@"\r\s+", RegexOptions.Compiled);

        protected override void Render(HtmlTextWriter writer)
        {
            using (var htmlwriter = new HtmlTextWriter(new System.IO.StringWriter()))
            {
                base.Render(htmlwriter);
                var html = htmlwriter.InnerWriter.ToString();

                html = RegexBetweenTags.Replace(html, "> <");
                html = RegexLineBreaks.Replace(html, string.Empty);
                html = html.Replace("//<![CDATA[", "").Replace("//]]>", "");
                html = html.Replace("// <![CDATA[", "").Replace("// ]]>", "");

                writer.Write(html.Trim());
            }
        }
در هر صفحه رویدادی به نام Render وجود دارد که خروجی نهایی را می‌توان در آن تغییر داد. همانگونه که مشاهده می‌شود عملیات یافتن و حذف فضاهای خالی در این متد انجام می‌شود.
این عمل در ASP.NET Webform به آسانی انجام شده و باعث حذف فضاهای خالی در خروجی صفحه می‌شود.
برای انجام این عمل در ASP.NET MVC روال کار به این صورت نیست و نمی‌توان مانند ASP.NET Webform عمل کرد.
چون در MVC از ViewPage استفاده می‌شود و ما مستقیما به خروجی آن دسترسی نداریم یک روش این است که می‌توانیم یک کلاس برای ViewPage تعریف کرده و رویداد Write آن را تحریف کرده و مانند مثال بالا فضای خالی را در خروجی حذف کرد. البته برای استفاده باید کلاس ایجاد شده را به عنوان فایل پایه جهت ایجاد صفحات در MVC فایل web.config معرفی کنیم. این روش در اینجا به وضوح شرح داده شده است.
اما هدف ما پیاده سازی با استفاده از اکشن فیلتر هاست. برای پیاده سازی ایتدا یک اکشن فیلتر به نام CompressAttribute تعریف می‌کنیم مانند زیر:
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace PWS.Common.ActionFilters
{
    public class CompressAttribute : ActionFilterAttribute
    {
         #region Methods (2) 

        // Public Methods (1) 

        /// <summary>
        /// Called by the ASP.NET MVC framework before the action method executes.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var response = filterContext.HttpContext.Response;
            if (IsGZipSupported(filterContext.HttpContext.Request))
            {
                String acceptEncoding = filterContext.HttpContext.Request.Headers["Accept-Encoding"];
                if (acceptEncoding.Contains("gzip"))
                {
                    response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
                    response.AppendHeader("Content-Encoding", "gzip");
                }
                else
                {
                    response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
                    response.AppendHeader("Content-Encoding", "deflate");
                }
            }
            // Allow proxy servers to cache encoded and unencoded versions separately
            response.AppendHeader("Vary", "Content-Encoding");
           //حذف فضاهای خالی
response.Filter = new WhitespaceFilter(response.Filter); } // Private Methods (1)  /// <summary> /// Determines whether [is G zip supported] [the specified request]. /// </summary> /// <param name="request">The request.</param> /// <returns></returns> private Boolean IsGZipSupported(HttpRequestBase request) { String acceptEncoding = request.Headers["Accept-Encoding"]; if (acceptEncoding == null) return false; return !String.IsNullOrEmpty(acceptEncoding) && acceptEncoding.Contains("gzip") || acceptEncoding.Contains("deflate"); } #endregion Methods  } /// <summary> /// Whitespace Filter /// </summary> public class WhitespaceFilter : Stream { #region Fields (3)  private readonly Stream _filter; /// <summary> /// /// </summary> private static readonly Regex RegexAll = new Regex(@"\s+|\t\s+|\n\s+|\r\s+", RegexOptions.Compiled); /// <summary> /// /// </summary> private static readonly Regex RegexTags = new Regex(@">\s+<", RegexOptions.Compiled); #endregion Fields  #region Constructors (1)  /// <summary> /// Initializes a new instance of the <see cref="WhitespaceFilter" /> class. /// </summary> /// <param name="filter">The filter.</param> public WhitespaceFilter(Stream filter) { _filter = filter; } #endregion Constructors  #region Properties (5)  //methods that need to be overridden from stream /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports reading. /// </summary> /// <returns>true if the stream supports reading; otherwise, false.</returns> public override bool CanRead { get { return true; } } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports seeking. /// </summary> /// <returns>true if the stream supports seeking; otherwise, false.</returns> public override bool CanSeek { get { return true; } } /// <summary> /// When overridden in a derived class, gets a value indicating whether the current stream supports writing. /// </summary> /// <returns>true if the stream supports writing; otherwise, false.</returns> public override bool CanWrite { get { return true; } } /// <summary> /// When overridden in a derived class, gets the length in bytes of the stream. /// </summary> /// <returns>A long value representing the length of the stream in bytes.</returns> public override long Length { get { return 0; } } /// <summary> /// When overridden in a derived class, gets or sets the position within the current stream. /// </summary> /// <returns>The current position within the stream.</returns> public override long Position { get; set; } #endregion Properties  #region Methods (6)  // Public Methods (6)  /// <summary> /// Closes the current stream and releases any resources (such as sockets and file handles) associated with the current stream. Instead of calling this method, ensure that the stream is properly disposed. /// </summary> public override void Close() { _filter.Close(); } /// <summary> /// When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device. /// </summary> public override void Flush() { _filter.Flush(); } /// <summary> /// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset" /> and (<paramref name="offset" /> + <paramref name="count" /> - 1) replaced by the bytes read from the current source.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin storing the data read from the current stream.</param> /// <param name="count">The maximum number of bytes to be read from the current stream.</param> /// <returns> /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached. /// </returns> public override int Read(byte[] buffer, int offset, int count) { return _filter.Read(buffer, offset, count); } /// <summary> /// When overridden in a derived class, sets the position within the current stream. /// </summary> /// <param name="offset">A byte offset relative to the <paramref name="origin" /> parameter.</param> /// <param name="origin">A value of type <see cref="T:System.IO.SeekOrigin" /> indicating the reference point used to obtain the new position.</param> /// <returns> /// The new position within the current stream. /// </returns> public override long Seek(long offset, SeekOrigin origin) { return _filter.Seek(offset, origin); } /// <summary> /// When overridden in a derived class, sets the length of the current stream. /// </summary> /// <param name="value">The desired length of the current stream in bytes.</param> public override void SetLength(long value) { _filter.SetLength(value); } /// <summary> /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written. /// </summary> /// <param name="buffer">An array of bytes. This method copies <paramref name="count" /> bytes from <paramref name="buffer" /> to the current stream.</param> /// <param name="offset">The zero-based byte offset in <paramref name="buffer" /> at which to begin copying bytes to the current stream.</param> /// <param name="count">The number of bytes to be written to the current stream.</param> public override void Write(byte[] buffer, int offset, int count) { string html = Encoding.Default.GetString(buffer); //remove whitespace html = RegexTags.Replace(html, "> <"); html = RegexAll.Replace(html, " "); byte[] outdata = Encoding.Default.GetBytes(html); //write bytes to stream _filter.Write(outdata, 0, outdata.GetLength(0)); } #endregion Methods  } }
در این کلاس فشرده سازی (gzip و deflate نیز اعمال شده است) در متد OnActionExecuting ابتدا در خط 24 بررسی می‌شود که آیا درخواست رسیده gzip را پشتیبانی می‌کند یا خیر. در صورت پشتیبانی خروجی صفحه را با استفاده از gzip یا deflate فشرده سازی می‌کند. تا اینجای کار ممکن است مورد نیاز ما نباشد. اصل کار ما (حذف کردن فضاهای خالی) در خط 42 اعمال شده است. در واقع برای حذف فضاهای خالی باید یک کلاس که از Stream ارث بری دارد تعریف شده و خروجی کلاس مورد نظر به فیلتر درخواست ما اعمال شود.
در کلاس WhitespaceFilter با تحریف متد Write الگوهای فضای خالی موجود در درخواست یافت شده و آنها را حذف می‌کنیم. در نهایت خروجی این کلاس که از نوع استریم است به ویژگی فیلتر صفحه اعمال می‌شود.

برای معرفی فیلتر تعریف شده می‌توان در فایل Global.asax در رویداد Application_Start به صورت زیر فیلتر مورد نظر را به فیلترهای MVC اعمال کرد.
GlobalFilters.Filters.Add(new CompressAttribute());
برای آشنایی بیشتر فیلترها در ASP.NET MVC را مطالعه نمایید.
پ.ن: جهت سهولت، در این کلاس ها، صفحات فشرده سازی و همزمان فضاهای خالی آنها حذف شده است.
اشتراک‌ها
با سی شارپ 8 از دست NullReferenceExceptions ها خلاص شوید

A .NET guideline specifies that an application should never throw a NullReferenceException. However, many applications and libraries do. The NullReferenceException is the most common exception happening. That’s why C# 8 tries to get rid of it. With C# 8, reference types are not null be default. This is a big change, and a great feature. However, what about all the legacy code? Can old libraries be used with C# 8 applications, and can C# 7 applications make use of C# 8 libraries?

This article demonstrates how C# 8 allows mixing old and new assemblies. 

با سی شارپ 8 از دست NullReferenceExceptions ها خلاص شوید
اشتراک‌ها
نگاهی به آینده WebAssembly

The future of WebAssembly - A look at upcoming features and proposals

WebAssembly is a performance optimised virtual machine that was shipped in all four major browsers earlier this year. It is a nascent technology and the current version is very much an MVP (minimum viable product). This blog post takes a look at the WebAssembly roadmap and the features it might be gain in the near future.

I’ll try to keep this blog post relatively high-level, so I’ll skip over some of the more technical proposals, instead focusing on what they might mean for languages that target WebAssembly. 

نگاهی به آینده WebAssembly
نظرات مطالب
نوشتن TagHelperهای سفارشی برای ASP.NET Core
با سلام،
همانطور که می‌دانید helper@ در حال حاضر در asp.net core 2 پشتیبانی نمی‌شود.
من می‌خواهم قطعه کد ذیل را که در asp.net mvc 5 نوشته شده را مطابق با asp.net core 2 بازنویسی کنم.
چگونه می‌توانم آن را انجام دهم؟
//MyHelpers.cshtml:
//Recursive function for rendering child nodes for the specified node

@helper CreateNavigation(int parentId, int depthNavigation, int currentPageId)
{
   @MyHelpers.Navigation(parentId, depthNavigation, currentPageId);
}

@helper Navigation(int parentId, int depthNavigation, int currentPageId)
{

   if ()
   {
       if ()
       {
         <ul style="">
            @foreach ()
            {
               if ()
                {
                   <li class="">
                      @Navigation(child.Id, depthNavigation, currentPageId)
                   </li>
                }
             }
         </ul>
      }
   }
}
//I call the method in _Menu.cshtml:
 @MyHelpers.CreateNavigation(rootNode.Id, 2,currentPageId);

مطالب
بهبود کارآیی عبارات باقاعده در دات نت 7
دات نت 7 به همراه یک Regex Source Generator توکار است که به کمک آن می‌توان عبارات باقاعده را تبدیل به کدهای سی‌شارپ معادل آن‌ها کرد و پیش از اجرای برنامه، آن‌ها را کامپایل و جزئی از خروجی نهایی نمود. این روش نسبت به روش پیشین تولید کدهای معادل عبارات باقاعده در زمان اجرای برنامه، از مزایای زیر برخوردار است:
- اجرای یک عبارت باقاعده سریعتر خواهد شد. در این حالت دیگر نیازی نیست تا در حین اجرای برنامه، منتظر پردازش و تولید کدهای سی‌شارپ معادل آن شد.
- کدهای تولیدی پیش از کامپایل برنامه، از مزایای بهینه سازی ویژه‌ای برخوردار می‌شوند که پیشتر تنها با ذکر پرچم RegexOptions.Compiled در زمان اجرا میسر می‌شدند.
- بعضی از سکوهای کاری مانند iOS، از تولید کد در زمان اجرای برنامه پشتیبانی نمی‌کنند. در این حالت یک تولید کننده‌ی کد سی‌شارپ معادل در زمان کامپایل برنامه، حداکثر کارآیی را برای اینگونه سکوهای کاری به ارمغان می‌آورد.
- امکان مطالعه‌ی کدهای سی‌شارپ تولیدی معادل یک عبارت باقاعده، برای اولین بار پیش از اجرای برنامه میسر شده‌است.
- کدهای تولیدی معادل، قابلیت دیباگ دارند.
- می‌توان با مطالعه‌ی این کدها، نکات جدیدی را فرا گرفت!


چه عبارت باقاعده‌ای را می‌توان به Regex source generators تبدیل کرد؟

برای استفاده از این تولید کننده‌ی کدهای معادل عبارات باقاعده، باید از NET 7. و C# 11 استفاده کرد. همچنین تمام پارامترهای Regex تعریف شده نیز باید ثابت باشند. برای نمونه در دو مثال زیر، در اولی، pattern ثابت است و در دومی هم pattern و هم سایر تنظیمات ذکر شده؛ بنابراین قابلیت تبدیل به روش استفاده از تولید کننده‌های کد را دارند:
if(new Regex("[a-z]+").IsMatch("abc")){}

if(Regex.IsMatch(value, "[a-z]+", RegexOptions.CultureInvariant, TimeSpan.FromSeconds(1))){}
اما مثال زیر خیر؛ در این مثال چون pattern یک متغیر است، امکان تبدیل آن به روش تولید کننده‌ی خودکار کدهای معادل وجود ندارد:
public static bool Match(string value, string pattern)
{
    return Regex.IsMatch(value, pattern);
}


روش استفاده از Regex source generators

برای تبدیل مثال‌هایی که عنوان شدند به نمونه‌ی source generator، باید ابتدا یک partial method مزین شده‌ی به ویژگی [GeneratedRegex] را ایجاد کرد؛ برای نمونه:
public partial class MyRegexes
{
    [GeneratedRegex("^[a-z]+$", RegexOptions.CultureInvariant, 1000)]
    public static partial Regex LowercaseLettersRegex();
}
سپس می‌توان از این partial method‌، که کدهای آن به صورت خودکار تولید می‌شوند، در قسمت‌های مختلف برنامه استفاده کرد؛ برای مثال:
public class RegexTests
{
    public static bool IsLowercase(string value) => MyRegexes.LowercaseLettersRegex().IsMatch(value);
}
اگر علاقمند بودید تا کد معادل این partial method را مشاهده کنید، بر روی آن کلیک راست کرده و گزینه‌ی «Go to Definition» را انتخاب کنید (و یا نگه داشتن دکمه‌ی ctrl و سپس کلیک بر روی تعریف partial متد):


همچنین ابزارهای refactoring خودکاری نیز در IDEهای جدید برای این منظور تعبیه شده‌اند تا بتوان به سرعت کدهای قدیمی را به روش source generators تبدیل کرد:


و partial method تولیدی، اینبار به همراه توضیح کامل نحوه‌ی عملکرد عبارت باقاعده‌ی مورد استفاده نیز هست:

اشتراک‌ها
مروری بر قالب ساخت نصاب در Visual Studio 2019

thanks to a new feature added in Visual Studio 2019 16.1, we can combine the best of both worlds when it comes to support the App Installer technology: the easiness of automatically generating an .appinstaller file as part of the package creation process and the flexibility of the new update features added in Windows 10 1903. 

مروری بر قالب ساخت نصاب در Visual Studio 2019
اشتراک‌ها
تشخیص تغییرات در Angular2

The basic task of change detection is to take the internal state of a program and make it somehow visible to the user interface. This state can be any kind of objects, arrays, primitives, … just any kind of JavaScript data structures. 

تشخیص تغییرات در Angular2
اشتراک‌ها
کتاب رایگان WPF Debugging and Performance Succinctly

WPF allows you to build modern desktop applications for Windows, and part of building an application is debugging code and optimizing performance. In Alessandro Del Sole’s WPF Debugging and Performance Succinctly, you will learn how to debug a WPF application by leveraging all the powerful tools in Visual Studio, including the most recent additions that allow you to investigate the behavior of the UI at runtime. Also, you will learn how to analyze and improve an application’s performance in order to provide your customers with the best possible experience and thereby make them happy.

Table of Contents
  1. Debugging WPF Applications
  2. Stepping Through Code
  3. Working with Debug Windows
  4. Debugger Visualizers and Trace Listeners
  5. XAML Debugging
  6. Analyzing the UI Performances
  7. Analyzing the Application Performances 
کتاب رایگان WPF Debugging and Performance Succinctly
اشتراک‌ها
بهبودهای کارآیی LINQ در دات‌نت 9
.NET 9.0 LINQ Performance Improvements

With .NET 9, LINQ becomes faster in several common scenarios. As with every new version of .NET, you simply need to migrate and recompile to take advantage of these improvements. Additionally, LINQ has been optimized in other ways: SIMD is utilized whenever possible, such as when summing a sequence of integers. Moreover, enumerating empty sequences incurs lower costs due to early detection.
بهبودهای کارآیی LINQ در دات‌نت 9
اشتراک‌ها
پلاگین SonarLint برای بهینه سازی کدها

SonarLint is a free IDE extension that lets you fix coding issues before they exist! Like a spell checker, SonarLint highlights Bugs and Security Vulnerabilities as you write code, with clear remediation guidance so you can fix them before the code is even committed. SonarLint in VS Code supports analysis of C, C++, HTML, Java, JavaScript, PHP, Python and TypeScript, and you can install it directly from the VS Code Marketplace! 

پلاگین SonarLint برای بهینه سازی کدها