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.

Sunday, April 30, 2023

.Net Core- Integrates OpenAI ChatGPT APIs in .Net Core Web Api

ChatGPT is a natural language processing model created as an AI-powered chatbot. It is designed to help customers interface with businesses more efficiently and effectively, providing human-like responses in real-time. The model is trained to recognize the context of customer requests, understand the content of conversations, and generate answers to customer queries.

By integrating ChatGPT with our .Net Core Web Api, we can elevate our aplication’s capabilities and provide users with a more interactive experience.

Here we are going to see the step-by-step integration of OpenAI’s ChatGPT APIs into .Net Core Web API.

Signup for an OpenAI API Key

To use the OpenAI’s ChatGPT APIs in your .Net Core Web Api, the first step is to signup for API Key. Go to OpenAI website and create your account by providing your details like name, email address and password.Once you have created your account, create your API key as shown below-

Its important to keep your API key safe and secure, as it provides access to use OpenAI’s ChatGPT APIs. Once you have your API key, you are ready to move on to the next step.

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


Friday, July 7, 2017

ASP.Net MVC - Custom Model Binding

custom-model-binding
In last article, we have discussed about what is ASP.NET Model binding and saw a basic introduction to the Model Binder. In this post we will see creating Custom Model Binding in ASP.Net MVC with simple example.

Model Binder in ASP.NET MVC

For model binding MVC uses the following types-

IModelBinder interface - This defines methods that are required for a Model Binder, like the BindModelAsync method. This method is responsible for binding a model to some values using ModelBindingContext

IModelBinderProvider interface - This interface contains methods that enables dynamic implementation of model binding for classes which implement the IModelBinder interface. This is used to manage the custom binder for the type of data posted by the end-user in views.

Creating Custom Model Binder

We creating our custom model binder by implementing the IModelBinder and IModelBinderProvider interfaces. Let see how we will do that.

Note :I have used ASP.Net MVC Core project here.All the codes are in ASP.Net MVC Core.

Monday, July 3, 2017

ASP.Net MVC Model Binding

 Model Binding

Model Binding

What is Model Binding?

Model Binding in ASP.Net MVC maps the data from HTTP request to action method parameters. These parameters may be simple types such as string, integer or they may be complex type. It is a great feature as it relieves developer from writing all the type casting and “HTML-Model mapping code”. The Model binder is capable of retrieving the data from HTML form variables, POSTed variables and files, query string parameters and the values added in the routes.


How model binding works?

When MVC receives HTTP request, it routes the request to a specific action method of a controller. It determines which action method is going to execute based on what is in the route data, then it maps values from the HTTP request to action method’s parameter(s). For ex. Consider the below URL-

http://abc.com/books/edit/2

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

Friday, December 13, 2013

How To- Load ASP.Net User Control Dynamically Using jQuery and Ajax

Here in this post, I am going to explain how to dynamically load the Asp.Net user control using jQuery and Ajax. For loading the user control we will use the Web Method on server side and call that web method through Ajax call using jQuery.

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

So, lets start the example. In this example I have used one aspx page name Demo.aspx and one user control to load on the aspx page DemoUserControl.ascx.
ASPX Page

<div style="width:350px">
        <table width="100%">
            <tr>
                <td>
                    <asp:Label ID="lblName" runat="server" Font-Bold="true" Text="Name"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Label ID="lblAge" runat="server" Font-Bold="true" Text="Age"></asp:Label>
                </td>
                <td>
                    <asp:TextBox ID="txtAge" runat="server"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td colspan="2">
                    <asp:Button ID="btnLoadUserControl" runat="server" Text="LoadControl" />
                </td>
            </tr>
        </table>
    </div>
    <fieldset style="width:350px">
        <legend>User Control Content</legend>
        <div id="userControlContent">
        </div>
    </fieldset>

In the above aspx page, there are two TextBoxes for capturing the input and one Button to load the user control and show the enterd value.

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;
}

Wednesday, August 14, 2013

LINQ- Difference between First and FirstOrDefault- First vs FirstOrDefault

In my previous post Single vs SingleOrDefault, we talk about Single and SingleOrDefault method and difference between these methods. In this post we are going to explore two more extension methods First and FirstOrDefault.


You can find some other useful topics and posts here. Below is a chart explaining about First() and FirstOrDefault(). You can easily differentiate these methods from this chart. I have also given examples of each method.

Monday, August 12, 2013

LINQ- Difference between Single and SingleOrDefault- Single vs SingleOrDefault

In today's development, we all are frequently users of LINQ. So In this post and some incoming posts, I will try to explain about some LINQ's extension methods that seems trivial, but can really helpful to improve your code by making it easier.

Here, In this post I am going to explain you about Single and SingleOrDefault method and difference between these methods.

You can find some other useful topics and posts here. Below is a chart explaining about Single() and SingleOrDefault(). You can easily differentiate these methods from this chart. I have also given examples of each method.

Saturday, June 22, 2013

How To- Bind Data to Gridview using jQuery in ASP.Net

In this post, I am explaining how to bind data to Gridview using jQuery in ASP.Net through Ajax call.

In previous posts, I explained Page Scroll to Top with jQuery, Automatically Refresh Page Using Java Script , How to Create a Textarea Character Counter, Animated Sliding Recent Post Widget For Blogger, Change Input to Upper Case using Java Script, Calculate Age from Date of Birth Using Java Script, jQuery .toggleClass() example and some other articles related to C#ASP.Net jQuery, Java Script and SQL Server.

ASPX Page

Gridview Markup
<asp:GridView ID="grdDemo" runat="server" AutoGenerateColumns="False" Font-Names="Arial"
    Font-Size="10pt" HeaderStyle-BackColor="GrayText" HeaderStyle-ForeColor="White" Width="500px">
    <Columns>
        <asp:BoundField DataField="ID" HeaderText="ID" />
        <asp:BoundField DataField="FName" HeaderText="First Name"/>
        <asp:BoundField DataField="LName" HeaderText="Last Name"/>
        <asp:BoundField DataField="Email" HeaderText="E-mail"/>
    </Columns>
</asp:GridView>

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-

Friday, May 24, 2013

How To- Get Query String Value using Java Script

Query String Value using Java Script
In web application development, we all are well aware of Query String and Its uses. We can easily retrieve the Query String values from URL on server-side, but sometimes we need to find the Query String values from URL on client-side i.e using Java Script. But in Java Script, there is no standard way or function to get the Query String values from URL. So here I am explaining how can you get the Query String values from URL using Java Script.

In previous posts, I explained Page Scroll to Top with jQuery, Automatically Refresh Page Using Java Script , How to Create a Textarea Character Counter, Animated Sliding Recent Post Widget For Blogger, Change Input to Upper Case using Java Script, Calculate Age from Date of Birth Using Java Script, jQuery .toggleClass() example and some other articles related to jQuery, Java Script etc.

The following Java Script code snippet facilitates you to retrieve the query string key value. You can also pass the default value if the key value is not find. Here is the function-
^ Scroll to Top