.NET Core ต่อ Database (Console#2)

สร้างโปรเจ็กส์ Console

> dotnet new console -o ConsoleApp

เพิ่มไฟล์ .gitignore (optional)

*.swp
*.*~
project.lock.json
.DS_Store
*.pyc
nupkg/

# Visual Studio Code
.vscode

# Rider
.idea

# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates

# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
x86/
build/
bld/
[Bb]in/
[Oo]bj/
[Oo]ut/
msbuild.log
msbuild.err
msbuild.wrn

# Visual Studio 2015
.vs/

รันโปรเจ็กส์ด้วยคำสั่ง dotnet run

> cd ConsoleApp
> dotnet run

ติดตั้ง System.Data.SqlClient

> dotnet add package System.Data.SqlClient --version 4.8.2

ติดตั้ง Microsoft.Extensions.Configuration

> dotnet add package Microsoft.Extensions.Configuration --version 5.0.0

ติดตั้ง Microsoft.Extensions.Configuration.Json

> dotnet add package Microsoft.Extensions.Configuration.Json --version 5.0.0

ติดตั้ง Microsoft.Extensions.Configuration.Binder

> dotnet add package Microsoft.Extensions.Configuration.Binder --version 5.0.0

สร้างไฟล์ appsettings.json

{
    "DbConfig": {
        "ServerName": "localhost",
        "DatabaseName": "myDatabase",
        "UserName": "myUsername",
        "Password": "myPassword"
    }
}

เพิ่มไฟล์ Model.Student.cs

using System;

namespace ConsoleApp.Model
{
    public class Student
    {
        public int id { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string email { get; set; }
        public string mobile { get; set; }
    }
}

เพิ่มไฟล์ Data.StudentDAL.cs

using ConsoleApp.Model;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;

namespace ConsoleApp.Data
{
    public class StudentDAL
    {
        private string _connectionString;

        public StudentDAL(IConfiguration config)
        {
            string _server = config.GetValue<string>("DbConfig:ServerName");
            string _database = config.GetValue<string>("DbConfig:DatabaseName");
            string _username = config.GetValue<string>("DbConfig:UserName");
            string _password = config.GetValue<string>("DbConfig:Password");
            _connectionString = ($"Server={_server};Database={_database};User ID={_username};Password={_password};Trusted_Connection=False;MultipleActiveResultSets=true;");
        }
        public List<Student> GetList()
        {
            List<Student> students = new List<Student>();
            try
            {
                using (SqlConnection con = new SqlConnection(_connectionString))
                {
                    DataTable dt = new DataTable();
                    string sql = @"
SELECT * 
FROM Student
ORDER BY id";

                    SqlDataAdapter da = new SqlDataAdapter(sql, con);
                    da.Fill(dt);

                    foreach (DataRow row in dt.Rows)
                    {
                        Student std = new Student();
                        std.id = Convert.ToInt32(row["id"]);
                        std.firstname = row["Firstname"] as string;
                        std.lastname = row["Lastname"] as string;
                        std.email = row["Email"] as string;
                        std.mobile = row["mobile"] as string;
                        students.Add(std);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return students;
        }
    }
}

แก้ไขไฟล์ Program.cs

using ConsoleApp.Data;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Text.Json;

namespace ConsoleApp
{
    class Program
    {
        private static IConfiguration _iconfiguration;
        static void Main(string[] args)
        {
            GetAppSettingsFile();

            var studentDAL = new StudentDAL(_iconfiguration);
            var students = studentDAL.GetList();
            students.ForEach(item =>
            {
                string jsonString = JsonSerializer.Serialize(item);
                Console.WriteLine(jsonString);
            });
        }

        static void GetAppSettingsFile()
        {
            var builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
            _iconfiguration = builder.Build();
        }
    }
}

.NET Core ต่อ Database (Blazor)

สร้างโปรเจ็กส์ Blazor

> dotnet new blazorserver -o BlazorApp --no-https

รันโปรเจ็กส์ด้วยคำสั่ง dotnet run

> cd BlazorApp
> dotnet run

หรือ แก้ไขหน้า Page ดูผลการแก้ไขได้เลย

> dotnet watch run

ติดตั้ง System.Data.SqlClient

> dotnet add package System.Data.SqlClient --version 4.8.2

เพิ่ม Config ที่ไฟล์ appsettings.json

{
    "Logging": {
        "LogLevel": {
            "Default": "Information",
            "Microsoft": "Warning",
            "Microsoft.Hosting.Lifetime": "Information"
        }
    },
    "DbConfig": {
        "ServerName": "localhost",
        "DatabaseName": "myDatabase",
        "UserName": "myUsername",
        "Password": "myPassword"
    },
    "AllowedHosts": "*"
}

เพิ่มไฟล์ Data.Student.cs

using System;

namespace BlazorApp.Data
{
    public class Student
    {
        public int id { get; set; }
        public string firstname { get; set; }
        public string lastname { get; set; }
        public string email { get; set; }
        public string mobile { get; set; }
    }
}

เพิ่มไฟล์ Data.StudentService.cs

using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;

namespace BlazorApp.Data
{
    public class StudentService
    {
        private IConfiguration config;
        public StudentService(IConfiguration configuration)
        {
            config = configuration;
        }

        private string ConnectionString
        {
            get
            {
                string _server = config.GetValue<string>("DbConfig:ServerName");
                string _database = config.GetValue<string>("DbConfig:DatabaseName");
                string _username = config.GetValue<string>("DbConfig:UserName");
                string _password = config.GetValue<string>("DbConfig:Password");
                return ($"Server={_server};Database={_database};User ID={_username};Password={_password};Trusted_Connection=False;MultipleActiveResultSets=true;");
            }
        }

        public async Task<List<Student>> GetStudent()
        {
            List<Student> students = new List<Student>();
            DataTable dt = new DataTable();
            SqlConnection con = new SqlConnection(ConnectionString);
            string sql = @"
SELECT * 
FROM Student
ORDER BY id";
            SqlDataAdapter da = new SqlDataAdapter(sql, con);
            da.Fill(dt);
            foreach (DataRow row in dt.Rows)
            {
                Student std = new Student();
                std.id = Convert.ToInt32(row["id"]);
                std.firstname = row["Firstname"] as string;
                std.lastname = row["Lastname"] as string;
                std.email = row["Email"] as string;
                std.mobile = row["mobile"] as string;
                students.Add(std);
            }

            return await Task.FromResult(students);
        }
    } // end class
}

สร้าง Razor Page ชื่อ Pages/StudentList.razor

@page "/student-list"
@using BlazorApp.Data
@inject StudentService stdService

<h1>Student</h1>

@if (students == null)
{
    <div>There is no student</div>
}
else
{
    foreach (Student std in students)
    {
        <div style="padding:15px;border-bottom:solid 1px #0094ff;">
            @std.id | @std.firstname | @std.lastname | @std.email | @std.mobile
        </div>
    }
}

@code {
    private List<Student> students;
    protected override async Task OnInitializedAsync()
    {
        students = await stdService.GetStudent();
    }
}

Register service ใน Startup.cs

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddRazorPages();
            services.AddServerSideBlazor();
            services.AddSingleton<WeatherForecastService>();
            services.AddSingleton<StudentService>();
        }

รันและเรียกไปที่ http://localhost:5000/student-list

หรือแปะไว้หน้า index โดยแก้ไขไฟล์ Pages/index.razor

@page "/"

<h1>Hello, world!</h1>

Welcome to your new app.

<SurveyPrompt Title="How is Blazor working for you?" />

<StudentList />

Python3

Set Python’s default version to 3.x on OS X

Open ~/.bash_profile file.

$ nano ~/.bash_profile

Then put the alias as follows:

alias python='python3'

Now save the file and then run the ~/.bash_profile file.

$ source ~/.bash_profile

Congratulation !!! Now, you can use python3 by typing python.

$ python --version
Python 3.8.1

Upgrade pip command

$ pip3 install --upgrade pip

Install virtualenv

$ pip3 install virtualenv

ใช้ brew ติดตั้ง python

$ brew install python

Android/Java การสร้าง RecyclerView

ใช้ RecyclerView แสดงรายการแบบ list ทำให้สามารถแสดงรายการจำนวนมากๆได้

  1. ใช้งาน RecyclerView
  2. ปรับแต่งเส้นคั่นด้วยไลบรารี่ RecyclerView-FlexibleDivider
  3. วาดตัวอักษรด้วยไลบรารี่ TextDrawable

ไฟล์ที่เกี่ยวข้อง

  • build.gradle (Module: app)
  • activity_main.xml
  • MainActivity.java
  • values/colors.xml
  • drawable/item_state.xml
  • layout/custom_layout.xml
  • CustomItem.java
  • CustomHolder.java
  • CustomAdapter.java
Continue reading