@manhng

Welcome to my blog!

DbUp + Sql Server + EF Core 6 + DB First + Database First + Dapper

February 16, 2022 18:22

DbUp + Sql Server + EF Core 6 + DB First + Database First + Dapper (edit)

EF Core 6

Entity Framework Core with Existing Database (entityframeworktutorial.net)

Generating a model from an existing database | Learn Entity Framework Core

DbUpDemo/Program.cs at master · krishrana17/DbUpDemo (github.com)

Generate Context and Entity Classes from an Existing Database (entityframeworktutorial.net)

Using Database Project and DbUp for database management - Kamil Grzybek

EF 6

Code First to an Existing Database - EF6 | Microsoft Docs

Dapper: Generic repository pattern using Dapper

Generic repository pattern using Dapper | by Damir Bolic | ITNEXT

Dapper POCO Oracle

January 25, 2022 15:53

Dapper POCO Oracle (edit)

  • Oracle 12c 64bit database (Nuget: Oracle.ManagedDataAccess)
  • MySQL 5.7.21 (GPL) database (Nuget: MySqlConnector)

DBeaver (kết nối cơ sở dữ liệu MySQL, Oracle)

  • Tự động sinh ra Entity Relationship Diagram (ERD)
  • Tự động sinh ra các cấu Raw SQL tương ứng các bảng trong cơ sở dữ liệu
  • Kết hợp Dapper + DapperExtensions để thực hiện CRUD, tạo POCO từ database có sẵn cấu trúc bảng
  • Hỗ trở cả MySQL và Oracle

Tools:

Samples:

.NET code samples for Oracle database developers

oracle/dotnet-db-samples: .NET code samples for Oracle database developers (github.com)

https://github.com/oracle/dotnet-db-samples/issues/208

https://github.com/oracle/dotnet-db-samples/

CQRS Raw SQL and DDD with Dapper

January 5, 2022 16:47

CQRS Raw SQL and DDD with Dapper (edit)

  • MyProject.Api
  • MyProject.Application
  • MyProject.Infrastructure
  • MyProject.Domain

Simple CQRS implementation with raw SQL and DDD

Simple CQRS implementation with raw SQL and DDD - Kamil Grzybek

Sample .NET Core REST API CQRS implementation with raw SQL and DDD using Clean Architecture

kgrzybek/sample-dotnet-core-cqrs-api: Sample .NET Core REST API CQRS implementation with raw SQL and DDD using Clean Architecture. (github.com)

  • DDD
  • Clean Architecture
  • Unit Testing
  • Integration Testing
  • Dapper
  • Sql Server
  • Serilog
  • Microsoft.NET.Test.Sdk
  • NUnit3T
  • NSubstitut

sample-dotnet-core-cqrs-api/SampleProject.IntegrationTests.csproj at master · gtechsltn/sample-dotnet-core-cqrs-api (github.com)

ASP.NET Core Web API: Plugin Controllers and Services

The middle ground between monolithic applications and an explosion of microservices
This is a concise guide on how to implement plugin controllers and share services between the ASP.NET Web API application and the plugin.

ASP.NET Core Web API: Plugin Controllers and Services - CodeProject

Mapping Generator

August 8, 2021 21:58

Mapping Generator (edit)

MappingGenerator was initially created as a design-time alternative to AutoMapper. Now it is evolving into a coding assistant to whom you can delegate the most mundane coding tasks.

Alternative to AutoMapper

MappingGenerator - Visual Studio Marketplace

A Simple and Fast Object Mapper (HAY HAY HAY)

Nuget: Boxed.Mapping

A Simple and Fast Object Mapper - Muhammad Rehan Saeed

AutoMapper Usage Guidelines

Nuget: AutoMapper

AutoMapper Usage Guidelines (jimmybogard.com)

Adding errors to model state and returning bad request within asp.net core 3.1

Adding errors to model state and returning bad request within asp.net core 3.1 - Developer Ramblings of Kevin Smith (kevsoft.net)

Paging data in MongoDB with C#

Paging data in MongoDB with C# - Developer Ramblings of Kevin Smith (kevsoft.net)

Storing GUIDs as strings in MongoDB with C#

Storing GUIDs as strings in MongoDB with C# - Developer Ramblings of Kevin Smith (kevsoft.net)

Managing Relationships With Dapper

Managing Relationships With Dapper | Learn Dapper

Dapper Extensions with Oracle database

June 18, 2021 21:28

Dapper Extensions with Oracle database (edit)

Advanced operations using Dapper.Net | InfoWorld

Dapper Extensions

Dapper + DapperExtensions + CodeGenerator easy to play SqlServer + MySql + Oracle + PostgreSql + Sqlite

GitHub - znyet/DapperExtensions: Dapper + DapperExtensions + CodeGenerator easy to play sqlserver、mysql、oracle、postgresql、sqlite

GitHub - tmsmith/Dapper-Extensions: Dapper Extensions is a small library that complements Dapper by adding basic CRUD operations (Get, Insert, Update, Delete) for your POCOs. For more advanced querying scenarios, Dapper Extensions provides a predicate system. The goal of this library is to keep your POCOs pure by not requiring any attributes or base class inheritance.

Dapper Extensions Alternatives - .NET ORM | LibHunt

A simple but effective mini-profiler for ASP.NET (and Core) websites

GitHub - MiniProfiler/dotnet: A simple but effective mini-profiler for ASP.NET (and Core) websites

NUnit 3 for VS 2019

NUnit 3 Test Adapter - Visual Studio Marketplace

Running Tests with the NUnit Visual Studio Adapter - Alteridem

https://dapper-tutorial.net/query
https://zetcode.com/csharp/dapper/
https://www.learndapper.com/parameters
https://medium.com/geekculture/integrating-dapper-with-entity-framework-core-55aacc94b5b0
https://github.com/znyet/DapperExtensions
https://github.com/tmsmith/Dapper-Extensions

Dapper Generic Repository PostgreSQL

March 7, 2021 16:22

Dapper + Generic Repository + PostgreSQL (edit)

.NET Core

https://www.codeproject.com/Articles/1186566/Dapper-Generic-Repository

https://techbrij.com/asp-net-core-postgresql-dapper-crud

.NET Web API

http://www.mukeshkumar.net/articles/web-api/dapper-and-repository-pattern-in-web-api

DI in .NET Core Console App

https://andrewlock.net/using-dependency-injection-in-a-net-core-console-application/

https://long2know.com/2018/02/net-core-console-app-dependency-injection-and-user-secrets/

https://auth0.com/blog/dependency-injection-in-dotnet-core/

EF Core + MySQL + Repository (ASP.NET Core Series)

