اشتراک‌ها
انتشار Entity Framework Core 7 Preview 6

In EF7, SaveChanges performance has been significantly improved, with a special focus on removing unneeded network roundtrips to your database. In some scenarios, we’re seeing a 74% reduction in time taken – that’s a four-fold improvement! 

انتشار Entity Framework Core 7 Preview 6
مطالب
بررسی دقیق عملکرد AutoMapper
همانطور که اطلاع دارید، AutoMapper ابزاری برای نگاشت خودکار بین Model و Dto می‌باشد؛ که به صورت نادرست تصور کاهش سرعت در استفاده کردن از آن، بین توسعه دهندگان جا افتاده‌است. در این مقاله قصد داریم به صورت دقیق، به بررسی سرعت عملکرد استفاده از AutoMapper و مقایسه آن با نگاشت دستی بپردازیم.
کد‌های کامل این قسمت را میتوانید از اینجا clone کرده و شخصا تست نمایید.

ابتدا یک پروژه‌ی Console Application را ساخته و AutoMapper را به همراه Ef6، نصب مینماییم. سپس دو کلاس جدید را به نام‌های User و Address به صورت زیر در پوشه‌ی Models مینویسیم.
using System.Collections.Generic;

namespace AutoMapperComparison.Models
{
    public class User
    {
        public int Id { get; set; }

        public string Name { get; set; }

        public ICollection<Address> Addresses { get; set; }
    }
}
using System.ComponentModel.DataAnnotations.Schema;

namespace AutoMapperComparison.Models
{
    public class Address
    {
        public int Id { get; set; }

        public double? Code { get; set; }

        public string Title { get; set; }

        public int UserId { get; set; }

        [ForeignKey(nameof(UserId))]
        public virtual User User { get; set; }
    }
}
بدیهی است که این دو مدل با همدیگر رابطه‌ی 1 به چند دارند. حال کافیست AppDbContext خود را به صورت زیر تعریف نماییم.
نکته: در متد Seed، برای ثبت رکورد‌های اولیه، از BulkInsert استفاده شده است (باید پکیج BulkInsert را نیز نصب نمایید)
using EntityFramework.BulkInsert.Extensions;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.SqlClient;

namespace AutoMapperComparison.Models
{
    public class AppDbContextInitializer : DropCreateDatabaseAlways<AppDbContext>
    {
        protected override void Seed(AppDbContext context)
        {
            User user = context.Users.Add(new User { Name = "Test" });

            context.SaveChanges();

            List<Address> addresses = new List<Address>();

            for (int i = 0; i < 500000; i++)
            {
                addresses.Add(new Address { Id = i, Code = 1, Title = "Test", UserId = user.Id });
            }

            context.BulkInsert(addresses);

            base.Seed(context);
        }
    }

    public class AppDbContext : DbContext
    {
        static AppDbContext()
        {
            Database.SetInitializer(new AppDbContextInitializer());

            //Database.SetInitializer<AppDbContext>(null);
        }

        public AppDbContext()
            : base(new SqlConnection(@"Data Source=.;Initial Catalog=AppDbContext;Integrated Security=True"), contextOwnsConnection: true)
        {
            Configuration.AutoDetectChangesEnabled = false;
            Configuration.EnsureTransactionsForFunctionsAndCommands = false;
            Configuration.LazyLoadingEnabled = false;
            Configuration.ProxyCreationEnabled = false;
            Configuration.ValidateOnSaveEnabled = false;
            Configuration.UseDatabaseNullSemantics = false;
        }

        public DbSet<User> Users { get; set; }

        public DbSet<Address> Addresses { get; set; }
    }
}
 برای اینکه مقایسه انجام شده دقیق باشد، تمامی Configuration‌های اضافی را نیز غیر فعال نموده‌ام.
فقط نیاز داریم یک Dto را برای Address نیز تعریف کنیم؛ چون قرار است نگاشت از Model به Dto از روی Address و AddressDto انجام شود.
کلاس AddressDto را به صورت زیر ایجاد میکنیم:
namespace AutoMapperComparison.Models
{
    public class AddressDto
    {
        public int Id { get; set; }

        public double? Code { get; set; }

        public string Title { get; set; }

        public int UserId { get; set; }

        public string UserName { get; set; }
    }
}
قرار است به صورت خودکار از طریق AutoMapper و همچنین به صورت دستی، نگاشت از Model به Dto مربوطه انجام شود.
 حال نیاز است فایل Program.cs را باز کرده و تغییرات زیر را اعمل نماییم:
