مطالب
پیاده سازی CQRS توسط MediatR - قسمت چهارم
در این قسمت قصد داریم به بررسی Behavior‌ ها در فریمورک MediatR بپردازیم. کدهای این قسمت به‌روزرسانی و از این ریپازیتوری قابل دسترسی است.

با استفاده از Behavior‌ها امکان پیاده سازی AOP را براحتی خواهید داشت. Behavior‌ها، مانند Filter‌‌ ها در ASP.NET MVC هستند. همانطور که با استفاده از متدهای OnActionExecuting و OnActionExecuted میتوانستیم اعمالی را قبل و بعد از اجرای یک اکشن‌متد انجام دهیم، چنین قابلیتی را با Behavior‌ها در MediatR نیز خواهیم داشت. مزیت اینکار این است که شما میتوانید کدهای Cross-Cutting-Concern خود را یکبار نوشته و چندین بار بدون تکرار مجدد، از آن استفاده کنید.


Performance Counter Behavior

فرض کنید میخواهید زمان انجام کار یک متد را اندازه گیری کرده و در صورت طولانی بودن زمان انجام آن، لاگی را مبنی بر کند بودن بیش از حد مجاز این متد، ثبت کنید. شاید اولین راهی که برای انجام اینکار به ذهنتان بیاید این باشد که داخل تمام متدهایی که میخواهیم زمان انجام آنها را  محاسبه کنیم، چنین کدی را تکرار کنیم:
public class SomeClass
{
    private readonly ILogger _logger;

    public SomeClass(ILogger logger)
    {
        _logger = logger;
    }

    public void SomeMethod()
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        // TODO: Do some work here

        stopwatch.Stop();

        if (stopwatch.ElapsedMilliseconds > TimeSpan.FromSeconds(5).Milliseconds)
        {
            // This method has taken a long time, So we log that to check it later.
            _logger.LogWarning($"SomeClass.SomeMethod has taken {stopwatch.ElapsedMilliseconds} to run completely !");
        }
    }
}
در این صورت تمام متدهایی که نیاز به محاسبه زمان پردازش را دارند، باید به کلاسشان Logger تزریق شود. Stopwatch باید ایجاد، Start و Stop شود و در نهایت، بررسی کنیم که آیا زمان انجام این متد از حداکثری که برای آن مشخص کرده‌ایم گذشته است یا خیر.

علاوه بر این تصور کنید روزی تصمیم بگیرید که حداکثر زمان برای Log کردن را از 5 ثانیه به 10 ثانیه تغییر دهید. در این صورت بدلیل اینکه در همه متدها این قطعه کد تکرار شده‌است، مجبور به تغییر تمام کدهای برنامه برای اصلاح این بخش خواهید شد. در اینجا اصل DRY نقض شده‌است.

 

برای حل این مشکل از Behavior‌ها استفاده میکنیم. برای پیاده سازی Behavior‌ها داخل MediatR، کافیست از interface ای بنام IPipelineBehavior ارث بری کنیم:
public class RequestPerformanceBehavior<TRequest, TResponse> :
    IPipelineBehavior<TRequest, TResponse>
{
    private readonly ILogger<RequestPerformanceBehavior<TRequest, TResponse>> _logger;

    public RequestPerformanceBehavior(ILogger<RequestPerformanceBehavior<TRequest, TResponse>> logger)
    {
        _logger = logger;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        Stopwatch stopwatch = new Stopwatch();
        stopwatch.Start();

        TResponse response = await next();

        stopwatch.Stop();

        if (stopwatch.ElapsedMilliseconds > TimeSpan.FromSeconds(5).Milliseconds)
        {
            // This method has taken a long time, So we log that to check it later.
            _logger.LogWarning($"{request} has taken {stopwatch.ElapsedMilliseconds} to run completely !");
        }

        return response;
    }
}
همانطور که میبینید منطق کد ما تغییری نکرده‌است. از IPipelineBehavior ارث بری کرده و متد Handle آن را پیاده سازی کرده‌ایم. همانند Middleware‌ ها در ASP.NET Core، در اینجا نیز یک RequestHandlerDelegate بنام next داریم که با اجرا و return آن، روند اجرای بقیه Command/Query‌ها ادامه پیدا خواهد کرد.

