Category - Microsoft-.NET-5

.NET Performance Analysis: Newtonsoft.Json vs System.Text.Json
Jul 23, 2024

In the world of .NET development, handling JSON serialization and deserialization is a common task, especially when dealing with web APIs, configuration files, and data interchange between systems. Two prominent libraries for JSON processing in the .NET ecosystem are Newtonsoft.Json (often referred to simply as Newtonsoft) and System.Text.Json. In this article, we'll compare and contrast these two libraries, exploring their features, examples, advantages, and disadvantages. Newtonsoft.Json Newtonsoft.Json, developed by James Newton-King, has been the go-to library for JSON serialization and deserialization in the .NET ecosystem for many years. It offers a wide range of features and has garnered widespread adoption among developers. Let's explore some of its characteristics:   Features of Newtonsoft.Json   Flexible and Robust: Newtonsoft.Json provides comprehensive support for JSON serialization and deserialization, handling complex object graphs, custom conversions, and nullable types effortlessly. Customization Options: Developers can customize the serialization and deserialization process using attributes, custom converters, and serialization settings, allowing fine-grained control over JSON representation. Widely Adopted: Newtonsoft.Json is battle-tested and widely adopted in the .NET community, with extensive documentation, tutorials, and community support available.   using Newtonsoft.Json; // Serialization string json = JsonConvert.SerializeObject(myObject); // Deserialization MyObject obj = JsonConvert.DeserializeObject<MyObject>(json); System.Text.Json System.Text.Json, introduced in .NET Core 3.0 and later versions, is Microsoft's built-in JSON processing library, aiming to provide a modern, high-performance alternative to Newtonsoft.Json. While it may not offer the same level of features and flexibility as Newtonsoft.Json, it focuses on performance and seamless integration with the .NET ecosystem. Features of System.Text.Json Performance: System.Text.Json is optimized for performance, offering faster serialization and deserialization compared to Newtonsoft.Json in certain scenarios. Built-in Support: It seamlessly integrates with other .NET features such as async/await, streams, and memory management, making it a natural choice for .NET Core and .NET 5+ projects. Minimalistic API: System.Text.Json provides a minimalistic API surface, emphasizing simplicity and ease of use for common scenarios. using System.Text.Json; // Serialization string json = JsonSerializer.Serialize(myObject); // Deserialization MyObject obj = JsonSerializer.Deserialize<MyObject>(json);   Advantages and Disadvantages Newtonsoft.Json Advantages Comprehensive feature set with extensive customization options. Widely adopted with a large community and ecosystem. Mature and battle-tested library. Disadvantages Performance may degrade for large datasets compared to System.Text.Json. Requires additional dependencies for .NET Core and .NET 5+ projects.    System.Text.Json Advantages Optimized for performance, especially in scenarios with large datasets. Built-in support in .NET Core and .NET 5+, eliminating the need for additional dependencies. Seamless integration with other .NET features. Disadvantages Less feature-rich compared to Newtonsoft.Json, lacking some advanced customization options. Limited community support and fewer resources compared to Newtonsoft.Json. [Benchmark] public void NewtonsoftDeserializeIndividualData() { foreach (var user in serializedTestUsersList) { _ = Newtonsoft.Json.JsonConvert.DeserializeObject<User>(user); } } [Benchmark] public void MicrosoftDeserializeIndividualData() { foreach (var user in serializedTestUsersList) { _ = System.Text.Json.JsonSerializer.Deserialize<User>(user); } } Results: Data Method Count Mean  Ratio  Allocated Alloc Ratio Newtonsoft 10000 15.974 ms 1.00 35.5 MB 1.00 Microsoft 10000 8.472 ms 1.00 3.96 MB 1.0      Conclusion In the realm of JSON serialization and deserialization within the .NET landscape, our benchmarks present a compelling case. Despite claims of high performance from Newtonsoft.Json, the results unequivocally demonstrate that Microsoft’s System.Text.Json consistently outperforms its counterpart. Whether handling large or small datasets, System.Text.Json showcases superior speed and memory efficiency.

Dependency Injection with Example
Jun 12, 2024