using AutoMapper;
using AutoMapper.QueryableExtensions;
using AutoMapperComparison.Models;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace AutoMapperComparison
{
    public class Program
    {
        public static void Main()
        {
            Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Address, AddressDto>();
            });

            Console.WriteLine($"Create Db {DateTimeOffset.UtcNow}");
            using (AppDbContext db = new AppDbContext())
            {
                db.Database.Initialize(force: true);
                db.Database.ExecuteSqlCommand("DBCC DROPCLEANBUFFERS"); //Removes all clean buffers from the buffer pool, and columnstore objects from the columnstore object pool
                Console.WriteLine(db.Addresses.ProjectTo<AddressDto>());
                Console.WriteLine(db.Addresses.Select(add => new AddressDto { Id = add.Id, Code = add.Code, Title = add.Title, UserId = add.UserId, UserName = add.User.Name }));
            }

            Console.WriteLine($"Normal Select {DateTimeOffset.UtcNow}");
            using (AppDbContext db = new AppDbContext())
            {
                db.Database.ExecuteSqlCommand("DBCC DROPCLEANBUFFERS");
                Stopwatch watch = Stopwatch.StartNew();
                List<AddressDto> addresses = db.Addresses.AsNoTracking().Select(add => new AddressDto { Id = add.Id, Code = add.Code, Title = add.Title, UserId = add.UserId, UserName = add.User.Name }).ToList();
                List<AddressDto> addresses2 = db.Addresses.AsNoTracking().Select(add => new AddressDto { Id = add.Id, Code = add.Code, Title = add.Title, UserId = add.UserId, UserName = add.User.Name }).ToList();
                watch.Stop();
                Console.WriteLine($"{watch.ElapsedMilliseconds} {addresses.Count} {addresses2.Count}");
            }

            Console.WriteLine($"AutoMapper Exec {DateTimeOffset.UtcNow}");
            using (AppDbContext db = new AppDbContext())
            {
                db.Database.ExecuteSqlCommand("DBCC DROPCLEANBUFFERS");
                Stopwatch watch = Stopwatch.StartNew();
                List<AddressDto> addresses = db.Addresses.AsNoTracking().ProjectTo<AddressDto>().ToList();
                List<AddressDto> addresses2 = db.Addresses.AsNoTracking().ProjectTo<AddressDto>().ToList();
                watch.Stop();
                Console.WriteLine($"{watch.ElapsedMilliseconds} {addresses.Count} {addresses2.Count}");
            }

            Console.ReadKey();
        }
    }
}
نکته: از دستور DBCC DROPCLEANBUFFERS جهت خالی کردن بافر sql server برای رسیدن به نتیجه‌ی هرچه دقیق‌تر استفاده شده است.
بعد از اجرا کردن، ابتدا بررسی میکنیم که کوئری اجرا شده‌ی دو نوع مختلف، هیچ تفاوتی با هم نداشته باشند.


حال نتایج بدست آمده، در قسمت پایین‌تر آن نمایان میشود:


البته نتیجه‌ی این آزمایش بسته به سخت افزار سیستم شما ممکن است کمی متفاوت باشد.

در سه آزمایش دیگر به صورت متوالی نتیجه‌ی زیر بدست آمد:

Normal   AutoMapper
 2451  2378
 2120  2111
 2202  2124

اگر این مقدار جزئی از تفاوت بین دو نوع مختلف آزمایش را مورد نظر نگیریم، میتوان گفت که هر دو روش نتیجه‌ی کاملا یکسانی خواهند داشت. فقط با استفاده از AutoMapper کد‌های کمتری نوشته شده‌است!

اما دلیل چیست؟ از آنجایی که ProjectTo از Dto به Model انجام شده و Lambda Expressionی که به سمت Entity Framework فرستاده شده‌است با روش Normal کاملا برابر است و بقیه‌ی عملیات توسط EF انجام میشود، با قاطعیت میتوان گفت که هر دو روش ذکر شده از نظر Performance کاملا یکسان خواهند بود.

