Thursday, March 23, 2023

How to read data in .net from Oracle using Dapper

Following is an async C# method, that use the OracleConnection class to create a connection to the Oracle database. The QueryAsync method is called on the connection object to execute the query asynchronously and retrieve the Employee objects already mapped to the data returned by the SQL query. The AsList method is called on the result of the query to convert it to a list of Employee objects.

Note that you will need to add the reference to the Oracle.ManagedDataAccess.Client package.

 

using System.Collections.Generic;
using System.Data;
using System.Threading.Tasks;
using Dapper;
using Oracle.ManagedDataAccess.Client;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromOracleAsync()
{
    List<Employee> employees;
    string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)
(HOST=hostName)(PORT=portNumber))(CONNECT_DATA=(SERVER=DEDICATED)
(SERVICE_NAME=serviceName)));User Id=userName;Password=password;";
 
    using (IDbConnection connection = new OracleConnection(connectionString))
    {
        employees = (await connection.QueryAsync<Employee>("SELECT * FROM Employee")).AsList();
    }
   
    return employees;
}
 

Different ways to write a method that reads list of entities from SQL Server in C# language

There are different ways we can do same work. With evolution of .net technologies we have found different technologies to perform data operations. Here we will look at different ways of getting a list of employees from SQL Server database using different data access technologies.

Method-1: using ADO.NET

This method retrieves the employee list from the "Employee" table in the SQL Server database using a SELECT query, and maps the data to a list of Employee objects. Note that in this example, the Employee class has properties for the Id, Name, Department, and Salary fields in the database, and the SqlDataReader's Get methods are used to retrieve the values for each field from each record.

using System.Data.SqlClient;
using System.Collections.Generic;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public List<Employee> GetEmployeeListFromSqlServer()
{
    List<Employee> employees = new List<Employee>();
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
    string query = "SELECT Id, Name, Department, Salary FROM Employee";
   
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        SqlCommand command = new SqlCommand(query, connection);
        connection.Open();
        SqlDataReader reader = command.ExecuteReader();
       
        while (reader.Read())
        {
            Employee employee = new Employee();
            employee.Id = reader.GetInt32(0);
            employee.Name = reader.GetString(1);
            employee.Department = reader.GetString(2);
            employee.Salary = reader.GetDecimal(3);
           
            employees.Add(employee);
        }
       
        reader.Close();
    }
   
    return employees;
}



Method-2: using ADO.NET async

In this async version of the method, the SqlConnection is opened asynchronously using await connection.OpenAsync(), and the SqlDataReader is created and executed asynchronously using await command.ExecuteReaderAsync(). The while loop that reads the data is also made asynchronous using await reader.ReadAsync(). Note that the using statements are still used to ensure proper disposal of resources.


using System.Data.SqlClient;
using System.Collections.Generic;
using System.Threading.Tasks;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromSqlServerAsync()
{
    List<Employee> employees = new List<Employee>();
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
    string query = "SELECT Id, Name, Department, Salary FROM Employee";
   
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
       
        using (SqlCommand command = new SqlCommand(query, connection))
        using (SqlDataReader reader = await command.ExecuteReaderAsync())
        {
            while (await reader.ReadAsync())
            {
                Employee employee = new Employee();
                employee.Id = reader.GetInt32(0);
                employee.Name = reader.GetString(1);
                employee.Department = reader.GetString(2);
                employee.Salary = reader.GetDecimal(3);
               
                employees.Add(employee);
            }
        }
    }
   
    return employees;
}



Method-3: using Dapper

In this async version of the method, the SqlConnection is opened asynchronously using await connection.OpenAsync(). The query is then executed asynchronously using Dapper's QueryAsync method, which returns a list of Employee objects already mapped to the data returned by the SQL query. The using statement is still used to ensure proper disposal of resources.

using System.Data.SqlClient;
using System.Collections.Generic;
using System.Threading.Tasks;
using Dapper;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromSqlServerAsync()
{
    List<Employee> employees;
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
    string query = "SELECT Id, Name, Department, Salary FROM Employee";
   
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
        employees = (await connection.QueryAsync<Employee>(query)).AsList();
    }
   
    return employees;
}


