@manhng

Welcome to my blog!

Api Convert Currency

January 5, 2022 16:03

Api Convert Currency (edit)

  • DbUp: Chạy script để đồng bộ database
  • Oracle Server Side Paging: Paging phía Server truyền lên PageSize, PageIndex dùng câu Raw SQL
  • Dapperdùng với Raw SQL
  • cUrl: Chuyển đổi tiền tệ giữa VND-USD-JPY (Việt-Nhật-Mỹ) dùng API online public
  • Oracle DbDataReader: Pagination in Oracle - @manhng
  • Oracle Command Timeout: Pagination in Oracle - @manhng

Pagination in Oracle - @manhng

Api Convert Currency Online

1 VND to USD - Vietnamese Dongs to US Dollars Exchange Rate (xe.com)

1 USD to VND - US Dollars to Vietnamese Dongs Exchange Rate (xe.com)

1 JPY to VND - Japanese Yen to Vietnamese Dongs Exchange Rate (xe.com)

1 VND to JPY - Vietnamese Dongs to Japanese Yen Exchange Rate (xe.com)

cURL - @manhng

curl -X GET "https://www.xe.com/currencyconverter/convert/?Amount=1&From=VND&To=USD"

Dapper

Working With Parameters When Using Dapper | Learn Dapper

Paging

Paging in ASP.NET Core Web API - Code Maze (code-maze.com)

Paging Oracle

SELECT A.*, CEIL(TOTAL_NUM_ROWS / 10) TOTAL_NUM_PAGES
FROM ( SELECT B.ID, B.FIRST_NAME, B.LAST_NAME, B.UPLOAD_DATE, row_number() OVER(ORDER BY UPLOAD_DATE DESC) rn, COUNT(*) OVER() TOTAL_NUM_ROWS
FROM PERSON B
) A
WHERE rn BETWEEN (1 - 1) * 10 + 1 AND 1 * 10


SELECT A.*, CEIL(TOTAL_NUM_ROWS / 10) TOTAL_NUM_PAGES
FROM ( SELECT B.ID, B.FIRST_NAME, B.LAST_NAME, B.UPLOAD_DATE, row_number() OVER(ORDER BY UPLOAD_DATE DESC) rn, COUNT(*) OVER() TOTAL_NUM_ROWS
FROM PERSON B
) A
WHERE rn BETWEEN (2 - 1) * 10 + 1 AND 2 * 10


SELECT A.*, CEIL(TOTAL_NUM_ROWS / :PAGESIZE) TOTAL_NUM_PAGES
FROM ( SELECT B.ID, B.FIRST_NAME, B.LAST_NAME, B.UPLOAD_DATE, row_number() OVER(ORDER BY UPLOAD_DATE DESC) rn, COUNT(*) OVER() TOTAL_NUM_ROWS
FROM PERSON B
) A
WHERE rn BETWEEN (:PAGEINDEX - 1) * :PAGESIZE + 1 AND :PAGEINDEX * :PAGESIZE

DbDataReader Oracle

Retrieving Data Using a DataReader - ADO.NET | Microsoft Docs

DbUp Oracle

Releases · DbUp/DbUp (github.com)

DbUp/DbUp: DbUp is a .NET library that helps you to deploy changes to SQL Server databases. It tracks which SQL scripts have been run already, and runs the change scripts that are needed to get your database up to date. (github.com)

Using Database Project and DbUp for database management - Kamil Grzybek

Simplifying database development with docker and DbUp | Blog (mcode.it) (HAY HAY HAY)

Snippet

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="dbup-core" version="4.5.0" targetFramework="net472" />
  <package id="dbup-oracle" version="4.5.0" targetFramework="net472" />
  <package id="Oracle.ManagedDataAccess" version="18.3.0" targetFramework="net472" />
</packages>

Snippet

using DbUp;
using DbUp.Oracle;
using System;
using System.Linq;
using System.Reflection;
 
namespace Oracle.DbUp
{
    class Program
    {
        [Obsolete]
        static void Main(string[] args)
        {
            var connectionString =
                args.FirstOrDefault()
                ?? "DATA SOURCE=localhost/ORCL;USER ID=sa;PASSWORD=123456;Min Pool Size=5;Decr Pool Size=10;PERSIST SECURITY INFO=True";
            var upgrader = DeployChanges.To
                .OracleDatabase(connectionString)
                .WithScriptsEmbeddedInAssembly(Assembly.GetExecutingAssembly())
                .LogToConsole()
                .Build();
            var result = upgrader.PerformUpgrade();
            if (!result.Successful)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine(result.Error);
                Console.ResetColor();
                Environment.Exit(-1);
            }
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine(value: "Success!");
            Console.ResetColor();
            Environment.Exit(0);
        }
    }
}

 

cURL

January 18, 2018 15:22