What is the Dependency Injection Design Pattern? Dependency Injection is a design pattern used to execute Inversion of control (IoC). It is a process of injecting the dependency object into a class that depends on it. Dependency Injection is the often-used design pattern these days to separate the dependencies between the objects that allow us to implement loosely coupled software components. It allows the making of dependent objects outside of the class and supplies those objects to a class in distinct ways. Let’s talk about the bit-by-bit process to implement dependency Injection in the ASP.Net Core application. The ASP.NET Core Framework provides inbuilt support for Dependency Injection design patterns. It injects the dependency objects to a class via a constructor, method, or property using the built-in IoC container. The inbuilt IoC container is elected by IServiceProvider implementation, which supports default construction injection. The classes managed by built-in IoC Containers are called services.   Types of Services in ASP.NET Core There are 2 types of services in ASP.NET core. Framework Services: Services that are a part of the ASP.NET core framework, like IApplicationBuilder, IHostingEnvironment, ILoggerFactory, etc. Application Services: The services you create as a programmer for your application. Before registering services, let’s first know the different methods to register a service. The ASP.NET core gives 3 methods to register a service with a Dependency Injection container. The method that we use to register a service will determine the lifetime of the service. Singleton: A Singleton service is created only once per application lifetime. The same instance is used all over the application. Common uses contain configuration services, logging, or other services where a single instance is enough and advisable. Since the same instance is used throughout, you need to ensure that Singleton services are thread-safe. Not suitable for saving user-specific data or request-specific data. This can be reached by adding the service as a singleton through the AddSingleton method of the IServiceCollection. Transient: A Transient service is created every time it is requested from the service container. This means that a new instance is provided to every class or method that requires it. Suitable for lightweight, stateless services. Since a new instance is created every time, you don’t need to worry about thread safety related to the internal state. While transient services are simple and provide clean separation, they can be more resource-intensive if they are vast or require significant resources to build. This can be got by adding the service through the AddTransient method of the IServiceCollection. Scoped: A scoped service is created once per client request (means per HTTP request). Perfect for services that need to maintain state within a single request but should not be shared across different requests. This can be achieved by adding the service through the AddScoped method of the IServiceCollection.   How to Register a Service with ASP.NET Core Dependency Injection Container? We need to register a service to the in-built dependency injection container with the program class.  The below code shows how to register a service with different lifetimes. var builder = WebApplication.CreateBuilder(args); // ADD FRAMEWORK MVC SERVICES TO THE CONTAINER builder.Services.AddMvc(); // ADD APPLICATION SERVICES TO THE CONTAINER builder.Services.Add(new ServiceDescriptor(typeof(ISubjectTypesDA), new SubjectTypesDA())); // BY DEFAULT SINGLETON builder.Services.Add(new ServiceDescriptor(typeof(ISubjectTypesDA), new SubjectTypesDA(),ServiceLifetime.Singleton)); // SINGLETON builder.Services.Add(new ServiceDescriptor(typeof(ISubjectTypesDA), new SubjectTypesDA(),ServiceLifetime.Transient)); // TRANSIENT builder.Services.Add(new ServiceDescriptor(typeof(ISubjectTypesDA), new SubjectTypesDA(),ServiceLifetime.Scoped)); // SCOPED   What is the ServiceDescriptor class in .NET Core? This class speaks for a descriptor of a service in the DI Container. It essentially describes how to service should be instantiated and managed by the container. So, it describes a service, including its lifetime, the service type, and the implementation type. Extension methods for Registration ASP.NET Core framework contains extension methods for each type of lifetime: AddSingleton, AddTransient, and AddScoped methods.  The below example shows how to register types of lifetimes using extension methods. // ADD APPLICATION SERVICE TO THE CONTAINER. services.AddTransient<IEmailSenderBL, EmailSenderBL>(); // TRANSIENT services.AddScoped<ISubjectTypesBL, SubjectTypesBL>(); // SCOPED services.AddSingleton<ICPCalculationBL, CPCalculationBL>(); // SINGLETON   The dependent class is a class which depends on the dependency class. The dependency class is a class that provides service to the dependent class. The interface injects the dependency class object into the dependent class.   There are 3 types of Dependency Injection. Constructor Injection Property Injection Method Injection   Constructor Injection: we register the service, the IoC automatically executes constructor injection if a service type is included as a parameter in a constructor. Example: public class CenterController : BaseController { private ICenterBL _centerBL; public CenterController(ICenterBL centerBL) : base(myLoginUser) { _centerBL = centerBL; } [Authorize] public IActionResult Index() { try { var data = _centerBL.GetCenterpageList(); return View(data); } catch (Exception EX) { throw EX; } } }   Property Injection: Not required to add dependency services in the constructor. We can manually access the services configured with built-in IoC containers using the RequestServices property of HttpContext.   public class AddressController : Controller { [Authorize] public IActionResult Index() { var services = this.HttpContext.RequestServices; IAddressBL _address = (IAddressBL)services.GetService(typeof(IAddressBL)); var data = _address.GetAddressList(); return View(data); } }   Method Injection: Occasionally, we may only need a dependency object in a single action method. In that case, we need to use the [FromServices] attribute with the service type parameter in the action method. In the below example, you can see we are using the [FromServices] attribute within the Index action method. So, at runtime, the IoC Container will inject the dependency object to the IAddressBL repository reference variable. As we inject the dependency object through a method, it is called method dependency injection. public class CommonController: Controller { public IActionResult Index([FromServices] IAddressBL _addressBL) { var list = _addressBL.GetAddressList(); return View(list); } } Advantages of Dependency Injection Loose Coupling: we can separate our classes from their dependencies. This results in code that is simpler to maintain and test. Testability: we can increase the testability of our code since we can easily replace dependencies with mock objects during unit testing. Extensibility: enhance the extensibility of our code by offering the flexibility to switch out dependencies conveniently. Reusability: makes our code more reusable since we can conveniently share dependencies among various classes.  