https://code-maze.com/net-core-series/

https://code-maze.com/net-core-web-development-part4/

https://code-maze.com/net-core-web-development-part5/

Ways to consume Restful API

https://code-maze.com/different-ways-consume-restful-api-csharp/

  • HttpWebRequest
  • WebClient
  • HttpClient
  • RestSharp
  • ServiceStack
  • cUrl (command-line tool)

Repository Pattern

https://www.codeproject.com/Articles/1119652/Repository-Pattern-For-Net

Windows Service in .NET Core

https://www.stevejgordon.co.uk/running-net-core-generic-host-applications-as-a-windows-service

Work with EFCore Dapper together in the PostgreSQL database

March 5, 2021 08:42

Work with EFCore Dapper together in the PostgreSQL database (edit)

Install-Package Dapper
Install-Package Npgsql

Install-Package Microsoft.EntityFrameworkCore
Install-Package Microsoft.EntityFrameworkCore.Design
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Install-Package Microsoft.EntityFrameworkCore.Relational
Install-Package Dapper
Install-Package Npgsql
Install-Package System.Data.SqlClient

https://codewithmukesh.com/blog/using-entity-framework-core-and-dapper/ (HAY)

https://github.com/iammukeshm/EFCoreAndDapper

https://dotnetcoretutorials.com/2020/07/11/dapper-with-mysql-postgresql-on-net-core/

https://www.c-sharpcorner.com/article/getting-started-with-postgresql-using-dapper-in-net-core/

https://techbrij.com/asp-net-core-postgresql-dapper-crud/ (HAY)

https://dotnetcorecentral.com/blog/postgresql-and-dapper-in-net-core/

Oracle + Dapper

October 21, 2020 13:45

Oracle (edit)

The ADO.NET provider with invariant name 'Oracle.ManagedDataAccess.Client' is either not registered in the machine or application config file, or could not be loaded. See the inner exception for details

c# - The ADO.NET provider 'Oracle.ManagedDataAccess.Client' is either not registered in the machine or application config file, or could not be loaded - Stack Overflow

Solution: I resolved this by adding ODP.NET (Oracle.ManagedDataAccess.EntityFramework 12c) from NuGet. I'm running VS2015 with EF 6.2.0.

Oracle Dapper C# : Problem with Kanji characters (Oracle database in Japanese)

C# - How to save unicode data to oracle? - Stack Overflow

ASP.NET - Why are my Chinese characters not displayed correctly in c# string - Stack Overflow

C# - OdbcConnection returning Chinese Characters as "?" - Stack Overflow

C#: DbType.String versus DbType.AnsiString - Stack Overflow

C#/Oracle: Specify Encoding/Character Set of Query? - Stack Overflow

Oracle database: Unicode Database and Unicode Datatype

Ký tự hán tự (kanji character): 鄭 瑋萱

Supporting Multilingual Databases with Unicode (oracle.com)

 //INSERT WITH PARAMETER BINDING - UNICODE SAVED
using (System.Data.OracleClient.OracleConnection cn = new System.Data.OracleClient.OracleConnection(connString))
{
cn.Open();
System.Data.OracleClient.OracleCommand cmd = new System.Data.OracleClient.OracleCommand("insert into kuku (kuku) values(:UnicodeString)", cn);
cmd.Parameters.Add(":UnicodeString", System.Data.OracleClient.OracleType.NVarChar).Value = input + " OK" ;
cmd.ExecuteNonQuery();
cn.Close();
}

//FETCH RESULT
using (System.Data.OracleClient.OracleConnection cn = new System.Data.OracleClient.OracleConnection(connString))
{
cn.Open();
System.Data.OracleClient.OracleCommand cmd = new System.Data.OracleClient.OracleCommand("select kuku from kuku", cn);
System.Data.OracleClient.OracleDataReader dr = cmd.ExecuteReader();
if(dr.Read())
{
string output = (string) dr[0];
char sa = output[0];
}
cn.Close();
}

Oracle With Dapper

whit-wu/OracleWithDapper: Shows .NET devs working with Oracle DBs how to utilize Dapper. Shows nuances between using Dapper with SQL Server and using it with Oracle. (github.com)

DIPSAS/Dapper.Oracle: Oracle support for Dapper Micro ORM. (github.com)

https://aspnetmaker.dev/ (Code Generate: ASP.NET Maker)

Oracle Managed ODP.NET | Vijay Ganesh (BASIC)

Connect to Oracle database from .NET core application

[Translation] ASP.NET Core Web API using Oracle database and Dapper read this is enough - Programmer All

Oracle Design Basics (haw-hamburg.de)

Oracle/dotnet-db-samples: .NET code samples for Oracle database developers (github.com)

ASP.NET Core Web API With Oracle Database And Dapper (c-sharpcorner.com)

  • NTierOracleIdentityExample.Bll
  • NTierOracleIdentityExample.Dll
  • NTierOracleIdentityExample.Web

ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 01 | Codementor

ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 02 | Codementor

  • .NET CORE
  • ASP.NET CORE
  • ASP.NET MVC
  • DESIGN PATTERN
  • ORACLE

oracle identity manager architecture

jQuery Ajax CRUD in ASP.NET Core MVC with Modal Popup - CodAffection

Build ASP.NET MVC Project with Oracle Data Base using Entity Framework DB first approach

  • Install-Package EntityFramework -Version 6.2.0
  • Install-Package EntityFramework.ja -Version 6.2.0
  • Oracle.ManagedDataAccess.dll -Version 18.3.0
  • Oracle.ManagedDataAccess.EntityFramework.dll -Version 18.3.0

Oracle/dotnet-db-samples: .NET code samples for Oracle database developers (github.com)

Oracle Data Access Components (ODAC) for Windows Downloads

Using ASP.NET with Oracle Database

Connecting ASP.NET with Oracle Database - Doyensys Blog

Oracle .NET and Visual Studio Downloads for Oracle Database

ASP.NET Core Web API with Entity Framework Core - @manhng

Dapper - @manhng

Using Dapper - @manhng

Dapper - @manhng

Dapper POCO Oracle - @manhng

CQRS Raw SQL and DDD with Dapper - @manhng

Mapping Generator - @manhng

Dapper Extensions with Oracle database - @manhng

Dapper + Object Extensions + Visual Studio Extensions - @manhng

Dapper Generic Repository PostgreSQL - @manhng

Dapper Log4net AutoMapper - @manhng

Dapper Transaction - @manhng

Work with EFCore Dapper together in the PostgreSQL database - @manhng

Integration Tests (Microsoft.VisualStudio.TestTools.UnitTesting + Dapper + Stored Procedure + XML) - @manhng