نکته: البته به این موضوع باید توجه شود که اگر همین آزمایش را بطور مثال با استفاده از یک Listی از رکورد‌های درون Memory ساخته شده توسط خودمان انجام دهیم، آن موقع نتیجه‌ی یکسانی نخواهیم داشت، به دلیل اینکه EFی دیگر وجود نخواهد داشت که مسئولیت بازگشت داده‌ها را بر عهده بگیرد. از آنجائیکه اکثر کارهایی که توقع داریم AutoMapper برای ما انجام دهد، توسط ORM بازگشت داده میشود، پس میتوان گفت نکته‌ی فوق تقریبا در دنیای واقعی رخ نخواهد داد و باعث مشکل نخواهد شد.

اشتراک‌ها
کار با بیت و بایت‌ها در #C

Bit hacks are an incredibly powerful tool in every developer's toolbox. When used correctly, they can bring simplicity, performance, scalability, and even be used for compact data representation in probabilistic Data Structures. 

کار با بیت و بایت‌ها در #C
اشتراک‌ها
Visual Studio 2019 version 16.11.4 منتشر شد
حجم تقریبی آپدیت از نسخه قبلی (16.11.3) حدود 1.11G میشه.
  • Windows 11 SDK support.
  • Adds Xcode 13.0 support.
  • Add AMD64 math functions to ARM64X CRT.
  • Updates to the ARM64 and ARM64EC interfaces between the binary and the POGO instrumentation runtime.
  • Fixed several problems with IntelliSense responsiveness and correctness affecting C++20 concepts, ranges, and abbreviated function templates.
  • Fixed a false positive in local lifetime checks.
  • Corrected an issue where arrays allocated with a constant of size > 32bits could allocate less memory than requested.
  • Ensures that ATL string initialization occurs during static variable initialization, in the default AppDomain.
  • Fixed a bug in C++ Concurrency::parallel_for_each that was crashing the calling process due to integer overflow.
  • Fixed a bug in the STL's iterator debugging machinery that could cause crashes in multithreaded programs using STL containers.
  • We have fixed a fatal internal compiler error caused by unnamed structs whose fields are referenced from SAL annotations.
  • Fixes a rare crash when analyzing templated code that uses __uuidof.
  • Fixed an issue that caused C++ static analysis results to sometimes not display correctly in the FixIt action.
  • Fixed opening .uitest extension files in Coded UI project
  • Fire component change events for non-component objects also in WinForms .NET designer
  • Fix for crash on deleting ContextMenuStrip control in Windows Forms .NET designer.
  • Guard against crashes when the Windows Forms designer reloads when dragging.
  • Fix for intermittent VS crash while interacting with WinForms .NET designer during solution or project rebuild.
  • Fixed a bug causing .NET 5 projects to be reported as out of date when they should have been up to date, causing slower builds.
  • Automatically disable asset-indexing for large scale Unity projects.
  • This release fixes an issue with deploying certain Windows Application Packaging projects where deployment is unnecessarily copying unmodified files. 