Method-4: using EF Core

In this async version of the method, a DbContextOptionsBuilder is used to configure the connection string and then used to create a new DbContext instance. The Set method is used to retrieve the DbSet<Employee>, and then the ToListAsync method is called to execute the query asynchronously and retrieve the Employee objects already mapped to the data returned by the SQL query. The using statement is still used to ensure proper disposal of resources. Note that you will need to add the appropriate NuGet packages and configure EF Core for your specific database provider.

 

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromSqlServerAsync()
{
    List<Employee> employees;
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
   
    DbContextOptionsBuilder dbContextOptionsBuilder = new DbContextOptionsBuilder();
    dbContextOptionsBuilder.UseSqlServer(connectionString);
    using (var dbContext = new DbContext(dbContextOptionsBuilder.Options))
    {
        employees = await dbContext.Set<Employee>().ToListAsync();
    }
   
    return employees;
}
 


Method-5: LINQ to SQL:

In this async version of the method, a DataContext is used to connect to the database and a Table<Employee> is used to retrieve the table of Employee objects. The ToListAsync method is called on the Table<Employee> to execute the query asynchronously and retrieve the Employee objects already mapped to the data returned by the SQL query. Note that you will need to add the appropriate references to System.Data.Linq and configure the DataContext for your specific database provider. The using statement is still used to ensure proper disposal of resources.

using System.Data.Linq;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Linq;

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Department { get; set; }
    public decimal Salary { get; set; }
}

public async Task<List<Employee>> GetEmployeeListFromSqlServerAsync()
{
    List<Employee> employees;
   
    string connectionString = "Data Source=serverName;Initial Catalog=databaseName;
User ID=userName;Password=password";
   
    DataContext dataContext = new DataContext(connectionString);
    Table<Employee> employeeTable = dataContext.GetTable<Employee>();
   
    employees = await employeeTable.ToListAsync();
   
    return employees;
}



 


Thursday, July 7, 2022

What is Interface in C#? What are the benefits of using Interface?

 

Interface

Interface: An interface contains definitions for a group of related functionalities that a non-abstract class or a struct must implement.

Interfaces can contain instance methods, properties, events, indexers, or any combination of those four member types. Interfaces may contain static constructors, fields, constants, or operators.

Benefits: Interface helps us to implement all of Object Oriented Programming concepts. There are several benefits of using interfaces in .NET, including:

1. Loose Coupling:  Interface allows us developing very loosely coupled system. An interface defines a contract that a class must follow. By using an interface, you can ensure that the class implementing it adheres to a specific set of rules and functionality.

2. Abstraction: Interface helps us developing secured system by implementing abstraction. It is a contract that contains properties and method signatures and implementation is done in inherited class. Thus it helps hiding implementation of internal business logic from external systems.

3. Inheritance: Interface in C# helps to achieve multiple inheritance. C# does not allow multiple class inheritance, but a class can implement multiple interfaces. This allows you to create objects with functionality from multiple sources, without the complications that can arise from multiple inheritance.

4. Polymorphism: Interfaces allow us to define polymorphism in a declarative way, unrelated to implementation. Two elements are polymorphic with respect to a set of behaviors if they realize the same interfaces.

5. Plug and Play: Interfaces are the key to the "plug-and-play" ability of an architecture.

6. Testing: Interfaces enable mocking objects which makes easier and better unit testing.

7. Dependency Injection: Interfaces are great for implementing Inversion of Control or Dependency Injection.

8. Extensibility: We can satisfy extensibility using the interfaces in C#.

9. Parallel Programming: Interfaces enable parallel application development.

10. Code Re usability: An interface can be implemented in multiple classes that enables greater code reuse. This can reduce the amount of code you need to write, and make it easier to modify or update existing code.

In conclusion we can say that using interfaces can help to create more modular, maintainable, and reusable code, while also enabling polymorphism and simplifying testing.

 

* Beginning with C# 8.0, an interface may define a default implementation for members.

Friday, December 10, 2021

How to split a comma separated string into multiple records using T-SQL function?

 Let's say you have a comma separated string like: 