.NET Core With Oracle Database Using Dapper - @manhng (HAY HAY HAY)

CRUD Operations In ASP.NET Core-3.1 Using Oracle Database (c-sharpcorner.com) (BASIC)

.NET 5.0 - CRUD API Example and Tutorial | Jason Watmore's Blog

ECRUD (Easy-CRUD)

wvswill/ecrud (github.com)

Dapper.Fast.CRUD

MoonStorm/Dapper.FastCRUD: The fastest micro-orm extension for Dapper (github.com)

Connect application with Oracle Database using entity framework in MVC 5

Here are good example that discus step by step , please following below links:

https://csharp.today/entity-framework-6-database-first-with-oracle/

http://www.codeproject.com/Tips/421105/Using-Oracle-with-EntityFramework

Please following below link, show you CRUD

http://www.codeproject.com/Tips/869553/CRUD-operation-with-Entity-Framework-Database-Fi

http://www.codeproject.com/Articles/812005/ASP-NET-MVC-CRUD-Application-with-drop-down-list

http://www.c-sharpcorner.com/uploadfile/dhananjaycoder/crud-operation-in-Asp-Net-mvc-framework/

http://cybarlab.com/crud-operation-in-asp-net-mvc-using-entity-framework

Oracle XE

https://geraldonit.com/2019/08/19/how-to-install-oracle-database-18c-xe-on-windows/

https://blog.toadworld.com/2018/09/26/how-to-install-oracle-database-18c-on-windows/

https://rustamkhodjaev.com/2020/04/28/install_database_express_edition_18c_on_windows/

A WinForms SQL client for generating C# query result classes, Dapper productivity

Note: Only for OleDb, MySql, SqlServer, SqlCe, not for Oracle

adamfoneil/Postulate.Zinger: A WinForms SQL client for generating C# query result classes, Dapper productivity (github.com)

HigLabo

higty/higlabo: HigLabo library provide features of Mail, Ftp, Rss, Twitter, ObjectMapper, ORM, ASP.NET Mvc...etc (github.com)

Dapper + DapperExtensions + CodeGenerator easy to play sqlserver, mysql, oracle, postgresql, sqlite

znyet/DapperExtensions: Dapper + DapperExtensions + CodeGenerator easy to play sqlserver、mysql、oracle、postgresql、sqlite (github.com)

ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 01

ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 01

In this tutorial series we will be creating ASP.NET Core MVC Web application using ORACLE Database. Before we dive into anything, whole code with database scripts will be available on Github.This tutorial series will be split into 3 parts.

First part is setting up our development environment, setting up multiple projects with structure that will use couple of design patterns like N-tier architecture, SOC, Unit of Work and scaffolding existing ORACLE 12.2 database and creating our first migration.

Second part will be explaining our architecture of application, implementing Repository pattern for our Data layer, keeping SoC, implementing base interfaces for CRUD operations on existing database. Then we will create our service or Business logic layer by implementing interfaces that will represent Unit of Work. And last, in our web project we will use model to view model mapping and create our mapping profile.

Third part will be explaining how to use ASP.NET Identity with ORACLE database and with Windows authentication. So lets start shall we?
First things first lets explain what type of project are we going to use and how are we going to connect to database using code first approach of entity framework. Open your Visual Studio (Mine is 2019), then File -> New -> Project.
1_iwYNZZlwOIOb2fk51cPxQQ.png

Next we are going to choose out project type. We will be using ASP.NET Core Web App(Model-View-Controller) type of project.
1_TA9GthyVn80Xkn75QRCyRw (1).png

Then click next and name your project and solution and choose folder. For out N-Tier artchitecture we will be creating three projects. First will be our Web project, Second will be our Business logic layer and last will be Data logic layer. So when creating we will name our Web project with .Web extension. Next two project will have .Bll and .Dll extensions as well.
1_rzJZm0mXiIukAJLC7Fjyug.png

Next we will use .NET 5.0 as our target framework and will not choose any type of authentication for now, as we will be adding Windows authentication with ASP.NET Identity later. Click create and we are done.
1_6DK_hMflh9t9iyN17-BjBQ.png

So now we have to add two more projects for our business and data layers. Right click on solution and choose New project.
1_f3vgVDo68e8xq9rZtqmAiQ.png

Choose Class library(not .NET Framework one), and click next. Choose same name of web project but with .Dll and .Bll extensions.
1_hO4Cw4OTCuAdeB12RxHBzQ.png1_LOeVwyy3h-BRyCsPkwsQ7w.png

Click Next and choose .NET 5.0 as target framework and last create your project.
1_zKEUXmqj6STmrzW-_mKZ_A.png

We will have structure like on next image.
1_4KFUHUr3DTbtEyBc_PvrrQ.png

Next thing that we will do is to setup our Dll project. This will include installing additional packages for connecting to Oracle database, organizing our project with SoC pattern (separation of concerns) and setting up our first migration.

So go to NuGet package manager, either by right clicking on Dll project and choosing “Manage NuGet packages” or opening console. Then browse for next packages and install them:

  • Microsoft.EntityFrameworkCore.Design
  • Oracle.EntityFrameworkCore

Next we will add a few folders that will structure our application in order to implement our design patterns and organize it properly.
First add next 4 folders:

  • Context
  • Entities
  • Migrations
  • Repositories

And in Repositories add Abstract and Implementation folders. These folders will hold our abstract repositories for accessing our data. Context folder will hold our generated Context class, Migrations folder will hold our migrations and Entities will hold our generated classes/models for data access. Project structure should look like this.
1_yqUggIjd8ckxr6mnJuS3vQ.png

Next we will generate our Context class and Entities. Just to mention, we are generating context and entities from existing database, which means that we are scaffolding from existing database. Initially if we did not have already existing database, we would just create those classes and execute our first migration that will create new tables in our database.

First we need to install dotnet cli. For more reference check this official link:

Go to package manager console, choose .Dll project and execute this command:
1_pAXNZXnDk079RHQSBIHNPg.png

So, now we will generate our context and entity classes from our existing database schema on Oracle 12c release 2 (12.2). To do that we need to use dotnet ef command with specifying of couple parameters:
-o tells us what output directory of our Dll project will entities be placed in. In our case it is Entities

  • -context-dir tells us what output directory of our Dll project will context be placet. In our case it is Context folder
    -c tells what will be name of our
    -p tells us on what project command will execute. In our case it id Dll project
    -f tells us that we do not need to confirm our scaffolding

Whole command should look like this:

dotnet ef dbcontext scaffold "User Id=EXAMPLE_SCHEMA;Password=my_password;Data Source=server:1521/orcl;Connection Timeout=600;min pool size=0;connection lifetime=18000;PERSIST SECURITY INFO=True;" Oracle.EntityFrameworkCore -o Entities --context-dir Context -c EXAMPLE_SCHEMA_Context -f -p NTierOracleIdentityExmple.Dll

