Sunday, June 25, 2023

.NET Core - Understanding Scoped, Transient, and Singleton Lifetime

Scoped, Transient, and Singleton Lifetime

Scoped, Transient, and Singleton are three lifetime options available in .NET Core for registering and managing services within the dependency injection container. Understanding these options is crucial for building scalable and maintainable applications. Let's explore each of them:

  1. Transient Lifetime:

    A transient service is created each time it is requested from the dependency injection container. This means a new instance is created for every resolution. Transient services are suitable for lightweight and stateless components that don't require shared state. For instance, if you have a service that performs simple calculations or generates random numbers, using the transient lifetime is appropriate.

    To register a transient service in .NET Core, you can use the 'AddTransient' method during service registration:

    services.AddTransient<ITransientService, TransientService>();

Friday, June 23, 2023

Understanding the Use, Run, and Map Functions for Middleware in .NET Core

use,run and map in .net core

Introduction:

Middleware plays a vital role in handling and processing HTTP requests within a .NET Core application's request pipeline. It enables developers to customize and extend the application's behavior. In this post, we will delve into three crucial functions used for configuring middleware: Use, Run, and Map.



  1. Use:

    The Use function is extensively used when configuring middleware in .NET Core. It allows the addition of middleware components to the request pipeline. This function accepts a delegate or a middleware class as a parameter. The delegate or middleware class is responsible for processing an HTTP request and generating an appropriate response.

    Consider the following example that demonstrates the Use function in adding custom middleware:

    public void Configure(IApplicationBuilder app)
    {
        app.Use(async (context, next) =>
        {
            // Perform some logic before the request reaches the next middleware
            await next.Invoke();
            // Perform some logic after the request has been processed by subsequent middleware
        });
        // Add more middleware components using the Use function if necessary
    }
    

Wednesday, June 21, 2023

Middleware in .NET Core: A Developer's Guide

middleware .net core

Introduction:

Middleware plays a vital role in web development, and having a clear understanding of its concept and implementation is crucial for .NET Core developers. Middleware acts as a bridge between incoming requests and outgoing responses in an application, enabling developers to customize and extend the request-processing pipeline. In this article, we will explore the world of middleware in .NET Core, discussing its significance, usage, and providing practical examples.


Understanding Middleware:

In the context of .NET Core, middleware refers to a software component or a set of components that are executed sequentially to process HTTP requests and responses. It forms a chain of components that intercept requests, perform specific actions, and pass control to the next component in the pipeline. Middleware empowers developers to add, remove, or modify behavior at various stages of request processing without altering the core application code.

Middleware in .NET Core:

In .NET Core, the request pipeline is constructed using middleware components. It comprises a series of middleware components that receive an incoming HTTP request and pass it along until a response is generated. Each middleware component can inspect, modify, or terminate the request pipeline.

Middleware components in .NET Core are represented by classes that implement either the IMiddleware interface or the RequestDelegate delegate. The IMiddleware interface provides a convenient way to encapsulate middleware logic, while the RequestDelegate delegate offers finer control over middleware behavior.

Saturday, May 6, 2023

Default values for lambda expressions - C#12

In C#12, you can now define default values for parameters on lambda expressions. The syntax and rules are the same as adding default values for arguments to any method or local function.For example:

var addWithDefault = (int addTo = 2) => addTo + 1;
addWithDefault(); // 3
addWithDefault(5); // 6

Prior to C# 12 you needed to use a local function or the unwieldy DefaultParameterValue from the System.Runtime.InteropServices namespace to provide a default value for lambda expression parameters.

Using directives for additional types - C#12

C# 12 extends using directive support to any type.Now you can use the using alias directive to alias any type, not just named types. That means you can create semantic aliases for tuple types, array types, pointer types, or other unsafe types. Below are few examples :

using Measurement = (string, int);
using PathOfPoints = int[];
using DatabaseInt = int?;

You can now alias almost any type. You can alias nullable value types, although you cannot alias nullable reference types.

Friday, May 5, 2023

Primary Constructor - C# 12

Primary constructor allows you to add parameters to calss declaration itself and use these values in class body. Promary constructor was introduced for records in C#9. C#12 extends it to all classes and structs.

c sharp primary constructor

Thursday, July 27, 2017