سپس باید Behavior‌های خود را از طریق DI به MediatR معرفی کنیم. داخل Startup.cs به این صورت RequestPerformanceBehavior خود را Register میکنیم:
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(RequestPerformanceBehavior<,>));

در نهایت برای تست کارکرد این Behavior، در کوئری GetCustomerByIdQueryHandler خود 5 ثانیه Delay ایجاد میکنیم تا طول اجرای آن، از Maximum زمان مشخص شده بیشتر و Log انجام شود:
public class GetCustomerByIdQueryHandler : IRequestHandler<GetCustomerByIdQuery, CustomerDto>
{
    private readonly ApplicationDbContext _context;
    private readonly IMapper _mapper;

    public GetCustomerByIdQueryHandler(ApplicationDbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    public async Task<CustomerDto> Handle(GetCustomerByIdQuery request, CancellationToken cancellationToken)
    {
        Customer customer = await _context.Customers
            .FindAsync(request.CustomerId);

        if (customer == null)
        {
            throw new RestException(HttpStatusCode.NotFound, "Customer with given ID is not found.");
        }

        // For testing PerformanceBehavior
        await Task.Delay(5000, cancellationToken);

        return _mapper.Map<CustomerDto>(customer);
    }
}

پس از اجرای برنامه و فراخوانی GetCustomerById ، داخل Console این پیغام را خواهید دید:



Transaction Behavior


یکی دیگر از استفاده‌های Behavior‌ها میتواند پیاده سازی Transaction و Rollback باشد. فرض کنید میخواهیم افزودن یک مشتری به دیتابیس فقط زمانی صورت گیرد که تمام کارهای داخل Command با موفقیت و بدون رخ دادن Exception انجام شود. برای انجام اینکار میتوان یک TransactionBehavior نوشت تا بدنه Command‌ها را داخل یک TransactionScope قرار دهد و در صورت وقوع Exception ، عمل Rollback صورت گیرد :
public class TransactionBehavior<TRequest, TResponse> :
    IPipelineBehavior<TRequest, TResponse>
{
    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var transactionOptions = new TransactionOptions
        {
            IsolationLevel = IsolationLevel.ReadCommitted,
            Timeout = TransactionManager.MaximumTimeout
        };

        using (var transaction = new TransactionScope(TransactionScopeOption.Required, transactionOptions,
            TransactionScopeAsyncFlowOption.Enabled))
        {
            TResponse response = await next();

            transaction.Complete();

            return response;
        }
    }
}

سپس این Behavior را داخل DI Container خود Register میکنیم :
services.AddScoped(typeof(IPipelineBehavior<,>), typeof(TransactionBehavior<,>));

در نهایت متد Handle در CreateCustomerCommandHandler را که در قسمت‌های قبل ایجاد کردیم، تغییر داده و بعد از SaveChanges مربوط به Entity Framework، یک Exception را صادر میکنیم:
public class CreateCustomerCommandHandler : IRequestHandler<CreateCustomerCommand, CustomerDto>
{
    readonly ApplicationDbContext _context;
    readonly IMapper _mapper;
    readonly IMediator _mediator;

    public CreateCustomerCommandHandler(ApplicationDbContext context,
        IMapper mapper,
        IMediator mediator)
    {
        _context = context;
        _mapper = mapper;
        _mediator = mediator;
    }

    public async Task<CustomerDto> Handle(CreateCustomerCommand createCustomerCommand, CancellationToken cancellationToken)
    {
        Domain.Customer customer = _mapper.Map<Domain.Customer>(createCustomerCommand);

        await _context.Customers.AddAsync(customer, cancellationToken);
        await _context.SaveChangesAsync(cancellationToken);

        throw new Exception("======= MY CUSTOM EXCEPTION =======");

        // Raising Event ...
        await _mediator.Publish(new CustomerCreatedEvent(customer.FirstName, customer.LastName, customer.RegistrationDate), cancellationToken);

        return _mapper.Map<CustomerDto>(customer);
    }
}