After we execute command we will generate context class, entities and migration in our folders that we have created.

Also there is a shortcut to dotnet ef and that is EF Core Power Tools that can be found on next link.

It can be installed as and VS2019 extension that can generate needed stuff either by scaffolding existing DB using code first or database first approach(create edmx file) and can generate migrations for existing code.
So lets assume that we have our schema already created in our database with some tables in it. So it might look like this.
1_yBw5UreXxuSzwOaBzcmRvQ.png

After execution of previous command, our project should include next generated classes for our context and existing entities.
1_JX9K1gjK8A-n_xaHEhY_dA.png

Next thing is to modify our Context. First install next package from NuGet:

  • Microsoft.EntityFrameworkCore.Proxies
    https://stackoverflow.com/questions/55234943/what-is-the-equivalent-of-configuration-proxycreationenabled-in-ef-core
    Next modify OnConfiguring method in context and add next line that contain our connection string:
if (!optionsBuilder.IsConfigured)
{
//Proxy for navigation properties //Microsoft.EntityFrameworkCore.Proxies
optionsBuilder.UseLazyLoadingProxies().UseOracle(“User Id=SCHEMA_NAME;Password=xxxxx;Data Source=server:1521/SID;Connection Timeout=600;min pool size=0;connection lifetime=18000;PERSIST SECURITY INFO=True;”);
}

First our edit contains connection string that will be used from our context to connect and create/apply new migrations. Second change is change that is using UseLazyLoadingProxies that includes navigational properties from our context entities that we select. This is explained in next Stackoverflow question.

Our last change will include changing the OnModelCreating method. Add next line:

base.OnModelCreating(modelBuilder);

Now we are ready to create our first migration. Our first migration will include only one table that will represent our log table for logging data from our application. Later in next part we will create repository, service and controller actions for implementing CRUD functionalities over that table. Also we will create our CRUD functionalities over Identity table in part 3.

So first things first, lets define our table. Create next class in Entities folder of our DLL project.

public class Log
{
  public int pk { get; set; }
  public string CreatedBy { get; set; }
  public DateTime CreationDate { get; set; }
  public string ModifiedBy { get; set; }
  public DateTime ModifiedDate { get; set; }
  public DateTime? Date { get; set; }
  public string Value { get; set; }
}

Next thing is to create how our table is going to look when we create it in Oracle database schema. Open Context class from Context folder of our DLL project.
First add our table as DbSet.

public virtual DbSet<Log> Log{ get; set; }

Next is to define how our table is going to look when our context class build our entity. Add next code to OnModelCreating method.

modelBuilder.Entity<Log>(entity =>
{
  entity.HasKey(e => e.pk).HasName("LOG_PK");
  entity.ToTable("LOG");
  entity.Property(e => e.pk)
  .HasColumnType("NUMBER(10)")
  .HasColumnName("PK");
  entity.Property(e => e.CreatedBy)
  .HasMaxLength(256)
  .IsUnicode(false)
  .HasColumnName("CREATED_BY");
  entity.Property(e => e.CreationDate)
  .HasColumnType("DATE")
  .HasColumnName("CREATION_DATE");
  entity.Property(e => e.ModifiedBy)
  .HasMaxLength(256)
  .IsUnicode(false)
  .HasColumnName("MODIFIED_BY");
  entity.Property(e => e.ModifiedDate)
  .HasColumnType("DATE")
  .HasColumnName("MODIFIED_DATE");
  entity.Property(e => e.Value)
  .IsUnicode(false)
  .HasColumnName("LOG_VALUE");
});

Only thing remaining is to create our first migration and update database. Lets create our DATA_LOG migration.

dotnet ef migrations add EXAMPLE_SCHEMA_LOG -p NTierOracleIdentityExmple.Dll -c NTierOracleIdentityExample.Dll.Context.EXAMPLE_SCHEMA_Context -o Migrations

After executing this command, our migration class will be created in Migrations folder of our DLL project.
1_vcWstuzdro_DdCFdNoK94g.png

Now lets update our database

dotnet ef database update EXAMPLE_SCHEMA_LOG -p NTierOracleIdentityExmple.Dll -c NTierOracleIdentityExample.Dll.Context.EXAMPLE_SCHEMA_Context

Now if you open the Oracle database from any client tool like SQLDeveloper or Toad you will see our table created, with migration history table.
1_hxMho8Vf6T-ZJrTO-gk5dg.png

That is it for now. Next part will be explaining how to create base repository, services for our CRUD operations with couple of design patterns.iting here...

ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 02

Published Jan 11, 2022
ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 02ASP.NET Core MVC with .NET 5.0 ORACLE, Identity using N-tier architecture-Part 02

In this part of our tutorial, we will dive into creating basic project structure for N-tier project including creating base repository and creating data layer, creating service layer and using all of newly created stuff in our Web project.
First things first, in previous part we have created our context with entities, explained how to create migration (code first approach) with Oracle database using EFCore and how to scaffold existing database entities into our project (database first approach). Now we will put everything in use through couple of design patterns in multiple layers.

Data logic layer and Repository Pattern

First pattern that we will implement is Repository pattern in our data-access layer. Our code will create generic IBaseRepository with CRUD operations that contains INSERT, UPDATE, DELETE and SELECT operations and later we are going to add implementation of IBaseRepository.

Entity Framework already implements the repository pattern as we can access, add, modify and delete entities through DbSet. We are creating generic IBaseRepository interface and implementation of that repository to avoid boilerplate code for CRUD operations of every repostory for each entity.

Now lets create generic interface IBaseRepository with basic CRUD operation.
Add IBaseRepository interface class in Repositores/Abstract folder of DLL project:

public interface IBaseRepository<T> where T : class
{
  #region Select methods
  Task<T> SelectById(int id);
  Task<List<T>> SelectAll();
  #endregion
  #region Insert methods
  Task<T> Insert(T entity);
  #endregion
  #region Update methods
   void Update(T entity);
  #endregion
  #region Delete methods
  void Delete(int Id);
  #endregion
  #region Other methods
  void SaveChanges();
  #endregion
}

The IBaseRepository interface accept one generic type T. T as defined must be a class, so it must be entity just like one from our Entities folder in DLL project. As previously explained our generic IBaseRepository interface is defining base CRUD operations that we will implement later in our BaseRepository implementation. Lets create implementation of our generic IBaseRepository.
Add BaseRepository implementation in Repositores/Implementation folder of DLL project:

public class BaseRepository<T> : IBaseRepository<T> where T : class
{
  #region Fields
  protected readonly DbContext _context;
  protected readonly DbSet<T> dbSet;
  #endregion
  #region Constructor
  protected BaseRepository(DbContext context)
  {
    _context = context;
    dbSet = context.Set<T>();
  }
  #endregion
  #region Select methods
  public virtual async Task<T> SelectById(int id)
  {
    return await dbSet.FindAsync(id);
  }
  public virtual async Task<List<T>> SelectAll()
  {
    return await dbSet.ToListAsync();
  }
  #endregion
  #region Insert methods
  public virtual async Task<T> Insert(T entity)
  {
   var addedEntity = (await dbSet.AddAsync(entity)).Entity;
   await _context.SaveChangesAsync();
   return addedEntity;
  }
  #endregion
  #region Update methods
  public virtual async void Update(T entity)
  {
   dbSet.Update(entity);
   await _context.SaveChangesAsync();
  }
  #endregion
  #region Delete methods
  public async void Delete(int Id)
  {
   T entity = dbSet.Find(Id);
   var removedEntity = dbSet.Remove(entity).Entity;
   await _context.SaveChangesAsync();
  }
  #endregion
  #region Other methods
  public void SaveChanges()
  {
    _context.SaveChanges();
  }
  #endregion
}

Your project structure should look like this.
1_-K38JXeQ4YxxzIMVtrz9kQ.png

Now, next step would be for us to implement entity repository for our database entities. In previous chapter we have created two entities: Log and ExampleTable. Lets create interfaces for our entity repositories and implementation of those repositories. First add ILogRepository interface in Repositores/Abstract folder of DLL project:

public interface ILogRepository : IBaseRepository<Log>, IDisposable
{
 //Additional methods or override ones from BaseRepository
 #region Select methods
 #endregion
 #region Insert methods
 #endregion
 #region Update methods
 #endregion
 #region Delete methods
 #endregion
 #region Other methods
 #endregion
}

Next, Add LogRepository implementation in Repositores/Implementation folder of DLL project:

public class LogRepository : BaseRepository<Log>, ILogRepository
{
 //Implement additional methods or override ones from BaseRepository and implement them
 #region Select methods
 public LogRepository(EXAMPLE_SCHEMA_Context context) : base(context)
 { }
 #endregion
#region Select methods
#endregion
#region Insert methods
#endregion
#region Update methods
#endregion
#region Delete methods
#endregion
#region Other methods
public void Dispose()
 {
 _context.Dispose();
 }
#endregion
}

Now lets do the same for our second entity ExampleTable. First add IExampleTableRepository interface in Repositores/Abstract folder of DLL project:

public interface IExampleTableRepository : IBaseRepository<ExampleTable>, IDisposable
{
 //Additional methods or override ones from BaseRepository
 #region Select methods
 #endregion
 #region Insert methods
 #endregion
 #region Update methods
 #endregion
 #region Delete methods
 #endregion
 #region Other methods
 #endregion
}

Next, Add ExampleTableRepository implementation in Repositores/Implementation folder of DLL project:

public class ExampleTableRepository : BaseRepository<ExampleTable>, IExampleTableRepository
{
 //Implement additional methods or override ones from BaseRepository and implement them
 #region Select methods
 public ExampleTableRepository(EXAMPLE_SCHEMA_Context context) :  base(context)
 { }
 #endregion
 #region Select methods
 #endregion
 #region Insert methods
 #endregion
 #region Update methods
 #endregion
 #region Delete methods
 #endregion
 #region Other methods
 public void Dispose()
 {
   _context.Dispose();
 }
 #endregion
}

As we can see, we are extending BaseRepository in our entity repositories. In ILogRepository or any other interface we can add additional methods that are applicable only for that entity. That is why we are extending LogRepository as BaseRepository and implementing ILogRepository. BaseRepository contains basic CRUD operations and ILogRepository contains entity specific methods, procedures and other LINQ code.

Your project structure should look like this.
1_jak9gYGZdM2-GePR8CjjeQ.png

Business logic layer and Services

Now that we have implemented the repositories in our DLL project it is time to move to Business logic layer project to implement our services which will implement Unit of Work pattern. Unit of work pattern tracks a business transaction and translate that transaction into database transaction. For example if we have ten steps for our business transaction, and those steps are connected with business logic in some way, we can collectively run that transaction as one unit.
Implementation of Unit of Work pattern should look like this.
1_CtbFSP_5iZ234f1USahz4A.png

So lets create ILogService, IExampleTableServices interfaces and LogService, ExampleTableService as implementation of those interfaces.

public interface ILogService
{
 #region Select methods
 Task<List<Log>> SelectLog();
 Task<Log> SelectLogById(int Id);
 #endregion
 #region Insert methods
 void InsertLog(Log entity);
 #endregion
 #region Update methods
 void UpdateLog(Log entity);
 #endregion
 #region Delete methods
 void DeleteLog(int Id);
 #endregion
}
public class LogService : ILogService
{
 //Service can have multiple repositories implementing UoW(Unit oof Work) design pattern.
 #region Fields
 private readonly ILogRepository _logRepository;
 #endregion
 #region Constructor
 public LogService(ILogRepository logRepository)
 {
  _logRepository = logRepository;
 }
 #endregion
 #region Select methods
 public Task<List<Log>> SelectLog()
 {
   return _logRepository.SelectAll();
 }
 public Task<Log> SelectLogById(int Id)
 {
  return _logRepository.SelectById(Id);
 }
 #endregion
 #region Insert methods
 public void InsertLog(Log entity)
 {
   _logRepository.Insert(entity);
 }
 #endregion
 #region Update methods
 public void UpdateLog(Log entity)
 {
   _logRepository.Update(entity);
 }
 #endregion
 #region Delete methods
 public void DeleteLog(int Id)
 {
   _logRepository.Delete(Id);
 }
 #endregion
 #region Other methods
 #endregion
}
public interface IExampleTableService
{
 #region Select methods
 Task<List<ExampleTable>> SelectExampleTable();
 Task<ExampleTable> SelectExampleTableById(int Id);
 #endregion
 #region Insert methods
 void InsertExampleTable(ExampleTable entity);
 #endregion
 #region Update methods
 void UpdateExampleTable(ExampleTable entity);
 #endregion
 #region Delete methods
 void DeleteExampleTable(int Id);
 #endregion
}
public class ExampleTableService : IExampleTableService
{
 //Service can have multiple repositories implementing UoW(Unit oof Work) design pattern.
 #region Fields
 private readonly IExampleTableRepository _exampleTableRepository;
 #endregion
 #region Constructor
 public ExampleTableService(IExampleTableRepository ExampleTableRepository)
 {
   _exampleTableRepository = ExampleTableRepository;
 }
 #endregion
 #region Select methods
 public Task<List<ExampleTable>> SelectExampleTable()
 {
   return _exampleTableRepository.SelectAll();
 }
 public Task<ExampleTable> SelectExampleTableById(int Id)
 {
   return _exampleTableRepository.SelectById(Id);
 }
 #endregion
 #region Insert methods
 public void InsertExampleTable(ExampleTable entity)
 {
   _exampleTableRepository.Insert(entity);
 }
 #endregion
 #region Update methods
 public void UpdateExampleTable(ExampleTable entity)
 {
   _exampleTableRepository.Update(entity);
 }
 #endregion
 #region Delete methods
 public void DeleteExampleTable(int Id)
 {
   _exampleTableRepository.Delete(Id);
 }
 #endregion
 #region Other methods
 #endregion
}

