Chủ Nhật, 6 tháng 11, 2016

Lập trình NodeJS

1. Cài đặt

Download NodeJS


Kiểm tra version nodejs trên máy: cmd + node version

Download Git SCM


2. Tạo project

- Tạo thư mục tên project
- Tạo *.js
- Chuột phải vào thư tên project, chọn Git Bash Here
- Gõ node *.js, nhấn Enter

3. Biến

var ten_bien = gia_tri;

4. Mảng

var mang = {0,1,2,3,4,5};
console.log(mang[0]); // 0

 

5. Hàm

function tinhtinh(a,b)
{
       return a+b;
}
var x = tinhtong(1,3);

/////////////////////////////////////////////////////
function hello()
{
conslole.log("Hello");
}
function goiHam(fn)
{
      fn();
}
goiHam(hello); // Hello

////////////////////////////////////////////////////

var tong = function()
{
      console.log("thuongthinh");
}
tong();

6. Modules

// hello.js
var name = "hello thuongthinh";
module.exports = name;

// module.js
var n = require(./hello.js);
console.log(n); // hello thuongthinh

7. Lập trình hướng đối tượng

// pesion.js

var persion = {
    ho  : "ta",
    ten : "thuong"
    xinchao : function()
    {
        console.log("hello" + this.ten);
    }
}
// Sử dụng

persion.xinchao(); // hello ta
console.log(persion["ten"]); // thuong

// khoahoc.js

function KhoaHoc(ten, hocphi) {
     this.Ten = ten;
     this.HocPhi = hocphi
}

KhoaHoc.prototype.mota = function()
{
     console.log("hello" + this.HocPhi);
}

// Sử dung
var nodejs = new KhoaHoc("NodeJS", 1000);
nodejs.mota();  // Nodejs 1000

8. Buffer

Truyền tải dữ liệu qua internet.

// Buffer.js
var buffer = new Buffer("hello","uft-8");
console.log (buffer);
console.log(buffer.toString()); // hello

9. File

var fs = require("fs");
var noidung = fs.readFileSync(__dirname + "/danhsach.txt");
console.log(nodung);

10. Cài đặt Express

Module hỗ trợ làm WebServer

// package.json
{
      "name"       : "ten_project",
      "version"    : "0.0.1",
      "private"    : "true",
      "dependencies"  : {
             "express"  :  "*"
       }
}

- Chuột phải vào thư mục Project, chọn Git Bash Here
- Gõ: npm install  (đọc file package.json để download express về project)

// App.js

var express  = require("express");
var app = express();
var server = require("http").createServer(app)
server.listen(3000); // Lắng nghe cổng 3000

// Trả về khi có requet từ client
app.get("/", function(res,res) {
    res.send("<font color=red>Hello</font>");
});


// Send file html

app.get("/", function(res,res) {
    res.sendFile(__dirname + ./index.html);
});

// Routing

app.get("/gioithieu.aspx", function(res,res) {
    res.sendFile(__dirname + ./index.html);
});

// Get parameters

app.get("/gioithieu.aspx/:so1/:so2", function(res,res) {
    
    var n = req.params.so1;
    res.send(n);
});

11. Socket IO

// package.json
{
      "name"       : "ten_project",
      "version"    : "0.0.1",
      "private"    : "true",
      "dependencies"  : {
             "express"  :  "*",
             "socket.io":  "*",
             "socketio-file-upload": "^.0.4.4"
       }
}

// Server.js
 
var express = require("express");
var app = express();
var server = require("http").createServer(app);
var io = require("socket.io").listen(server);
var fs = require("fs");
server.listen(process.env.PORT || 3000);

io.sockets.on('connection', function (socket) {
 
console.log("Co nguoi connect"); 
 
io.sockets.emit('serverguitinnhan', { noidung: "okbaby" });
  
socket.on('servernhantinnhan', function (data) { 
 
       // emit toi tat ca moi nguoi
       io.sockets.emit('serverguitinnhan', { noidung: data });
 
       // emit tới máy nguoi vừa gửi
       socket.emit('serverguitinnhan', { noidung: data });
  });
});

 

Chủ Nhật, 14 tháng 8, 2016

Tuple C#

Tuple là một khái niệm khá “lạ”, mình gặp khái niệm này lần đầu ở Python, giờ mới biết trong C# cũng có. Có thể hiểu đơn giản tuple là 1 “cục” tập hợp của nhiều fields, tương tự như class, nhưng define nhanh và dễ hơn. Ví dụ:
1
2
3
4
var love = new Tuple<int>(1);
var lie = new Tuple<int, string>(1, "Why");
var lay = new Tuple<int, int, string>(1, 2, "Gay");
Console.WriteLine(lay.Item1 + " " + lay.Item2 + " " + lay.Item3);// 1 2 Gay
Anonymous type có 1 khuyết điểm, đó là ko thể dùng anonymous type làm kiểu trả về, hoặc parameter truyền vào cho 1 function.
1
2
3
4
5
6
7
8
9
public ??? GetStu() //Làm sao trả về
 {
   List<Student> students = new List<Student>();
   var stu = students.Select(st => new {st.Name, st.Age });
   return stu;
 }
DoSomething(stu);
public void DoSomething(???); // Làm sao truyền vào
Với tuple, vấn đề đó được giải quyết nhanh chóng:
1
2
3
4
5
6
7
8
9
public List<Tuple<string, int>> GetStu()
 {
   List<Student> students = new List<Student>();
   var stu = students.Select(st => new Tuple<string, int>(st.Name, st.Age)).ToList();
   return stu;
 }
public void DoSomething( List<Tuple<string, int>> input);
DoSomething(stu);
Có thể các bạn sẽ hỏi: Tại sao ko tạo 1 class mới, dùng anonymous type với tuple làm gì cho mệt? Xin trả lời:
  • Có 1 số trường hợp ta cần extract 1 số field, nếu mỗi lần lấy vài fields ta đều tạo class mới thì code sẽ khá dư và vô nghĩa.
  • Nếu tạo class mới, ta phải override lại hàm Equals và GetHashCode nếu cần so sánh. Anonymous type và tuples đã tự động implement hàm này cho chúng ta.
Ví dụ: 

1
2
3
4
5
6
7
8
9
public List<Tuple<int,int>> getSoLuongTonKho()
{
     var query = from p in context.tbThuocs
                 where p.TrangThaiThuoc == 1
                 select p;
     var result = query.Select(t => new { t.IdThuoc, t.SoLuongTonKho }).AsEnumerable().Select(t => new Tuple<int, int>(t.IdThuoc, t.SoLuongTonKho)).ToList();
     return result;

}