اگر برنامه را اجرا کنید خواهید دید با اینکه Exception ما بعد از SaveChanges رخ داده است، اما بدلیل استفاده از Transaction Behavior ای که نوشتیم، عملیات Rollback صورت گرفته و داخل دیتابیس رکوردی ثبت نشده‌است.

* نکته : قبل از استفاده از Transaction‌ها حتما این مطالب ( 1 , 2 ) را مطالعه کنید.

MediatR دارای 2 اینترفیس IRequestPreProcessor و IRequestPostProcessor نیز هست که اگر نیاز داشته باشید یک عمل فقط قبل یا بعد از انجام یک Command/Query صورت گیرد، میتوانید از آنها استفاده کنید.

همچنین پیاده سازی‌های پیشفرضی از این 2 اینترفیس با نام‌های RequestPreProcessorBehavior و RequestPostProcessorBehavior داخل فریمورک، بطور پیشفرض وجود دارد که قبل و بعد از تمامی Handler‌ها اجرا خواهند شد.
اشتراک‌ها
PostgreSQL 11 منتشر شد

Postgres 11 is out and brings more robustness and performance for partitioning, enhanced capabilities for query parallelism, Just-in-Time (JIT) compilation for expressions, and a couple of more useful or convenient changes. 

PostgreSQL 11 منتشر شد
اشتراک‌ها
Visual Studio 2017 version 15.6.7 منتشر شد
  • VS is more responsive when running Git operations.
  • Debugging large solutions with /debug:fastlink PDBs is more robust. Changes in the PDB/DIA lead to reduced latency and a 30% reduction in heap memory consumption in the VS debugger that used to cause crashes.
  • C++ compiler bugfixes:
    • Fix for the SSA optimizer incorrectly sinking a function call past a store to a variable used in a __finally handler.
    • Fix for the SSA optimizer sometimes incorrectly analyzing memory loads from locations with negative offsets.
    • Fix for the optimizer incorrectly transforming a pre-incremented loop into a post-incremented loop. This was found compiling the ICU project.
  • Microsoft bumped up the Java™ Development Kit 8 to Update 172 (JDK version 8u172). 
Visual Studio 2017 version 15.6.7 منتشر شد
اشتراک‌ها
ده مقاله برتر Visual Studio Magazine از سری "چگونه" در سال 2012
این ده مقاله به شرح زیر می‌باشند:

10) Practical .NET: Powerful JavaScript With Upshot and Knockout
The Microsoft JavaScript Upshot library provides a simplified API for retrieving data from the server and caching it at the client for reuse. Coupled with Knockout, the two JavaScript libraries form the pillars of the Microsoft client-side programming model.

9) On VB: Database Synchronization with the Microsoft Sync Framework
The Microsoft Sync Framework is a highly flexible framework for synchronizing files and data between a client and a master data store. With great flexibility often comes complexity and confusion, however.

8) C# Corner: Performance Tips for Asynchronous Development in C#
Visual Studio Async is a powerful development framework, but it's important to understand how it works to avoid performance hits.

7) 2 Great JavaScript Data-Binding Libraries
JavaScript libraries help you build powerful, data-driven HTML5 apps.

6) On VB: Entity Framework Code-First Migrations
Code First Migrations allow for database changes to be implemented all through code. Through the use of Package Manager Console (PMC), commands can be used to scaffold database changes.

5) C# Corner: The New Read-Only Collections in .NET 4.5
Some practical uses for the long-awaited interfaces, IReadOnlyList and IReadOnlyDictionary, in .NET Framework 4.5.

4) C# Corner: Building a Windows 8 RSS Reader
Eric Vogel walks through a soup-to-nuts demo for building a Metro-style RSS reader.

3) C# Corner: The Build Pattern in .NET
How to separate complex object construction from its representation using the Builder design pattern in C#.