ASP.Net MVC - Multiple Models in Single View - Part2

In last post, we have talked about different approaches to pass the multiple models in single view. We have also looked some of them like Dynamic,View Data and View Bag.

This post is the continuation of previous post. Here we will see the use of ViewModel,Tuple and ViewComponent for passing multiple model in single view . Let's first see what was our problem statement-

Problem Statement

We have two models Student and Course and we need to show the the list of Students and Courses in a single view.

Below are the model definition for Student and Course
public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }       
}

public class Course
{
    public int CourseID { get; set; }
    public string CourseName { get; set; }
}

Solutions to achieve

Here we will see ViewModel,Tuple and ViewComponent to achieve our requirement

1. View Model

ViewModel is a class which contains the properties which are represented in view or represents the data that we want to display on our view.

If we want to create a View where we want to display list of Students and Courses then we will create our View Model (StudentCourseViewModel.cs).

Tuesday, July 25, 2017

ASP.Net MVC - Multiple Models in Single View - Part1

In MVC we cannot use multiple model tag on a view. But Many times we need to pass multiple models from controller to view or we want to show data from multiple model on a view. So In this post we will see the different ways to bind or pass the multiple models to single view.

Problem Statement

Lets suppose we have two models Student and Course and we need to show the the list of Students and Courses in a single view.

Below are the model definition for Student and Course
public class Student
{
    public int StudentID { get; set; }
    public string StudentName { get; set; }       
}

public class Course
{
    public int CourseID { get; set; }
    public string CourseName { get; set; }
}

Below is the Repository class which have two method for returning the list of Students and Courses
public class Repository
{
    public static List<student> GetStudents()
    {
          return new List<student>{ new Student() { StudentID = 1, StudentName = "Manish" },
                 new Student() { StudentID = 2, StudentName = "Prashant" },
                 new Student() { StudentID = 3, StudentName = "Deepak" }
                 };
     }
     public static List<course> GetCourses()
     {
          return new List<course> {
                 new Course () {  CourseID = 1, CourseName = "Chemistry"},
                 new Course () {  CourseID = 2, CourseName = "Physics"},
                 new Course () {  CourseID = 3, CourseName = "Math" },
                 new Course () {  CourseID = 4, CourseName = "Computer Science" }
                 };
     }
}

Thursday, July 13, 2017

Deserialize XML to C# object

In this post we will see the simple approach to deserialize XML to C# object.

Our XML String


string xmlString = "<Students><Student><Id>1</Id><Name>Manish Dubey</Name></Student><Student><Id>2</Id><Name>Pankaj</Name></Student></Students>";

Create our class


public class Student
{
  public int Id { get; set; }
  public string Name { get; set; }
}

Create XML Serializer and StringReader Object


//First argument is type of object and second argument is root attribute of your XML string/source

  XmlSerializer serializer = new XmlSerializer(typeof(List<student>), new XmlRootAttribute("Students"));
  StringReader stringReader = new StringReader(xmlString);

At last, deserialize XMl to C# object


List<student> studentList = (List<student>)serializer.Deserialize(stringReader);

Output

deseralize-xml-to-c#-object
Add caption


Tuesday, October 6, 2015

C# : What is New in C# 6.0?


New features in C#6.0
In this post we will see the newly added features in C# 6.0. In C# 6.0 some very cool features has been added like "Auto-property Enhancements", "Primary Constructors", "Expressions as Function Body", "Use of Static", "Exception Filters", "inline declarations", "nameof Expressions", "Null-conditional Operators", "String interpolation", "Await in catch and finally".





Introduction

Here, you will find nine new cool features of C# 6.0:

  1. Auto-property Enhancements
  2. Parameters on Classes and Structs
  3. Using Static
  4. Exception Filters
  5. Null-conditional Operators
  6. Index Initializers
  7. $ sign
  8. String Interpolation
  9. nameof Expression
  10. Await in catch and finally block

Thursday, August 29, 2013

C#: Difference between “throw” and “throw ex” in C# .Net Exception

In day to day development, we all are very familiar with Exception  handling. We pretty much all know that we should wrap the code which may cause for any error in try/catch block and do something about error like give a error message to end user. Here I am not going to explain about Exception handling in C#. Instead I am going to talk about a particular aspect of Exception  handling, which is "throw" vs "throw ex".