split,a,comma,separated,string

 

Now you need to convert the string to follow rows:

split
a
comma
separated
string

 

Solution:

You can create a user defined UDF like the one shown below. Then, just pass in the comma separated list from another query and it will return a table with each value in a separate row. The function used here is a table valued function.

 

CREATE FUNCTION [dbo].[fnSplitStringToTable]
(
    @input nvarchar(MAX),
    @delimiter char(1) = ','
)
RETURNS
@Result TABLE
(
    Value nvarchar(MAX)
)
AS
BEGIN
    DECLARE @chIndex int
    DECLARE @item nvarchar(MAX)

    WHILE CHARINDEX(@delimiter, @input, 0) <> 0
    BEGIN
        SET @chIndex = CHARINDEX(@delimiter, @input, 0)
        SELECT @item = SUBSTRING(@input, 1, @chIndex - 1)

        IF LEN(@item) > 0
        BEGIN
            INSERT INTO @Result(Value)
            VALUES (@item)
        END
        SELECT @input = SUBSTRING(@input, @chIndex + 1, LEN(@input))
    END
    IF LEN(@input) > 0
    BEGIN
        INSERT INTO @Result(Value)
        VALUES (@input)
    END
    RETURN
END

 

Here is how you can execute the function and produce results as expected:

 

 


Tuesday, November 30, 2021

What are the functions of Data Mining?

Data mining is defined as the process of discovering patterns in data. The process must be automatic or (more usually) semiautomatic. The patterns discovered must be meaningful in that they lead some advantage, usually an economic one.


Data mining have two major functions: 

1. Classification:

  • Classification maps data into predefined groups or classes. 
  • It is often referred to as supervised learning because the classes are determined before examining the data. 
  • Classification creates a function from training data. The training data consist of pairs of input objects, and desired output. The output of the function can be a continuous value, or can predict a class label of the input object. 
  • The task of the classification is to predict the value of the function for any valid input object after having seen only a small number of training examples.

 2. Clustering:

  • Clustering is similar to classification except that the groups are not predefined, but rather defined by the data alone. 
  • Clustering is alternatively referred to as unsupervised learning or segmentation. 
  • It can be thought of as partitioning or segmenting the data into groups that might or might not be disjointed. 
  • The clustering is usually accomplished by determining the similarity among the data on predefined attributes. The most similar data are grouped into clusters.




What is Machine Learning? What are different types of Machine Learning?

Machine Learning:

Machine learning provides the technical basis of data mining. It is a branch of artificial intelligence, which concerns the construction and study of systems that can learn from data.

For example, a machine learning system could be trained on email messages to learn to distinguish between spam and non-spam messages. After learning, it can then be used to classify new email messages into spam and non-spam folders.


Types of Machine Learning:

 
Supervised learning is basically a synonym of classification. The supervision in the learning comes from the labeled instances in the training data. 

Unsupervised learning is essentially a synonym of clustering. The learning process is unsupervised since the input instances are not class labeled. 

Semi-supervised learning is a class of machine learning technology that make use of both labeled and unlabelled instances when learning a model. 

Active learning is a machine learning approach that lets users play an active role in the learning process. An active learning approach can ask a user (e.g., a domain expert) to label an instance, which may be from a set of unlabelled instances.

What is Data Mining? What Kinds of Data can be Mined?

Data mining is also known as Knowledge Discovery from Data, or KDD for short, which turns a large collection of data into knowledge. Data mining is a multidisciplinary field including machine learning, artificial intelligence, pattern recognition, knowledge-based systems, high-performance computing, database technology, and data visualization. 

  • Data mining is the process of analyzing data from different perspectives and summarizing it into useful information. 
  • Data mining is the process of finding hidden information and patterns in a huge database. 
  • Data mining is the extraction of implicit, previously unknown, and potentially useful information from data.

 

Data, Information, and Knowledge
Data: Data are any recorded facts, numbers, or text that can be processed by a computer - scientific data, medical data, demographic data, financial data, and marking data.

Information: The patterns, associations, or relationships among all this data can provide information.

Knowledge: Information can be converted into knowledge about historical patterns and future trends.

 

