<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Yashdesai on Medium]]></title>
        <description><![CDATA[Stories by Yashdesai on Medium]]></description>
        <link>https://medium.com/@yashdesai281?source=rss-c7f482a84bb5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*UzFYLo226JPZq_dAg4uKeg.jpeg</url>
            <title>Stories by Yashdesai on Medium</title>
            <link>https://medium.com/@yashdesai281?source=rss-c7f482a84bb5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 17:26:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@yashdesai281/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Types of Testing]]></title>
            <link>https://medium.com/@yashdesai281/types-of-testing-f902f3657338?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/f902f3657338</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Thu, 24 Oct 2024 04:07:37 GMT</pubDate>
            <atom:updated>2024-10-24T06:26:48.511Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Types of Testing</strong></p><ul><li><strong>Unit Testing:</strong> Tests individual components or units of code (e.g., functions, methods) in isolation from the rest of the application. These tests are fast and help ensure that each part of the code works correctly.</li><li><strong>Integration Testing:</strong> Tests the interactions between different components or systems to ensure they work together as expected. These tests are more complex and slower than unit tests but are essential for verifying that the integrated parts of the application function correctly.</li><li><strong>Functional Testing:</strong> Tests the application against its functional requirements to ensure it behaves as expected. This type of testing can be done manually or automatically and focuses on the end-to-end functionality of the application.</li><li><strong>Acceptance Testing:</strong> Tests whether the application meets the business requirements and is acceptable for delivery. These tests are often conducted by end-users or stakeholders to validate that the system performs as expected.</li><li><strong>Performance Testing:</strong> Tests the application’s performance under various conditions to ensure it meets performance criteria. This includes load testing, stress testing, and scalability testing.</li><li><strong>Security Testing:</strong> Tests the application’s security features to identify vulnerabilities and ensure that data is protected against unauthorized access.</li><li><strong>Regression Testing:</strong> This type of testing tests the application after changes or updates to ensure that the new changes do not break existing functionality.</li></ul><p><strong>What is Unit Testing?</strong></p><p>Unit Testing is a software testing method where individual units or components of a software application are tested to ensure they function correctly. These units are the smallest testable parts of an application, such as methods or functions. The purpose is to validate that each unit of the software performs as designed.</p><p><strong>Why is Unit Testing Important?</strong></p><ul><li><strong>Quality Assurance:</strong> Unit tests ensure that each part of the application functions correctly, contributing to the overall quality of the software.</li><li><strong>Early Bug Detection:</strong> By catching bugs early in the development process, unit tests reduce the cost and effort needed to fix issues later.</li><li><strong>Documentation:</strong> Unit tests serve as documentation that explains how different parts of the application are supposed to work, making it easier for new developers to understand the codebase.</li></ul><p><strong>What are the Core Principles of Unit Testing?</strong></p><ul><li><strong>Isolation</strong>: Tests should be independent of external dependencies (like databases, file systems, or network resources) to ensure they are fast and reliable.</li><li><strong>Repeatability:</strong> Tests should produce the same results every time they are run, regardless of the environment in which they are executed.</li><li><strong>Simplicity</strong>: Each test should focus on a single unit of work and be simple to understand and maintain.</li><li><strong>Fast Execution</strong>: Tests should execute quickly to provide immediate feedback during development. This encourages frequent running of tests.</li></ul><p><strong>What is Unit Testing in ASP.NET Core?</strong></p><p>Unit Testing in ASP.NET Core refers to the process of testing individual units or components of an ASP.NET Core application in isolation to ensure they behave as expected. These tests are usually written using a testing framework that integrates with ASP.NET Core and the broader .NET environment, such as xUnit.net, NUnit, or MSTest.</p><p>This testing approach focuses on verifying the functionality of specific parts of the application, such as controllers, services, or repositories, without relying on external dependencies like databases, file systems, or network services.</p><p><strong>Unit Testing Frameworks for ASP.NET Core?</strong></p><ul><li><strong>xUnit:</strong> A popular and extensible testing framework, it is the default choice for ASP.NET Core applications. It supports parallel test execution and has a rich set of assertions.</li><li><strong>NUnit:</strong> Another widely used testing framework used for all kinds of .NET applications. It offers a comprehensive set of features for writing and running tests.</li><li><strong>MSTest:</strong> Microsoft’s own testing framework, fully integrated into the Visual Studio environment, making it easy to use for developers in the Microsoft ecosystem.</li><li>Assert.Equal(expected, actual): Verifies that two values are equal.</li><li>Assert.NotEqual(notExpected, actual): Verifies that two values are not equal.</li><li>Assert.True(condition): Verifies that a condition is true. For example, Assert.True(result &gt; 0);</li><li>Assert.False(condition): Verifies that a condition is false. For example, Assert.False(result &lt; 0);</li><li>Assert.Null(object): Verifies that an object is null.</li><li>Assert.NotNull(object): Verifies that an object is not null.</li><li>Assert.Same(expected, actual): Verifies that two object references refer to the same object.</li><li>NotSame: Assert.NotSame(notExpected, actual): Verifies that two object references do not refer to the same object.</li><li>Assert.Empty(collection): Verifies that a collection is empty.</li><li>Assert.NotEmpty(collection): Verifies that a collection is not empty.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*-co-2QQxvrZtYkJbK8vtdQ.png" /></figure><p>package</p><p>dotnet add package Newtonsoft.Json<br>dotnet add reference D:\unittesing\book_mvc\book_mvc.csproj</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f902f3657338" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Polymorphism]]></title>
            <link>https://medium.com/@yashdesai281/polymorphism-539ee031a70b?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/539ee031a70b</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 18:49:02 GMT</pubDate>
            <atom:updated>2024-10-16T18:49:02.354Z</atom:updated>
            <content:encoded><![CDATA[<p>The word polymorphism is derived from two Greek words: poly and morphs. The word “Poly” means many, and “morphs” means forms. Therefore, polymorphism means “many forms” or we can say that the word polymorphism means the ability to take more than one form. That is one thing that can take many forms.</p><p><strong>Real-Time Examples of Polymorphism:</strong></p><p>Let us understand a few real-time examples to understand this Polymorphism concept.</p><p><strong>Example1:</strong></p><p>Suppose you are in a classroom, then at that time, you will behave like a student. But when you are in the shopping mall, at that time you will behave like a customer. Again, when you are traveling on a bus, then you will behave like a passenger. And when you are at your home at that time, you will behave like a son or daughter. Here, you are one person but performing different behaviors. This is nothing but polymorphism. The behaviors change based on the place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/0*Y1SNxzY-BIIpDDf3" /></figure><p><strong>Example2:</strong></p><p>A security guard in an organization behaves differently with different people entering the organization. The security behaves in a different way when the Boss comes and, in another way, when the employees come. And when the customers enter, the same security guard will respond differently. So here, the behavior of the security guard changes from person to person. It depends on the member who is entering the organization.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*k_PpBQO0e3iwtzp-" /></figure><p><strong>Example3:</strong></p><p>Another good real-time example of polymorphism is water. We all know that water is a liquid at normal temperature, but it changes to a solid when it is frozen, and the same water changes to a gas when it is heated at its boiling point. This is also polymorphism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/0*uY5L69tbW7Nar4P9" /></figure><p><strong>Example4:</strong></p><p>One of the best real-time examples of polymorphism is Women in society. The same woman performs a different role in society. The woman can be the wife of someone, the mother of her child, can be doing a job in an organization, and many more at the same time. But the Woman is only one. So, the same woman performing different roles is nothing but performing polymorphism.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*IgSG-QFnxaUUlc8W" /></figure><p><strong>Types of Polymorphism in C#:</strong></p><p>There are two types of polymorphism in C#. They are as follows:</p><ol><li><strong>Static Polymorphism / Compile-Time Polymorphism / Early Binding</strong></li><li><strong>Dynamic Polymorphism / Run-Time Polymorphism / Late Binding</strong></li></ol><p>The following diagram shows different types of polymorphisms in C# with their examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/0*K5wYFIR2YiY5xeVL" /></figure><p><strong>What is Method Overloading or Function Overloading in C#?</strong></p><p>Method Overloading means it is an approach to defining multiple methods under the class with a single name. So, we can define more than one method with the same name in a class. But the point that you need to remember the parameters of all those methods should be different (different in terms of number, type, and order of the parameters).</p><p>So, if we are defining multiple methods with the same name but with a different signature in a class or in the Parent and Child Classes, then it is called Method Overloading in C#. That means C#.NET not only allows method overloading in the same class but also allows method overloading in Parent and Child classes. So, we can create a method in the Derived/Child class with the same name as the method name defined in the Base/Parent class in C#.</p><p>In simple words, we can say that the Method Overloading in C# allows a class to have multiple methods with the same name but with a different signature. The functions or methods can be overloaded based on the number, type (int, float, etc), order, and kind (Value, Ref or Out) of parameters. For a better understanding, please have a look at the below image. All the Methods are going to be valid and based on the method call, the compiler will automatically decide which overloaded version to be invoked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*IDp0lc6ePpTfStGb" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=539ee031a70b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encapsulation vs Abstraction in C#]]></title>
            <link>https://medium.com/@yashdesai281/encapsulation-vs-abstraction-in-c-45027a4db09d?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/45027a4db09d</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Wed, 16 Oct 2024 17:10:40 GMT</pubDate>
            <atom:updated>2024-10-16T17:10:40.979Z</atom:updated>
            <content:encoded><![CDATA[<ol><li>The Encapsulation Principle is all about data hiding (o<strong>r information hiding</strong>). On the other hand, the Abstraction Principle is all about detailed hiding (<strong>implementation hiding</strong>).</li><li>Using the Encapsulation principle, we can protect our data, i.e., from outside the class, nobody can access the data directly. We are exposing the data through publicly exposed methods and properties. The advantage is that we can validate the data before storing and returning it. On the other hand, using the Abstraction Principle, we are exposing only the services so that the user can consume the services, but how the services/methods are implemented is hidden from the user. The user will never know how the method is implemented.</li><li>With the Encapsulation Principle, we group data members and member functions into a single unit called class, interface, enum, etc. On the other hand, with the Abstraction Principle, we are exposing the interface or abstract class to the user and hiding implementation details, i.e., hiding the child class information.</li><li>We can implement Encapsulation by declaring the data members as private and exposing the data members only through publicly exposed methods and properties with proper validation. On the other hand, we can implement abstraction through abstract classes and interfaces.</li><li>In abstraction, only the abstract view is presented to the user, while complex and detailed data is hidden from the user. On the other hand, in encapsulation, data member and member functions are bundled as a single unit and can be protected or made accessible using access modifiers and getter and setter methods.</li><li>Abstraction in C# is used to hide unwanted data and shows only the required properties and methods to the user. Encapsulation in C# is used to bind data members and member functions into a single unit to prevent outsiders from accessing it directly.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45027a4db09d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ADO.NET]]></title>
            <link>https://medium.com/@yashdesai281/datatable-c08f65a5d263?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c08f65a5d263</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Mon, 30 Sep 2024 18:08:29 GMT</pubDate>
            <atom:updated>2024-10-08T06:04:26.731Z</atom:updated>
            <content:encoded><![CDATA[<h3>ADO.NET</h3><p><strong>What is ADO.NET?</strong></p><p><strong>ADO stands for Microsoft ActiveX Data Objects</strong></p><p>ADO.NET is one of Microsoft’s Data Access Technologies, which we can use to communicate with different data sources.</p><p>It is a part of the .NET Framework, which establishes a connection between the .NET Application and different data sources.</p><p>The Data Sources can be SQL Server, Oracle, MySQL, XML, etc. ADO.NET consists of a set of predefined classes that can be used to connect, retrieve, insert, update, and delete data</p><p>ADO.NET (ActiveX Data Objects .NET) is a<strong> data access technology </strong>in the Microsoft .<strong><em>NET framework that provides a set of libraries and classes for working with data from various sources</em></strong>, including databases, XML files, and more.</p><p>ADO.NET is designed to provide a <strong><em>bridge between your application code and the underlying data sources.</em></strong></p><p>It offers a way to perform tasks like <strong><em>connecting to databases, executing queries, retrieving and updating data, and managing connections and transactions.</em></strong> This is especially important for building data-driven applications and services.</p><p><strong>What Types of Applications Use ADO.NET?</strong></p><p>ADO.NET can be used to develop any .NET application. The following are some of the .NET applications where you can use ADO.NET Data Access Technology to interact with a data source.</p><ol><li><strong>ASP.NET Web Form Applications</strong></li><li><strong>Windows Applications</strong></li><li><strong>ASP.NET MVC Application</strong></li><li><strong>Console Applications</strong></li><li><strong>ASP.NET Web API Applications</strong></li><li><strong>ASP.NET Core Applications</strong></li></ol><p><strong>Components of ADO.NET</strong></p><p>Components are designed for data manipulation and faster data access.</p><p><strong>1.Connection,</strong></p><p><strong>2.Command,</strong></p><p><strong>3.DataReader,</strong></p><p><strong>4.DataAdapter,</strong></p><p><strong>5.DataSet</strong></p><p><strong>6.DataView</strong></p><p>are the components of ADO.NET that are used to perform database operations.</p><ul><li><strong>Connection:</strong> The Connection component<strong><em> establishes a connection to a data source, such as a database</em></strong>. It manages the underlying connection to the database server and provides methods to open and close the connection.</li><li><strong>Command:</strong> The Command component represents a command that is executed against a data source. It encapsulates SQL statements, stored procedure calls, and other database commands.</li><li><strong>DataReader:</strong> The DataReader component efficiently reads data from a data source. It provides a forward-only, read-only stream of data that is particularly useful for retrieving large datasets. Reading data with a DataReader is fast and memory-efficient.</li><li><strong>DataAdapter:</strong> The DataAdapter bridges the application’s DataSet (in-memory cache of data) and the data source. It facilitates the retrieval of data from the data source into the DataSet and also allows changes to be updated in the DataSet back to the data source.</li><li><strong>DataSet:</strong> The DataSet is an in-memory data cache that can hold multiple tables, relationships, and constraints. It allows disconnected data manipulation, meaning that data is retrieved from the data source, disconnected from the connection, and then manipulated without direct interaction with the data source. The Data Set can be considered an in-memory representation of the database.</li><li><strong>DataTable:</strong> A data table is a component within a Data Set that represents a table of data. It consists of rows and columns and allows you to store and manipulate tabular data. DataTables can have relationships and constraints to maintain data integrity.</li><li><strong>DataView:</strong> The DataView is used to filter, sort, and navigate through data within a DataTable. It provides a dynamic view of the data, allowing you to customize how it is presented to the user.</li><li><strong>Transaction:</strong> The Transaction component provides support for managing transactions in ADO.NET. Transactions group multiple data access operations into a single unit of work that can be either committed (made permanent) or rolled back (undone) as a whole.</li><li><strong>Connection String:</strong> The connection string is a configuration string that provides the necessary information to connect to a data source. It includes details such as the database server’s location, credentials, and other settings.</li></ul><p>ADO.NET has two main components that are used for accessing and manipulating data. They are as follows:</p><ol><li><strong>Data Provider and</strong></li><li><strong>DataSet.</strong></li></ol><p>The Database can not directly execute our C# code; it only understands SQL. So, if a .NET application needs to retrieve data or to do some insert, update, and delete operations from or to a database, then the .NET application needs to</p><ol><li><strong>Connect to the Database</strong></li><li><strong>Prepare an SQL Command</strong></li><li><strong>Execute the Command</strong></li><li><strong>Retrieve the results and display them in the application</strong></li></ol><p>This is possible with the help of .NET Data Providers.</p><p><strong>Different .NET Data Providers</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/0*_uaJcx9bSur_jOCB" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/0*TAKzAPT2Ugv8ckOt" /></figure><p>Remember that the ADO.NET objects (Connection, Command, DataReader, and DataAdapter) have different prefixes depending on the provider, as shown below.</p><ol><li><strong>Connection </strong>— SQLConnection, OracleConnection, OleDbConnection, OdbcConnection, etc.</li><li><strong>Command </strong>— SQLCommand, OracleCommand, OleDbCommand, OdbcCommand, etc.</li><li><strong>DataReader </strong>— SQLDataReader, OracleDataReader, OleDbDataReader, OdbcDataReader, etc.</li><li><strong>DataAdapter </strong>— SQLDataAdapter, OracleDataAdapter, OleDbDataAdapter, OdbcDataAdapter, etc.</li></ol><p>ADO.NET Data Providers are libraries or components facilitating <strong><em>communication between </em></strong>your .NET application and specific data sources, such as <strong><em>databases</em></strong>. They are responsible for <strong><em>connecting to the data source, executing queries, and managing data retrieval and updates.</em></strong></p><ul><li><strong>SqlClient:</strong> This is the ADO.NET Data Provider for Microsoft SQL Server. It provides optimized support for connecting to and interacting with SQL Server databases. The System.Data.SqlClient namespace contains classes like SqlConnection and SqlCommand.</li><li><strong>OleDb:</strong> The OleDb Data Provider allows you to connect to various data sources using the OLE DB technology. It can be used to connect to different databases, including Microsoft Access and other OLE DB-compatible data sources. The System.Data.OleDb namespace contains classes like OleDbConnection and OleDbCommand.</li><li><strong>Odbc:</strong> The Odbc Data Provider enables database connectivity using the ODBC (Open Database Connectivity) API. It supports a wide range of databases through ODBC drivers. The System.Data.Odbc namespace includes classes like OdbcConnection and OdbcCommand.</li><li><strong>OracleClient:</strong> This Data Provider connects to Oracle databases. Note that as of my last update in September 2021, Oracle has deprecated OracleClient, and using Oracle’s own .NET driver or other alternatives is recommended.</li><li><strong>SQLite:</strong> SQLite is a self-contained, serverless, zero-configuration, transactional SQL database engine. There are ADO.NET Data Providers specifically designed for SQLite, allowing you to work with SQLite databases in your .NET applications.</li><li><strong>MySqlClient:</strong> This Data Provider is used to connect to MySQL databases. It allows .NET applications to interact with MySQL database servers.</li><li><strong>Npgsql:</strong> <strong><em>Npgsql is a popular Data Provider for PostgreSQL databases. It supports connecting to and working with PostgreSQL databases in .NET applications</em></strong>.</li><li><strong>Other Third-Party Providers:</strong> Third-party ADO.NET Data Providers are also available for various other databases and data sources. The database vendors or other developers often create these providers to enhance connectivity.</li></ul><p><strong>DataSet:</strong></p><p>The DataSet object in ADO.NET is not Provider-Specific. Once you connect to a database, execute the command and retrieve the data into the .NET application. The data can then be stored in a DataSet and work independently of the database. So, it is used to access data independently from any data source. The DataSet contains a collection of one or more DataTable objects.</p><p><strong>When to use ADO.NET?</strong></p><ol><li><strong>Performance Optimization:</strong> If your application demands high performance and you need more control over data access operations, ADO.NET can provide more control over connection management, query execution, and data retrieval. This is useful when dealing with large datasets or complex queries.</li><li><strong>Data Source Variety:</strong> ADO.NET’s flexibility to work with various data sources beyond relational databases, such as XML files, can be beneficial when dealing with heterogeneous data storage scenarios.</li><li><strong>Ad Hoc Queries and Reports:</strong> If your application needs to generate dynamic or complex queries for ad hoc reporting or analysis, ADO.NET’s ability to dynamically construct and execute queries can be useful.</li><li><strong>Low-Level Data Manipulation:</strong> ADO.NET’s DataSet and DataTable structures allow you to work with disconnected data and perform various operations, such as sorting, filtering, and data transformation.</li></ol><h3><strong>Methods of SqlCommand Class in C#</strong></h3><p>The SqlCommand class in C# provides the following methods.</p><ol><li><strong>BeginExecuteNonQuery():</strong> This method initiates the asynchronous execution of the Transact-SQL statement or stored procedure that is described by this System.Data.SqlClient.SqlCommand.</li><li><strong>Cancel():</strong> This method tries to cancel the execution of a System.Data.SqlClient.SqlCommand.</li><li><strong>Clone():</strong> This method creates a new System.Data.SqlClient.SqlCommand object is a copy of the current instance.</li><li><strong>CreateParameter():</strong> This method creates a new instance of a System.Data.SqlClient.SqlParameter object.</li><li><strong>ExecuteReader():</strong> This method Sends the System.Data.SqlClient.SqlCommand.CommandText to the System.Data.SqlClient.SqlCommand.Connection and builds a System.Data.SqlClient.SqlDataReader.</li><li><strong>ExecuteScalar():</strong> This method Executes the query and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.</li><li><strong>ExecuteNonQuery():</strong> This method executes a Transact-SQL statement against the connection and returns the number of rows affected.</li><li><strong>Prepare():</strong> This method creates a prepared version of the command on an instance of SQL Server.</li><li><strong>ResetCommandTimeout():</strong> This method resets the CommandTimeout property to its default value.</li></ol><h3><strong>ExecuteReader Method of SqlCommand Object in C#:</strong></h3><p>As we already discussed, this method sends the CommandText to the Connection and builds a SqlDataReader. When your T-SQL statement returns <strong><em>more than a single value (for example, rows of data),</em></strong> then you need to use the ExecuteReader method. Let us understand this with an example. The following example uses the <strong>ExecuteReader</strong> method of the SqlCommand object to execute the T-SQL statement, which <strong><em>returns multiple rows of data.</em></strong></p><pre>using Npgsql;<br>class ADONET<br>{<br>    static NpgsqlConnection conn = new NpgsqlConnection(&quot;Host=localhost;Username=postgres;Password=root;Database=windows_froms;&quot;);<br>    ADONET()<br>    {<br>        if (conn != null)<br>        {<br>            Console.WriteLine(&quot;connection is done......&quot;);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;connection is not done&quot;);<br>        }<br>    }<br><br>    public static void ExecuteReader()<br>    {<br>        //command<br>        conn.Open();<br>        NpgsqlCommand cmd = new NpgsqlCommand(&quot;SELECT * FROM t_customer&quot;, conn);<br>        NpgsqlDataReader reader = cmd.ExecuteReader();<br>        <br>        while (reader.Read())<br>        {<br>            Console.WriteLine(&quot;First Name: &quot; + reader[&quot;c_fname&quot;]);<br>            Console.WriteLine(&quot;Last Name : &quot; + reader[&quot;c_lname&quot;]);<br>            Console.WriteLine(&quot;Date of Birth: &quot; + reader[&quot;c_dob&quot;]);<br>            Console.WriteLine(&quot;Email     : &quot; + reader[&quot;c_email&quot;]);<br>            Console.WriteLine(&quot;PIN       : &quot; + reader[&quot;c_pin&quot;]);<br>            Console.WriteLine(&quot;Contact   : &quot; + reader[&quot;c_contact&quot;]);<br>            Console.WriteLine(&quot;Profile Image: &quot; + reader[&quot;c_profile_image&quot;]);<br>            Console.WriteLine(&quot;--------------------------&quot;);<br>        }<br>        conn.Close();<br>    }<br><br>}<br><br>#region 21&gt;ADO.NET<br><br>            ADONET.ExecuteReader();<br><br>            #endregion</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*GtvT9ZoeTflRyuL5187Evw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/0*DRCK-TjnDmzj2pbZ" /></figure><h3><strong>ExecuteScalar Method of SqlCommand Object in C#:</strong></h3><p>When your T-SQL query or stored procedure returns a <strong><em>single </em></strong>(i.e., scalar) value, then you need to use the <strong>ExecuteScalar</strong> method of the SqlCommand object in C#. Let us understand this with an example. Now, <strong><em>we need to fetch the total number of records present in the Student table.</em></strong> It will return a single value, so this is an ideal situation to use the <strong>ExecuteScalar</strong> method. The following example will <strong><em>retrieve the total number of records present in the Student table.</em></strong></p><pre>using Npgsql;<br>class ADONET<br>{<br>    static NpgsqlConnection conn = new NpgsqlConnection(&quot;Host=localhost;Username=postgres;Password=root;Database=windows_froms;&quot;);<br>    ADONET()<br>    {<br>        if (conn != null)<br>        {<br>            Console.WriteLine(&quot;connection is done......&quot;);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;connection is not done&quot;);<br>        }<br>    }<br><br>    public static void ExecuteScalar(){<br>        conn.Open();<br>        NpgsqlCommand cmd = new NpgsqlCommand(&quot;SELECT COUNT(*) FROM t_customer&quot;, conn);<br>        object result=cmd.ExecuteScalar();<br>        conn.Close();<br>        Console.WriteLine(&quot;Total Rows: &quot; + Convert.ToInt32(result));<br>    }<br><br>}<br><br>#region 21&gt;ADO.NET<br><br>    <br>            ADONET.ExecuteScalar();<br><br>            #endregion</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*ks6B15E5YCbM9mcU_zMMaw.png" /></figure><p><strong>ExecuteNonQuery Method of ADO.NET SqlCommand Object in C#:</strong></p><p>When you want to perform <strong>Insert, Update, or Delete</strong> operations and return the number of rows affected by your query, you need to use the <strong>ExecuteNonQuery</strong> method of the SqlCommand object in C#. Let us understand this with an example. The following example performs Insert, Update, and Delete operations using the<strong> ExecuteNonQuery()</strong> method.</p><h3><strong>What is ADO.NET SqlDataReader Class in C#?</strong></h3><p>The ADO.NET SqlDataReader class in C# is used to read data from the SQL Server database in the most efficient manner. It reads data in the forward-only direction. It means once it reads a record, it will then read the next record; there is no way to go back and read the previous record.</p><ul><li><strong>SqlDataReader is Connection-Oriented.</strong> It means it requires an open or active connection to the data source while reading the data. The data is available as long as the connection with the database exists.</li><li><strong>SqlDataReader is Read-Only.</strong> It means it is also not possible to change the data using SqlDataReader. You also need to open and close the connection explicitly.</li><li><strong>Forward-Only:</strong> The SqlDataReader works forwardly, meaning it can only read data in one direction — from the first to the last.</li></ul><pre>using Npgsql;<br>class ADONET<br>{<br>    static NpgsqlConnection conn = new NpgsqlConnection(&quot;Host=localhost;Username=postgres;Password=root;Database=windows_froms;&quot;);<br>    ADONET()<br>    {<br>        if (conn != null)<br>        {<br>            Console.WriteLine(&quot;connection is done......&quot;);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;connection is not done&quot;);<br>        }<br>    }<br><br>    public static void ExecuteScalar(){<br>        conn.Open();<br>        NpgsqlCommand cmd = new NpgsqlCommand(&quot;SELECT COUNT(*) FROM t_customer&quot;, conn);<br>        object result=cmd.ExecuteScalar();<br>        conn.Close();<br>        Console.WriteLine(&quot;Total Rows: &quot; + Convert.ToInt32(result));<br>    }<br><br>}<br><br>#region 21&gt;ADO.NET<br><br>    <br>            ADONET.ExecuteScalar();<br><br>            #endregion</pre><ol><li><strong>NextResult():</strong> It advances the data reader to the next result when reading the results of batch Transact-SQL statements.</li><li><strong>Read():</strong> It Advances the System.Data.SqlClient.SqlDataReader to the next record, returns true if there are more rows; otherwise, it is false.</li></ol><p><strong>How do you create an instance of the ADO.NET SqlDataReader class in C#?</strong></p><p>You can not create the instance of SqlDataReader using the new keyword. Then, the question is how we get or create the instance of the SqlDataReader class. To create the instance of the SqlDataReader class, what you need to do is call the <strong>ExecuteReader</strong> method of the <strong>SqlCommand</strong> object, which will return an instance of the <strong>SqlDataReader</strong> class, as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/0*3DPy-uNxVtM6Q9Qw" /></figure><p><strong>Example to Understand SqlDataReader in C#</strong></p><p>In the example below, we access the data from the SqlDataReader object using the index number. Here, the index is starting from 0. So, the Name Index position is 0, the Email Index Position is 1, and the Mobile Index Position is 2. So, you can retrieve the data from the data reader by either using the string key or the Integer index position.</p><pre>using Npgsql;<br>class ADONET<br>{<br>    static NpgsqlConnection conn = new NpgsqlConnection(&quot;Host=localhost;Username=postgres;Password=root;Database=windows_froms;&quot;);<br>    ADONET()<br>    {<br>        if (conn != null)<br>        {<br>            Console.WriteLine(&quot;connection is done......&quot;);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;connection is not done&quot;);<br>        }<br>    }<br><br>    public static void ExecuteReader()<br>    {<br>        //command<br>        conn.Open();<br>        NpgsqlCommand cmd = new NpgsqlCommand(&quot;SELECT * FROM t_customer&quot;, conn);<br>        NpgsqlDataReader reader = cmd.ExecuteReader();<br><br>        while (reader.Read())<br>        {<br>            Console.WriteLine(&quot;First Name: &quot; + reader[1]);<br>            Console.WriteLine(&quot;Last Name : &quot; + reader[2]);<br>            Console.WriteLine(&quot;Date of Birth: &quot; + reader[3]);<br>            Console.WriteLine(&quot;Email     : &quot; + reader[4]);<br>            Console.WriteLine(&quot;PIN       : &quot; + reader[5]);<br>            Console.WriteLine(&quot;Contact   : &quot; + reader[6]);<br>            Console.WriteLine(&quot;Profile Image: &quot; + reader[7]);<br>            Console.WriteLine(&quot;--------------------------&quot;);<br>        }<br>        conn.Close();<br>    }<br><br>    <br><br>}<br>#region 21&gt;ADO.NET<br><br>            ADONET.ExecuteReader();<br>            <br><br>            #endregion<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*x03ekvEzTT81bWwJwZL9dA.png" /></figure><p><strong>How to Access Multiple Result Sets Using DataReader in C#?</strong></p><p>As of now, we have discussed how to retrieve the result set using the Read method of the Data Reader object. Now, you will understand how to access multiple result sets using a data reader.</p><pre><br>    public static void ExecuteReader_multipledataset()<br>    {<br>        //command<br>        conn.Open();<br>        NpgsqlCommand cmd = new NpgsqlCommand(&quot;SELECT * FROM t_customer;select * from t_account;&quot;, conn);<br>        NpgsqlDataReader reader = cmd.ExecuteReader();<br><br><br>        while (reader.Read())<br>        {<br>            Console.WriteLine(&quot;First Name: &quot; + reader[&quot;c_fname&quot;]);<br>            Console.WriteLine(&quot;Last Name : &quot; + reader[&quot;c_lname&quot;]);<br>            Console.WriteLine(&quot;Date of Birth: &quot; + reader[&quot;c_dob&quot;]);<br>            Console.WriteLine(&quot;Email     : &quot; + reader[&quot;c_email&quot;]);<br>            Console.WriteLine(&quot;PIN       : &quot; + reader[&quot;c_pin&quot;]);<br>            Console.WriteLine(&quot;Contact   : &quot; + reader[&quot;c_contact&quot;]);<br>            Console.WriteLine(&quot;Profile Image: &quot; + reader[&quot;c_profile_image&quot;]);<br>            Console.WriteLine(&quot;--------------------------&quot;);<br><br>            //  Console.WriteLine(&quot;First Name: &quot; + reader[1]);<br>            // Console.WriteLine(&quot;Last Name : &quot; + reader[2]);<br>            // Console.WriteLine(&quot;Date of Birth: &quot; + reader[3]);<br>            // Console.WriteLine(&quot;Email     : &quot; + reader[4]);<br>            // Console.WriteLine(&quot;PIN       : &quot; + reader[5]);<br>            // Console.WriteLine(&quot;Contact   : &quot; + reader[6]);<br>            // Console.WriteLine(&quot;Profile Image: &quot; + reader[7]);<br>            // Console.WriteLine(&quot;--------------------------&quot;);<br>        }<br><br>        while (reader.NextResult())<br>        {<br>            while (reader.Read())<br>            {<br>                Console.WriteLine(&quot;Account Number   : &quot; + reader[&quot;c_account_num&quot;]);<br>                Console.WriteLine(&quot;ID               : &quot; + reader[&quot;c_id&quot;]);<br>                Console.WriteLine(&quot;Balance          : &quot; + reader[&quot;c_balance&quot;]);<br>                Console.WriteLine(&quot;Bank Name        : &quot; + reader[&quot;c_bank_name&quot;]);<br>                Console.WriteLine(&quot;IFSC Code        : &quot; + reader[&quot;c_ifsc_code&quot;]);<br>                Console.WriteLine(&quot;Created At       : &quot; + reader[&quot;c_created_at&quot;]);<br>                Console.WriteLine(&quot;Monthly Limit    : &quot; + reader[&quot;c_monthly_limit&quot;]);<br>                Console.WriteLine(&quot;-------------------------------&quot;);<br>            }<br>        }<br>        conn.Close();<br>    }</pre><p><strong>When to Use ADO.NET SqlDataReader Class in C#?</strong></p><p>Here are some situations where you might consider using SqlDataReader:</p><ul><li><strong>High-Performance Data Reading:</strong> Use SqlDataReader when performance is critical. It is optimized for fast, efficient data reading and faster than other methods like DataTable or DataSet because it does not load all data into memory at once.</li><li><strong>Read-Only Data Access:</strong> If you only need to read data from the database and don’t need to perform any updates, inserts, or deletes, SqlDataReader is a suitable choice.</li><li><strong>Large Volume Data Processing:</strong> For processing large volumes of data, SqlDataReader is ideal because it reads data row-by-row, which means it uses less memory and can handle large datasets more efficiently.</li><li><strong>Sequential Data Access:</strong> When you need to access data sequentially, SqlDataReader is the way to go. It’s a forward-only reader, meaning you can only read data in the order it is received from the database.</li><li><strong>Data Binding in Web Applications:</strong> In web applications, SqlDataReader can be used for simple data binding scenarios where the data is displayed in data-bound controls and no manipulation or updates are required.</li><li><strong>Real-Time Data Display:</strong> For scenarios where data needs to be fetched and displayed in real-time, like in dashboards or reporting tools, SqlDataReader provides an efficient way to retrieve and present data quickly.</li><li><strong>Minimizing Memory Footprint:</strong> If you want to minimize the memory footprint of your application, SqlDataReader is a good choice as it does not store the entire dataset in memory.</li><li><strong>Streaming Data:</strong> SqlDataReader is suitable for streaming data scenarios, where you process data as it’s read without waiting for the entire set of data to be loaded.</li></ul><p><strong>Best Practices</strong></p><ul><li><strong>Using Statement:</strong> Always use a using statement for SqlDataReader and SqlConnection to ensure that resources are properly released.</li><li><strong>Exception Handling:</strong> Implement proper exception handling, especially for database operations, which can fail for various reasons.</li><li><strong>Performance Considerations:</strong> Since SqlDataReader is connected and forward-only, it’s very efficient for large data reads. However, ensure the database connection is not kept open longer than necessary.</li><li><strong>Read-only Access:</strong> Remember that SqlDataReader is read-only and forward-only. If you need more functionality, like editing data or moving back and forth, consider other ADO.NET objects like DataTable or DataSet.</li></ul><h3>ADO.NET SqlDataAdapter Class in C#</h3><p>The ADO.NET SqlDataAdapter in C# bridges a DataSet or DataTable and a Data Source (SQL Server Database) to retrieve data. The SqlDataAdapter is a class that represents a set of SQL commands and a database connection. It is used to fill the DataSet or DataTable and update the data source as well.</p><p><strong>How to create an instance of the C# SqlDataAdapter class in ADO.NET?</strong></p><p>In order to create an instance of the SqlDataAdapter class in C#, we need to specify two things. The SQL command we want to execute and the connection we want to execute is like how we create the SqlCoomand object. Following is the syntax to create an instance of the SqlDataAdapter class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/0*3ie2krKYdWsVdVNj" /></figure><p><strong>Example to Understand ADO.NET SqlDataAdapter in C#</strong></p><p>Now, we need to develop an application where we will fetch all the data from the student table, and then we need to display the student data in the console using SqlDataAdapter in C# using ADO.NET. Let us first write the code, and then we will understand the code.</p><pre><br>    public static void SqlDataAdapter_using_datatable()<br>    {<br><br>        conn.Open();<br>        NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(&quot;SELECT * FROM t_customer&quot;, conn);<br>        conn.Close();<br>        System.Data.DataTable dt = new System.Data.DataTable();<br>        dataAdapter.Fill(dt);<br><br><br>        // Now you can iterate through the DataTable and display data<br>        // foreach (DataRow row in dt.Rows)<br>        // {<br>        //     Console.WriteLine(string.Join(&quot;, &quot;, row.ItemArray));  // Printing all columns of each row<br>        // }<br><br>        foreach (DataRow row in dt.Rows)<br>        {<br>            Console.WriteLine(&quot;First Name: &quot; + row[&quot;c_fname&quot;]);<br>            Console.WriteLine(&quot;Last Name : &quot; + row[&quot;c_lname&quot;]);<br>            Console.WriteLine(&quot;Date of Birth: &quot; + row[&quot;c_dob&quot;]);<br>            Console.WriteLine(&quot;Email     : &quot; + row[&quot;c_email&quot;]);<br>            Console.WriteLine(&quot;PIN       : &quot; + row[&quot;c_pin&quot;]);<br>            Console.WriteLine(&quot;Contact   : &quot; + row[&quot;c_contact&quot;]);<br>            Console.WriteLine(&quot;Profile Image: &quot; + row[&quot;c_profile_image&quot;]);<br>            Console.WriteLine(&quot;--------------------------&quot;);<br><br>        }<br><br><br><br>    }</pre><p>using Dataset</p><pre> public static void SqlDataAdapter_using_dataset()<br>    {<br><br>        conn.Open();<br>        NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(&quot;SELECT * FROM t_customer;select * from t_account&quot;, conn);<br>        conn.Close();<br>        System.Data.DataSet dt = new System.Data.DataSet();<br>        dataAdapter.Fill(dt);<br><br><br>        Console.WriteLine(&quot;tables : - &quot; + dt.Tables.Count);<br><br>        Console.WriteLine(&quot;table 1:- &quot; + dt.Tables[0]);<br>        Console.WriteLine(&quot;table 2:- &quot; + dt.Tables[1]);<br><br>        System.Data.DataTable table = dt.Tables[0];<br><br>        foreach (DataRow row in table.Rows)<br>        {<br>            Console.WriteLine(&quot;First Name: &quot; + row[&quot;c_fname&quot;]);<br>            Console.WriteLine(&quot;Last Name : &quot; + row[&quot;c_lname&quot;]);<br>            Console.WriteLine(&quot;Date of Birth: &quot; + row[&quot;c_dob&quot;]);<br>            Console.WriteLine(&quot;Email     : &quot; + row[&quot;c_email&quot;]);<br>            Console.WriteLine(&quot;PIN       : &quot; + row[&quot;c_pin&quot;]);<br>            Console.WriteLine(&quot;Contact   : &quot; + row[&quot;c_contact&quot;]);<br>            Console.WriteLine(&quot;Profile Image: &quot; + row[&quot;c_profile_image&quot;]);<br>            Console.WriteLine(&quot;--------------------------&quot;);<br><br>        }<br><br><br><br>    }</pre><p><strong>C# SqlDataAdapter using SQL Server Stored Procedure:</strong></p><pre>public static void SqlDataAdapter_using_storeprocedure()<br>    {<br>        try<br>        {<br><br>            conn.Open();<br>            NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(&quot;select * from get_all_customers25()&quot;, conn);<br>            dataAdapter.SelectCommand.CommandType = CommandType.Text;  // Using CommandType.Text because it&#39;s a function call<br><br>            System.Data.DataSet ds = new System.Data.DataSet();<br>            dataAdapter.Fill(ds);<br>            conn.Close();<br>            Console.WriteLine(&quot;Tables : &quot; + ds.Tables.Count);<br><br>            if (ds.Tables.Count &gt; 0)<br>            {<br>                Console.WriteLine(&quot;Table 1: &quot;);<br>                foreach (DataRow row in ds.Tables[0].Rows)<br>                {<br>                    Console.WriteLine(&quot;First Name: &quot; + row[&quot;c_fname1&quot;]);<br>                    Console.WriteLine(&quot;Last Name : &quot; + row[&quot;c_lname1&quot;]);<br>                    Console.WriteLine(&quot;Date of Birth: &quot; + row[&quot;c_dob1&quot;]);<br>                    Console.WriteLine(&quot;Email     : &quot; + row[&quot;c_email1&quot;]);<br>                    Console.WriteLine(&quot;PIN       : &quot; + row[&quot;c_pin1&quot;]);<br>                    Console.WriteLine(&quot;Contact   : &quot; + row[&quot;c_contact1&quot;]);<br>                    Console.WriteLine(&quot;Profile Image: &quot; + row[&quot;c_profile_image1&quot;]);<br>                    Console.WriteLine(&quot;--------------------------&quot;);<br>                }<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine(&quot;Error: &quot; + ex.Message);<br>        }<br><br>    }</pre><ul><li><strong>Disconnected Data Operations:</strong> If your application needs to work with data offline (i.e., without a continuous connection to the database), SqlDataAdapter is a good choice. It allows you to fill a DataSet or DataTable with data, manipulate it locally, and then apply changes back to the database.</li><li><strong>Caching and Offline Access:</strong> You can use SqlDataAdapter to populate a DataSet with data, store it in memory, and allow users to work with the data even when offline or disconnected from the database.</li><li><strong>Performance:</strong> In scenarios where you want to minimize the number of database round-trips while working with data, SqlDataAdapter allows you to fetch a bulk of data at once and work with it locally before applying changes back to the database.</li><li><strong>Batch Updates:</strong> SqlDataAdapter supports batch updates, where you can accumulate changes made to multiple rows in memory and then commit them to the database in a single batch. This can improve efficiency and reduce the number of round-trips to the database.</li><li><strong>Data Binding:</strong> If you’re building data-bound user interfaces, SqlDataAdapter simplifies the process. You can bind controls directly to the DataTable within a DataSet, making it easier to display and manipulate data.</li></ul><p>limitations:</p><ol><li>It might not be as memory-efficient as using a SqlDataReader for large data sets, as it loads all the data into memory.</li><li>It’s more suitable for scenarios where you have a relatively small number of rows compared to cases where you’re dealing with very large datasets.</li></ol><h3><strong>What is ADO.NET DataTable in C#?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*-3fJOppN83zwxgOi.png" /></figure><p>The DataTable in C# is similar to the Tables in SQL. That means the DataTable will also represent the relational data in tabular form.</p><p>you must have to include the <strong>System.Data </strong>namespace.</p><h3><strong>Properties of ADO.NET DataTable in C#:</strong></h3><p>The ADO.NET DataTable class in C# provides the following properties.</p><ol><li><strong>Columns</strong>: It collects the columns that belong to this table.</li><li><strong>Constraints</strong>: t is used to get the collection of constraints maintained by this table.</li><li><strong>DataSet</strong>: It is used to get the Data Set to which this table belongs.</li><li><strong>DefaultView</strong>: It is used to get a customized view of the table that may include a filtered view.</li><li><strong>HasErrors</strong>: It is used to get a value indicating whether there are errors in any of the rows in the table of the DataSet.</li><li><strong>MinimumCapacity</strong>: It is used to get or set the initial starting size for this table.</li><li><strong>PrimaryKey</strong>: It is used to get or set an array of columns that function as primary keys for the data table.</li><li><strong>Rows</strong>: It is used to collect the rows that belong to this table.</li><li><strong>TableName</strong>: It is used to get or set the name of the DataTable.</li></ol><h3><strong>Methods of C# DataTable in ADO.NET:</strong></h3><p>The C# DataTable class provides the following methods</p><ol><li><strong>AcceptChanges()</strong>: It is used to commit all the changes made to this table.</li><li><strong>Clear()</strong>: It is used to clear the DataTable of all data.</li><li><strong>Clone()</strong>: It is used to clone the structure of the DataTable.</li><li><strong>Copy():</strong> It is used to copy both the structure and data of the DataTable.</li><li><strong>CreateDataReader():</strong> It returns a DataTableReader corresponding to the data within this DataTable.</li><li><strong>CreateInstance():</strong> It is used to create a new instance of DataTable.</li><li><strong>GetRowType():</strong> It is used to get the row type.</li><li><strong>GetSchema()</strong>: It is used to get the table schema.</li><li><strong>ImportRow(DataRow):</strong> It is used to copy a DataRow into a DataTable.</li><li><strong>Load(IDataReader):</strong> It is used to fill a DataTable with values from a data source using the supplied IDataReader.</li><li><strong>Merge(DataTable, Boolean):</strong> It merges the specified DataTable with the current DataTable.</li><li><strong>NewRow():</strong> It creates a new DataRow with the same schema as the table.</li><li><strong>Select()</strong>: It is used to get an array of all DataRow objects.</li><li><strong>WriteXml(String):</strong> It is used to write the current contents of the DataTable as XML using the specified file.</li></ol><p><strong>When Should We Use ADO.NET DataTable in C#?</strong></p><p>DataTable from ADO.NET is a versatile tool that serves as an in-memory representation of tabular data. It’s useful in various scenarios where you need to work with data in a structured format. Here are some situations where you might consider using DataTable:</p><ol><li><strong>Disconnected Data Manipulation:</strong> When you need to work with data in a disconnected manner (i.e., without a continuous connection to the database), DataTable provides a way to load and manipulate data locally before synchronizing changes back to the database.</li><li><strong>Data Binding:</strong> If you’re building data-driven user interfaces, you can use DataTable as a data source for controls like grids, lists, and combo boxes. This allows you to display and interact with data in a user-friendly way.</li><li><strong>Complex Data Manipulation:</strong> In scenarios where you need to perform data manipulation operations like sorting, filtering, and grouping, DataTable provides built-in methods to achieve these tasks.</li><li><strong>Interchange Format:</strong> DataTable can serve as a container for data during data exchange between different layers of an application or even between different applications. You can serialize it to formats like XML or JSON for this purpose.</li><li><strong>Local Caching:</strong> If your application frequently accesses the same data, you can use DataTable to store a local copy of the data, reducing the need for frequent database queries.</li><li><strong>Small to Moderate Data Sizes:</strong> DataTable is suitable for managing data of moderate size. It’s not optimized for very large datasets, where other techniques like streaming and pagination might be more appropriate.</li><li><strong>Data Transformation:</strong> You can use DataTable to transform data from one format to another before sending it to another layer of your application or storing it in a different format.</li><li><strong>Batch Updates:</strong> If your application requires updating multiple records in a single transaction, you can accumulate changes in a DataTable and then perform a batch update to the database.</li><li><strong>Offline Access:</strong> In cases where users might need to work with data while disconnected from the network (e.g., in mobile applications), DataTable can store the required data for local usage.</li><li><strong>Data Validation:</strong> You can apply constraints and validation rules to columns within a Data Table to ensure data integrity before persisting changes to the database.</li></ol><ul><li>For large datasets, a more memory-efficient approach like streaming with SqlDataReader or pagination might be better.</li><li>For read-only scenarios, where you’re primarily retrieving data, using SqlDataReader or similar approaches can be more efficient.</li><li>If your application is built around modern data-binding frameworks, they might offer more advanced data manipulation capabilities.</li></ul><h3>DataTable Methods in C#</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/356/0*SngzYJ-HvJmkC76D.png" /></figure><p><strong>Copying and Cloning the DataTable in C#:</strong></p><p>If you want to create a full copy of a data table, then you need to use the Copy method of the DataTable object, which will copy the DataTable data and its schema. But if you want to copy the data table schema without data, then you need to use the Clone method of the data table. The following example shows the use of both the clone and copy methods.</p><pre>System.Data.DataTable copytable = student.Copy();<br><br>            Console.WriteLine(&quot;------------------------------copy table--------------------------------------&quot;);<br>            foreach (DataRow row3 in copytable.Rows)<br>            {<br>                Console.WriteLine(row3[&quot;id&quot;] + &quot;,  &quot; + row3[&quot;Name&quot;] + &quot;,  &quot; + row3[&quot;Email&quot;]);<br>            }<br>            Console.WriteLine(&quot;--------------------------------------------------------------------&quot;);<br><br><br>            System.Data.DataTable clonetable = student.Clone();<br><br>            clonetable.Rows.Add(1, &quot;yash&quot;, &quot;yash281@gmail.com&quot;);<br>            clonetable.Rows.Add(2, &quot;dev&quot;, &quot;yash281@gmail.com&quot;);<br>            clonetable.Rows.Add(3, &quot;yash&quot;, &quot;yash281@gmail.com&quot;);<br><br><br>            Console.WriteLine(&quot;-------------------------------clone table--------------------------------&quot;);<br><br>            foreach (DataRow row4 in clonetable.Rows)<br>            {<br>                Console.WriteLine(row4[&quot;id&quot;] + &quot;,  &quot; + row4[&quot;Name&quot;] + &quot;,  &quot; + row4[&quot;Email&quot;]);<br>            }<br><br></pre><p><strong>Deleting Data Row from a DataTable in C#:</strong></p><p>You can delete a DataRow from the DataRowCollection by calling the <strong>Remove </strong>method of the <strong>DataRowCollection</strong>, or by calling the Delete method of the DataRow object.</p><p>The <strong>Remove </strong>method will remove the row from the collection, whereas the <strong>Delete </strong>method marks the DataRow for removal. The actual removal will occur when you call the <strong>AcceptChanges </strong>method. If you want to roll back, then you need to use the <strong>RejectChanges </strong>method, which will roll back to the previous state. The <strong>RejectChanges </strong>method will copy the Original data row version to the Current data row version.</p><pre><br>            DataRow row = student.Rows.Find(102);<br>            if (row != null)<br>            {<br>                student.Rows.Remove(row);<br>            }</pre><pre>using Npgsql;<br>using System.Data;<br>class ADONET<br>{<br>    static NpgsqlConnection conn = new NpgsqlConnection(&quot;Host=localhost;Username=postgres;Password=root;Database=windows_froms;&quot;);<br>    ADONET()<br>    {<br>        if (conn != null)<br>        {<br>            Console.WriteLine(&quot;connection is done......&quot;);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;connection is not done&quot;);<br>        }<br>    }<br><br>    public static void ExecuteReader()<br>    {<br>        //command<br>        conn.Open();<br>        NpgsqlCommand cmd = new NpgsqlCommand(&quot;SELECT * FROM t_customer&quot;, conn);<br>        NpgsqlDataReader reader = cmd.ExecuteReader();<br><br>        while (reader.Read())<br>        {<br>            Console.WriteLine(&quot;First Name: &quot; + reader[&quot;c_fname&quot;]);<br>            Console.WriteLine(&quot;Last Name : &quot; + reader[&quot;c_lname&quot;]);<br>            Console.WriteLine(&quot;Date of Birth: &quot; + reader[&quot;c_dob&quot;]);<br>            Console.WriteLine(&quot;Email     : &quot; + reader[&quot;c_email&quot;]);<br>            Console.WriteLine(&quot;PIN       : &quot; + reader[&quot;c_pin&quot;]);<br>            Console.WriteLine(&quot;Contact   : &quot; + reader[&quot;c_contact&quot;]);<br>            Console.WriteLine(&quot;Profile Image: &quot; + reader[&quot;c_profile_image&quot;]);<br>            Console.WriteLine(&quot;--------------------------&quot;);<br><br>            //  Console.WriteLine(&quot;First Name: &quot; + reader[1]);<br>            // Console.WriteLine(&quot;Last Name : &quot; + reader[2]);<br>            // Console.WriteLine(&quot;Date of Birth: &quot; + reader[3]);<br>            // Console.WriteLine(&quot;Email     : &quot; + reader[4]);<br>            // Console.WriteLine(&quot;PIN       : &quot; + reader[5]);<br>            // Console.WriteLine(&quot;Contact   : &quot; + reader[6]);<br>            // Console.WriteLine(&quot;Profile Image: &quot; + reader[7]);<br>            // Console.WriteLine(&quot;--------------------------&quot;);<br>        }<br>        conn.Close();<br>    }<br><br>    public static void ExecuteReader_multipledataset()<br>    {<br>        //command<br>        conn.Open();<br>        NpgsqlCommand cmd = new NpgsqlCommand(&quot;SELECT * FROM t_customer;select * from t_account;&quot;, conn);<br>        NpgsqlDataReader reader = cmd.ExecuteReader();<br><br><br>        while (reader.Read())<br>        {<br>            Console.WriteLine(&quot;First Name: &quot; + reader[&quot;c_fname&quot;]);<br>            Console.WriteLine(&quot;Last Name : &quot; + reader[&quot;c_lname&quot;]);<br>            Console.WriteLine(&quot;Date of Birth: &quot; + reader[&quot;c_dob&quot;]);<br>            Console.WriteLine(&quot;Email     : &quot; + reader[&quot;c_email&quot;]);<br>            Console.WriteLine(&quot;PIN       : &quot; + reader[&quot;c_pin&quot;]);<br>            Console.WriteLine(&quot;Contact   : &quot; + reader[&quot;c_contact&quot;]);<br>            Console.WriteLine(&quot;Profile Image: &quot; + reader[&quot;c_profile_image&quot;]);<br>            Console.WriteLine(&quot;--------------------------&quot;);<br><br>            //  Console.WriteLine(&quot;First Name: &quot; + reader[1]);<br>            // Console.WriteLine(&quot;Last Name : &quot; + reader[2]);<br>            // Console.WriteLine(&quot;Date of Birth: &quot; + reader[3]);<br>            // Console.WriteLine(&quot;Email     : &quot; + reader[4]);<br>            // Console.WriteLine(&quot;PIN       : &quot; + reader[5]);<br>            // Console.WriteLine(&quot;Contact   : &quot; + reader[6]);<br>            // Console.WriteLine(&quot;Profile Image: &quot; + reader[7]);<br>            // Console.WriteLine(&quot;--------------------------&quot;);<br>        }<br><br>        while (reader.NextResult())<br>        {<br>            while (reader.Read())<br>            {<br>                Console.WriteLine(&quot;Account Number   : &quot; + reader[&quot;c_account_num&quot;]);<br>                Console.WriteLine(&quot;ID               : &quot; + reader[&quot;c_id&quot;]);<br>                Console.WriteLine(&quot;Balance          : &quot; + reader[&quot;c_balance&quot;]);<br>                Console.WriteLine(&quot;Bank Name        : &quot; + reader[&quot;c_bank_name&quot;]);<br>                Console.WriteLine(&quot;IFSC Code        : &quot; + reader[&quot;c_ifsc_code&quot;]);<br>                Console.WriteLine(&quot;Created At       : &quot; + reader[&quot;c_created_at&quot;]);<br>                Console.WriteLine(&quot;Monthly Limit    : &quot; + reader[&quot;c_monthly_limit&quot;]);<br>                Console.WriteLine(&quot;-------------------------------&quot;);<br>            }<br>        }<br>        conn.Close();<br>    }<br><br>    public static void ExecuteScalar()<br>    {<br>        conn.Open();<br>        NpgsqlCommand cmd = new NpgsqlCommand(&quot;SELECT COUNT(*) FROM t_customer&quot;, conn);<br>        object result = cmd.ExecuteScalar();<br>        conn.Close();<br>        Console.WriteLine(&quot;Total Rows: &quot; + Convert.ToInt32(result));<br>    }<br><br>    public static void SqlDataAdapter_using_datatable()<br>    {<br><br>        conn.Open();<br>        NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(&quot;SELECT * FROM t_customer&quot;, conn);<br>        conn.Close();<br>        System.Data.DataTable dt = new System.Data.DataTable();<br>        dataAdapter.Fill(dt);<br><br><br><br>        // Now you can iterate through the DataTable and display data<br>        // foreach (DataRow row in dt.Rows)<br>        // {<br>        //     Console.WriteLine(string.Join(&quot;, &quot;, row.ItemArray));  // Printing all columns of each row<br>        // }<br><br>        foreach (DataRow row in dt.Rows)<br>        {<br>            Console.WriteLine(&quot;First Name: &quot; + row[&quot;c_fname&quot;]);<br>            Console.WriteLine(&quot;Last Name : &quot; + row[&quot;c_lname&quot;]);<br>            Console.WriteLine(&quot;Date of Birth: &quot; + row[&quot;c_dob&quot;]);<br>            Console.WriteLine(&quot;Email     : &quot; + row[&quot;c_email&quot;]);<br>            Console.WriteLine(&quot;PIN       : &quot; + row[&quot;c_pin&quot;]);<br>            Console.WriteLine(&quot;Contact   : &quot; + row[&quot;c_contact&quot;]);<br>            Console.WriteLine(&quot;Profile Image: &quot; + row[&quot;c_profile_image&quot;]);<br>            Console.WriteLine(&quot;--------------------------&quot;);<br><br>        }<br><br><br><br>    }<br><br>    public static void SqlDataAdapter_using_dataset()<br>    {<br><br>        conn.Open();<br>        NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(&quot;SELECT * FROM t_customer;select * from t_account&quot;, conn);<br>        conn.Close();<br>        System.Data.DataSet dt = new System.Data.DataSet();<br>        dataAdapter.Fill(dt);<br><br><br>        Console.WriteLine(&quot;tables : - &quot; + dt.Tables.Count);<br><br>        Console.WriteLine(&quot;table 1:- &quot; + dt.Tables[0]);<br>        Console.WriteLine(&quot;table 2:- &quot; + dt.Tables[1]);<br><br>        System.Data.DataTable table = dt.Tables[0];<br><br>        foreach (DataRow row in table.Rows)<br>        {<br>            Console.WriteLine(&quot;First Name: &quot; + row[&quot;c_fname&quot;]);<br>            Console.WriteLine(&quot;Last Name : &quot; + row[&quot;c_lname&quot;]);<br>            Console.WriteLine(&quot;Date of Birth: &quot; + row[&quot;c_dob&quot;]);<br>            Console.WriteLine(&quot;Email     : &quot; + row[&quot;c_email&quot;]);<br>            Console.WriteLine(&quot;PIN       : &quot; + row[&quot;c_pin&quot;]);<br>            Console.WriteLine(&quot;Contact   : &quot; + row[&quot;c_contact&quot;]);<br>            Console.WriteLine(&quot;Profile Image: &quot; + row[&quot;c_profile_image&quot;]);<br>            Console.WriteLine(&quot;--------------------------&quot;);<br><br>        }<br><br><br><br><br>    }<br>    public static void SqlDataAdapter_using_storeprocedure()<br>    {<br>        try<br>        {<br><br>            conn.Open();<br>            NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(&quot;select * from get_all_customers25()&quot;, conn);<br>            dataAdapter.SelectCommand.CommandType = CommandType.Text;  // Using CommandType.Text because it&#39;s a function call<br><br>            System.Data.DataSet ds = new System.Data.DataSet();<br>            dataAdapter.Fill(ds);<br>            conn.Close();<br>            Console.WriteLine(&quot;Tables : &quot; + ds.Tables.Count);<br><br>            if (ds.Tables.Count &gt; 0)<br>            {<br>                Console.WriteLine(&quot;Table 1: &quot;);<br>                foreach (DataRow row in ds.Tables[0].Rows)<br>                {<br>                    Console.WriteLine(&quot;First Name: &quot; + row[&quot;c_fname1&quot;]);<br>                    Console.WriteLine(&quot;Last Name : &quot; + row[&quot;c_lname1&quot;]);<br>                    Console.WriteLine(&quot;Date of Birth: &quot; + row[&quot;c_dob1&quot;]);<br>                    Console.WriteLine(&quot;Email     : &quot; + row[&quot;c_email1&quot;]);<br>                    Console.WriteLine(&quot;PIN       : &quot; + row[&quot;c_pin1&quot;]);<br>                    Console.WriteLine(&quot;Contact   : &quot; + row[&quot;c_contact1&quot;]);<br>                    Console.WriteLine(&quot;Profile Image: &quot; + row[&quot;c_profile_image1&quot;]);<br>                    Console.WriteLine(&quot;--------------------------&quot;);<br>                }<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            Console.WriteLine(&quot;Error: &quot; + ex.Message);<br>        }<br>    }<br><br><br><br>    public static void SqlDataAdapter_using_dataset_batch_update()<br>    {<br><br>        conn.Open();<br>        NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(&quot;SELECT * FROM student&quot;, conn);<br>        NpgsqlCommandBuilder commandBuilder = new NpgsqlCommandBuilder(dataAdapter);<br>        conn.Close();<br>        System.Data.DataSet dt = new System.Data.DataSet();<br>        dataAdapter.Fill(dt);<br><br>        Console.WriteLine(&quot;table count :- &quot; + dt.Tables.Count);<br><br>        System.Data.DataTable student = dt.Tables[0];<br><br>        foreach (DataRow row in student.Rows)<br>        {<br>            Console.WriteLine(&quot;id= &quot; + row[&quot;s_id&quot;] + &quot;  name = &quot; + row[&quot;s_name&quot;] + &quot;  phone = &quot; + row[&quot;s_pho&quot;] + &quot;  email = &quot; + row[&quot;s_email&quot;]);<br>        }<br>        Console.WriteLine(&quot;--------------------------------------------------------------------&quot;);<br><br>        student.PrimaryKey = new DataColumn[] { student.Columns[&quot;s_id&quot;] };<br>        DataRow row1 = student.Rows.Find(1);<br><br>        if (row1 != null)<br>        {<br>            Console.WriteLine(&quot;----------------------------------find data in student----------------------------------&quot;);<br>            Console.WriteLine(&quot;id= &quot; + row1[&quot;s_id&quot;] + &quot;  name = &quot; + row1[&quot;s_name&quot;] + &quot;  phone = &quot; + row1[&quot;s_pho&quot;] + &quot;  email = &quot; + row1[&quot;s_email&quot;]);<br>            row1[&quot;s_name&quot;] = &quot;yash&quot;;<br><br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;row not found&quot;);<br>        }<br>        Console.WriteLine(&quot;--------------------------------------------------------------------&quot;);<br><br>        foreach (DataRow row in student.Rows)<br>        {<br>            Console.WriteLine(&quot;id= &quot; + row[&quot;s_id&quot;] + &quot;  name = &quot; + row[&quot;s_name&quot;] + &quot;  phone 000000= &quot; + row[&quot;s_pho&quot;] + &quot;  email = &quot; + row[&quot;s_email&quot;]);<br>        }<br>        Console.WriteLine(&quot;--------------------------------------------------------------------&quot;);<br><br>        DataRow row2 = student.Rows.Find(9);<br><br>        if (row2 != null)<br>        {<br>            Console.WriteLine(&quot;----------------------------------find data in student----------------------------------&quot;);<br>            Console.WriteLine(&quot;id= &quot; + row2[&quot;s_id&quot;] + &quot;  name = &quot; + row2[&quot;s_name&quot;] + &quot;  phone = &quot; + row2[&quot;s_pho&quot;] + &quot;  email = &quot; + row2[&quot;s_email&quot;]);<br>            row2.Delete();<br><br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;row not found&quot;);<br>        }<br>        //student.AcceptChanges();<br>        student.RejectChanges();<br>        Console.WriteLine(&quot;--------------------------------------------------------------------&quot;);<br><br>        foreach (DataRow row in student.Rows)<br>        {<br>            if (row.RowState != DataRowState.Deleted)  // Skip deleted rows<br>            {<br>                Console.WriteLine(&quot;id= &quot; + row[&quot;s_id&quot;] + &quot;  name = &quot; + row[&quot;s_name&quot;] + &quot;  phone = &quot; + row[&quot;s_pho&quot;] + &quot;  email = &quot; + row[&quot;s_email&quot;]);<br>            }<br>        }<br>        Console.WriteLine(&quot;--------------------------------------------------------------------&quot;);<br><br>        student.Rows.Add(3, &quot;vedu&quot;, 45484815, &quot;vedu55@gmail.com&quot;);<br><br><br><br>        dataAdapter.UpdateCommand = commandBuilder.GetUpdateCommand();<br>        dataAdapter.DeleteCommand = commandBuilder.GetDeleteCommand();<br>        dataAdapter.InsertCommand = commandBuilder.GetInsertCommand();<br><br>        int rowsAffected1 = dataAdapter.Update(student);<br>        Console.WriteLine($&quot;Rows affected in student: {rowsAffected1}&quot;);<br><br><br><br><br><br>    }<br><br><br><br><br><br><br>}<br><br></pre><h3><strong>What is ADO.NET DataSet in C#?</strong></h3><p>The DataSet represents a subset of the database in memory. That means the ADO.NET DataSet is a collection of tables containing relational data in memory in tabular format.</p><p>It does not require a continuous open or active connection to the database. The DataSet is based on the disconnected architecture.</p><p><strong>Note: </strong>The ADO.NET DataSet class is the core component for providing data access in a distributed and disconnected environment. The ADO.NET DataSet class belongs to the <strong>System.Data</strong> namespace.</p><p><strong>Example to understand DataSet in C#:</strong></p><p>Let us understand how to create and use ADO.NET DataSet in C# with an example. Here, we want to create two data tables (Customers and Orders), and then we want to add both these data tables to the DataSet, and then we want to log the data into the console.</p><p><strong>Creating Customers Data Table:</strong></p><p>We have already discussed how to create a Data Table in our previous article. If you have not read that article, please read our ADO.NET DataTable article before proceeding. Please have a look at the below image. As you can see here, we created one <strong>DataTable </strong>with the name <strong>Customer</strong>. Then we created three data columns (ID of type Int32, Name of type string, and Mobile of type string) and added these three columns to the Customer data table. Finally, we created two data rows and added these two data rows to the Customer data table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/0*h0t6nPrkBHFzM-Du" /></figure><p><strong>Creating Orders Data Table:</strong></p><p>Please have a look at the following image. Here, you can see we created the DataTable with the name Orders. Then we created three data columns (Id of type Int32, CustomerId of type Int32, and Amount of type Int32) and added these three data columns to the Orders data table. Finally, we created two data rows and added these two data rows to the Orders data table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/0*m62MGhySz3dnlUop" /></figure><p><strong>Creating DataSet with DataTable:</strong></p><p>As we already discussed, the DataSet is a collection of data tables. So, let’s create a DataSet object and then add the two data tables (Customers and Orders) into the DataSet. Please have a look at the following image. Here, first, we created an instance of the DataSet and then added the two data tables using the Tables property of the DataSet object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*uYKC-d9n9yNfSEwN" /></figure><p><strong>Fetch DataTable from DataSet:</strong></p><p>Now, let us see how to fetch the data table from the dataset. You can fetch the data table from a dataset in two ways i.e. using the index position and using the table name (if provided).</p><p><strong>Fetching DataTable from DataSet using index position:</strong></p><p>As we first add the Customers table to DataSet, the Customer table Index position is 0. If you want to iterate through the Customer’s table data, you could use a for-each loop to iterate, as shown in the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/563/0*DvVadNUbWcpI8-6c" /></figure><p><strong>Fetching DataTable From DataSet using Name:</strong></p><p>The second data table we added to the dataset is Orders, which will be added at index position 1. Further, if you notice, while creating the data table, we have provided a name for the data table, i.e., Orders. Now, if you want to fetch the data table from the dataset, then you can use the name instead of the index position. The following image shows how to fetch the data table using the name and looping through the data using a for each loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*PPzqIoc5BNbf1aqH" /></figure><h3><strong>ADO.NET DataView Class in C#:</strong></h3><p>we can display or represent the DataTable’s data in various styles, or formats. For example, using DataView we can display the DataTable data in various <strong><em>sorting orders</em></strong>, and we can also<strong><em> filter </em></strong>the DataTable’s data. And the most important point is that we can create any number of DataViews for a single DataTable to <strong><em>respreset the data in different formats.</em></strong></p><p>DataView represents a data-bindable, customized view of a DataTable for sorting, filtering, searching, editing, and navigation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/0*LJY_PaAN0aH3_3DI" /></figure><p><strong>Syntax: DataView dataView = new DataView(dataTable);</strong></p><p><strong>Syntax: DataView dataView = dataTable.DefaultView;</strong></p><p><strong>Displaying a Dataview in C#:</strong></p><p>Using a for loop and using the integer index position, we can access the elements of a data view as follows:</p><p><strong>Using For Loop to access the DataView</strong><br><strong>for(int i = 0; i&lt;dataView.Count;i++)</strong><br><strong>{</strong><br><strong> Console.WriteLine(dataView[i][“DataTableColumnName”]);</strong><br><strong>}</strong></p><p><strong>Using Foreach Loop to access the DataView</strong><br><strong>foreach (DataRowView rowView in dataView1)</strong><br><strong>{</strong><br><strong> DataRow = rowView.Row;</strong><br><strong> Console.WriteLine(row[“DataTableColumnName”]);</strong><br><strong>}</strong></p><ol><li><strong>Sort:</strong> This property is used to get or set the sort column or columns, and sort order for the DataView. It returns a string that contains the column name followed by “ASC” (ascending) or “DESC” (descending). Columns are sorted ascending by default. Multiple columns can be separated by commas.</li><li><strong>RowFilter:</strong> This property is used to get or get the expression used to filter which rows are viewed in the DataView. It returns a string that specifies how rows are to be filtered.</li></ol><pre>using System.Data;<br>using Npgsql;<br>class Dataview_prc<br>{<br>    static NpgsqlConnection conn = new NpgsqlConnection(&quot;Host=localhost;Username=postgres;Password=root;Database=windows_froms;&quot;);<br>    public Dataview_prc()<br>    {<br>        if (conn != null)<br>        {<br>            Console.WriteLine(&quot;connection is done......&quot;);<br>        }<br>        else<br>        {<br>            Console.WriteLine(&quot;connection is not done&quot;);<br>        }<br>    }<br><br>    public static void dataview()<br>    {<br>        NpgsqlDataAdapter dataAdapter = new NpgsqlDataAdapter(&quot;SELECT Id, Name, Email, Mobile, Age, Salary, Department FROM EMPLOYEE&quot;, conn);<br><br>        System.Data.DataTable EmployeeDataTable = new System.Data.DataTable();<br><br>        dataAdapter.Fill(EmployeeDataTable);<br><br>        DataView dataView1 = new DataView(EmployeeDataTable);<br><br>        //dataView1.Sort=&quot;Age ASC&quot;;<br>        //dataView1.Sort=&quot;Age ASC,name DESC&quot;;<br>        //dataView1.RowFilter=&quot;Age &gt;=27&quot;;<br>        //dataView1.RowFilter = &quot;Age &gt;= 27 AND name LIKE &#39;%a%&#39;&quot;;<br>        //dataView1.RowFilter = &quot;Age &gt;= 25 AND Department=&#39;IT&#39;&quot;;<br><br>        // dataView1.AllowNew = true;<br>        // DataRowView newRow = dataView1.AddNew();<br>        // newRow[&quot;Name&quot;] = &quot;yash&quot;;<br>        // newRow[&quot;Email&quot;] = &quot;Ayash.net&quot;;<br>        // newRow[&quot;Mobile&quot;] = &quot;1234567890&quot;;<br>        // newRow[&quot;Age&quot;] = 25;<br>        // newRow[&quot;Salary&quot;] = 10000;<br>        // newRow[&quot;Department&quot;] = &quot;IT&quot;;<br><br>        //dataView1.AllowEdit = true;<br>        dataView1.AllowDelete = true;<br><br><br><br>        // display<br>        foreach (DataRowView rowView in dataView1)<br>        {<br>            DataRow row = rowView.Row;<br><br>            // if(row[&quot;Department&quot;].ToString()==&quot;IT&quot;){<br>            //     rowView.Delete();<br>            // }<br>            //Console.WriteLine(&quot;------------------------------------update------------------------------------------&quot;);<br>            Console.WriteLine($&quot;Id: {row[&quot;Id&quot;]}, Name: {row[&quot;name&quot;]}, Age: {row[&quot;Age&quot;]}, Salary: {row[&quot;Salary&quot;]}, Department: {row[&quot;Department&quot;]}&quot;);<br><br>            // row[&quot;Salary&quot;] = Convert.ToInt32(row[&quot;Salary&quot;]) + 1000;<br>            // Console.WriteLine($&quot;Id: {row[&quot;Id&quot;]}, Name: {row[&quot;name&quot;]}, Age: {row[&quot;Age&quot;]}, Salary: {row[&quot;Salary&quot;]}, Department: {row[&quot;Department&quot;]}&quot;);<br>        }<br><br>        // foreach (DataRowView rowView in dataView1)<br>        // {<br>        //     DataRow row = rowView.Row;<br><br>        //     Console.WriteLine($&quot;Id: {row[&quot;Id&quot;]}, Name: {row[&quot;name&quot;]}, Age: {row[&quot;Age&quot;]}, Salary: {row[&quot;Salary&quot;]}, Department: {row[&quot;Department&quot;]}&quot;);<br>        // }<br><br><br><br>    }<br><br><br><br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c08f65a5d263" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multithreading in C#]]></title>
            <link>https://medium.com/@yashdesai281/multithreading-in-c-b80332b777b1?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/b80332b777b1</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Tue, 24 Sep 2024 19:00:12 GMT</pubDate>
            <atom:updated>2024-09-26T19:28:02.583Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is Multitasking?</strong></p><p>Before understanding the concept of Multithreading in C#, let us first understand multitasking. As the name says, multitasking means performing multiple tasks <strong>simultaneously</strong>.</p><p>Windows Operating System is a multitasking operating system. It means it has the ability to run multiple applications at the same time. For example, on my machine,<strong> I can open the Google Chrome Browser, Microsoft Word Document, Notepad, VLC Media Player, Visual Studio</strong>, etc., at the same time. This is possible because, on my machine, I have installed the Windows operating system, which is a multitasking operating system.</p><p>Multitasking is a fundamental feature of modern operating systems and plays an important role in improving computers’ efficiency, responsiveness, and usability.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*yh2qmKXsBt4Dlifh" /></figure><p><strong>How Does the Operating System Execute Multiple Applications at a time?</strong></p><p>The operating system uses processes internally to execute multiple applications (Google Chrome Browser, Microsoft Word Document, Notepad, VLC Media Player, Visual Studio, etc.) simultaneously.</p><p><strong>What is Thread?</strong></p><p>Generally, a Thread is a lightweight process. In simple words, we can say that a Thread is a unit of a process that is <strong>responsible for executing the application code.</strong></p><p>So, every program or application <strong>has some logic or code, and to execute that logic or code</strong>, <strong>Thread</strong> comes into the picture.</p><p>In an operating system (OS), a thread is a <strong>smaller unit of execution within a process.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*bUSnkKU10Odg5P1U" /></figure><p>Threads are sometimes called “lightweight processes” because they share the same memory space as the parent process, including its code, data, and resources. However, threads have their own execution context, including a program counter, registers, and stack.</p><p>Threads within the same process can run concurrently, allowing for parallel execution of tasks.</p><p>By default, every process has at least one thread that is responsible for executing the application code, and that thread is called <strong>Main Thread</strong>. So, every application by default is a single-threaded application.</p><p><strong>Note:</strong> All the threading-related classes in C# belong to <strong>System.Threading</strong> namespace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CqdeZQ-a8S4NSKrq9EF2rw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9R97RcFB_7Hmg1NnfdYVKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*RAyyYVYhAPk06xB8OxTe4Q.png" /></figure><p>The process can be split down into so many threads. <strong>For example</strong>, in a browser, many tabs can be viewed as threads. MS Word uses many threads — formatting text from one thread, processing input from another thread, etc.</p><h3>1. Program Code:</h3><ul><li><strong>Why it’s needed</strong>: All threads in a process need to execute the same or related instructions. The <strong>Program Code</strong> contains the set of instructions that all threads will execute. Instead of duplicating the code for every thread, it is shared among them to save memory and maintain consistency.</li></ul><p><strong>Example</strong>: Imagine you have a program to process a large dataset. Three threads may be running different parts of the same processing function on different chunks of data:</p><ul><li>Thread 1 processes the first third of the data.</li><li>Thread 2 processes the second third.</li><li>Thread 3 processes the final third.</li></ul><p>All threads share the same <strong>Program Code</strong> but process different portions of the data in parallel.</p><h3>2. PC Register (Program Counter Register):</h3><ul><li><strong>Why it’s needed</strong>: The <strong>Program Counter (PC) Register</strong> keeps track of the next instruction a thread should execute. Since each thread can execute different parts of the program simultaneously, they each need their own PC to track where they are in the code.</li><li><strong>Example</strong>: If one thread is at instruction 50 and another is at instruction 120 in the same program, they need their own PC registers to keep track of their position. This allows them to execute independently and not interfere with each other’s progress.</li></ul><h3>3. Stack:</h3><ul><li><strong>Why it’s needed</strong>: Each thread has its own <strong>stack</strong> to manage its local variables, function calls, and return addresses. The stack is necessary to maintain the unique execution context of each thread, as threads may call different functions with different data at the same time.</li><li><strong>Example</strong>: If Thread 1 calls a function that calculates a sum, and Thread 2 calls a function that reads a file, both threads need their own stack to store temporary variables and track the flow of execution separately. Without separate stacks, one thread’s function calls and local variables would overwrite those of another thread, causing data corruption or crashes.</li></ul><h3>4. Files:</h3><ul><li><strong>Why it’s needed</strong>: <strong>Files</strong> are typically shared between threads because they represent external resources (like disk files) that multiple threads might need to access. Instead of duplicating file handles or file data in memory for each thread, the process shares access to these files.</li><li><strong>Example</strong>: In a web server application, multiple threads might need to log information to the same log file. The threads share access to this file, allowing them all to write data without needing separate copies of the file. However, mechanisms like file locking may be used to ensure threads don’t corrupt the file when writing concurrently.</li></ul><h3>Summary of Why They Are Needed:</h3><ul><li><strong>Program Code</strong> is shared to avoid redundancy and to save memory.</li><li><strong>PC Register</strong> is individual to track where each thread is in the code execution.</li><li><strong>Stack</strong> is individual to each thread so they can manage their own function calls and local variables.</li><li><strong>Files</strong> are shared so that threads can access and manipulate common resources without duplication.</li></ul><h3>A Real-World Example:</h3><p>Imagine a web server (e.g., Apache or Nginx) that handles multiple requests simultaneously:</p><ol><li><strong>Program Code</strong>: The server’s code to handle requests is the same for all threads (e.g., how to process HTTP requests).</li><li><strong>PC Register</strong>: Each thread handling a client request is at a different point in the program, depending on how far along it is in processing that specific request.</li><li><strong>Stack</strong>: Each thread needs its own stack to store details about the client’s request, such as headers and the request path.</li><li><strong>Files</strong>: If the web server logs requests to a file, multiple threads may write to the same log file, sharing the file resource.</li></ol><h3>Types of Threads in an Operating System:</h3><ol><li><strong>Kernel-Level Threads (KLT)</strong></li><li><strong>User-Level Threads (ULT)</strong></li></ol><p><strong>1.Kernel-Level Threads (KLT)</strong></p><p>Kernel-level threads are managed directly by the operating system’s kernel. The kernel knows about each thread, schedules them, and handles their management (like switching between threads).</p><p>The kernel is responsible for creating, scheduling, and managing these threads.</p><h4>Advantages:</h4><ul><li><strong>True Multithreading</strong>: The kernel can schedule multiple threads across different processors in a multi-core system.</li><li><strong>No blocking in a single thread affects others</strong>: Since the kernel manages them, if one thread blocks (e.g., waiting for I/O), the kernel can switch to another thread.</li></ul><p><strong>Disadvantages:</strong></p><p><strong>Less Control for Applications</strong>: Since the kernel controls these threads, the user/application has limited flexibility in their management.</p><h4>Real-World Scenario:</h4><ul><li><strong>Web Servers</strong>: A web server like <strong>Apache</strong> may handle thousands of concurrent requests. With kernel-level threads, the operating system can schedule each thread across multiple cores, allowing efficient multitasking even in cases where some threads are blocked, such as waiting for I/O (e.g., reading from a database).</li></ul><p>2. <strong>User-Level Threads (ULT)</strong></p><p>User-level threads are managed by a user-space library or a runtime environment rather than the operating system kernel. The kernel is unaware of these threads, treating the entire process as a single thread.</p><h4>The application manages its threads without kernel intervention.</h4><h4>Advantages:</h4><ul><li><strong>Efficient</strong>: Thread creation, context switching, and management are much faster since no kernel calls are involved.</li><li><strong>Custom Scheduling</strong>: Applications can implement their custom thread scheduling strategies tailored to their needs.</li><li><strong>Portable</strong>: User-level threads are more portable across different operating systems since they don’t depend on the kernel for scheduling.</li></ul><h4>Disadvantages:</h4><ul><li><strong>Blocking Issues</strong>: If a user-level thread makes a blocking system call (e.g., waiting for I/O), the entire process can be blocked because the kernel thinks the entire process is waiting, not just the thread.</li><li><strong>No True Parallelism</strong>: Since the kernel isn’t aware of the individual threads, it can’t schedule them on multiple cores. This means that user-level threads can’t achieve true parallel execution on multi-core systems.</li></ul><h3>Use Both</h3><h4>Real-World Scenario:</h4><ul><li><strong>Database Systems</strong>: Databases like <strong>Oracle</strong> or <strong>PostgreSQL</strong> might use a hybrid threading model. User-level threads can be used for lightweight tasks like managing connections or internal state, while kernel-level threads handle more resource-intensive tasks like query execution, which require true parallelism.</li></ul><h3>Conclusion:</h3><ul><li><strong>Kernel-Level Threads</strong>: Ideal for applications that require high concurrency, multitasking, and can benefit from true parallelism (e.g., web servers, multi-core CPU tasks).</li><li><strong>User-Level Threads</strong>: Useful for lightweight, fast-switching tasks where direct OS intervention isn’t necessary (e.g., internal state management, lightweight tasks in programming languages like Go).</li></ul><p><strong>What are the drawbacks of Single-Threaded Applications</strong></p><p><strong>Limited CPU Utilization:</strong>Single-threaded applications can only execute one task or operation simultaneously. This means they cannot fully utilize modern multi-core processors.</p><p><strong>Poor Responsiveness:</strong> In a single-threaded application, time-consuming operations can block the entire execution, making the application appear unresponsive to user input.</p><p><strong>For example</strong>:if a long-running computation occurs on the main thread, the user interface won’t update until the computation is complete. This can result in a poor user experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*V9h0623tyrA7KIkn-iYOJA.gif" /></figure><ul><li><strong>Scalability Challenges:</strong> Single-threaded applications often face challenges when scaling to simultaneously handle multiple users or workloads. They may not be well-suited for scenarios requiring high concurrency or parallel processing, such as web servers or real-time data processing applications.</li><li><strong>Inefficient Resource Utilization:</strong> Single-threaded applications may not efficiently utilize other system resources, such as memory and I/O. For example, they might block the thread while waiting for I/O operations to complete, leading to wasted CPU cycles that could be used for other tasks.</li></ul><p>all the logic or code present in the program will be executed by a single thread only, i.e., the Main thread. For example, if we have three methods in our application. All these three methods will be called from the Main method. Then, the Main thread is only responsible for executing all these three methods sequentially, i.e., one by one. It will execute the first method, and once it completes the execution of the first method, it only executes the second method, and so on. Let us understand this with an example. Modify the program as shown below.</p><pre>class Single_Threaded<br>{<br>    public static void Method1()<br>    {<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method1 :&quot; + i);<br>        }<br>    }<br><br>    public static void Method2()<br>    {<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method2 :&quot; + i);<br>            <br>        }<br>    }<br>    public static void Method3()<br>    {<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method3 :&quot; + i);<br>        }<br>    }<br>}<br><br><br>            #region 10&gt;single-threaded<br><br>            Single_Threaded.Method1();<br>            Single_Threaded.Method2();<br>            Single_Threaded.Method3();<br><br>            #endregion</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/184/1*AQmNi0SoZbUjYUrt4WShdg.png" /></figure><p>As you can see in the above output, the methods are called and executed one after the other. The Main thread first executes Method1, and once it completes the execution of Method1, it calls Method2 and Method3.</p><p><strong>What is the problem with the above Program Execution?</strong></p><p>Suppose Method2 is going to interact with a database, or it is going to invoke any web services or any web APIs, which will take more than 10 seconds to provide the response. In that case, the Method2 execution will be delayed for 10 seconds as it is waiting to get a response from the database, the Web Service, or the Web API. Until Method2 has not completed its execution, Method3 will not be executed because of the sequential execution of the program, i.e., one by one.</p><p><strong>Example to Understand the Problem of Single-Threaded Application .</strong></p><p>we will not perform any database or Web Service call; instead, we will use the Thread class Sleep method to delay the execution of Method2 for 10 seconds.</p><pre>class Single_Threaded<br>{<br>    public static void Method1()<br>    {<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method1 :&quot; + i);<br>        }<br>    }<br><br>    public static void Method2()<br>    {<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method2 :&quot; + i);<br>            if (i == 3)<br>                {<br>                    Console.WriteLine(&quot;Performing the Database Operation Started&quot;);<br>                    //Sleep for 10 seconds<br>                    Thread.Sleep(10000);<br>                    Console.WriteLine(&quot;Performing the Database Operation Completed&quot;);<br>                }<br>        }<br>    }<br>    public static void Method3()<br>    {<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method3 :&quot; + i);<br>        }<br>    }<br>}<br><br><br> #region 10&gt;single-threaded<br><br>            Single_Threaded.Method1();<br>            Single_Threaded.Method2();<br>            Single_Threaded.Method3();<br><br>            #endregion</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*LS9cCqzoDbg2PgfucMOb7A.png" /></figure><p>Now, run the application and notice that the Method2 execution is delayed for 10 seconds. Once Method2 completes its execution, only Method3 starts its execution. This is because all three methods are executed by a single thread, which is the drawback of the single-threaded application.</p><p><strong>How do we solve the above problem?</strong></p><p>To solve the above problem, we have a concept called <strong>Multithreading</strong> in C#. As we already discussed Operating System has Processes used to run our applications. The Process <strong>contains Thread</strong>, which will <strong>actually run our application code.</strong></p><p>A process, by <strong>default, uses a single thread</strong> to run our application code, but a process can have multiple threads, and multiple threads can run our application code <strong>simultaneously</strong>. In this case, each thread will perform a different task, or you can say each thread will execute different parts of our application code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*VuudQ4MLt96ILSPN" /></figure><p>In our application, we have three methods. So, the three methods we defined in our application can be executed by three threads. The advantage is that the execution takes place <strong>simultaneously</strong>. So, when multiple threads try to execute the application code, the operating system allocates some time for each thread.</p><p><strong>example: </strong>we want to execute the three methods using three different threads. let us say t1, t2, and t3. The thread t1 is going to execute Method1, and thread t2 is going to execute the Method2. At the same time, Method3 will be executed by thread t3.</p><pre>class Multithreading<br>{<br>    public static void Method1()<br>    {<br>        Console.WriteLine(&quot;Method1 Started using &quot; + Thread.CurrentThread.Name);<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method1 :&quot; + i);<br>        }<br>        Console.WriteLine(&quot;Method1 Ended using &quot; + Thread.CurrentThread.Name);<br>    }<br>    public static void Method2()<br>    {<br>        Console.WriteLine(&quot;Method2 Started using &quot; + Thread.CurrentThread.Name);<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method2 :&quot; + i);<br>            if (i == 3)<br>            {<br>                Console.WriteLine(&quot;Performing the Database Operation Started&quot;);<br>                //Sleep for 10 seconds<br>                Thread.Sleep(10000);<br>                Console.WriteLine(&quot;Performing the Database Operation Completed&quot;);<br>            }<br>        }<br>        Console.WriteLine(&quot;Method2 Ended using &quot; + Thread.CurrentThread.Name);<br>    }<br>    public static void Method3()<br>    {<br>        Console.WriteLine(&quot;Method3 Started using &quot; + Thread.CurrentThread.Name);<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method3 :&quot; + i);<br>        }<br>        Console.WriteLine(&quot;Method3 Ended using &quot; + Thread.CurrentThread.Name);<br>    }<br>}<br><br><br>           #region 11&gt; Multithreading<br><br>            Console.WriteLine(&quot;Main Thread Started&quot;);<br>            //Creating Threads<br>            Thread t1 = new Thread(Multithreading.Method1)<br>            {<br>                Name = &quot;Thread1&quot;<br><br>            };<br>            Thread t2 = new Thread(Multithreading.Method2)<br>            {<br>                Name = &quot;Thread2&quot;<br>            };<br>            Thread t3 = new Thread(Multithreading.Method3)<br>            {<br>                Name = &quot;Thread3&quot;<br>            };<br><br>            //Executing the methods<br>            t1.Start();<br>            t2.Start();<br>            t3.Start();<br>            Console.WriteLine(&quot;Main Thread Ended&quot;);<br><br>            #endregion</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*nV7jdgKSVr7IRVec5bLwvA.png" /></figure><p>the output is different every time is due to <strong>multithreading</strong>. When multiple threads are running simultaneously, the <strong>order of execution</strong> of the threads is determined by the <strong>operating system’s thread scheduler</strong>, which does not guarantee that threads will run in a specific sequence.</p><p>but every time is method 2 is done by end because it’s tacks more time so all method is execute before method 2</p><p><strong>What is Multithreading in C#?</strong></p><p>If multiple threads are used to execute your application code, it is called Multithreading.Multithreading is a mechanism to implement Concurrent Programming where multiple threads operate simultaneously.</p><p>Thread usage increases the efficiency of an application and reduces CPU cycle time wastage. The main advantage of using Multithreading is the maximum utilization of CPU resources.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*fe4oRhQ24lGEyIPN.jpg" /></figure><p><strong>Key Features of Multithreading in C#:</strong></p><ul><li><strong>Thread Class:</strong> C# provides the System.Threading.Thread class, which allows you to create and manage threads. Using this class, you can create new threads, start and stop them, set their priorities, and perform various synchronization and coordination tasks.</li><li><strong>Parallel Programming:</strong> Multithreading is often used for parallel programming, where multiple threads work on separate parts of a problem to improve performance.</li><li><strong>Improved Responsiveness:</strong> Multithreading can keep the user interface (UI) responsive while performing time-consuming tasks in the background. For example, in a GUI application, you can run a time-consuming computation on a separate thread so that the UI remains interactive and doesn’t freeze.</li><li><strong>Concurrency:</strong> Multithreading enables concurrent execution of code sections, which is useful for scenarios where multiple threads need to access shared resources, perform I/O operations, or handle multiple client requests simultaneously.</li><li><strong>Async/Await:</strong> C# includes the async and await keywords, simplifying asynchronous programming. These keywords allow you to write asynchronous code that can run concurrently with other tasks without blocking the calling thread. Asynchronous programming is essential for scalable and responsive applications.</li></ul><p><strong>Why do we need to Protect the Shared Resources in Multithreading in C#?</strong></p><p>In a multithreading application, it is very important for us to handle multiple threads for executing critical section code or you can say shared resources.</p><p>For example: if we have a shared resource, and multiple threads want to access the shared resource, then we need to<strong> protect the shared resource from concurrent access</strong> otherwise we will get some inconsistent behavior or output.</p><p>In C#, we can use <strong>Lock and Monitor</strong> to provide thread safety in a multithreaded application. Both lock and monitor provide a <strong>mechanism that ensures that only one thread is executing the critical section code</strong> at any given point in time to avoid any functional breaking of code or to avoid inconsistent behavior or output.</p><pre> <br>class Lock_Multithread<br>{<br>    private static readonly object LockDisplayMethod = new object();<br>    public static void DisplayMessage()<br>    {<br>        lock (LockDisplayMethod)<br>        {<br>            Console.Write(&quot;[Welcome to the &quot;);<br>            Thread.Sleep(1000);<br>            Console.WriteLine(&quot;world of dotnet!]&quot;);<br>        }<br>    }<br><br>}<br><br><br>            #region  17&gt; Lock multithreading in C#<br>            Thread t1 = new Thread(Lock_Multithread.DisplayMessage);<br>            Thread t2 = new Thread(Lock_Multithread.DisplayMessage);<br>            Thread t3 = new Thread(Lock_Multithread.DisplayMessage);<br>            t1.Start();<br>            t2.Start();<br>            t3.Start();<br>            Lock_Multithread.DisplayMessage();<br>            Lock_Multithread.DisplayMessage();<br>            Lock_Multithread.DisplayMessage();<br><br>            Console.Read();<br><br>            #endregion</pre><p><strong>Understanding the Monitor Class in C#:</strong></p><p>The Monitor class is a static class belonging to the System.Threading namespace. As a static class, it provides a collection of static methods,</p><ol><li><strong>Enter():</strong> When we invoke the Enter method of the Monitor class, it acquires an exclusive lock on the specified object. This also marks the beginning of a critical section or the beginning of a shared resource.</li><li><strong>Exit():</strong> When the Monitor class’s Exit method is invoked, it releases the lock on the specified object. This marks the end of a critical section or the end of the shared resource protected by the locked object.</li><li><strong>Pulse():</strong> When the Pulse method is invoked of the Monitor class, it sends a signal to a thread in the waiting queue of a change in the locked object’s state.</li><li><strong>Wait():</strong> When the Monitor class’s Wait method is invoked, it releases the lock on an object and blocks the current thread until it reacquires the lock.</li><li><strong>PulseAll():</strong> When the Monitor class’s PulseAll method is invoked, it sends signals to all waiting threads about a change in the locked object’s state.</li><li><strong>TryEnter():</strong> When we invoke the Monitor class’s TryEnter method, it attempts to acquire an exclusive lock on the specified object.</li></ol><p><strong>Example to understand Monitor Class in C# to Protect Shared Resource from Concurrent Access:</strong></p><p>To understand how the Monitor class works in C#, please have a look at the following diagram. As shown in the image below, as soon as a thread executes the Enter method of the Thread class, it will be in the Ready Queue, and in the same way, many threads can be in the Ready Queue. Then, one of the threads from the Ready Queue will acquire an Exclusive Lock on the Object and will enter inside the Critical Section and execute the code, and at that time, no other threads can get a chance to enter into the Critical Section. When we execute the Exit method of the thread class, the currently executing thread will move into the waiting queue and send one signal to the threads in the ready queue. One of the Threads from the Ready queue will acquire the lock, and enter the Critical section, and start executing the code of the Critical Section. This is how the Monitor class works in C#.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*3S8hsgZyEZG20iMg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/0*hKCnPxZG6HjLPlwK" /></figure><pre>class Monitor<br>{<br>    private static readonly object lockPrintNumbers = new object();<br>    public static void PrintNumbers()<br>    {<br>        Console.WriteLine(Thread.CurrentThread.Name + &quot; Trying to enter into the critical section&quot;);<br><br>        try<br>        {<br>            // Fully qualify System.Threading.Monitor<br>            System.Threading.Monitor.Enter(lockPrintNumbers);<br>            Console.WriteLine(Thread.CurrentThread.Name + &quot; Entered into the critical section&quot;);<br>            for (int i = 0; i &lt; 5; i++)<br>            {<br>                Thread.Sleep(100);<br>                Console.Write(i + &quot;,&quot;);<br>            }<br>            Console.WriteLine();<br>        }<br>        catch (Exception e)<br>        {<br>            Console.WriteLine(e);<br>        }<br>        finally<br>        {<br>            System.Threading.Monitor.Exit(lockPrintNumbers);<br>            Console.WriteLine(Thread.CurrentThread.Name + &quot; Exit from critical section&quot;);<br>        }<br>    }<br>}<br><br><br><br> Thread[] Threads = new Thread[3];<br>            for (int i = 0; i &lt; 3; i++)<br>            {<br>                Threads[i] = new Thread(Monitor.PrintNumbers)<br>                {<br>                    Name = &quot;Child Thread &quot; + i<br>                };<br>            }<br>            foreach (Thread t in Threads)<br>            {<br>                t.Start();<br>            }<br>            Console.ReadLine();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*tLx-C13rbpVsM-g3VZYuAg.png" /></figure><p><strong>Example to Understand TryEnter(Object, TimeSpan, Boolean) Method of Monitor Class in C#:</strong></p><p>This method attempts to acquire an exclusive lock on the specified object for a specified amount of time. It automatically sets a value that indicates whether the lock was taken or not. The syntax for using the <strong>TryEnter(Object, TimeSpan, Boolean)</strong> Method of Monitor Class in C# is given below.</p><pre><br><br>class Monitor_tryenter<br>{<br><br>    private static readonly object lockPrintNumbers = new object();<br>    public static void PrintNumbers1()<br>    {<br>        TimeSpan timeout = TimeSpan.FromMilliseconds(6000);<br>        bool lockTaken = false;<br>        try<br>        {<br>            Console.WriteLine(Thread.CurrentThread.Name + &quot; Trying to enter into the critical section&quot;);<br>            System.Threading.Monitor.TryEnter(lockPrintNumbers, timeout, ref lockTaken);<br>            if (lockTaken)<br>            {<br>                Console.WriteLine(Thread.CurrentThread.Name + &quot; Entered into the critical section&quot;);<br>                for (int i = 0; i &lt; 5; i++)<br>                {<br>                    Thread.Sleep(600);<br>                    Console.Write(i + &quot;,&quot;);<br>                }<br>                Console.WriteLine();<br>            }<br>            else<br>            {<br>                // The lock was not acquired.<br>                Console.WriteLine(Thread.CurrentThread.Name + &quot; Lock was not acquired&quot;);<br>            }<br>        }<br>        finally<br>        {<br>            // To Ensure that the lock is released.<br>            if (lockTaken)<br>            {<br>                System.Threading.Monitor.Exit(lockPrintNumbers);<br>                Console.WriteLine(Thread.CurrentThread.Name + &quot; Exit from critical section&quot;);<br>            }<br>        }<br>    }<br>}<br><br><br><br><br><br>Thread[] Threads = new Thread[3];<br>            for (int i = 0; i &lt; 3; i++)<br>            {<br>                Threads[i] = new Thread(Monitor_tryenter.PrintNumbers1)<br>                {<br>                    Name = &quot;Child Thread &quot; + i<br>                };<br>            }<br>            foreach (Thread t in Threads)<br>            {<br>                t.Start();<br>            }<br>            Console.ReadLine();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/245/0*O2ws0-C60MK7NzJ9.gif" /></figure><p><strong>Example to Understand Wait() and Pulse() Methods of Monitor Class in C#:</strong></p><p>The calling thread waits while another thread accesses the object. The Pulse signals are used to notify waiting threads about changes to a locked object’s state.</p><p>Let us understand this with one real-time example. Our business requirement is to print the even and Odd number sequence using two different threads. One thread will print the even numbers, and another thread will print the odd numbers.<br><strong>Thread T1: 0,2,4,6,8…</strong><br><strong>Thread T2: 1,3,5,7,9…</strong><br><strong>Output: 0,1,2,3,4,5,6,7,8,9…</strong></p><p>To solve the above problem, let us use the signaling mechanism using the Monitor Class Wait() and Pulse() Methods in C#. In the following example, we use the Monitor.Wait() method to make the thread waiting and Monitor.Pulse() method is used to signal other threads. The process is as follows:</p><ol><li>First, the Even thread will start to print the number on the console.</li><li>Then, the Even thread will signal the Odd thread to be ready to print the number using the Monitor.Pulse() method.</li><li>Then, the Event thread will call the Monitor.Wait() method, which will allow the current thread to block and the Odd thread to start execution.</li><li>The Odd Thread will also do the same thing.</li><li>The Odd thread will start to print the number on the console.</li><li>Then, the Odd thread will signal the Even thread to be ready to print the number using the Monitor.Pulse() method.</li><li>Then the Odd thread will call the Monitor.Wait() method, which will allow the current thread to block and allow the Even thread to start execution.</li><li>The same process is going on.</li></ol><pre><br>class Monitor_Wait_pulse<br>{<br>    //Printing of Even Numbers Function<br>    const int numberLimit = 20;<br>    static  object _lockMonitor = new object();<br>    public static void PrintEvenNumbers()<br>    {<br>        try<br>        {<br>            //Implement lock as the Console is shared between two threads<br>            System.Threading.Monitor.Enter(_lockMonitor);<br>            for (int i = 0; i &lt;= numberLimit; i = i + 2)<br>            {<br>                //Printing Even Number on Console)<br>                Console.Write($&quot;{i} &quot;);<br>                //Notify Odd thread that I&#39;m done, you do your job<br>                //It notifies a thread in the waiting queue of a change in the <br>                //locked object&#39;s state.<br>                System.Threading.Monitor.Pulse(_lockMonitor);<br>                //I will wait here till Odd thread notify me <br>                //Monitor.Wait(monitor);<br>                //Without this logic application will wait forever<br>                bool isLast = false;<br>                if (i == numberLimit)<br>                {<br>                    isLast = true;<br>                }<br>                if (!isLast)<br>                {<br>                    //I will wait here till Odd thread notify me<br>                    //Releases the lock on an object and blocks the current thread <br>                    //until it reacquires the lock.<br>                    System.Threading.Monitor.Wait(_lockMonitor);<br>                }<br>            }<br>        }<br>        finally<br>        {<br>            //Release the lock<br>            System.Threading.Monitor.Exit(_lockMonitor);<br>        }<br>    }<br>    //Printing of Odd Numbers Function<br>    public static void PrintOddNumbers()<br>    {<br>        try<br>        {<br>            //Hold lock as the Console is shared between two threads<br>            System.Threading.Monitor.Enter(_lockMonitor);<br>            for (int i = 1; i &lt;= numberLimit; i = i + 2)<br>            {<br>                //Printing the odd numbers on the console<br>                Console.Write($&quot;{i} &quot;);<br>                Thread.Sleep(1000);<br>                //Notify Even thread that I&#39;m done, you do your job<br>                System.Threading.Monitor.Pulse(_lockMonitor);<br>                // I will wait here till even thread notify me<br>                // Monitor.Wait(monitor);<br>                // without this logic application will wait forever<br>                bool isLast = false;<br>                if (i == numberLimit - 1)<br>                {<br>                    isLast = true;<br>                }<br>                if (!isLast)<br>                {<br>                    //I will wait here till Even thread notify me<br>                    System.Threading.Monitor.Wait(_lockMonitor);<br>                }<br>            }<br>        }<br>        finally<br>        {<br>            //Release lock<br>            System.Threading.Monitor.Exit(_lockMonitor);<br>        }<br>    }<br>}<br><br><br>            Thread EvenThread = new Thread(Monitor_Wait_pulse.PrintEvenNumbers);<br>            Thread OddThread = new Thread(Monitor_Wait_pulse.PrintOddNumbers);<br>            //First Start the Even thread.<br>            EvenThread.Start();<br>            //Puase for 10 ms, to make sure Even thread has started <br>            //or else Odd thread may start first resulting different sequence.<br>            Thread.Sleep(100);<br>            //Next, Start the Odd thread.<br>            OddThread.Start();<br>            //Wait for all the childs threads to complete<br>            OddThread.Join();<br>            EvenThread.Join();<br>            Console.WriteLine(&quot;\nMain method completed&quot;);<br>            Console.ReadKey();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*oaZlGzXmR_gwMdRrcwwn-A.png" /></figure><h3>Scenario:</h3><ul><li><strong>Producer</strong>: Produces data (e.g., sensor data) and places it in a buffer.</li><li><strong>Consumer</strong>: Consumes (processes) the data from the buffer.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*_gnDVYTpHQxuvcLE.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*aJ07O6sY9JpH2j0v.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*B7_v-QIVMOgi-kOn" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*-78F-8yMh54WGgGg.gif" /></figure><h3>Multithreading vs. Asynchronous Programming vs. Parallel Programming in C#</h3><ol><li><strong>Multithreading:</strong> This is all about a single process split into multiple threads.</li><li><strong>Parallel Programming:</strong> This is all about multiple tasks running on multiple cores simultaneously.</li><li><strong>Asynchronous Programming:</strong> This is all about a single thread initiating multiple tasks without waiting for each to complete.</li></ol><p><strong>What is Multithreading in C#?</strong></p><p>Multithreading in C# refers to the capability to create and manage multiple threads within a single process. A thread is the smallest unit of execution within a process, and multiple threads can run concurrently, sharing the same resources of the parent process but executing different code paths. For a better understanding, please have a look at the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/0*0dtxfGHoxIl_SuV6" /></figure><p><strong>Advantages:</strong></p><ul><li><strong>Improved Responsiveness:</strong> In GUI applications, a long-running task can be moved to a separate thread to keep the UI responsive.</li><li><strong>Better Resource Utilization:</strong> Allows more efficient CPU use, especially on multi-core processors.</li></ul><p><strong>Challenges:</strong></p><ul><li><strong>Deadlocks:</strong> Occur when two or more threads are waiting for each other to release resources, resulting in a standstill.</li><li>Creating too many threads can degrade the application performance due to context-switching overhead.</li><li>Threads consume resources, so that excessive use can degrade performance and responsiveness.</li></ul><h4>use Multithreading</h4><p><strong>CPU-bound Operations:</strong></p><ul><li>If an operation is computationally intensive and can be broken down into smaller, independent tasks, distributing these tasks among multiple threads can lead to faster completion, especially on multi-core processors.</li><li><strong>Asynchronous I/O Operations:</strong></li></ul><p>Though asynchronous programming often handles I/O-bound operations, there are scenarios where traditional multithreading might be used, especially in older codebases or systems that don’t support async/await patterns.</p><ul><li>Asynchronous, multithreaded: you hire two more cooks, one to cook eggs and one to cook toast. Now you have the problem of coordinating the cooks so that they do not conflict with each other in the kitchen when sharing resources. And you have to pay them.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/0*56kzXwsT_DdAEvVf.gif" /></figure><p><strong>Real-Time Processing:</strong></p><ul><li>In applications where real-time processing is crucial, such as gaming or financial trading systems, multithreading can be used to ensure that specific tasks meet their time constraints.</li><li><strong>Resource Pooling:</strong>In scenarios like connection or thread pooling, multiple threads can be pre-spawned to handle incoming tasks efficiently, reducing the overhead of creating a new thread for every new task.</li></ul><h3>Thread Pool in C#</h3><p>When the thread object is created some resources are allocated to that thread object such as memory. After then the task is executed and once the task is completed then the garbage collector removes that thread object to free up memory allocation. This is the life cycle of a thread in C#.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*Imh9uUVjymAi_w63" /></figure><p>These steps are going to be repeated again and again for each request that comes in a multithread application. That means every time a new thread object is created, it gets allocated in the memory. If there are many requests then there will be many thread objects and if there are many thread objects then there will be a load on the memory which slows down your application.</p><p>There is great room for performance improvements. The Thread object is created, resources are allocated, the task is executed, and then it should not go for garbage collection, instead of how about taking the thread object and putting it into a pool as shown in the below image? This is where thread pooling comes into the picture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/0*kDi60KfKcELS69GJ" /></figure><p><strong>Thread Pool in C#:</strong></p><p>The Thread pool in C# is nothing but a collection of threads that can be reused to perform a number of tasks in the background. Now when a request comes, then it directly goes to the thread pool and checks whether there are any free threads available or not. If available, then it takes the thread object from the thread pool and executes the task as shown in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*rN0htFf4ezdiqcaH" /></figure><p>Once the thread completes its task then it is again sent back to the thread pool so that it can reuse. This reusability avoids an application to create a number of threads and this enables less memory consumption.</p><p><strong>using System.Threading;</strong></p><p>Threading namespace, then you need to use the <strong>ThreadPool</strong> class</p><p>using this class you need to call the <strong>QueueUserWorkItem</strong> static method.</p><p>if you go to the definition of the <strong>QueueUserWorkItem</strong> method, then you will see that this method takes one parameter of the type <strong>WaitCallback</strong> object.</p><p>While creating the object of the <strong>WaitCallback</strong> class, you need to pass the method name that you want to execute as shown below</p><p>the <strong>QueueUserWorkItem</strong> method Queues the function for execution and that function executes when a thread becomes available from the thread pool.</p><p>If no thread is available then it will wait until one thread gets freed.</p><pre>class Thread_pool<br>{<br>    public static void MyMethod(object obj)<br>    {<br>        Thread thread = Thread.CurrentThread;<br>        string message = $&quot;Background: {thread.IsBackground}, Thread Pool: {thread.IsThreadPoolThread}, Thread ID: {thread.ManagedThreadId}&quot;;<br>        Console.WriteLine(message);<br>    }<br><br>    public static void MyMethod_not_use_thread_pool()<br>    {<br>        Thread thread = Thread.CurrentThread;<br>        string message = $&quot;Background: {thread.IsBackground}, Thread Pool: {thread.IsThreadPoolThread}, Thread ID: {thread.ManagedThreadId}&quot;;<br>        Console.WriteLine(message);<br>    }<br><br><br>    public static void MethodWithThread()<br>    {<br>        for (int i = 0; i &lt; 10; i++)<br>        {<br>            Thread thread = new Thread(Test);<br>            thread.Start();<br>        }<br>    }<br>    public static void MethodWithThreadPool()<br>    {<br>        for (int i = 0; i &lt; 10; i++)<br>        {<br>            ThreadPool.QueueUserWorkItem(new WaitCallback(Test));<br>        }<br>    }<br>    public static void Test(object obj)<br>    {<br>        // Thread thread = Thread.CurrentThread;<br>        // if (thread.IsBackground == false)<br>        // {<br>        //     string message = $&quot;Background: {thread.IsBackground}, Thread Pool: {thread.IsThreadPoolThread}, Thread ID: {thread.ManagedThreadId}&quot;;<br>        //     Console.WriteLine(message);<br>        // }<br><br>    }<br>}<br><br> #region 13&gt;ThreadPool<br><br>            for (int i = 0; i &lt; 10; i++)<br>            {<br>                ThreadPool.QueueUserWorkItem(new WaitCallback(Thread_pool.MyMethod));<br>            }<br>            Console.Read();<br><br>            for (int i = 0; i &lt; 10; i++)<br>            {<br>                Thread thread = new Thread(Thread_pool.MyMethod_not_use_thread_pool)<br>                {<br>                    Name = &quot;Thread&quot; + i<br>                };<br>                thread.Start();<br>            }<br>            Console.Read();<br><br>            for (int i = 0; i &lt; 10; i++)<br>            {<br>                Thread_pool.MethodWithThread();<br>                Thread_pool.MethodWithThreadPool();<br>            }<br>        <br>            Stopwatch stopwatch = new Stopwatch();<br>            Console.WriteLine(&quot;Execution using Thread&quot;);<br>            stopwatch.Start();<br>            Thread_pool.MethodWithThread();<br>            stopwatch.Stop();<br>            Console.WriteLine(&quot;Time consumed by MethodWithThread is : &quot; +stopwatch.ElapsedTicks.ToString());<br><br>            stopwatch.Reset();<br>            Console.WriteLine(&quot;Execution using Thread Pool&quot;);<br>            stopwatch.Start();<br>            Thread_pool.MethodWithThreadPool();<br>            stopwatch.Stop();<br>            Console.WriteLine(&quot;Time consumed by MethodWithThreadPool is : &quot; +stopwatch.ElapsedTicks.ToString());<br><br>            Console.Read();<br><br>            #endregion</pre><h3>Foreground and Background Threads in C#</h3><ol><li><strong>Foreground Thread</strong></li><li><strong>Background Thread</strong></li></ol><p><strong>Foreground Thread in C#:</strong></p><p>Foreground threads are those threads that keep running even after the main application exits or quits.</p><p>That means if the Main thread leaves the application, then still the foreground threads are running to complete their assigned task.</p><p>So, the foreground threads in C# do not care whether the main thread is alive or not, it completes only when it finishes its assigned work.</p><p>That means the life of a foreground thread in C# does not depend upon the main thread.</p><p>The foreground thread has the ability to<strong> prevent the current application from terminating. </strong>The <strong>CLR will not shut down the application until all the Foreground Threads have finished their assigned work</strong>. The <strong>main thread is a foreground thread.</strong></p><pre><br>class Foreground_Background_Threads<br>{<br><br><br>    // Static method<br>    public static void Method1()<br>    {<br>        Console.WriteLine(&quot;Method1 Started&quot;);<br>        for (int i = 0; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine(&quot;Method1 is in Progress!!&quot;);<br>            Thread.Sleep(1000);<br>        }<br>        Console.WriteLine(&quot;Method1 Exited&quot;);<br>        Console.WriteLine(&quot;Press any key to Exit.&quot;);<br>        Console.ReadKey();<br>    }<br><br>    public static void callMethod1()<br>    {<br>        // A thread created here to run Method1 Parallely<br>        Thread thread1 = new Thread(Method1);<br>        Console.WriteLine($&quot;Thread1 is a Background thread:  {thread1.IsBackground}&quot;);<br>        thread1.Start();<br><br>        //The control will come here and will exit <br>        //the main thread or main application<br>        Console.WriteLine(&quot;Main Thread Exited&quot;);<br><br>    }<br><br>     <br><br>        <br>}<br><br><br>Foreground_Background_Threads.callMethod1();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/363/1*ASrPt3RPCwRl87_1Q_P5Zw.png" /></figure><p><strong>Background Thread in C#:</strong></p><p>By default when we created a thread in C#, it is a Foreground Thread.</p><p>And, if you want to make a thread as a background thread, then you need to set the IsBackground property of the thread object to true.</p><p>Background Threads are the threads that will quit if our main thread quits i.e. if all the foreground threads quit, then automatically the background thread quits. Let us understand this with an example.</p><p>We are rewriting the previous example and here we simply set the IsBackground property to true of the thread object.</p><pre><br>class Foreground_Background_Threads<br>{<br><br>  <br>  <br>     // Static method<br>        static void Background_Method1()<br>        {<br>            Console.WriteLine(&quot;Method1 Started&quot;);<br>            for (int i = 0; i &lt;= 5; i++)<br>            {<br>                Console.WriteLine(&quot;Method1 is in Progress!!&quot;);<br>                Thread.Sleep(1000);<br>            }<br>            Console.WriteLine(&quot;Method1 Exited&quot;);<br>            Console.WriteLine(&quot;Press any key to Exit.&quot;);<br>            Console.ReadKey();<br>        }<br><br>        public static void call_Background_Method1(){<br>             // A thread created here to run Method1 Parallely<br>            Thread thread1 = new Thread(Background_Method1)<br>            {<br>                //Thread becomes background thread<br>                IsBackground = true<br>            };<br>            <br>            Console.WriteLine($&quot;Thread1 is a Background thread:  {thread1.IsBackground}&quot;);<br>            thread1.Start();<br><br>            //The control will come here and will exit <br>            //the main thread or main application<br>            Console.WriteLine(&quot;Main Thread Exited&quot;);<br><br>            //As the Main thread (i.e. foreground thread exits the application)<br>            //Automatically, the background thread quits the application<br>        }<br>}   <br><br>Foreground_Background_Threads.call_Background_Method1();</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*aUdKXbMRXRHqJKPZx-m9nw.png" /></figure><p><strong>Points to Remember:</strong></p><ol><li>The primary thread (or main application thread).</li><li>All threads are created by calling a Thread class constructor.</li><li>thread is either a background thread or a foreground thread. Background threads are similar to the foreground threads, except that the background threads do not prevent a process from terminating.</li></ol><p>By default, the following threads execute in the background (that is, their IsBackground property returns true):</p><ol><li>Thread pool threads are a pool of worker threads maintained by the runtime. You can configure the thread pool and schedule work on thread pool threads by using the ThreadPool class.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*MtB7MO71Jw_6cTrov37i2w.png" /></figure><h3>Asynchronous programming</h3><p>Asynchronous programming in C# is a method of performing tasks without blocking the main or calling thread. This is especially beneficial for I/O-bound operations (like reading from a file, fetching data from the web, or querying a database), where waiting for the task to be completed might waste valuable CPU time that could be better spent doing other work. For a better understanding, please have a look at the following diagram.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/839/0*__U-gJinhWD-uvVz" /></figure><p>As you can see in the above image, when a request comes to the server, the server will use the Thread Pool thread and start executing the application code. But the important point that you need to keep in mind is that if the thread performs some IO Operation, it will not wait till the IO Operation is completed, which means the thread will not block; it will come back to the Thread Pool and the same thread can handle another request. In this way, it will use the CPU resources effectively, i.e., it can handle more client requests and improve the application’s overall performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/0*aPSijf0s0MzFIMLF.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/0*VAYzYW3cAF3BZIEt.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*0RN03h3X6NNPGF4b.gif" /></figure><ul><li>Asynchronous, single threaded: you start the eggs cooking and set a timer. You start the toast cooking, and set a timer. While they are both cooking, you clean the kitchen. When the timers go off you take the eggs off the heat and the toast out of the toaster and serve them.</li></ul><p><strong>Considerations</strong></p><ul><li>Using async and await doesn’t mean you’re introducing <strong>multithreading. It’s about the efficient use of threads</strong>.</li><li>Asynchronous code can sometimes be more challenging to debug and reason about, especially when dealing with exceptions or coordinating multiple asynchronous operations.</li></ul><pre>using System.Diagnostics;<br><br>class Async_Await<br>{<br>    // Asynchronous method to read the file using async/await<br>    public static async Task&lt;string&gt; ReadFileAsync(string filePath)<br>    {<br>        try<br>        {<br>            using (StreamReader reader = new StreamReader(filePath))<br>            {<br>                // Asynchronously read the file content<br>                string content = await reader.ReadToEndAsync();<br>                return content;<br>            }<br>        }<br>        catch (Exception ex)<br>        {<br>            return $&quot;Error reading file: {ex.Message}&quot;;<br>        }<br>    }<br><br>    public static async Task call_read_file_function()<br>    {<br>        Console.WriteLine(&quot;Main Method Started&quot;);<br><br>        // Measure the execution time<br>        Stopwatch stopwatch = new Stopwatch();<br>        stopwatch.Start();<br><br>        // Call the async method to read the file (doesn&#39;t block main thread)<br>        Task&lt;string&gt; task = ReadFileAsync(&quot;demo.txt&quot;);<br><br>        // Meanwhile, do other work (this happens while the file is being read)<br>        for (int i = 1; i &lt;= 5; i++)<br>        {<br>            Console.WriteLine($&quot;Doing other work {i}...&quot;);<br>            await Task.Delay(500); // Simulating some other work<br>        }<br>        for (int i = 1; i &lt;= 10; i++)<br>        {<br>            Console.WriteLine($&quot;Doing other work  222{i}...&quot;);<br>            await Task.Delay(500); // Simulating some other work<br>        }<br><br>        // Now await the result from the file reading (if it&#39;s completed)<br>        string content = await task;<br>        Console.WriteLine(&quot;File content:\n&quot; + content);<br><br>        stopwatch.Stop();<br>        Console.WriteLine($&quot;Async File I/O Completed in {stopwatch.ElapsedMilliseconds} ms&quot;);<br>    }<br>}<br><br><br><br>            #region 13&gt; AsyncFileIO<br><br>            Task t = Async_Await.call_read_file_function();<br><br>            Console.WriteLine(&quot;main method is not block .........&quot;);<br>            for (int i = 1; i &lt;= 10; i++)<br>            {<br>                Console.WriteLine($&quot;Doing other work  main method ......{i}...&quot;);<br>                await Task.Delay(500); // Simulating some other work<br>            }<br>            await t;<br><br>            #endregion</pre><h4>use Asynchronous Programming</h4><p><strong>I/O-bound Operations:</strong></p><ul><li><strong>File I/O:</strong> When reading or writing large files, use asynchronous methods to prevent blocking, especially in user-facing applications.</li><li><strong>Network I/O:</strong> When making network requests, such as calling external APIs, fetching resources over the internet, or any other network operations.</li><li><strong>Database Operations:</strong> Database queries, especially those that might take a long time, can be executed asynchronously to prevent blocking the main execution flow.</li><li><strong>Web Servers:</strong> Asynchronous programming can dramatically improve the scalability of web servers. For example, ASP.NET Core uses an asynchronous model to handle requests, allowing the server to manage more concurrent requests with fewer resources.</li></ul><p><strong>Chaining Multiple Operations:</strong></p><ul><li>With async and await, it’s easy to chain multiple asynchronous operations, ensuring they execute in the required order but without blocking the main thread during waits.</li><li><strong>IO-Bound Operations:</strong> Asynchronous programming is best suited for IO-Bound Operations.</li><li><strong>CPU-Bound Operations:</strong> Parallel Programming and Multithreading best suitable for CPU-Bound Operations.</li></ul><p><strong>Multithreading:</strong></p><ul><li><strong>Concurrent Execution:</strong> Multithreading allows multiple threads to execute concurrently because multiple tasks need to run simultaneously or to keep a system responsive by separating long-running tasks from short-lived ones.</li><li><strong>Resource Sharing:</strong> Multiple threads of the same process share the same memory space. This means different threads can work on shared data (though care must be taken to synchronize access).</li><li><strong>Better Resource Utilization:</strong> Rather than having a CPU idle while waiting for I/O operations (like reading a file or waiting for network data), multithreading can utilize that CPU time to do other tasks.</li><li><strong>Responsiveness:</strong> A dedicated UI thread can remain responsive to user actions in UI applications, while background threads handle other tasks.</li></ul><p><strong>Asynchronous Programming:</strong></p><ul><li><strong>Non-blocking Execution:</strong> The primary goal of asynchronous programming is to perform operations without blocking the executing thread, which is especially relevant for I/O-bound tasks.</li><li><strong>Improved Responsiveness:</strong> By not waiting for a task to be completed, systems (like UIs) can remain responsive. The system can start a task and then move on to other operations, returning to the initial task once it’s finished.</li><li><strong>Scalability:</strong> In server applications, asynchronous operations can handle many client requests without tying up resources and waiting for tasks like database queries or network calls to complete.</li><li><strong>Cleaner Code for Complex Operations:</strong> With constructs like async and await in C#, managing complex operations, especially I/O-bound ones, becomes more straightforward compared to traditional callback mechanisms.</li></ul><p><strong>Parallel Programming:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/0*6CPvWyvcPlO_LLLw" /></figure><ul><li><strong>Maximize CPU Utilization:</strong> The primary goal of parallel programming is to leverage all available CPU cores to perform computation-intensive tasks faster.</li><li><strong>Data Parallelism:</strong> Execute the same operation on multiple data elements simultaneously. For example, processing an array of numbers or applying a filter to an image.</li><li><strong>Task Parallelism:</strong> Execute different operations in parallel if they’re independent of each other.</li><li><strong>Reduce Computation Time:</strong> The total computation time can be reduced significantly for tasks that can be broken down and executed in parallel.</li><li><strong>Efficiently Solve Large Problems:</strong> Problems like simulations, complex calculations, or large-scale data processing can be tackled more efficiently.</li></ul><p>In my case, I have 4 cores and 8 logical processors as shown in the below image. This means that each core can do two operations simultaneously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ldTIg2X-nGiUR7AqjfSCTQ.png" /></figure><p><strong>Thread Class Properties in C#:</strong></p><p>The Thread class in C# provides lots of properties. Some of the important properties are as follows:</p><ol><li><strong>CurrentThread</strong>: This property is used to get the currently running thread. It returns a Thread that is the representation of the currently running thread.</li><li><strong>IsAlive</strong>: This property is used to get a value indicating the execution status of the current thread. It returns true if this thread has been started and has not terminated normally or aborted; otherwise, false.</li><li><strong>IsBackground</strong>: This property is used to get or set a value indicating whether or not a thread is a background thread. It returns true if this thread is or is to become a background thread; otherwise, false.</li><li><strong>ManagedThreadId</strong>: This property is used to get a unique identifier for the current managed thread. It returns an integer that represents a unique identifier for this managed thread.</li><li><strong>Name</strong>: This property is used to get or set the name of the thread. It returns a string containing the name of the thread, or null if no name was set.</li><li><strong>Priority</strong>: This property is used to get or set a value indicating the scheduling priority of a thread. It returns one of the System.Threading.ThreadPriority values. The default value is System.Threading.ThreadPriority.Normal.</li><li><strong>ThreadState</strong>: This property is used to get a value containing the states of the current thread. It returns one of the System.Threading.ThreadState values indicate the state of the current thread. The initial value is Unstarted.</li><li><strong>IsThreadPoolThread</strong>: This property is used to get a value indicating whether or not a thread belongs to the managed thread pool. It returns true if this thread belongs to the managed thread pool; otherwise, false.</li></ol><p><strong>Thread Class Methods in C#:</strong></p><p>The Thread class in C# provides lots of methods. Some of the important methods are as follows:</p><ol><li><strong>Abort():</strong> This method is used to terminate the thread. Raises a ThreadAbortException in the thread on which it is invoked, to begin the process of terminating the thread. Calling this method usually terminates the thread.</li><li><strong>Join():</strong> This method is used to block the calling thread until the thread represented by this instance terminates while continuing to perform standard COM and SendMessage pumping.</li><li><strong>ResetAbort():</strong> This method is used to an System.Threading.Thread.Abort(System.Object) requested for the current thread.</li><li><strong>Resume():</strong> This method is used to resume a thread that has been suspended.</li><li><strong>Sleep(Int32):</strong> This method is used to suspend the current thread for the specified number of milliseconds.</li><li><strong>Start():</strong> This method causes the operating system to change the state of the current instance to System.Threading.ThreadState.Running.</li><li><strong>Suspend():</strong> This method is used to either suspend the thread or if the thread is already suspended, have no effect</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b80332b777b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[joins]]></title>
            <link>https://medium.com/@yashdesai281/joins-8a7cbb2cf257?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7cbb2cf257</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Mon, 23 Sep 2024 19:31:56 GMT</pubDate>
            <atom:updated>2024-09-23T19:31:56.629Z</atom:updated>
            <content:encoded><![CDATA[<pre>create table dept(<br>dept_id serial primary key not null,<br> name VARCHAR(100) NOT NULL,<br>    location VARCHAR(50),<br>    budget NUMERIC(12, 2)<br>);<br><br>create table emp(<br>emp_id serial primary key not null,<br>name VARCHAR(100) NOT NULL,<br>    dept_id INT REFERENCES dept(dept_id),<br>    salary NUMERIC(10, 2),<br>    status VARCHAR(20)<br>);<br><br>create table product(<br>p_id serial primary key not null,<br> name VARCHAR(100) NOT NULL,<br>    category_id INT,<br>    price NUMERIC(10, 2)<br>);<br><br>create table orders(<br>o_id serial primary key not null,<br>emp_id INT,<br>    p_id INT ,<br>    total NUMERIC(10, 2),<br>    order_date DATE,<br> constraint fk_key_emp foreign key(emp_id)references emp(emp_id),<br> constraint fk_key_product foreign key(p_id)references product(p_id)<br><br>);</pre><p>insert data</p><pre>-- Insert data into &#39;departments&#39;<br>INSERT INTO dept (name, location, budget)<br>VALUES<br>(&#39;HR&#39;, &#39;NYC&#39;, 50000),<br>(&#39;IT&#39;, &#39;SF&#39;, 200000),<br>(&#39;Sales&#39;, &#39;LA&#39;, 150000),<br>(&#39;Finance&#39;, &#39;NYC&#39;, 300000),<br>(&#39;Marketing&#39;, &#39;LA&#39;, 120000);<br><br>-- Insert data into &#39;employees&#39;<br>INSERT INTO emp (name, dept_id, salary, status)<br>VALUES<br>(&#39;Alice&#39;, 1, 60000, &#39;active&#39;),<br>(&#39;Bob&#39;, 2, 8000, &#39;active&#39;),<br>(&#39;Charlie&#39;, 3, 55000, &#39;inactive&#39;),<br>(&#39;David&#39;, 4, 90000, &#39;active&#39;),<br>(&#39;Eve&#39;, 5, 75000, &#39;active&#39;),<br>(&#39;yash&#39;, 1, 60000, &#39;active&#39;),<br>(&#39;dev&#39;, 2, 80000, &#39;active&#39;),<br>(&#39;vedu&#39;, 1, 55000, &#39;inactive&#39;),<br>(&#39;deep&#39;, 1, 90000, &#39;active&#39;),<br>(&#39;zeel&#39;, 5, 75000, &#39;active&#39;);<br><br>select * from emp<br><br>-- Insert data into &#39;products&#39;<br>INSERT INTO product (name, category_id, price)<br>VALUES<br>(&#39;Laptop&#39;, 1, 1500),<br>(&#39;Phone&#39;, 1, 800),<br>(&#39;Tablet&#39;, 2, 600),<br>(&#39;Headphones&#39;, 3, 150),<br>(&#39;Smartwatch&#39;, 2, 200);<br><br>-- Insert data into &#39;orders&#39;<br>INSERT INTO orders (emp_id, p_id, total, order_date)<br>VALUES<br>(1, 1, 1500, &#39;2024-08-01&#39;),<br>(2, 2, 800, &#39;2024-08-02&#39;),<br>(3, 3, 600, &#39;2024-08-03&#39;),<br>(4, 1, 1500, &#39;2024-08-04&#39;),<br>(5, 4, 150, &#39;2024-08-05&#39;),<br>(4, 1, 1500, &#39;2024-08-04&#39;);</pre><pre>select d.name,m.salary,m.name from dept as d<br>join  <br>(select name,dept_id,salary from emp where (dept_id,salary) in (select dept_id,max(salary) as salary from emp group by dept_id))<br> as m<br>on m.dept_id=d.dept_id;</pre><p>all employees who work in departments located in ‘NYC’?</p><pre><br><br>select e.name,d.name,d.location <br>from emp as e <br>join dept as d<br> on e.dept_id=d.dept_id where d.location=&#39;NYC&#39;<br><br><br>select e.name from emp as e<br> join dept as d<br> on e.dept_id=d.dept_id where d.location=&#39;NYC&#39;<br><br><br>select name from emp where <br>dept_id in (select dept_id from dept where location=&#39;NYC&#39;)<br></pre><p>names of products that have been ordered more than 2times?</p><pre>select name from product where p_id in(<br>select p_id from orders group by p_id having count(*)&gt;2);<br><br>select name from product as p  where  exists(<br>select p_id from orders where p.p_id=p_id group by p_id having count(*)&gt;2);</pre><p>departments that have more than 1 employees?</p><pre><br>select name from dept where dept_id <br>in (select dept_id from emp group by dept_id having count(*)&gt;1);<br><br>select d.name from dept as d inner join emp as e <br>on  d.dept_id=e.dept_id group by (d.dept_id) having count(*)&gt;1;</pre><p>employees who have a salary greater than the average salary of their department</p><pre>select name from emp as e where salary &gt; (<br>select avg(salary) as avgsalary from emp as d where e.dept_id=d.dept_id<br>)<br><br></pre><p>all employees that do not have any orders</p><pre>select e.name from emp as e left join orders as o <br>on e.emp_id=o.emp_id where o.o_id is null<br><br><br>select name from emp where emp_id not in(select emp_id from orders)<br><br><br>select name from emp as e where not exists (<br>select emp_id from orders as o <br> where o.emp_id=e.emp_id<br>)<br></pre><p>total number of employees in each department</p><pre>select d.name,count(*) from emp as e join dept as d <br>on <br>d.dept_id=e.dept_id group by d.name<br><br>select dept_id,count(*)from emp group by dept_id<br><br></pre><p>will list the names of employees who work in departments that are located in ‘SF’ and have a budget greater than 100,000</p><pre>select e.name from emp as e join dept as d <br>on<br>e.dept_id =d.dept_id where d.location=&#39;SF&#39; AND budget&gt;1000;<br><br><br>select name from emp where dept_id in (<br>select dept_id from dept where location=&#39;SF&#39; AND budget&gt;1000<br>)<br><br><br>select name from emp as e where  exists (<br>select dept_id from dept as d where <br>e.dept_id =d.dept_id<br> AND location=&#39;SF&#39; <br>AND budget&gt;1000<br>)<br></pre><p>retrieve all employees who work in departments that do not have any active employees</p><pre><br>select e.name from emp as e <br>join dept as d<br>on <br>e.dept_id=d.dept_id where d.dept_id not in(select dept_id from emp where status=&#39;active&#39;);<br><br><br>select name from emp  where dept_id not in(<br>select dept_id from emp where status=&#39;active&#39;<br>);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7cbb2cf257" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[pgsql]]></title>
            <link>https://medium.com/@yashdesai281/pgsql-08a430d67af4?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/08a430d67af4</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 19:04:42 GMT</pubDate>
            <atom:updated>2024-09-23T05:07:03.645Z</atom:updated>
            <content:encoded><![CDATA[<pre>create table sales(<br>sid serial primary key not null,<br>product varchar(50),<br>category varchar(50),<br>region varchar(50),<br>quantity int,<br>saleamount decimal(10,2),<br>saledate date<br>);<br><br></pre><pre>insert into sales(product,category,region,quantity,saleamount,saledate)<br>values(&#39;Product A&#39;, &#39;Category 1&#39;, &#39;East&#39;, 10, 100.00, &#39;2024-01-01&#39;),<br>(&#39;Product B&#39;, &#39;Category 2&#39;, &#39;West&#39;, 5, 50.00, &#39;2024-01-02&#39;),<br>(&#39;Product C&#39;, &#39;Category 1&#39;, &#39;East&#39;, 7, 70.00, &#39;2024-01-03&#39;),<br>(&#39;Product A&#39;, &#39;Category 1&#39;, &#39;West&#39;, 15, 150.00, &#39;2024-01-04&#39;),<br>(&#39;Product B&#39;, &#39;Category 2&#39;, &#39;East&#39;, 8, 80.00, &#39;2024-01-05&#39;),<br>(&#39;Product C&#39;, &#39;Category 1&#39;, &#39;North&#39;, 12, 120.00, &#39;2024-01-06&#39;);</pre><p>The <strong>GROUP BY</strong> clause in SQL is used to group rows that have the same values in specified columns into summary rows,</p><p>like finding the <strong>sum</strong>, <strong>count</strong>, <strong>average</strong>, <strong>min</strong>, or <strong>max</strong> of groups of data. It is often used in conjunction with aggregate functions such as SUM(), COUNT(), AVG(), MIN(), and MAX().</p><p>The GROUP BY clause groups the rows based on the specified column(s) and returns a single row for each group.</p><h3>Key Points About GROUP BY:</h3><ol><li>The GROUP BY clause is used to <strong>group rows</strong> that have the same values in one or more columns.</li><li>It works with <strong>aggregate functions</strong> (SUM(), COUNT(), AVG(), etc.) to return a summary result for each group.</li><li>It is typically used in combination with <strong>SELECT</strong> to return a summary of grouped data.</li><li>You cannot select columns that are not part of the GROUP BY clause unless they are inside aggregate functions.</li></ol><pre>select count(category),category from sales group by category;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*QkCLtnNU-VcntEkl0BMqrg.png" /></figure><pre>select category,count(category) as countcal from sales group by category having count(category)&gt;2;</pre><p>The HAVING clause is used to filter results after grouping. It’s similar to the WHERE clause, but WHERE filters before the grouping, while HAVING filters after the groups are formed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/1*LemWr1lVMW3iMJJ6EtNw7Q.png" /></figure><pre><br>select category,count(category) from sales where region=&#39;East&#39; group by category ;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*vmvOh2xodmZ5kyVvs5An5g.png" /></figure><p>● <strong>UNION</strong>: Combines the results of two queries and removes duplicates.</p><p>● <strong>UNION ALL</strong>: Combines the results of two queries but does not remove duplicates.</p><p>● <strong>INTERSECT</strong>: Returns only the rows that are common between two queries.</p><p>● <strong>EXCEPT</strong>: Returns the rows that are in the first query but not in the second.</p><pre>select product from sales where region=&#39;East&#39;<br>union <br>select product from sales where region=&#39;West&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/249/1*mPULYabeDZqNhkW0cipeTg.png" /></figure><pre><br>CREATE TABLE Sales (<br>    Sale_ID SERIAL PRIMARY KEY,<br>    Product_Name VARCHAR(50) NOT NULL,<br>    Seller_Name VARCHAR(50) NOT NULL,<br>    Customer_Name VARCHAR(50) NOT NULL,<br>    Sale_Amount NUMERIC(10, 2) NOT NULL,<br>    Sale_Date DATE NOT NULL,<br>    Quantity INT NOT NULL<br>);<br><br><br>INSERT INTO Sales (Sale_ID, Product_Name, Seller_Name, Customer_Name, Sale_Amount, Sale_Date, Quantity)<br>VALUES<br>(1, &#39;Laptop&#39;, &#39;John&#39;, &#39;Alice&#39;, 1000, &#39;2023-09-01&#39;, 1),<br>(2, &#39;Smartphone&#39;, &#39;Alice&#39;, &#39;Bob&#39;, 600, &#39;2023-09-02&#39;, 2),<br>(3, &#39;Headphones&#39;, &#39;Carol&#39;, &#39;Alice&#39;, 150, &#39;2023-09-03&#39;, 1),<br>(4, &#39;Laptop&#39;, &#39;John&#39;, &#39;Dave&#39;, 1000, &#39;2023-09-04&#39;, 1),<br>(5, &#39;Smartphone&#39;, &#39;Alice&#39;, &#39;Eve&#39;, 600, &#39;2023-09-05&#39;, 1),<br>(6, &#39;Headphones&#39;, &#39;Carol&#39;, &#39;Bob&#39;, 150, &#39;2023-09-06&#39;, 2);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lrmaXEutj4T-D6z7du1oFQ.png" /></figure><h3>grouping sets</h3><p>The <strong>GROUPING SETS</strong> clause allows you to specify multiple groupings in a single query, avoiding the need for multiple GROUP BY queries. It can be thought of as a combination of several GROUP BY clauses.</p><pre><br>select Product_Name,Seller_Name,sum(Sale_Amount)from Sales <br>group by grouping sets(<br>(Product_Name),<br>(Seller_Name),<br>(Product_Name,Seller_Name),<br>()<br>);<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*__P09SbDWK1epIihvyYDtg.png" /></figure><p><strong>— Overall total (no grouping)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*6EV9wlVnFTDC-g9unL84Lg.png" /></figure><p><strong>— Group by both Product and Seller</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*jQ60Tdm9uT49xtOaKySriw.png" /></figure><p><strong>— Group by Product</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*_JgTtseHjQE_X_3JX8-hRQ.png" /></figure><p><strong>— Group by Seller</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*03kloFXU8RGI0Ovvt9llGQ.png" /></figure><h3>2. CUBE</h3><p>The <strong>CUBE</strong> clause generates a result set that includes all possible combinations of the specified columns, including all groupings, subtotals, and grand totals. It is useful for multidimensional data analysis.</p><pre>select Product_Name,Seller_Name,sum(Sale_Amount)from Sales<br> group by  cube<br>(Product_Name,Seller_Name);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*mvQg_XXS8hPNAnRjsR2ZPw.png" /></figure><p><strong>— Overall total ()</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*6EV9wlVnFTDC-g9unL84Lg.png" /></figure><p><strong>— Group by both Product and Seller</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*jQ60Tdm9uT49xtOaKySriw.png" /></figure><p><strong>— Group by Product</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/537/1*_JgTtseHjQE_X_3JX8-hRQ.png" /></figure><p><strong>— Group by Seller</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*03kloFXU8RGI0Ovvt9llGQ.png" /></figure><pre><br>select Product_Name,Seller_Name,sum(Sale_Amount),<br>count(Product_Name) as total_product<br>from Sales<br>group by  cube(Product_Name,Seller_Name);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*YlamcWlAITiH850BGHCLXQ.png" /></figure><h3>3. <strong>ROLLUP</strong></h3><p>The <strong>ROLLUP</strong> clause is similar to CUBE, but it produces hierarchical subtotals. It creates subtotals that &quot;roll up&quot; from the most detailed level to the grand total. It’s useful when you want subtotals at different levels of aggregation.</p><pre><br>select Product_Name,Seller_Name,sum(Sale_Amount) as total_product from Sales<br>group by  rollup(Product_Name,Seller_Name);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*hxCm7CgORwEUH0n6MIGXmQ.png" /></figure><pre><br>select Product_Name,Seller_Name,Customer_Name,<br>sum(Sale_Amount),count(Product_Name) as total_product from Sales <br>group by  rollup(Product_Name,Seller_Name,Customer_Name);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/853/1*zAaKc0O6XSPKEVtmt9TelQ.png" /></figure><p>cube</p><pre><br>select Product_Name,Seller_Name,Customer_Name,sum(Sale_Amount),<br>count(Product_Name)<br> as total_product from Sales group by  <br>cube(Product_Name,Seller_Name,Customer_Name);</pre><p>fine current date</p><pre>select current_date</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/188/1*wZi8z6n6qJGk7aEazCydYA.png" /></figure><p>date function extract()</p><pre>select extract(year from sale_date),<br>extract(day from sale_date),<br>extract(month from sale_date)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*MGk8zUvtIGQUO83FmDOj0A.png" /></figure><p>AGE function</p><pre>select age(sale_date)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/180/1*Hgh8w6DMOSlwq0A_pHolGQ.png" /></figure><p>date_part function</p><pre>select date_part(&#39;dow&#39;,sale_date)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/207/1*Ujf3PfyKU3fWMmKHHZwJBA.png" /></figure><pre>select date_part(&#39;doy&#39;,sale_date)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*MYs6ZaYQgvKE3b88Yea3xA.png" /></figure><pre>select date_part(&#39;month&#39;,sale_date)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*c8UMs9yUb_hukGv0qAUdNw.png" /></figure><h3><strong>String Functions</strong></h3><p>upper</p><pre>select upper(product_name)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/182/1*QyTuLrUtu6V2iojEh5ZWEQ.png" /></figure><p>lower</p><pre>select lower(product_name)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/167/1*XjPP2grXD8Ew8FkeJ0o9Qg.png" /></figure><p><strong>SUBSTRING</strong></p><pre>select substring(product_name,1,5)from sales<br><br>select substring(product_name from 1 for 5)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/163/1*dfJiicjeSHordV8vt62CgA.png" /></figure><p><strong>CONCAT</strong></p><pre>select concat(product_name,&#39;====&#39;,seller_name)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*i_Bj29k2OmPaquCzb4btrg.png" /></figure><pre><br>-- LENGTH: Returns the number of characters in a string.<br>SELECT LENGTH(&#39;PostgreSQL&#39;) AS length_result;<br><br>-- TRIM: Removes leading and trailing whitespace (or other characters).<br>SELECT TRIM(&#39;   PostgreSQL   &#39;) AS trim_result;<br><br>-- BTRIM: Removes specific characters from both ends of a string.<br>SELECT BTRIM(&#39;---PostgreSQL---&#39;, &#39;-&#39;) AS btrim_result;<br><br><br>-- POSITION: Finds the position of a substring within a string.<br>SELECT POSITION(&#39;gre&#39; IN &#39;PostgreSQL&#39;) AS position_result;<br><br>-- REVERSE: Reverses the characters in a string.<br>SELECT REVERSE(&#39;PostgreSQL&#39;) AS reverse_result;<br><br></pre><p><strong>Math Functions</strong></p><pre>select round(sale_amount)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/157/1*D3K3fP8NiOpBnl4Nm3X9mg.png" /></figure><pre>select power(sale_amount,2)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*WrtVM0K9f3QCZELBwhxA-A.png" /></figure><h3>1. ABS()</h3><p>Returns the absolute value of a number.</p><pre>SELECT ABS(-15.67) AS abs_result;</pre><p>Output: 15.67</p><h3>2. CEIL() / CEILING()</h3><p>Returns the smallest integer greater than or equal to the given number.</p><pre>SELECT CEIL(4.3) AS ceil_result;</pre><p>Output: 5</p><h3>3. FLOOR()</h3><p>Returns the largest integer less than or equal to the given number.</p><pre>SELECT FLOOR(4.7) AS floor_result;</pre><p>Output: 4</p><h3>4. SQRT()</h3><p>Returns the square root of a number.</p><pre>SELECT SQRT(16) AS sqrt_result;</pre><p>Output: 4</p><h3>5 CBRT()</h3><p>Returns the cube root of a number.</p><pre>SELECT CBRT(27) AS cbrt_result;</pre><p>Output: 3</p><h3>6. TRUNC()</h3><p>Truncates a number to the specified number of decimal places without rounding.</p><pre>SELECT TRUNC(4.567, 2) AS trunc_result;</pre><p>Output: 4.56</p><h3>7. SIGN()</h3><p>Returns the sign of a number: -1 for negative, 0 for zero, 1 for positive.</p><pre>SELECT SIGN(-10) AS sign_result;</pre><p>Output: -1</p><pre>-- PostgreSQL Math Functions Examples<br><br>-- ABS: Returns the absolute value of a number.<br>SELECT ABS(-15.67) AS abs_result;<br><br>-- CEIL: Returns the smallest integer greater than or equal to the given number.<br>SELECT CEIL(4.3) AS ceil_result;<br><br>-- FLOOR: Returns the largest integer less than or equal to the given number.<br>SELECT FLOOR(4.7) AS floor_result;<br><br>-- ROUND: Rounds a number to the nearest integer or to the specified decimal places.<br>SELECT ROUND(4.567, 2) AS round_result;<br><br>-- POWER: Raises a number to the power of another number.<br>SELECT POWER(2, 3) AS power_result;<br><br>-- SQRT: Returns the square root of a number.<br>SELECT SQRT(16) AS sqrt_result;<br><br>-- CBRT: Returns the cube root of a number.<br>SELECT CBRT(27) AS cbrt_result;<br><br>-- EXP: Returns e raised to the power of the given number.<br>SELECT EXP(1) AS exp_result;<br><br>-- LN: Returns the natural logarithm of a number.<br>SELECT LN(10) AS ln_result;<br><br>-- LOG: Returns the logarithm of a number with the given base.<br>SELECT LOG(10, 100) AS log_result;<br><br>-- PI: Returns the value of pi.<br>SELECT PI() AS pi_result;<br><br>-- TRUNC: Truncates a number to the specified number of decimal places.<br>SELECT TRUNC(4.567, 2) AS trunc_result;<br><br>-- SIGN: Returns the sign of a number.<br>SELECT SIGN(-10) AS sign_result;<br><br>-- DEGREES: Converts a value from radians to degrees.<br>SELECT DEGREES(PI()) AS degrees_result;<br><br>-- RADIANS: Converts a value from degrees to radians.<br>SELECT RADIANS(180) AS radians_result;<br><br>-- MOD: Returns the remainder of division.<br>SELECT MOD(10, 3) AS mod_result;<br><br>-- RANDOM: Generates a random number between 0 and 1.<br>SELECT RANDOM() AS random_result;<br><br>-- SETSEED: Sets the seed for the RANDOM() function.<br>SELECT SETSEED(0.5);<br>SELECT RANDOM() AS random_with_seed;<br><br>-- WIDTH_BUCKET: Returns the bucket number to which the given value falls.<br>SELECT WIDTH_BUCKET(5.35, 0.0, 10.0, 5) AS bucket_result;<br><br>-- Trigonometric functions<br>SELECT SIN(PI()/2) AS sin_result;<br>SELECT COS(PI()) AS cos_result;<br>SELECT TAN(PI()/4) AS tan_result;<br>SELECT ASIN(1) AS asin_result;<br>SELECT ACOS(1) AS acos_result;<br>SELECT ATAN(1) AS atan_result;<br><br>-- GCD: Greatest Common Divisor<br>SELECT GCD(15, 20) AS gcd_result;<br><br>-- LCM: Least Common Multiple<br>SELECT LCM(15, 20) AS lcm_result;</pre><h3><strong>Array Functions</strong></h3><p><strong>ARRAY_AGG</strong></p><pre>select array_agg(product_name)from sales</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/543/1*56l8GOEF4Po2TfdCSXM-Qw.png" /></figure><p>unnest</p><pre>select unnest(array_agg(product_name))from sales</pre><h3>4. ARRAY_APPEND()</h3><p>Appends a new element to the end of an array.</p><pre>SELECT ARRAY_APPEND(ARRAY[1, 2, 3], 4) AS appended_array;</pre><p>Output: {1, 2, 3, 4}</p><h3>5. ARRAY_PREPEND()</h3><p>Prepends a new element to the beginning of an array.</p><pre>SELECT ARRAY_PREPEND(0, ARRAY[1, 2, 3]) AS prepended_array;</pre><p>Output: {0, 1, 2, 3}</p><h3>6. ARRAY_CAT()</h3><p>Concatenates two arrays.</p><pre>SELECT ARRAY_CAT(ARRAY[1, 2], ARRAY[3, 4]) AS concatenated_array;</pre><p>Output: {1, 2, 3, 4}</p><h3>7. ARRAY_LENGTH()</h3><p>Returns the length of the array (number of elements).</p><pre>SELECT ARRAY_LENGTH(ARRAY[1, 2, 3, 4], 1) AS array_length;</pre><p>Output: 4</p><h3>8. CARDINALITY()</h3><p>Returns the total number of elements in a multi-dimensional array.</p><pre>SELECT CARDINALITY(ARRAY[[1, 2], [3, 4]]) AS cardinality_result;</pre><p>Output: 4</p><h3>9. ARRAY_DIMS()</h3><p>Returns the dimensions of a multi-dimensional array.</p><pre>SELECT ARRAY_DIMS(ARRAY[[1, 2], [3, 4]]) AS array_dims;</pre><p>Output: [1:2][1:2]</p><h3>10. ARRAY_FILL()</h3><p>Creates an array filled with a specified value and dimensions.</p><pre>SELECT ARRAY_FILL(0, ARRAY[3]) AS filled_array;</pre><p>Output: {0, 0, 0}</p><h3>11. ARRAY_POSITION()</h3><p>Finds the position of the first occurrence of a value in an array.</p><pre>SELECT ARRAY_POSITION(ARRAY[1, 2, 3, 4], 3) AS array_position;</pre><p>Output: 3</p><h3>12. ARRAY_REMOVE()</h3><p>Removes all occurrences of a value from an array.</p><pre>SELECT ARRAY_REMOVE(ARRAY[1, 2, 3, 2, 4], 2) AS array_without_twos;</pre><p>Output: {1, 3, 4}</p><h3>13. ARRAY_REPLACE()</h3><p>Replaces all occurrences of one value with another in an array.</p><pre>SELECT ARRAY_REPLACE(ARRAY[1, 2, 3, 2, 4], 2, 5) AS replaced_array;</pre><p>Output: {1, 5, 3, 5, 4}</p><h3>14. ARRAY_TO_STRING()</h3><p>Converts an array to a string with a specified delimiter.</p><pre>SELECT ARRAY_TO_STRING(ARRAY[1, 2, 3, 4], &#39;,&#39;) AS array_to_string;</pre><p>Output: 1,2,3,4</p><h3>15. STRING_TO_ARRAY()</h3><p>Converts a string into an array using a specified delimiter.</p><pre>SELECT STRING_TO_ARRAY(&#39;1,2,3,4&#39;, &#39;,&#39;) AS string_to_array;</pre><p>Output: {1, 2, 3, 4}</p><h3>19. ARRAY_SLICE()</h3><p>Extracts a subset of an array.</p><pre>SELECT ARRAY[1, 2, 3, 4, 5][2:4] AS sliced_array;</pre><p>Output: {2, 3, 4}</p><pre>-- PostgreSQL Array Functions Examples<br><br>-- Create an array<br>SELECT ARRAY[1, 2, 3, 4] AS array_literal;<br><br>-- Aggregate values into an array<br>SELECT ARRAY_AGG(id) AS id_array FROM my_table;<br><br>-- Unnest array into rows<br>SELECT UNNEST(ARRAY[1, 2, 3]) AS element;<br><br>-- Append an element to an array<br>SELECT ARRAY_APPEND(ARRAY[1, 2, 3], 4) AS appended_array;<br><br>-- Prepend an element to an array<br>SELECT ARRAY_PREPEND(0, ARRAY[1, 2, 3]) AS prepended_array;<br><br>-- Concatenate two arrays<br>SELECT ARRAY_CAT(ARRAY[1, 2], ARRAY[3, 4]) AS concatenated_array;<br><br>-- Get array length<br>SELECT ARRAY_LENGTH(ARRAY[1, 2, 3, 4], 1) AS array_length;<br><br>-- Get array cardinality<br>SELECT CARDINALITY(ARRAY[[1, 2], [3, 4]]) AS cardinality_result;<br><br>-- Get array dimensions<br>SELECT ARRAY_DIMS(ARRAY[[1, 2], [3, 4]]) AS array_dims;<br><br>-- Create a filled array<br>SELECT ARRAY_FILL(0, ARRAY[3]) AS filled_array;<br><br>-- Get position of an element in array<br>SELECT ARRAY_POSITION(ARRAY[1, 2, 3, 4], 3) AS array_position;<br><br>-- Remove an element from array<br>SELECT ARRAY_REMOVE(ARRAY[1, 2, 3, 2, 4], 2) AS array_without_twos;<br><br>-- Replace elements in an array<br>SELECT ARRAY_REPLACE(ARRAY[1, 2, 3, 2, 4], 2, 5) AS replaced_array;<br><br>-- Convert array to string<br>SELECT ARRAY_TO_STRING(ARRAY[1, 2, 3, 4], &#39;,&#39;) AS array_to_string;<br><br>-- Convert string to array<br>SELECT STRING_TO_ARRAY(&#39;1,2,3,4&#39;, &#39;,&#39;) AS string_to_array;<br><br>-- Check if array contains another array<br>SELECT ARRAY[1, 2, 3] @&gt; ARRAY[2] AS contains_result;<br><br>-- Check if array is contained by another array<br>SELECT ARRAY[1, 2] &lt;@ ARRAY[1, 2, 3] AS contained_result;<br><br>-- Check if two arrays overlap<br>SELECT ARRAY[1, 2, 3] &amp;&amp; ARRAY[3, 4, 5] AS overlap_result;<br><br>-- Slice array<br>SELECT ARRAY[1, 2, 3, 4, 5][2:4] AS sliced_array;<br><br>-- Generate subscript indexes<br>SELECT GENERATE_SUBSCRIPTS(ARRAY[1, 2, 3, 4], 1) AS subscript_indexes;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08a430d67af4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Normalization]]></title>
            <link>https://medium.com/@yashdesai281/normalization-15fece763f81?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/15fece763f81</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 18:12:46 GMT</pubDate>
            <atom:updated>2024-09-22T18:12:46.554Z</atom:updated>
            <content:encoded><![CDATA[<p>In database design, <strong>anomalies</strong> refer to problems that arise when the structure of a database is not well-designed. These anomalies can lead to data inconsistencies and inefficiencies when performing basic operations like inserting, updating, or deleting records. The three main types of anomalies are:</p><ul><li><strong>Insert Anomaly</strong></li><li><strong>Update Anomaly</strong></li><li><strong>Delete Anomaly</strong></li></ul><h3>1. Insert Anomaly</h3><p><strong>Definition</strong>: An insert anomaly occurs when we cannot insert data into a database due to missing information or when data needs to be inserted into multiple tables unnecessarily.</p><p><strong>Example</strong>: Consider a table that stores information about employees and departments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*0WjN15yYhl-JufLpxPJOGw.png" /></figure><p>Now, suppose you want to add a new department called <strong>“Finance”</strong>, but there are no employees in that department yet.</p><h3>Problem (Insert Anomaly):</h3><p>In the current table design, you cannot add the new department <strong>Finance</strong> without inserting an employee record, because the table requires an Employee_ID and Employee_Name to be filled in. Since there are no employees yet, you might end up doing one of the following:</p><ol><li><strong>Insert Dummy Data</strong>:</li></ol><ul><li>You might insert a dummy employee record with null or fake values to create the <strong>Finance</strong> department:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*WxzbiN3GvHbPb0buv9Zpzw.png" /></figure><h3>2. Update Anomaly</h3><p>An <strong>update anomaly</strong> occurs when changes in one piece of data require multiple updates across the table, leading to data inconsistency if all instances are not updated properly.</p><h4>Scenario (Unnormalized Table):</h4><p>Consider the following unnormalized table where <strong>employee</strong> and <strong>department</strong> information are stored together:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*e2xunFs_H5XvasbnSr6pBw.png" /></figure><h4>Problem (Update Anomaly):</h4><ul><li>Now, suppose the <strong>Sales</strong> department is renamed to <strong>Corporate Sales</strong>.</li><li>In this design, you need to update the <strong>Department_Name</strong> in every row where the department is <strong>Sales</strong>.</li><li>After updating Alice’s record:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*ty4qLXdITnbAtJabG8Mnaw.png" /></figure><h3>3. <strong>Delete Anomaly</strong></h3><p>A <strong>delete anomaly</strong> occurs when deleting one piece of data inadvertently removes other important data.</p><h4>Scenario (Unnormalized Table):</h4><p>Consider the same unnormalized table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*kJKsUFHlgOJJ37nDqbdEcQ.png" /></figure><h4>Problem (Delete Anomaly):</h4><ul><li>Suppose Bob is the only employee in the <strong>Marketing</strong> department, and Bob leaves the company.</li><li>When you delete Bob’s record from the table, you also delete all the information about the <strong>Marketing</strong> department, as it’s stored in the same table as the employees.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*1_ve6nXoQXUwpWlTgtCW2Q.png" /></figure><h3>Summary of the Problems and Solutions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*Z9WifNZofZfZW8RS0SCn4w.png" /></figure><h3><strong>Normalization</strong></h3><p>Normalization is a database design process that organizes data to minimize redundancy and dependency.</p><p>The goal of normalization is to ensure that the data is stored efficiently, maintaining data integrity and avoiding anomalies during data operations like insertions, updates, and deletions.</p><p>Normalization involves dividing a database into two or more tables and defining relationships between them.</p><h3>Normal Forms</h3><p>Normalization is generally done in several stages known as <strong>normal forms</strong> (NF). The most commonly used normal forms are:</p><ol><li><strong>First Normal Form (1NF)</strong></li><li><strong>Second Normal Form (2NF)</strong></li><li><strong>Third Normal Form (3NF)</strong></li><li><strong>Boyce-Codd Normal Form (BCNF)</strong></li></ol><h3><strong>1. First Normal Form (1NF)</strong></h3><p>Each column contains atomic (indivisible) values.</p><p><strong>Example</strong>: Consider a table storing information about students and their enrolled courses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*9M2mktDr6GcaIHpfumObDg.png" /></figure><p><strong>Issues</strong>:</p><ul><li>The Courses column contains multiple values (not atomic).</li></ul><p><strong>Solution (1NF)</strong>: Split the courses into individual rows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*mnv_UrQRedjxuynfYVkLEA.png" /></figure><h3>2. <strong>Second Normal Form (2NF)</strong></h3><p><strong>Definition</strong>: A table is in 2NF if:</p><ul><li>It is in 1NF.</li><li>All non-key attributes are fully functionally dependent on the primary key (no partial dependency).</li></ul><h4>Example to Understand 2NF:</h4><p>Consider the following table that contains information about students, courses, and instructors:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*jXzW0kmiDGs5Ywh4Ls6XtA.png" /></figure><p>Here, the <strong>composite primary key</strong> is (Student_ID, Course_ID), which uniquely identifies each record.</p><ul><li>The <strong>problem</strong> is that Instructor only depends on Course_ID, not the entire composite key (Student_ID, Course_ID).</li><li>This is a <strong>partial dependency</strong> because Instructor is dependent only on part of the primary key (Course_ID), not the whole key.</li></ul><h4>Converting to 2NF:</h4><p>To convert this table into <strong>Second Normal Form</strong>, we need to remove the partial dependency. We split the table into two tables:</p><ol><li><strong>Students Table</strong> (for student-specific information):</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*ckHQxqD5MF0O0VhkvCzXLg.png" /></figure><p><strong>Courses Table</strong> (for course and instructor-specific information):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*Rlpax1fm3WUr5z8gtTwUAQ.png" /></figure><p>In this design, Instructor now depends on Course_ID (a non-composite key), and the student-specific data is separated. This eliminates the <strong>partial dependency</strong>, and the design is now in <strong>2NF</strong>.</p><h3>3. Third Normal Form (3NF)</h3><p>A table is in <strong>Third Normal Form (3NF)</strong> if:</p><ol><li>It is in <strong>Second Normal Form (2NF)</strong>.</li><li>There are <strong>no transitive dependencies</strong>. This means that non-key attributes should not depend on other non-key attributes.</li></ol><h3>What is a Transitive Dependency?</h3><p>A transitive dependency occurs when a non-key attribute depends on another non-key attribute rather than directly depending on the primary key. This can lead to redundancy and potential anomalies.</p><p>Let’s start with an example of a <strong>Students</strong> table that is not in 3NF:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*kkHf6uW8Idm64_-rKOcrGg.png" /></figure><h3>Step 1: Identify the Problems</h3><ol><li><strong>Primary Key</strong>: In this table, the primary key could be Student_ID.</li><li><strong>Transitive Dependency</strong>: The Instructor and Department fields depend on the Course, not directly on Student_ID. For example, Math always has Dr. Smith as its instructor and belongs to the Science department.</li></ol><h3>Step 2: Convert to 3NF</h3><p>To eliminate transitive dependencies, we need to split the table into multiple related tables.</p><h4>Create New Tables</h4><ol><li><strong>Students Table</strong>:</li></ol><ul><li>This will hold student-specific information.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/842/1*la-LeDC0t32rxiuXekGM5Q.png" /></figure><p><strong>Courses Table</strong>:</p><ul><li>This table will hold information about courses, including the instructor and department.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*9myGSRza95QoIs0gojbfNA.png" /></figure><h3>Step 3: Establish Relationships</h3><p>Now, we have two tables:</p><ul><li><strong>Students</strong> table with Student_ID, Name, and Course.</li><li><strong>Courses</strong> table with Course, Instructor, and Department.</li></ul><h3>Benefits of This Structure</h3><ul><li><strong>Reduced Redundancy</strong>: Instead of repeating the Instructor and Department information for every student taking the same course, we store it only once in the <strong>Courses</strong> table.</li><li><strong>Easier Updates</strong>: If the instructor for Math changes, we only need to update it in the <strong>Courses</strong> table, not in every student record.</li></ul><h3>Summary of 3NF</h3><ol><li><strong>No Transitive Dependencies</strong>: Every non-key attribute must depend only on the primary key.</li><li><strong>Reduced Redundancy</strong>: Information is stored in a way that minimizes duplication.</li><li><strong>Easier Data Maintenance</strong>: Updates are simpler and less prone to errors.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15fece763f81" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Database Part 2]]></title>
            <link>https://medium.com/@yashdesai281/database-part-2-19d16a0a79ce?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d16a0a79ce</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 14:33:03 GMT</pubDate>
            <atom:updated>2024-09-22T14:33:03.578Z</atom:updated>
            <content:encoded><![CDATA[<h3>Types of Database Languages:</h3><ol><li><strong>Data Definition Language (DDL)</strong></li><li><strong>Data Manipulation Language (DML)</strong></li><li><strong>Data Control Language (DCL)</strong></li><li><strong>Transaction Control Language (TCL)</strong></li><li><strong>Data Query Language (DQL)</strong></li></ol><h3>1. Data Definition Language (DDL)</h3><p><strong>Definition</strong>:</p><ul><li>DDL is used to define and modify the <strong>structure of the database</strong> (schemas, tables, indexes, views, etc.).</li><li>These commands affect the schema and overall organization of the database, but not the data itself.</li></ul><p><strong>Common DDL Commands</strong>:</p><ul><li><strong>CREATE</strong>: Creates objects like tables, databases, indexes, etc.</li><li><strong>ALTER</strong>: Modifies existing objects in the database, like adding or modifying columns in a table.</li><li><strong>DROP</strong>: Deletes objects like tables, databases, or indexes.</li><li><strong>TRUNCATE</strong>: Removes all records from a table but keeps its structure.</li></ul><h3>2. Data Manipulation Language (DML)</h3><p><strong>Definition</strong>:</p><ul><li>DML is used for <strong>manipulating data</strong> within the database, such as inserting, updating, or deleting records.</li><li>DML commands work with the data stored in the tables.</li></ul><p><strong>Common DML Commands</strong>:</p><ul><li><strong>INSERT</strong>: Adds new records to a table.</li><li><strong>UPDATE</strong>: Modifies existing records in a table.</li><li><strong>DELETE</strong>: Removes records from a table.</li></ul><h3>3. Data Control Language (DCL)</h3><p><strong>Definition</strong>:</p><ul><li>DCL is used to <strong>control access to the data</strong> in the database. It manages permissions and access rights.</li><li>It helps in securing the data by giving and revoking privileges to users or roles.</li></ul><p><strong>Common DCL Commands</strong>:</p><ul><li><strong>GRANT</strong>: Gives user access privileges to database objects.</li><li><strong>REVOKE</strong>: Removes user access privileges from database objects.</li></ul><h3>4. Transaction Control Language (TCL)</h3><p><strong>Definition</strong>:</p><ul><li>TCL is used to <strong>manage transactions</strong> in the database. A transaction is a sequence of operations that must all succeed or fail as a unit to ensure data integrity.</li><li>These commands ensure that the database remains in a consistent state during transactions.</li></ul><p><strong>Common TCL Commands</strong>:</p><ul><li><strong>COMMIT</strong>: Saves the changes made by a transaction to the database.</li><li><strong>ROLLBACK</strong>: Undoes the changes made by a transaction if an error occurs.</li><li><strong>SAVEPOINT</strong>: Sets a point within a transaction to which you can roll back.</li><li><strong>SET TRANSACTION</strong>: Defines transaction properties like isolation level.</li></ul><h3>5. Data Query Language (DQL)</h3><p><strong>Definition</strong>:</p><ul><li>DQL is used to <strong>query the database</strong> to retrieve information.</li><li>The primary DQL command is <strong>SELECT</strong>, which fetches data from one or more tables.</li></ul><p><strong>Common DQL Command</strong>:</p><ul><li><strong>SELECT</strong>: Retrieves data from the database.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QXvFrxMMBTXMbxFtq6CE0w.png" /></figure><h3>▪ Data Models</h3><p>A data model provides a way to describe the design of database at the Physical, Logical and View level.</p><p>That means, data models define how data is connected to each other and; how they are processed and stored inside the system.</p><p><strong>Data models define how the logical structure of a database is modeled.</strong></p><p><strong>The data models can be classified into four different categories:</strong></p><ol><li>Relational Model</li><li>Entity-Relationship Data Model</li><li>Object-based Data Models</li><li>Semi-structured Data Model (XML)</li></ol><h3>Relational Model</h3><p>A relational model is a collection of tables to represent both data and the relationship among those data.</p><p>▪ Each table has multiple columns and each column has a unique name. and tables are also known as relations.</p><ul><li>The <strong>Relational Model</strong> is the most widely used data model in database management systems. It organizes data into <strong>tables (relations)</strong>, where each table consists of <strong>rows (tuples)</strong> and <strong>columns (attributes)</strong>.</li><li>Relationships between tables are established using <strong>keys</strong> (primary key, foreign key).</li></ul><p>For Example:</p><p>✓ Relational Database for the Bank Customer Account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kZg_edufSUQLzu-TAiHmkA.png" /></figure><h3>2. Entity-Relationship (ER) Data Model</h3><p><strong>Definition</strong>:</p><ul><li>The <strong>Entity-Relationship (ER) Model</strong> is a conceptual model that represents the database as a collection of <strong>entities</strong>, <strong>attributes</strong>, and <strong>relationships</strong>. It uses <strong>ER diagrams</strong> to visually represent data.</li><li>An <strong>entity</strong> is a real-world object or concept, and relationships define how entities are associated.</li></ul><p><strong>Key Features</strong>:</p><ul><li><strong>Entities</strong> represent real-world objects (e.g., students, customers).</li><li><strong>Attributes</strong> represent properties of entities (e.g., name, age, ID).</li><li><strong>Relationships</strong> show the association between entities (e.g., “Student enrolls in Course”).</li></ul><p><strong>Example</strong>: An <strong>ER diagram</strong> showing:</p><ul><li><strong>Entities</strong>: Student, Course.</li><li><strong>Relationship</strong>: A <strong>Student</strong> “enrolls in” a <strong>Course</strong>.</li><li><strong>Attributes</strong>: Student has attributes Student_ID, Name, Age.<br>Course has attributes Course_ID, Course_Name.</li></ul><p><strong>Advantages</strong>:</p><ul><li>Good for designing database at a high level.</li><li>Easy to understand and communicate with non-technical users.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/932/1*h-qVeHSqZqigV1LBXl36_w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*W1hwrIUMPgccKuxm5tX6yA.png" /></figure><h3>Types of Entity</h3><ol><li><strong>Entity</strong></li></ol><p>An entity can be either a living or non-living component.</p><p>It showcases an entity as a rectangle in an ER diagram.</p><p>For example, in a student study course, both the student and the course are entities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/633/0*MU4H9HljNKR8qvXo.png" /></figure><p><strong>2. Weak Entity</strong></p><p>An entity that depends on another entity called a weak entity. The weak entity doesn’t contain any key attribute of its own. The weak entity is represented by a double rectangle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/0*Zg2JMU-JYO9k2H8N.png" /></figure><h3>What is Attributes?</h3><p>Attributes are the properties that define the entity type. For example, Roll_No, Name, DOB, Age, Address, and Mobile_No are the attributes that define entity type Student. In ER diagram, the attribute is represented by an oval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*YAD_obWxrN29pKm_4Ktepw.png" /></figure><h3>Types of Attributes</h3><p><strong>1. Key Attribute</strong></p><p><strong>2. Composite Attribute</strong></p><p><strong>3. Multivalued Attribute</strong></p><p><strong>4. Derived Attribute</strong></p><h3>1. Key Attribute</h3><p>The attribute which <strong>uniquely identifies each entity </strong>in the entity set is called the key attribute. For example, Roll_No will be unique for each student. In ER diagram, the key attribute is represented by an oval with underlying lines.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*y2ExgPuy37QBXrJjWe5NsQ.png" /></figure><h3>2. Composite Attribute</h3><p>An attribute <strong>composed of many other attributes </strong>is called a composite attribute. For example, the Address attribute of the student Entity type consists of Street, City, State, and Country. In ER diagram, the composite attribute is represented by an oval comprising of ovals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*b9bR6t9o3I1wCwjy2UIclQ.png" /></figure><h3>3. Multivalued Attribute</h3><p>An attribute consisting of more than one value for a given entity. For example, Phone_No (can be more than one for a given student). In ER diagram, a multivalued attribute is represented by a double oval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*jezAR989X0dppmlDv3dR0w.png" /></figure><h3>4. Derived Attribute</h3><p>An attribute that can be derived from other attributes of the entity type is known as a derived attribute. e.g.; Age (can be derived from DOB). In ER diagram, the derived attribute is represented by a dashed oval.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*F2l9ZWO7eLRscf0lbBOZ_A.png" /></figure><h3>Relationship</h3><p>The diamond shape showcases a relationship in the ER diagram.</p><p>It depicts the relationship between two entities.</p><p>In the example below, both the student and the course are entities, and study is the relationship between them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/735/0*gbyS-Apdh3iaBcKK.png" /></figure><h4>One-to-One Relationship</h4><p>When a single element of an entity is associated with a single element of another entity, it is called a one-to-one relationship.</p><p>For example, a student has only one identification card and an identification card is given to one person.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*EVmB4rFfCKZpR0sp.png" /></figure><h4>One-to-Many Relationship</h4><p>When a single element of an entity is associated with more than one element of another entity, it is called a one-to-many relationship</p><p>For example, a customer can place many orders, but an order cannot be placed by many customers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*htsuxCIYyUBRW3hR.png" /></figure><h4>Many-to-One Relationship</h4><p>When more than one element of an entity is related to a single element of another entity, then it is called a many-to-one relationship.</p><p>For example, students have to opt for a single course, but a course can have many students.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/0*KJA6trGbU-b6HK-l.png" /></figure><h4>Many-to-Many Relationship</h4><p>When more than one element of an entity is associated with more than one element of another entity, this is called a many-to-many relationship.</p><p>For example, you can assign an employee to many projects and a project can have many employees.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/0*ZgBOYI1yhTHBwu09.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*KQqNVBt_j7mcT-aROIglXA.png" /></figure><h3>DBMS Keys</h3><p>In a Database Management System (DBMS), <strong>keys</strong> are essential elements that help uniquely identify records in a table and establish relationships between tables.</p><ol><li><strong>Primary Key</strong></li></ol><p><strong>2. Foreign Key</strong></p><p>3. <strong>Unique Key</strong></p><p>4. <strong>Composite Key</strong></p><p>5. <strong>Candidate Key</strong></p><h3>1. Primary Key</h3><p><strong>Definition</strong>:</p><ul><li>A <strong>Primary Key</strong> is a unique identifier for each record in a table. No two records can have the same primary key value, and it cannot contain NULL values.</li></ul><pre>CREATE TABLE Customers (<br>    Customer_ID INT PRIMARY KEY,<br>    Name VARCHAR(100),<br>    Email VARCHAR(100)<br>);</pre><p>In this example, Customer_ID is the primary key, ensuring that each customer has a unique ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*sZ6lZUL9WIX7L3oK_iHrew.png" /></figure><h3>2. Foreign Key</h3><p><strong>Definition</strong>:</p><ul><li>A <strong>Foreign Key</strong> is a field (or a collection of fields) in one table that refers to the primary key in another table. It establishes a relationship between the two tables.</li></ul><pre>CREATE TABLE Orders (<br>    Order_ID INT PRIMARY KEY,<br>    Order_Date DATE,<br>    Customer_ID INT,<br>    FOREIGN KEY (Customer_ID) REFERENCES Customers(Customer_ID)<br>);</pre><p>In this example, Customer_ID in the <strong>Orders</strong> table is a foreign key that references Customer_ID in the <strong>Customers</strong> table, creating a relationship between the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*_QYZ5zXyd7GrNOV3vQih1A.png" /></figure><h3>3. Unique Key</h3><p><strong>Definition</strong>:</p><ul><li>A <strong>Unique Key</strong> constraint ensures that all values in a column are different from one another, similar to a primary key, but it can contain NULL values.</li></ul><pre>CREATE TABLE Customers (<br>    Customer_ID INT PRIMARY KEY,<br>    Name VARCHAR(100),<br>    Email VARCHAR(100) UNIQUE<br>);</pre><p>In this case, each email must be unique, but one customer can have no email (NULL).</p><h3>4. Composite Key</h3><p><strong>Definition</strong>:</p><ul><li>A <strong>Composite Key</strong> consists of two or more columns that together uniquely identify a record in a table. It is used when a single column is not sufficient to uniquely identify a record.</li></ul><pre>CREATE TABLE Enrollments (<br>    Student_ID INT,<br>    Course_ID INT,<br>    Enrollment_Date DATE,<br>    PRIMARY KEY (Student_ID, Course_ID)<br>);</pre><p>In this case, the combination of Student_ID and Course_ID serves as the composite primary key, ensuring that each student can enroll in a specific course only once.</p><h3>5. Candidate Key</h3><p><strong>Definition</strong>:</p><ul><li>A <strong>Candidate Key</strong> is a set of attributes that uniquely identify a record in a table. There can be multiple candidate keys, and one of them is chosen as the primary key.</li></ul><pre>CREATE TABLE Users (<br>    User_ID INT PRIMARY KEY,<br>    Username VARCHAR(50) UNIQUE,<br>    Email VARCHAR(100) UNIQUE<br>);</pre><p>Here, both Username and Email can serve as candidate keys since they uniquely identify each user. However, User_ID is chosen as the primary key.</p><h3>Summary of Key Types:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*veidFd8wMqvz93NghqURyQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d16a0a79ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interface]]></title>
            <link>https://medium.com/@yashdesai281/interface-4817b804c2ec?source=rss-c7f482a84bb5------2</link>
            <guid isPermaLink="false">https://medium.com/p/4817b804c2ec</guid>
            <dc:creator><![CDATA[Yashdesai]]></dc:creator>
            <pubDate>Sun, 22 Sep 2024 14:21:03 GMT</pubDate>
            <atom:updated>2024-10-16T18:22:23.088Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>What is an Interface in C#?</strong></h3><p>The Interface in C# is a <strong>Fully Unimplemented Class</strong> used for declaring a set of operations/methods of an object.</p><p>So, we can define an interface as a pure abstract class, which allows us to define only abstract methods.</p><p>The abstract method means a method without a body or implementation. It is used to achieve multiple inheritances, which the class can’t achieve.</p><p>It is used to achieve full abstraction because it cannot have a method body.</p><p>Interfaces allow you to define a common set of functionality that multiple classes can share, promoting code reusability and ensuring a consistent structure for related classes.</p><ol><li><strong>Class:</strong> Contains only the Non-Abstract Methods (Methods with Method Body).</li><li><strong>Abstract Class:</strong> Contains both Non-Abstract Methods (Methods with Method Body) and Abstract Methods (Methods without Method Body).</li><li><strong>Interface:</strong> Contain only Abstract Methods (Methods without Method Body).</li></ol><p>class has another class as a Parent, a class can also have an Interface as a Parent. If a class has an interface as a Parent, the class is responsible for implementing all the abstract methods of the interface. For a better understanding, please have a look at the below diagram</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/0*ucvAkc1yh6K85wsz" /></figure><p>the Parent Interface imposes restrictions on the Child Classes. <strong>What restrictions?</strong> The restrictions are to implement each and every method of the interface under the child class.</p><p><strong>we cannot declare fields/variables, constructors, and destructors in an interface in C#.</strong></p><p><strong>Interfaces cannot contain fields</strong></p><p><strong>What are the Members we can and can’t define in an interface in C#?</strong></p><p>An interface can contain</p><ol><li><strong>Abstract methods</strong></li><li><strong>Properties</strong></li><li><strong>Indexes</strong></li><li><strong>Events</strong></li></ol><p>An interface cannot contain</p><ol><li><strong>Non-abstract functions</strong></li><li><strong>Data fields</strong></li><li><strong>Constructors</strong></li><li><strong>Destructors</strong></li></ol><p><strong>Abstract Class:</strong></p><ol><li>It is a partially implemented class. It allows us to define both concrete and abstract methods.</li><li>It should be declared as abstract by using the abstract keyword, abstract methods should also contain the abstract keyword.</li><li>Its member’s default accessibility modifier is private and can be changed to any of the other accessibility modifiers.</li><li>It is possible to declare data fields in an abstract class.</li><li>An abstract class can contain a non-abstract function.</li><li>An abstract class can inherit from another abstract class or from an interface.</li><li>An abstract class cannot be used to implement multiple inheritances.</li><li>Abstract class members can have Access Specifiers.</li></ol><p><strong>Interface:</strong></p><ol><li>It is a fully un-implemented class. It allows us to define only abstract methods.</li><li>It should be created by using the keyword interface. By default, all the members are abstract only. Explicitly using abstract keyword is not allowed.</li><li>Its member’s default accessibility modifier is public and cannot be changed.</li><li>It is not possible to declare any data fields in an interface.</li><li>An interface cannot contain non-abstract functions.</li><li>An interface can inherit from only other interfaces but cannot inherits from the abstract class.</li><li>An interface can be used to implement multiple inheritances.</li><li>Interface members cannot have Access Specifiers.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4817b804c2ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>