Facebook Authentication Setup in ASP.NET
Mar 18, 2024

Introduction: Integrating Facebook authentication into your .NET project offers a user-friendly login option, allowing users to sign in with their Facebook credentials. This guide will walk you through the steps to implement Facebook login, enhancing user convenience, trust, and providing access to user data. Creating a Demo for Facebook Authentication in .NET Step 1: Set Up .NET Project  1. Create a new ASP.NET MVC project using Visual Studio or your preferred IDE.  Step 2: Create Facebook Developer App  2. Go to the [Facebook Developer Portal] : https://developers.facebook.com/ 3. Create a new app.  4. Configure the app details and obtain the App ID and App Secret.     Step 3: Configure Facebook Authentication in .NET Project  5. In your .NET project, open `Startup.cs`.  6. Configure Facebook authentication:  services.AddAuthentication(options =>     {         options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;         options.DefaultChallengeScheme = FacebookDefaults.AuthenticationScheme;     })    .AddCookie()     .AddFacebook(options =>     {         options.AppId = "Your-Facebook-App-ID";         options.AppSecret = "Your-Facebook-App-Secret";         options.CallbackPath = new PathString("/Auth/FacebookCallback");    });  Step 4: Create AuthController  7. Create an `AuthController` with actions for Facebook login and callback:  public class AuthController : Controller     {         public IActionResult Index()         {             return View();         }         [HttpGet]         [Route("signin-facebook")]         public async Task<IActionResult> FacebookCallback()         {             var result = await HttpContext.AuthenticateAsync("Facebook");             if (result.Succeeded)             {                 // Authentication succeeded. Add your logic here.                 return RedirectToAction("Index", "Home");             }             // Authentication failed. Handle the error.             return RedirectToAction("Login", "Account");         }         public IActionResult FacebookLogin()         {             var properties = new AuthenticationProperties             {                 RedirectUri = Url.Action("https://localhost:7135/Auth/FacebookCallback"),             };              return Challenge(properties, FacebookDefaults.AuthenticationScheme);         }     }  Step 5: Implement Facebook Login Button  8. In your `Index.cshtml` or another appropriate view, add a button for Facebook login: <h1>Facebook Authentication</h1>  <button class="btn btn-primary"><a style="color:white" asp-controller="Auth" asp-action="FacebookLogin">Login with Facebook</a></button>  Step 6: Update App Settings  9. In the Facebook Developer Portal, update the "Valid OAuth Redirect URIs" with `https://localhost:7135/Auth/FacebookCallback`.    Login Facebook > Settings. Step 7: Run and Test  10. Run your .NET project and test the Facebook authentication by clicking the "Login with Facebook" button.      Click on Login with Facebook > Continue. You can create Successful login in redirect logic. You Can also use JavaScript SDK to use authenticate in Your project I n our case will use MVC    Here will use the same app we already create just we will Update the controller action to JS function provided by "Meta Developer" Quick Start Add this JavaScript code in your view where your login button is available  <button class="btn btn-primary"><a style="color:white" onclick="loginWithFacebook()">Login with Facebook</button> <script> window.fbAsyncInit = function () { FB.init({ appId: '1438230313570431', xfbml: true, version: 'v19.0' }); FB.AppEvents.logPageView(); }; (function (d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) { return; } js = d.createElement(s); js.id = id; js.src = "https://connect.facebook.net/en_US/sdk.js"; fjs.parentNode.insertBefore(js, fjs); }(document, 'script', 'facebook-jssdk')); function loginWithFacebook() { FB.login(function (response) { if (response.authResponse) { // User is logged in and authorized your app console.log('Successful login for: ' + response.authResponse.userID); console.log(response); debugger; window.location = "https://localhost:44304/Auth/SuccesfullLogin"; } else { // User cancelled login or did not authorize your app console.log('Login cancelled'); } }, { scope: 'public_profile,email' }); // Specify the required permissions } </script> Now we Have to add js.src link in your JS functions is need to be Added in Meta developer App In our case it is :   https://connect.facebook.net/en_US/sdk.js will go to again Use cases > customize > settings.  Will add our link in "Allowed Domains for the JavaScript SDK" section Make sure "Login with the JavaScript SDK" toggle is "Yes". Now, you have a comprehensive guide for creating a demo on Facebook authentication in a .NET project. Share this guide, and users can follow each step to implement Facebook login functionality in their ASP.NET applications. 