Our BLL project structure should look like this:
1_TMOErbMvMiJEdo4-ym0vFg.png

That is it. Unit of work consist of multiple repositories that implement some business logic, incorporating all of them in single service.

Dependency Injection

So what is our next step? Next we are going to use our repositories and services in our controllers. We are going to inject repositories into our services and later those services into our controllers which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies. There are multiple libraries that allow us to inject needed dependencies of a class, but we will use standard ASP.NET CORE DI framework for injecting our dependencies.

Before we dive into code, lets explain 3 lifetime modes for service being injected:
Scoped - lifetime services are created once per request within the scope.
Transient - lifetime services are created each time they are requested.
Singleton - which creates a single instance throughout the application. It creates the instance for the first time and reuses the same object in the all calls.

Lets open Startup.cs class and in ConfigureServices method inject our DBContext and needed services and repositories.

public void ConfigureServices(IServiceCollection services)
{
 services.AddControllersWithViews();
 //Dependency injection   services.AddEntityFrameworkOracle().AddDbContext<EXAMPLE_SCHEMA_Cont ext>();  services.AddScoped(typeof(IBaseRepository<>),typeof(BaseRepository<> ));  services.AddScoped(typeof(ILogRepository),typeof(LogRepository));  services.AddScoped(typeof(IExampleTableRepository),typeof(ExampleTab leRepository));
}

AutoMapper mapping between DLL entities and ViewModels

Next, problem that we are going to solve is problem of mapping of our DLL entities that are generated either by code first or database first approach. Every time we need to modify our entity we loose DataAnotations and we need to apply that change again, or we need to add new properties to every entity where we are copying data and change our logic for copying one object to another in our code (Entity to EntityViewModel and vice versa).

The AutoMapper in C# is a mapper between two objects. It maps the properties of two different objects by transforming the input object of one type to the output object of another type.

Lets first install AutoMapper either through GUI on our web project by Right Click on Dependencies of Web project and then Manage NuGet Packages
1_Qti0z5kwFfw9mfrEcEj-AQ.png

or executing following PM console commands on Web project:

  • Install-Package AutoMapper -Version 11.0.0
  • Install-Package AutoMapper.Extensions.Microsoft.DependencyInjection -Version 11.0.0

Next in our Startup.cs class in ConfigureServices method add next code:

public void ConfigureServices(IServiceCollection services)
{
 …
  //AutoMapper setup
  services.AddAutoMapper(typeof(Startup));
 …
 
 …
  //Dependency injection
  services.AddSingleton(provider => new MapperConfiguration(cfg =>
  {
    cfg.AddProfile(new EXAMPLE_SCHEMA_Profile());
  }).CreateMapper());
 …
}

Next, lets create ViewModel for our Log and ExampleTable entity classes:

public class LogViewModel
{
 public int pk { get; set; }
 public string CreatedBy { get; set; }
 public DateTime CreationDate { get; set; }
 public string ModifiedBy { get; set; }
 public DateTime ModifiedDate { get; set; }
 public DateTime? Date { get; set; }
 public string Value { get; set; }
}
public class ExampleTableViewModel
{
 public int Pk { get; set; }
 public string CreatedBy { get; set; }
 public DateTime CreationDate { get; set; }
 public string ModifiedBy { get; set; }
 public DateTime ModifiedDate { get; set; }
 public string Name { get; set; }
}

Next lets create AutoMapperConfigurations folder in NTierOracleIdentityExample.Web project. Then create new profile called EXAMPLE_SCHEMA_Profile class in newly created folder:

public class EXAMPLE_SCHEMA_Profile : Profile
{
 public EXAMPLE_SCHEMA_Profile()
 {
   CreateMap<Log, LogViewModel>().ReverseMap();
   CreateMap<ExampleTable, ExampleTableViewModel>().ReverseMap();
 }
}

As you can see from previous code, we need to map each property of entity class to the correspondent ViewModel class using AutoMapper.

Note: When the property names are different in Source and Destination types, then by default the C# Automapper will not map those properties.

Our Web project structure should look like this:
1_piQUnNi4DzEhORT_4UeyVQ.png

Wrapping up Controller

Last, lets add some code to our HomeController. We will inject ILogService and IMapper interfaces in contructor of HomeController. Next we will add some dummy methods for CRUD operations of our service, like GetLog, GetLogById, EditLog and DeleteLog.

public class HomeController : Controller
{
 #region Fields
 private readonly IMapper _mapper;
 private readonly ILogService _logService;
 #endregion
 #region Constructor
 public HomeController(ILogService logService, IMapper mapper)
 {
   _logService = logService;
   _mapper = mapper;
 }
 #endregion
 #region GET methods
 public IActionResult Index()
 {
   return View();
 }
 public JsonResult GetLog()
 {
   List<LogViewModel> logs = _mapper.Map<List<Log>,            List<LogViewModel>>(_logService.SelectLog().Result);
 
 var logList = from l in logs
 select new
 {
   Id = l.pk,
   LogDate = l.Date,
   LogValue = l.Value
 };
  return Json(new { status = “success”, records = logList.OrderBy(l => l.Id).ToList(), total = logList.Count() });
 }
 public JsonResult GetLogById(int pk)
 {
 LogViewModel log = _mapper.Map<Log, LogViewModel>(_logService.SelectLogById(pk).Result);
  return Json(new { status = “success”, records = log });
 }
 #endregion
#region POST methods
 [HttpPost]
 public JsonResult EditLog(LogViewModel viewModel)
 {
  if (ModelState.IsValid)
  {
   //Map viewModel to model
   Log model = _mapper.Map<Log>(viewModel);
   model.ModifiedBy = “DummyUser”;
   model.ModifiedDate = DateTime.Now;
   _logService.UpdateLog(model);
  return Json(new
  {
   success = true,
   message = “Log saved!”
  });
  }
  else
  {
   return Json(new { success = false, message = “Error!” });
  }
 }
[HttpPost]
 public JsonResult DeleteLog(int pk)
 {
 _logService.DeleteLog(pk);
 return Json(new { success = false, message = “Log deleted!” });
 }
#endregion
#region Helper methods
#endregion
}