Visual Studio 2019 version 16.11.4 منتشر شد
اشتراک‌ها
پیاده سازی یک Filter سفارشی برای نگاشت استثنای همزمانی به خطاهای MadelState
 public class HandleConcurrencyExceptionAttribute : FilterAttribute, IExceptionFilter
    {
        private PropertyMatchingMode _propertyMatchingMode;
        /// <summary>
        /// This defines when the concurrencyexception happens, 
        /// </summary>
        public enum PropertyMatchingMode
        {
            /// <summary>
            /// Uses only the field names in the model to check against the entity. This option is best when you are using 
            /// View Models with limited fields as opposed to an entity that has many fields. The ViewModel (or model) field names will
            /// be used to check current posted values vs. db values on the entity itself.
            /// </summary>
            UseViewModelNamesToCheckEntity = 0,
            /// <summary>
            /// Use any non-matching value fields on the entity (except timestamp fields) to add errors to the ModelState.
            /// </summary>
            UseEntityFieldsOnly = 1,
            /// <summary>
            /// Tells the filter to not attempt to add field differences to the model state.
            /// This means the end user will not see the specifics of which fields caused issues
            /// </summary>
            DontDisplayFieldClashes = 2
        }


        public HandleConcurrencyExceptionAttribute()
        {
            _propertyMatchingMode = PropertyMatchingMode.UseViewModelNamesToCheckEntity;
        }

        public HandleConcurrencyExceptionAttribute(PropertyMatchingMode propertyMatchingMode)
        {
            _propertyMatchingMode = propertyMatchingMode;
        }


        /// <summary>
        /// The main method, called by the mvc runtime when an exception has occured.
        /// This must be added as a global filter, or as an attribute on a class or action method.
        /// </summary>
        /// <param name="filterContext"></param>
        public void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled && filterContext.Exception is DbUpdateConcurrencyException)
            {
                //Get original and current entity values
                DbUpdateConcurrencyException ex = (DbUpdateConcurrencyException)filterContext.Exception;
                var entry = ex.Entries.Single();
                //problems with ef4.1/4.2 here because of context/model in different projects.
                //var databaseValues = entry.CurrentValues.Clone().ToObject();
                //var clientValues = entry.Entity;
                //So - if using EF 4.1/4.2 you may use this workaround
                var clientValues = entry.CurrentValues.Clone().ToObject();
                entry.Reload();
                var databaseValues = entry.CurrentValues.ToObject();

                List<string> propertyNames;

                filterContext.Controller.ViewData.ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                        + "was modified by another user after you got the original value. The "
                        + "edit operation was canceled and the current values in the database "
                        + "have been displayed. If you still want to edit this record, click "
                        + "the Save button again to cause your changes to be the current saved values.");
                PropertyInfo[] entityFromDbProperties = databaseValues.GetType().GetProperties(BindingFlags.FlattenHierarchy | BindingFlags.Public | BindingFlags.Instance);

                if (_propertyMatchingMode == PropertyMatchingMode.UseViewModelNamesToCheckEntity)
                {
                    //We dont have access to the model here on an exception. Get the field names from modelstate:
                    propertyNames = filterContext.Controller.ViewData.ModelState.Keys.ToList();
                }
                else if (_propertyMatchingMode == PropertyMatchingMode.UseEntityFieldsOnly)
                {
                    propertyNames = databaseValues.GetType().GetProperties(BindingFlags.Public).Select(o => o.Name).ToList();
                }
                else
                {
                    filterContext.ExceptionHandled = true;
                    UpdateTimestampField(filterContext, entityFromDbProperties, databaseValues);
                    filterContext.Result = new ViewResult() { ViewData = filterContext.Controller.ViewData };
                    return;
                }



                UpdateTimestampField(filterContext, entityFromDbProperties, databaseValues);

                //Get all public properties of the entity that have names matching those in our modelstate.
                foreach (var propertyInfo in entityFromDbProperties)
                {

                    //If this value is not in the ModelState values, don't compare it as we don't want
                    //to attempt to emit model errors for fields that don't exist.

                    //Compare db value to the current value from the entity we posted.

                    if (propertyNames.Contains(propertyInfo.Name))
                    {
                        if (propertyInfo.GetValue(databaseValues, null) != propertyInfo.GetValue(clientValues, null))
                        {
                            var currentValue = propertyInfo.GetValue(databaseValues, null);
                            if (currentValue == null || string.IsNullOrEmpty(currentValue.ToString()))
                            {
                                currentValue = "Empty";
                            }

                            filterContext.Controller.ViewData.ModelState.AddModelError(propertyInfo.Name, "Current value: "
                                 + currentValue);
                        }
                    }

                    //TODO: hmm.... how can we only check values applicable to the model/modelstate rather than the entity we saved?
                    //The problem here is we may only have a few fields used in the viewmodel, but many in the entity
                    //so we could have a problem here with that.
                    //object o = propertyInfo.GetValue(myObject, null);
                }

                filterContext.ExceptionHandled = true;

                filterContext.Result = new ViewResult() { ViewData = filterContext.Controller.ViewData };
            }
        }
پیاده سازی یک Filter سفارشی برای نگاشت استثنای همزمانی به خطاهای MadelState
مطالب
نکته‌ای مهم در طراحی قالب‌ برنامه‌های Silverlight

قالب سیلورلایتی را ایجاد کرده بودم و IE در حالت نمایش عادی این قالب 30 درصد CPU Usage ثابت داشت. علت را هم متوجه نمی‌شدم؛ چون در این حالت اصلا کدی وجود نداشت که بخواهد CPU Usage ایی را ایجاد کند. یک سری کد XAML جهت نمایش قالب در کنار هم قرار گرفته بودند و همین.
تا اینکه دیروز در وبلاگ رسمی مرتبط با کارآیی برنامه‌های Silverlight مطلبی منتشر شد که دقیقا مشکل طراحی قالب من هم همان بود:

خلاصه آن:
اگر در حالت نمایش برنامه Silverlight شما (بدون اینکه کدی در حال اجرا باشد) به صورت ثابت CPU Usage بالایی را مشاهده می‌کنید، پارامتر enableRedrawRegions تگ بارگذاری افزونه‌ی Silverlight را به true مقدار دهی کنید.
<object data="data:application/x-silverlight-2," type="application/x-silverlight-2">
...
<param name="enableRedrawRegions" value="true"/>
...
</object>

پس از فعال سازی این گزینه، برنامه را اجرا کنید. نواحی را که مرتبا در حال ترسیم مجدد هستند، با رنگ‌های آبی، زرد و صورتی مشاهده خواهید کرد.
در این حالت اگر ناحیه‌ای مرتبا در حال به روز رسانی مشاهده گردید، دقیقا همین ناحیه است که سبب CPU Usage بالا و ثابت برنامه شما شده است و باید فکری به حال آن کرد.

چه زمانی ممکن است این حالت (ترسیم‌های مجدد بدون پایان) رخ دهد؟
عموما این مشکل در حین استفاده ناصحیح از افکت‌های پیش فرض Silverlight مانند DropShadowEffect رخ می‌دهد. برای مثال می‌خواهید قسمتی از قالب شما سایه دار باشد اما نحوه‌ی اعمال این سایه بسیار مهم است.
        <Border CornerRadius="3">
<!--High cpu usage-->
<Border.Effect>
<DropShadowEffect BlurRadius="7" Color="#FF1E2224" Opacity="3" ShadowDepth="6" Direction="200" />
</Border.Effect>
<StackPanel>
...
...

در این مثال ابتدا یک border تعریف شده و سپس سایه‌ای به آن اعمال گردیده است. سپس داخل این Border یک StackPanel قرار گرفته است به همراه یک سری از اشیاء زیر مجموعه آن. این کار غلط است! همین مورد به ظاهر ساده 30 درصد CPU Usage ثابت را در برنامه ایجاد کرده بود.

علت چیست؟
با این نحوه‌‌ی تعریف اشتباه DropShadowEffect ، هر نوع تغییر بصری در مجموعه‌ی Border و StackPanel داخل آن، سبب ترسیم مجدد کل ناحیه می‌گردد. این تغییر بصری حتی می‌تواند شامل چشمک زدن یک cursor درون یک TextBox در قسمتی از این ناحیه نیز باشد که با استفاده از ویژگی enableRedrawRegions ، این مورد را به خوبی می‌توان مشاهده نمود.

راه حل این مساله کدام است؟
از دو Border استفاده کنید. یک Border با ضخامت کم تنها برای نمایش سایه (که دارای هیچ نوع شیء فرزندی نیست) و Border و StackPanel قبلی هم به همان صورت ابتدایی (البته با حذف DropShadowEffect از آن) باقی بماند.

اشتراک‌ها
کارآیی JavaScript بر روی گوشی‌های اندرویدی، 7 برابر کمتر از نمونه‌ی iOS ای است

This is just terrible for the web. When there's a 7x difference between the JS performance on a BRAND NEW PIXEL and a new iPhone, web app makers just have to approach the whole game differentially. I mean, the Pixel 5 is FIVE YEARS behind the performance game. 

کارآیی JavaScript بر روی گوشی‌های اندرویدی، 7 برابر کمتر از نمونه‌ی iOS ای است
اشتراک‌ها
چک لیست امنیتی برنامه های مبتنی بر Blazor
  • Validate arguments from events.
  • Validate inputs and results from JS interop calls.
  • Avoid using (or validate beforehand) user input for .NET to JS interop calls.
  • Prevent the client from allocating an unbound amount of memory.
    • Data within the component.
    • DotNetObject references returned to the client.
  • Guard against multiple dispatches.
  • Cancel long-running operations when the component is disposed.
  • Avoid events that produce large amounts of data.
  • Avoid using user input as part of calls to NavigationManager.NavigateTo and validate user input for URLs against a set of allowed origins first if unavoidable.
  • Don't make authorization decisions based on the state of the UI but only from component state.
  • Consider using Content Security Policy (CSP) to protect against XSS attacks.
  • Consider using CSP and X-Frame-Options to protect against click-jacking.
  • Ensure CORS settings are appropriate when enabling CORS or explicitly disable CORS for Blazor apps.
  • Test to ensure that the server-side limits for the Blazor app provide an acceptable user experience without unacceptable levels of risk. 
چک لیست امنیتی برنامه های مبتنی بر Blazor