Simplified Swagger Integration in .NET Core
Feb 22, 2024

Introduction: In the realm of modern APIs, the provision of clear and comprehensive documentation plays a pivotal role in facilitating developer adoption and ensuring efficient utilization. Swagger, aligned with the OpenAPI Initiative, stands out as a prominent solution, offering machine-readable documentation and a user-friendly interactive interface. In this guide, we'll delve into the seamless integration of Swagger into your .NET Core API. Step 1: Install the necessary packages Add Swashbuckle.AspNetCore NuGet package to a project: dotnet add package Swashbuckle.AspNetCore Add Swashbuckle.AspNetCore.SwaggerUI NuGet package to a project: dotnet add package Swashbuckle.AspNetCore.SwaggerUI Step 2: Add services in program.cs In the program.cs file, include the following service additions: builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen(); Additionally, add middleware in program.cs to enable Swagger in the development environment:   if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } Step 3: Run the API project and access the Swagger UI at: https://your-api-base-url/swagger Ensure the API project is running, and navigate to the provided URL to explore and interact with the Swagger UI seamlessly. Step 3:  Execute the APIs and test.  

Explore the Exciting Features of .NET 5
Jul 06, 2020

Microsoft Announces .NET 5 Microsoft announces that the next release after .Net core 3.0 will be .NET 5. .NET 5 will be the big release in the .NET family. You will able to use it to target Windows, Linux, Android, iOS, macOS, tvOS, watchOS, WebAssembly, and more. Microsoft will introduce new .NET APIs, language features, and runtime capabilities as a part of .NET 5. Microsoft intends to release .NET 5 in November 2020, with the first preview available in the first half of 2020. It will be supported with future updates to Visual Studio 2019, Visual Studio for Mac, and Visual Studio Code. .Net 5 Moves Ahead with .NET Core   .NET Core Functionalities: Cross-platform implementation in any device Support all key platform features for .net core, .Net Framework, xamarin Open-source and community-Oriented Support with future updates to Visual Studio Code, Visual Studio 2019, Command Line Interface, and Visual Studio for Mac. Fast, Scalable and High Performance Side-by-side installation Support for platform-specific features like Windows Forms, & WPF on Windows Smarter Deployment & packages Small projects Files   Three New major supports for developers Java Interoperability will be available on all  Swift and Objective-C Interoperability will be supported  on all multiple operating systems CoreFX will be extended to support static compilation of .Net, smaller footprints, and support for more operating systems.   The Other Highlights Features   Desktop Development with .NET 5 .NET 5 will come up with all key desktop development functionalities and libraries. WPF, Windows Forms, UWP, and xamarin are the four key desktop platforms.   Mobile Development with .NET .Net 5 will continue to build cross-platform mobile apps for Android, iOS, tvOS, macOS, and watchOS platforms using Xamarin.   Runtime and Language with .Net 5 Mono is the original cross-platform implementation of .NET. It started out as an open-source alternative to  .NET Framework and transitioned to targeting mobile devices like Android and iOS devices popular. CoreCLR is runtime used as part of .NET Core. It has been primarily targeted at supporting cloud applications, including the largest services at Microsoft and now is also being used for windows desktop, IOT, and machine learning applications.   Cloud Development with .NET 5 The major functionality of .Net 5 is Azure app Development. With the release of the latest version of .Net, developers will continue to develop software with Azure.   Game Development with .Net 5 Visual studio 2019 and .Net 5 will support utility, a vital part of .Net gaming to develop games for mobile and other gaming platforms. 

magnusminds website loader