So, that is it for this part. In next part we will cover the ASP.NET Identity with ORACLE database and how to create needed entities in database for Identity and how to implement it in our application. And finally run our application.

Dapper + Object Extensions + Visual Studio Extensions

March 24, 2020 13:56

Dapper + Object Extensions (edit)

Generic repository pattern using Dapper

https://itnext.io/generic-repository-pattern-using-dapper-bd48d9cd7ead

CRUD with JSON file

https://www.c-sharpcorner.com/article/crud-operation-with-json-file-data-in-c-sharp/

Best Visual Studio Extensions

https://www.syncfusion.com/blogs/post/15-must-have-visual-studio-extensions-for-developers.aspx

For Visual Studio 2019

https://www.telerik.com/blogs/top-15-visual-studio-code-extensions-in-2019

New For Visual Studio 2019

https://visualstudiomagazine.com/articles/2019/04/12/vs-2019-tools.aspx

Integration Tests (Microsoft.VisualStudio.TestTools.UnitTesting + Dapper + Stored Procedure + XML)

November 13, 2019 13:17

Integration Tests (Microsoft.VisualStudio.TestTools.UnitTesting + Dapper + Stored Procedure + XML) (edit)

https://www.teamscs.com/2018/10/simple-c-model-to-sql-server-stored-procedure-mapping-using-xml/

Tips & Tricks

October 3, 2018 16:24

Tips & Tricks (edit)

inurl: tips-tricks

https://gokulraja.wordpress.com/category/tips-tricks/

T3 Templates

https://www.codeproject.com/Articles/21162/Template-Based-Code-Generator

T4 Templates

https://www.tritac.com/blog/code-generationscaffolding-with-visual-studio-t4-templates/

http://paginaswebpublicidad.com/questions/40657/tuy-chon-gian-giao-tuy-chinh-asp-net-mvc-5-t4-templates

Dapper By Eample

https://www.tritac.com/blog/dappernet-by-example/

Generate SQL script (.SQL) from XML Schema (.XSD)

http://mssql.tools/Download.aspx?Id=118

JavaScript

http://crockford.com/javascript/

https://johnresig.com/blog/simple-javascript-inheritance/

OOP in JavaScript

  • Work effectively with JavaScript
  • JavaScript Built-in Functions
  • Prototype-based OOP
  • Class-based OOP
  • Pseudo-classes
  • Pseudo-elements

https://alistapart.com/article/prototypal-object-oriented-programming-using-javascript

In JavaScript, almost "everything" is an object.

  • Booleans can be objects (if defined with the new keyword)
  • Numbers can be objects (if defined with the new keyword)
  • Strings can be objects (if defined with the new keyword)
  • Dates are always objects
  • Maths are always objects
  • Regular expressions are always objects
  • Arrays are always objects
  • Functions are always objects
  • Objects are always objects

All JavaScript values, except primitives, are objects.

JavaScript defines 5 types of primitive data types:

  • string
  • number
  • boolean
  • null
  • undefined

Built-in methods

var message = "Hello world!";
var x = message.toUpperCase();

Adding a Method to an Object

person.name = function () {
return this.firstName + " " + this.lastName;
};

Prototype-based OOP

var genericAnimal = Object.create(null);

genericAnimal.name = 'Animal';

Class-based OOP

function Person(name) { ... }

var adam = new Person('Adam');

Using Dapper

March 25, 2018 11:09

Using Dapper

var data = new List<uspGetCustomersDynamicSearchPagingSorting>();
using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["DbPaging"].ConnectionString))
{
    //var dynamicParams = new DynamicParameters();
    //Dictionary<string, object> parameters = new Dictionary<string, object>();                
    //foreach (var key in parameters.Keys)
    //{
    //    dynamicParams.Add(key, parameters[key]);
    //}

    //var p = new DynamicParameters();
    //p.Add("a", 11);
    //p.Add("b", dbType: DbType.Int32, direction: ParameterDirection.Output);
    //p.Add("c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
    //db.Execute(@"create proc #TestProc @a int, @b int output as begin set @b = 999 select 1111 return @a end");
    //db.Query("#TestProc", p, commandType: CommandType.StoredProcedure).FirstOrDefault();
    //db.Query("#TestProc", p, commandType: CommandType.StoredProcedure).First().IsEqualTo(1111);
    //p.Get("c").IsEqualTo(11);
    //p.Get("b").IsEqualTo(999);

    var p = new DynamicParameters();
    p.Add("CustomersID", null);
    p.Add("Name", null);
    p.Add("City", null);
    p.Add("Email", null);
    p.Add("Company", null);
    p.Add("PageNbr", startRec / pageSize + 1);
    p.Add("PageSize", pageSize);
    p.Add("SortCol", string.Empty);
    p.Add("totalRecords", dbType: DbType.Int32, direction: ParameterDirection.Output);
    data = db.Query<uspGetCustomersDynamicSearchPagingSorting>("uspGetCustomersDynamicSearchPagingSorting", p, commandType: CommandType.StoredProcedure).ToList();

    // Total record count.
    totalRecords = p.Get("totalRecords");
}

 

Dapper Log4net AutoMapper

March 13, 2018 08:35

How to use the Dapper (edit)

- Create new ASP.NET Web Application called WebApplication1 (MVC: Web Forms, MVC, Web API) based on .NET Framework 4.5.2

- Nuget packages:

  + Install-Package log4net

  + Install-Package Dapper

  + Install-Package MySql.Data

  + Install-Package AutoMapper

  + Install-Package Newtonsoft.Json

- Web.config/App.config

  + Define connection string in <connectionStrings> or <appSettings>

- Controllers/HomeController.cs

- Documentation

Dapper with MS SQL Server

- Dapper with raw SQL

 

- Dapper with Stored Procedure

- Sample code

Dapper with MySQL

Nuget notes

+ .NET Framework 4.5
+ ASP.NET MVC 5.2
+ ASP.NET Web API 2.2
+ Web Pages 3.2

Update-Package
Install-Package jQuery -Version 1.12.4
Install-Package Bootstrap -version 3.3.7
Install-Package modernizr
Install-Package Newtonsoft.json
Install-Package log4net
Install-Package Dapper -Version 1.50.2 (.NET Framework 4.5)
Install-Package Microsoft.AspNet.WebApi (-Version 5.2.4)
Install-Package Swashbuckle (-Version 5.6.0)