2) Inside Visual Studio 11: A Guided Tour
Visual Studio 2012 (code-named Visual Studio 11 then) is packed with new features to help you be a more efficient, productive developer. Here's your guided tour.

1) HTML5 for ASP.NET Developers
The technologies bundled as HTML5 finally support what developers have been trying to get HTML to do for decades.

 

ده مقاله برتر Visual Studio Magazine از سری "چگونه" در سال 2012
اشتراک‌ها
7.Visual Studio 2017 15.9 منتشر شد

These are the customer-reported issues addressed in 15.9.7:

Security Advisory Notices

7.Visual Studio 2017 15.9 منتشر شد
اشتراک‌ها
انتشار Visual Studio 2022 version 17.6 Preview 1

GitHub Issues

The GitHub Issues integration allows you to search and reference your issues from the commit message box in VS, in response to this suggestion ticket. You can reference an issue or a pull request by typing # or clicking on the # button in the lower right side of the commit message text box. If you weren't already authenticated to access related issues, you will now be prompted to sign in to take advantage of this feature.

Line Unstaging

To continue improving our line-staging (aka interactive staging) feature, we've added unstage. You can now use the tool tip option to unstage changes, line by line, as requested here Unstage individual lines and hunks in a file - 4 votes

Arm64

We continue to build native support for Arm64 on Windows 11 for the most popular developer scenarios. We now support the .NET Multi-platform App UI (MAUI) workload on Arm64 Visual Studio.

C++

  • Available as a preview feature, you can now view Unreal Engine logs without leaving VS. To see the logs from the Unreal Engine Editor, click View > Other Windows > UE Log. To filter your logs, click on the "Categories" or "Verbosity" dropdowns. Since this is an experimental feature, feedback is greatly appreciated.
  • You can now import STM32CubeIDE projects for embedded development within Visual Studio with File > Open > Import STM32CubeIDE project. This generates a CMake project with device flashing and debugging settings for STLink. You must have the STM32CubeIDE installed with the board support package for your device. More details available here.
  • You can use the new CMake Debugger to debug your CMake scripts at build time. You can set breakpoints based on filenames, line numbers, and when CMake errors are triggered. Additionally, you can view call stacks of filenames and watch defined variables. Currently, this only works with bundled CMake, and projects targeting WSL or remote machines are not supported yet. We are actively working to add more support to the CMake debugger, and feedback is greatly appreciated. 
انتشار Visual Studio 2022 version 17.6 Preview 1
اشتراک‌ها
4.Visual Studio 2019 RC منتشر شد
  • Telerik UI for WPF controls disabled in Visual Studio 2019 Preview 3 and Preview 4.
  • Unhandled System.OperationCanceledException.
  • We have updated the Dockerfile scaffolding in Visual Studio Tools for Kubernetes to use the Microsoft Container Registry instead of Docker Hub.
  • We have fixed an issue in Visual Studio Tools for Kubernetes where modifying Dockerfile.develop does not cause the service to be redeployed.
  • We have fixed an issue in Visual Studio Tools for Kubernetes where a service in an Azure Dev Spaces project could fail to start.
  • We have fixed an issue in Visual Studio Tools for Kubernetes where a service in an Azure Dev Spaces project stops running after debugging is stopped in Visual Studio.
  • We have fixed an issue in Visual Studio Tools for Kubernetes where a null reference error dialog is sometimes displayed when picking accounts in the Azure Dev Spaces Dialog.
  • We have fixed an issue in Visual Studio Tools for Kubernetes where the cluster selection dialog is displayed when adding Kubernetes orchestration support. 
4.Visual Studio 2019 RC منتشر شد
اشتراک‌ها
Visual Studio Code 1.34 منتشر شد

Welcome to the April 2019 release of Visual Studio Code. During April, we were busy with the Preview release of the Remote Development extensions. These extensions let you work with VS Code over SSH on a remote machine or VM, in Windows Subsystem for Linux (WSL), or inside a Docker container. 

Visual Studio Code 1.34 منتشر شد