You can also find my other articles related to C#ASP.Net jQuery, Java Script and SQL Server. I am writing this post because I was asked this question recently in a interview and unfortunately I didn't  know the answer. So I am posting this for those guys who uses "throw" and "throw ex" frequently but don't know the differences (not all,some knows).

Difference between “throw” and “throw ex”

Take a look on the below code snippest-
throw ex throw

try
{
   //Code which fails and raise the error
}
catch (Exception ex)
{
   throw ex;
}

try
{
   //Code which fails and raise the error
}
catch (Exception ex)
{
   throw;
}

Tuesday, July 23, 2013

How To- Send DataGridView Data in Email in Window Form Application

In my one post I explained you how to Send Grdiview Data in Email. Here I am going to show you how to send DataGridview content in E-mail in window application.

You can also find my other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

First take a look on the below image.
DataGridView with Data

Monday, June 3, 2013

How To- Import Gmail Contacts in ASP.Net

In this post, I am explaining how can you import the Gmail contacts in your ASP.Net application. For importing Gmail contacts we need some dlls which you can get after download Google Data API and install on your system.

In my previous posts, I explained Export Gridview to PDF in ASP.Net with Image, Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

Create a new web application and add the reference of following dlls in your application.

Monday, May 27, 2013

How To- Export Gridview to PDF in ASP.Net with Image

In one of my previous articles I explained Export Gridview to PDF in ASP.Net . Here, I am explaining how to export Gridview to PDF which has images and pictures in it.

In my previous posts, I explained Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

Exporting Gridview to PDF


For exporting the data, I am using the iTextSharp (third party dll) in this post. Download the iTextSharp .
I have following Table which contains the Image Information like Image Name and Image Path.
Export Gridview to PDF in ASP.Net with Image
For exporting images into PDF we need to convert the ImagePath shown in table into its absolute URl. For example, In the above image-

Tuesday, May 21, 2013

C#- Find Similarity between Two Strings in Percentage

In this post, I am explaining how can you check the similarity between two strings in terms of percentage in  C# ? To check similarity between two strings we have formula by which we can find similarity in %.

In my previous posts, I explained Create Hindi TextBox Using Google Transliteration in ASP.Net, Convert Multipage Tiff file into PDF in ASP.Net using C#, Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

The formula to check the similarity between two strings in % is-

Tuesday, May 14, 2013

How To- Convert Multipage Tiff file into PDF in ASP.Net using C#

Multipage Tiff to PDF
Here, I am explaining how to convert a multipage tiff file into PDF file in C#. Sometimes we have a requirement to convert the multipage tiff file into PDF.I am using the iTextSharp (third party dll) for conversion of multipage tiff file into PDF file.

In my previous posts, I explained Send mail in ASP.Net, Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

Before starting the sample code, First of all download the iTextSharp and add the reference of following dll into your application.
itextsharp.dll

Tuesday, May 7, 2013

How To- Send mail in ASP.Net using C#, VB.Net

Send Mail in C#
This post is basically for freshers or newbies. In application development sometimes we need to send the mail through our application. Here I am explaining how you can send mail in ASP.Net using C#, VB.Net.

In my previous posts, I explained Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

The Microsoft .NET framework provides two namespaces, System.Net and System.Net.Sockets for managed implementation of Internet protocols that applications can use to send or receive data over the Internet.We use the SMTP protocol for sending mail in  C# .

Friday, May 3, 2013

How To- Create Zip FIle in ASP.Net Using C#, VB.Net

Zip File in Asp.Net
Here, I am explaining how to Create a zip file in ASp.Net Using C# and VB.Net. We can easily Create Zip Files Archives using DotNetZip Library.

In my previous posts, I explained Convert DataTable into List, Constructor Chainning in C#, Convert a Generic List to a Datatable, Get Property Names using Reflection in C#Hard drive information using C#Create Directory/Folder using C#Check Internet Connection using C#SQL Server Database BackUp using C# and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

For creating zip file add the reference of  Ionic.Zip.dll in your application and add following namespace-
using Ionic.Zip;
Place one FileUpload control on aspx page and one button to upload files and create zip file in it's Click Event.
Create Zip File in ASP.Net

^ Scroll to Top