What Kinds of Data can be Mined?
The most basic forms of data for mining are come from: 

  1. Database Data 
  2. Data Warehouses 
  3. Transactional Data


What is method overloading?

Method overloading is a polymorphism technique that allows us to have same method in different ways. Overloaded method can have different number of parameters, different parameter types, and different arrangement of parameters but with same name.

What is an interface? When to use interface over abstract class?


An interface contains definitions for a group of related functionalities that a class or a struct can implement.

Use interface over abstract class:

a. If the functionality you are creating will be useful across a wide range of disparate objects, use an interface.

b. If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.

Thursday, September 2, 2021

SQL update from one Table to another based on a ID match

SQL update from one Table to another based on a ID match

While working with SQL database you might often require to update one table data based on values of a column value in another table. For this to be done successfully you might require a common id field or foreign key which will match values of both tables to update.

Here is the syntax to perform the task in SQL Server:

UPDATE table1

SET t1.Col = t2.Col

FROM table1 t1

INNER JOIN table2  t2 ON t1.ID = t2.ID;

 

To demonstrated this let us assume we have following two tables: 


Place
===========
PlaceId                 int,
name                     nvarchar(200),
ispublished           bit


PlaceDetails
==============
PlaceDetailId          int,
PlaceId                     int,
DetailsDesc             nvarchar(max),
SeoTitle                   nvarchar(max),
SeoDescription         nvarchar(max)
,
status                       bit


Case 1: Update status field of PlaceDetails from values of ispublished in Place table.

Solution:

UPDATE PlaceDetails

SET d.status = p.ispublished

FROM PlaceDetails d

          INNER JOIN Place p ON d.PlaceId = p.PlaceId;


Case 2: Update status field of PlaceDetails from values of ispublished in Place table only for the places that are published.

Solution: You require to add a where condition along with previous query for this purpose.

UPDATE PlaceDetails

SET d.status = p.ispublished

FROM PlaceDetails d

          INNER JOIN Place p ON d.PlaceId = p.PlaceId 

         WHERE p.ispublished='True';


Case 3: Update SeoTitle and SeoDescription field of PlaceDetails for a specific placetypes

Solution: This is a complex implementation of the query that allows you to update a table values based on a complex query result. For this purpose we consider some more tables. 

The following query is used to generate SEO Titile and SEO Description information for all of the places of a category:

SELECT p.PlaceId, p.name, 'Book a room in ' + p.name +', '+ c.Name+' | addressschool.com',
p.name +' is a '+ t.Name+' in '+c.Name+', '+n.Name +' that is located in '+d.formatted_address
FROM     Place AS p INNER JOIN
                  PlaceDetail AS d ON p.PlaceId = d.PlaceId INNER JOIN
                  City AS c ON p.CityId = c.Id inner join
                  PlaceType t on p.PlaceTypeId = t.Id INNER JOIN
                  Country AS n ON p.CountryId = n.Id
WHERE  (p.PlaceTypeId = 1)

 

Now we use the above query as a inline view in the update statement to update SeoTitle and SeoDescription information in PlaceDetails table:

 UPDATE
    PlaceDetail
SET
    PlaceDetail.name = SR.SeoTitle,
    PlaceDetail.url = SR.SeoDescription
FROM
    PlaceDetail pd
INNER JOIN
    (SELECT p.PlaceId, p.name, 'Book a room in ' + p.name +', '+ c.Name+' | addressschool.com' as SeoTitle,
    p.name +' is a '+ t.Name+' in '+c.Name+', '+n.Name +' that is located in '+d.formatted_address as SeoDescription
    FROM     Place AS p INNER JOIN
                      PlaceDetail AS d ON p.PlaceId = d.PlaceId INNER JOIN
                      City AS c ON p.CityId = c.Id inner join
                      PlaceType t on p.PlaceTypeId = t.Id INNER JOIN
                      Country AS n ON p.CountryId = n.Id
    WHERE  (p.PlaceTypeId = 1)) SR
ON
    pd.PlaceId = SR.PlaceId;

 

 Hope this will help you.

Any query and comments will be appreciated and answered.