cURL (edit)

  • Thêm tham số [-k] để chạy với ứng dụng được host trên server là localhost
  • Chuyển dấu ['] sang dấu ["]
curl -k -X GET --header "Accept: application/json" "http://localhost:59166/api/DocumentApi/Search?searchDto.documentCode=1&searchDto.description=1"

curl -k -X GET --header "Accept: application/json" "http://localhost:59166/api/DocumentApi/Search?searchDto.documentCode=1&searchDto.description=1"

--------------------------------------------------------------------------------------------------------------

Tải về: https://curl.haxx.se/windows/

Giải nén và làm theo hướng dẫn: https://o7planning.org/vi/11617/cai-dat-curl-tren-windows

Cách dùng: Vào cmd -> chuyển đến thư mục bin -> curl www.google.com

// POST request to generate JWT
curl -k --request POST https://localhost:44349/Token/ --header "Content-Type: application/json" --data '{ "userId"0"firstName""Inventory""lastName""Admin""userName""InventoryAdmin""email""InventoryAdmin@abc.com""password""$admin@2017""createdDate""2020-08-22T00:00:00"}'

// GET request to fetch users
curl -k https://localhost:44349/api/Users/ --header "Content-Type: application/json" 

Postman save to cUrl

https://stackoverflow.com/questions/49432735/converting-a-postman-request-to-curl

--------------------------------------------------------------------------------------------------------------

https://curl.haxx.se/download.html

https://winampplugins.co.uk/curl/

cURL with Localhost (Update on 2021/07/20)

IBM Docs (https://www.ibm.com/docs/en/ibm-mq/9.1?topic=security-using-token-based-authentication-rest-api)

Use CURL to obtain an OAuth access token - IBM Documentation (https://www.ibm.com/docs/en/sva/10.0.1?topic=oauth-use-curl-obtain-access-token)

POST Login

curl -k https://localhost:44300/api/v1/users/login -X POST -H "Content-Type: application/json" --data "{\"username\":\"test\",\"password\":\"test\"}" -c c:\cookiejar.txt

POST OAuth2

curl -k -v -X POST -H 'Content-type: application/x-www-form-urlencoded' -d "client_id=testclient1&scope=read&grant_type=password&username=testuser1&password=passw0rd" https://localhost:44300/api/v1/oauth2/token

GET with Bearer Token

curl -k -v -­H "Authorization: Bearer C57M09" -H "Content­Type: application/json" -H "Accept: application/json" https://localhost:44300/api/v1/users

POST Create

curl -k https://localhost:44300/api/v1/users/create -X POST -b c:\cookiejar.txt -H "csrf-token: value" -H "Content-Type: application/json" --data "{\"name\":\"abc\"}"

DELETE queue

curl -k https://localhost:44300/api/v1/users/abc/queue -X DELETE -H "csrf-token: value" -b c:\cookiejar.txt -c c:\cookiejar.txt

Example with Github

curl https://api.github.com/users/caspyin

Includes HTTP-Header information in the output

curl --include https://api.github.com/users/caspyin

OAuth

curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com/gists/starred
curl -H "Authorization: token OAUTH-TOKEN" https://api.github.com/user
curl https://api.github.com/gists/starred?access_token=e72e16c7e42f292c6912e7710c838347ae178b4a
curl https://api.github.com/gists/starred?access_token=e72e16c7e42f292c6912e7710c838347ae178b4a&token_type=bearer

Example PHP Request

# using HTTP Basic Authentication
$ curl -u TestClient:TestSecret https://api.mysite.com/token -d 'grant_type=client_credentials'

# using POST Body
$ curl https://api.mysite.com/token -d 'grant_type=client_credentials&client_id=TestClient&client_secret=TestSecret'

A successful token request will return a standard access token in JSON format:
{"access_token":"03807cb390319329bdf6c777d4dfae9c0d3b3c35","expires_in":3600,"token_type":"bearer","scope":null}

Trying out OAuth2 via CURL

During development, it happens that you quickly want to try out a RESTful request. If you are running this request against an OAuth2 protected resource, you’ll need an access_token. So what is the easiest approach to get one? Unfortunately, OAuth2 is not supported just like Basic Authentication in the browser. The easiest option I’ve found is using CURL, the command-line utility for HTTP requests.

To get an access token for user demo and password 1234, I simply use the OAuth2 Resource Owner Password flow. Keep in mind, the token endpoint would need to be HTTPS in production, but for development this is fine:

The responsen will be the usual one:

Next, if you want to access a protected resource you have to pass the Authorization header. Let’s access our “current user” resource:

And the Response will be similar to this:

I hope you find this pretty straightforward, too!

REST API

REST API, JSON, Token and OAuth2

https://www.smashingmagazine.com/2018/01/understanding-using-rest-api/

https://www.smashingmagazine.com/2017/05/oauth2-logging-in-facebook/

REST API bao gồm các thành phần sau:

  • Điểm cuối (endpoint)
  • Phương pháp (method)
  • Tiêu đề (header)
  • Dữ liệu (data)

REST API bao gồm 5 method cơ bản sau:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

REST API trả về các trạng thái HTTP Status Code như sau

  • 200+ nghĩa là yêu cầu đã thành công .
  • 300+ nghĩa là yêu cầu được chuyển hướng đến một URL khác
  • 400+ có nghĩa là một lỗi bắt nguồn từ khách hàng đã xảy ra
  • 500+ nghĩa là lỗi xuất phát từ máy chủ đã xảy ra

Để gửi dữ liệu qua cURL

curl -X POST <URL> -d property1=value1

Để gửi nhiều trường dữ liệu:

curl -X POST <URL> -d property1=value1 -d property2=value2

Để gửi dữ liệu qua cURL

curl -X POST https://requestb.in/1ix963n1 \ -H "Content-Type: application/json" \ -d '{ "property1":"value1", "property2":"value2" }'

Để xác thực bằng tên đăng nhập và mật khẩu

curl -x POST -u "username:password" https://api.github.com/user/repos

Categories

Recent posts