Web API & Swagger + OAuth2
http://wmpratt.com/swagger-and-asp-net-web-api-part-1/

http://wmpratt.com/part-ii-swagger-and-asp-net-web-api-enabling-oauth2/

https://www.codeproject.com/Articles/1187872/Token-Based-Authentication-for-Web-API-where-Legac

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/ 

Dapper

December 9, 2017 16:58

Dapper (edit)

Asynchronous methods in Dapper

Dapper contains several asynchronous methods that you can use to perform asynchronous CRUD operations. Here is the list of asynchronous methods in Dapper:

  • ExecuteAsync
  • QueryAsync
  • QueryFirstAsync
  • QueryFirstOrDefaultAsync
  • QuerySingleAsync
  • QuerySingleOrDefaultAsync
  • QueryMultipleAsync

How to perform async operations using Dapper | InfoWorld

Using Entity Framework Core and Dapper in ASP.NET Core - Safe Transactions (codewithmukesh.com) (HAY HAY HAY)

gtechsltn/EFCoreAndDapper: Learn to Work with Dapper and Entity Framework within the Same ASP.NET Core Solutions. This is an implementation taking Transactions into concern as well. Probably a Facade Pattern too! (github.com)

Guidelinehttp://dapper-tutorial.net/

https://www.infoworld.com/article/3025784/application-development/how-to-work-with-dapper-in-c.html

https://www.codeproject.com/Articles/889668/SQL-Server-Dapper

https://www.c-sharpcorner.com/article/display-multiple-tables-data-in-single-view-from-database-in/

https://dotnetarchitect.wordpress.com/2012/03/26/fast-simple-data-access-using-dapper-net/

Transaction

http://dapper-tutorial.net/transaction

Multi Result

http://dapper-tutorial.net/querymultiple

https://stackoverflow.com/questions/6751052/how-to-map-multiple-records-from-a-single-sp-with-dapper-dot-net

https://medium.com/dapper-net/handling-multiple-resultsets-4b108a8c5172

Unit Test

https://www.intertech.com/Blog/unit-test-dapper-with-dapperparameters/

http://thesenilecoder.blogspot.com/2012/08/dapper-dot-net-dapperwrapper-and.html

Simple Sample

Nuget: Install-package dapper -version 1.50.2

1) App.config

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Server" value="192.168.200.179" />
<add key="DB" value="WEB" />
<add key="UserId" value="sa" />
<add key="Password" value="123456" />
<add key="ConnectTimeout" value="2" />
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>

2) Code Sample

using Dapper;
using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;

namespace QuicklyCheckASQLConnection
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var server = ConfigurationManager.AppSettings["Server"];
            var db = ConfigurationManager.AppSettings["DB"];
            var userId = ConfigurationManager.AppSettings["UserId"];
            var password = ConfigurationManager.AppSettings["Password"];
            var connectTimeout = 0;

            try
            {
                try
                {
                    connectTimeout = Convert.ToInt32(ConfigurationManager.AppSettings["ConnectTimeout"]);
                }
                catch
                {
                    connectTimeout = 2;
                }

                var connstr = new SqlConnectionStringBuilder
                {
                    DataSource = server,
                    InitialCatalog = db,
                    UserID = userId,
                    Password = password,
                    ConnectTimeout = connectTimeout
                }.ConnectionString;

                //using (var conn = new SqlConnection(connstr))
                //{
                //    conn.Open();
                //}

                TestProc(connstr);

                Console.WriteLine("Connect DB Successfully!");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Cannot Connect to DB. Exception: ");
                Console.WriteLine(ex.ToString());
                Console.ReadKey();
            }
        }

        ///
        /// ConnectTimeout
        ///
        ///
        private static void TestProc(string connstr)
        {
            var parameter = new DynamicParameters();
            parameter.Add("@userid", "username", DbType.String, ParameterDirection.Input);
            parameter.Add("@RowCount", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);
            using (var conn = new SqlConnection(connstr))
            {
                var list = conn.Query("sp_USER_INFO_GetUserInfo_ById", parameter, commandType: CommandType.StoredProcedure).ToList();

                //var list = conn.Query("sp_USER_INFO_GetUserInfo_ById", parameter, commandTimeout: 1, commandType: CommandType.StoredProcedure).ToList();
            }
        }

        /// 
        /// https://stackoverflow.com/questions/22353881/passing-output-parameters-to-stored-procedure-using-dapper-in-c-sharp-code
        /// 
        private static void TestProcSupport(string connstr)
        {
            var p = new DynamicParameters();
            p.Add("a", 11);
            p.Add("b", dbType: DbType.Int32, direction: ParameterDirection.Output);
            p.Add("c", dbType: DbType.Int32, direction: ParameterDirection.ReturnValue);

            using (var conn = new SqlConnection(connstr))
            {
                conn.Execute(@"create proc #TestProc
                         @a int,
                             @b int output
                             as
                             begin
                                 set @b = 999
                                 select 1111
                                 return @a
                             end");
                //conn.Query("#TestProc", p, commandType: CommandType.StoredProcedure).First().IsEqualTo(1111);
                //p.Get("c").IsEqualTo(11);
                //p.Get("b").IsEqualTo(999);
            }
        }

        /// 
        /// https://stackoverflow.com/questions/22353881/passing-output-parameters-to-stored-procedure-using-dapper-in-c-sharp-code
        /// 
        private static void InsertData(string connstr)
        {
            var p = new DynamicParameters();
            p.Add("VAR1", "John");
            p.Add("VAR2", "McEnroe");
            p.Add("BASEID", 1);
            p.Add("NEWID", dbType: DbType.Int32, direction: ParameterDirection.Output);
            using (var conn = new SqlConnection(connstr))
            {
                conn.Query("SP_MYTESTpROC", p, commandType: CommandType.StoredProcedure);
                int newID = p.Get("NEWID");
            }
        }
    }

    public class USER_INFO_GetUserInfo_ById
    {
        public string UserID { get; set; }
        public string NickName { get; set; }
        public string UserName { get; set; }
        public decimal? SEX { get; set; }
        public decimal? OnCash { get; set; }
        public string EMAIL { get; set; }
        public string PhotoPath { get; set; }
        public string PhotoNM { get; set; }
        public string PhotoNMNew { get; set; }
        public string PhotoPathNew { get; set; }
        public string PhotoSetYN { get; set; }
        public DateTime? LastLoginDate { get; set; }
        public DateTime? LastGiftDate { get; set; }
        public string StateMessage { get; set; }
        public decimal? LikeCnt { get; set; }
    }
}

Categories

Recent posts