@manhng

Welcome to my blog!

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/

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