-
Notifications
You must be signed in to change notification settings - Fork 85
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
XuanThuLab
committed
Aug 29, 2020
1 parent
a4a4257
commit 4a7039f
Showing
25 changed files
with
8,578 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
{ | ||
// Use IntelliSense to find out which attributes exist for C# debugging | ||
// Use hover for the description of the existing attributes | ||
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md | ||
"version": "0.2.0", | ||
"configurations": [ | ||
{ | ||
"name": ".NET Core Launch (web)", | ||
"type": "coreclr", | ||
"request": "launch", | ||
"preLaunchTask": "build", | ||
// If you have changed target frameworks, make sure to update the program path. | ||
"program": "${workspaceFolder}/bin/Debug/netcoreapp3.1/05.Session.dll", | ||
"args": [], | ||
"cwd": "${workspaceFolder}", | ||
"stopAtEntry": false, | ||
// Enable launching a web browser when ASP.NET Core starts. For more information: https://aka.ms/VSCode-CS-LaunchJson-WebBrowser | ||
"serverReadyAction": { | ||
"action": "openExternally", | ||
"pattern": "\\bNow listening on:\\s+(https?://\\S+)" | ||
}, | ||
"env": { | ||
"ASPNETCORE_ENVIRONMENT": "Development" | ||
}, | ||
"sourceFileMap": { | ||
"/Views": "${workspaceFolder}/Views" | ||
} | ||
}, | ||
{ | ||
"name": ".NET Core Attach", | ||
"type": "coreclr", | ||
"request": "attach", | ||
"processId": "${command:pickProcess}" | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
{ | ||
"version": "2.0.0", | ||
"tasks": [ | ||
{ | ||
"label": "build", | ||
"command": "dotnet", | ||
"type": "process", | ||
"args": [ | ||
"build", | ||
"${workspaceFolder}/05.Session.csproj", | ||
"/property:GenerateFullPaths=true", | ||
"/consoleloggerparameters:NoSummary" | ||
], | ||
"problemMatcher": "$msCompile" | ||
}, | ||
{ | ||
"label": "publish", | ||
"command": "dotnet", | ||
"type": "process", | ||
"args": [ | ||
"publish", | ||
"${workspaceFolder}/05.Session.csproj", | ||
"/property:GenerateFullPaths=true", | ||
"/consoleloggerparameters:NoSummary" | ||
], | ||
"problemMatcher": "$msCompile" | ||
}, | ||
{ | ||
"label": "watch", | ||
"command": "dotnet", | ||
"type": "process", | ||
"args": [ | ||
"watch", | ||
"run", | ||
"${workspaceFolder}/05.Session.csproj", | ||
"/property:GenerateFullPaths=true", | ||
"/consoleloggerparameters:NoSummary" | ||
], | ||
"problemMatcher": "$msCompile" | ||
} | ||
] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
<Project Sdk="Microsoft.NET.Sdk.Web"> | ||
|
||
<PropertyGroup> | ||
<TargetFramework>netcoreapp3.1</TargetFramework> | ||
<RootNamespace>06.Config</RootNamespace> | ||
</PropertyGroup> | ||
|
||
<ItemGroup> | ||
<PackageReference Include="Microsoft.AspNetCore.Session" Version="2.2.0" /> | ||
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="3.1.7" /> | ||
<PackageReference Include="Newtonsoft.Json" Version="12.0.3" /> | ||
</ItemGroup> | ||
|
||
</Project> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
using System; | ||
using System.Linq; | ||
using System.Text; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Http; | ||
using Microsoft.Extensions.Options; | ||
using Newtonsoft.Json; | ||
|
||
namespace _06.Config { | ||
public class ProductController { | ||
IListProductName lsPhone; | ||
IListProductName lsLaptop; | ||
|
||
TestOptions options; | ||
|
||
|
||
// Inject hai dịch vụ qua phương thức khởi tạo | ||
//Khởi tạo có Inject Option từ DI Container (chú ý tham số IOptions<TestOptions>) | ||
|
||
public ProductController (IListProductName lsphone, LaptopName lslaptop, IOptions<TestOptions> options) { | ||
Console.WriteLine (this.GetType ().Name + " created"); | ||
this.lsPhone = lsphone; | ||
this.lsLaptop = lslaptop; | ||
this.options = options.Value; | ||
|
||
} | ||
|
||
// Xuất danh sách sản phẩm cho Response | ||
public async Task List (HttpContext context) { | ||
|
||
CountAccess (context); | ||
|
||
var sb = new StringBuilder (); | ||
string lsPhoneHTML = string.Join ("", lsPhone.GetNames ().Select (name => name.HtmlTag ("li"))).HtmlTag ("ul"); | ||
string lsLaptopHTML = string.Join ("", lsLaptop.GetNames ().Select (name => name.HtmlTag ("li"))).HtmlTag ("ul"); | ||
// sb.Append ("Danh sách điện thoại".HtmlTag ("h2")); | ||
sb.Append($"{options.opt_key1}".HtmlTag("h2")); | ||
sb.Append (lsPhoneHTML); | ||
|
||
// sb.Append ("Danh sách Laptop".HtmlTag ("h2")); | ||
sb.Append($"{options.opt_key2.k1}".HtmlTag("h2")); | ||
|
||
sb.Append (lsLaptopHTML); | ||
|
||
string menu = HtmlHelper.MenuTop (HtmlHelper.DefaultMenuTopItems (), context.Request); | ||
string html = HtmlHelper.HtmlDocument ("DS Sản phẩm", menu + sb.ToString ().HtmlTag ("div", "container")); | ||
|
||
context.Response.StatusCode = 200; | ||
await context.Response.WriteAsync (html); | ||
} | ||
|
||
public void CountAccess (HttpContext context) { | ||
// Lấy ISession | ||
var session = context.Session; | ||
string key_access = "info_access"; | ||
|
||
// Lưu vào Session thông tin truy cập | ||
// Định nghĩa cấu trúc dữ liệu lưu trong Session | ||
var accessInfoType = new { | ||
count = 0, | ||
lasttime = DateTime.Now | ||
}; | ||
|
||
// Đọc chuỗi lưu trong Sessin với key = info_access | ||
string json = session.GetString (key_access); | ||
dynamic lastAccessInfo; | ||
if (json != null) { | ||
// Convert chuỗi Json - thành đối tượng có cấu trúc như accessInfoType | ||
lastAccessInfo = JsonConvert.DeserializeObject (json, accessInfoType.GetType ()); | ||
} else { | ||
// json chưa từng lưu trong Session, accessInfo lấy bằng giá trị khởi tạo | ||
lastAccessInfo = accessInfoType; | ||
} | ||
|
||
// Cập nhật thông tin | ||
var accessInfoSave = new { | ||
count = lastAccessInfo.count + 1, | ||
lasttime = DateTime.Now | ||
}; | ||
|
||
// Convert accessInfo thành chuỗi Json và lưu lại vào Session | ||
string jsonSave = JsonConvert.SerializeObject (accessInfoSave); | ||
session.SetString (key_access, jsonSave); | ||
Console.WriteLine (jsonSave); | ||
} | ||
public static string CountAccessInfo (HttpContext context) { | ||
var session = context.Session; // Lấy ISession | ||
string key_access = "info_access"; | ||
|
||
// Lưu vào Session thông tin truy cập | ||
// Định nghĩa cấu trúc dữ liệu lưu trong Session | ||
var accessInfoType = new { | ||
count = 0, | ||
lasttime = DateTime.Now | ||
}; | ||
|
||
// Đọc chuỗi lưu trong Sessin với key = info_access | ||
string json = session.GetString (key_access); | ||
dynamic lastAccessInfo; | ||
if (json != null) { | ||
// Convert chuỗi Json - thành đối tượng | ||
lastAccessInfo = JsonConvert.DeserializeObject (json, accessInfoType.GetType ()); | ||
} else { | ||
// json chưa từng lưu trong Session, accessInfo lấy bằng giá trị khởi tạo | ||
lastAccessInfo = accessInfoType; | ||
} | ||
if (lastAccessInfo.count == 0) { | ||
return "Chưa truy cập /Product lần nào".HtmlTag ("p"); | ||
} | ||
|
||
string thongtin = $"Số lần truy cập /Product: {lastAccessInfo.count} - lần cuối: {lastAccessInfo.lasttime.ToLongTimeString()}"; | ||
return thongtin; | ||
} | ||
|
||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
using System.Collections.Generic; | ||
using Microsoft.AspNetCore.Http; | ||
using System.Text; | ||
|
||
public static class HtmlHelper | ||
{ | ||
/// <summary> | ||
/// Phát sinh trang HTML | ||
/// </summary> | ||
/// <param name="title">Tiêu đề trang</param> | ||
/// <param name="content">Nội dung trong thẻ body</param> | ||
/// <returns>Trang HTML</returns> | ||
public static string HtmlDocument(string title, string content) { | ||
return $@" | ||
<!DOCTYPE html> | ||
<html> | ||
<head> | ||
<meta charset=""UTF-8""> | ||
<title>{title}</title> | ||
<link rel=""stylesheet"" href=""/css/site.min.css"" /> | ||
<script src=""/js/jquery.min.js""> | ||
</script><script src=""/js/popper.min.js""> | ||
</script><script src=""/js/bootstrap.min.js""></script> | ||
</head> | ||
<body> | ||
{content} | ||
</body> | ||
</html>"; | ||
} | ||
|
||
|
||
/// <summary> | ||
/// Phát sinh HTML thanh menu trên, menu nào active phụ thuộc vào URL mà request gủi đến | ||
/// </summary> | ||
/// <param name="menus">Mảng các menu item, mỗi item có cấu trúc {url, lable}</param> | ||
/// <param name="request">HttpRequest</param> | ||
/// <returns></returns> | ||
|
||
public static string MenuTop(object[] menus, HttpRequest request) { | ||
|
||
var menubuilder = new StringBuilder(); | ||
menubuilder.Append("<ul class=\"navbar-nav\">"); | ||
foreach (dynamic menu in menus) { | ||
string _class = "nav-item"; | ||
// Active khi request.PathBase giống url của menu | ||
if (request.PathBase == menu.url) _class += " active"; | ||
menubuilder.Append($@" | ||
<li class=""{_class}""> | ||
<a class=""nav-link"" href=""{menu.url}"">{menu.label}</a> | ||
</li> | ||
"); | ||
} | ||
menubuilder.Append("</ul>\n"); | ||
|
||
string menuhtml = $@" | ||
<div class=""container""> | ||
<nav class=""navbar navbar-expand-lg navbar-dark mainbackground""> | ||
<a class=""navbar-brand"" href=""/"">XTLAB</a> | ||
<button class=""navbar-toggler"" type=""button"" | ||
data-toggle=""collapse"" data-target=""#my-nav-bar"" | ||
aria-controls=""my-nav-bar"" aria-expanded=""false"" aria-label=""Toggle navigation""> | ||
<span class=""navbar-toggler-icon""></span> | ||
</button> | ||
<div class=""collapse navbar-collapse"" id=""my-nav-bar""> | ||
{menubuilder} | ||
</div> | ||
</nav></div>"; | ||
|
||
return menuhtml; | ||
} | ||
|
||
/// <summary> | ||
/// Những menu item mặc định cho trang | ||
/// </summary> | ||
/// <returns>Mảng các menuitem</returns> | ||
public static object[] DefaultMenuTopItems() { | ||
return new object[] { | ||
new { | ||
url = "/RequestInfo", | ||
label = "Request" | ||
}, | ||
new { | ||
url = "/Product", | ||
label = "Product" | ||
} | ||
, | ||
new { | ||
url = "/Encoding", | ||
label = "Encoding" | ||
}, | ||
new { | ||
url = "/Cookies", | ||
label = "Cookies" | ||
}, | ||
new { | ||
url = "/Json", | ||
label = "JSON" | ||
} | ||
}; | ||
} | ||
|
||
public static string HtmlTrangchu() { | ||
return $@" | ||
<div class=""container""> | ||
<div class=""jumbotron""> | ||
<h1 class=""display-4"">Đây là một trang Web .NET Core</h1> | ||
<p class=""lead"">Trang Web này xây dựng trên nền tảng <code>.NET Core</code>, | ||
chưa sử dụng kỹ thuật MVC - nhằm mục đích học tập. | ||
Mã nguồn trang này tại <a target=""_blank"" | ||
href=""https://github.com/xuanthulabnet/learn-cs-netcore/blob/master/ASP_NET_CORE/03.RequestResponse/""> | ||
Mã nguồn Ví dụ</a> | ||
</p> | ||
<hr class=""my-4""> | ||
<p><code>.NET Core</code> là một hệ thống chạy đa nền tảng (Windows, Linux, macOS)</p> | ||
<a class=""btn btn-danger btn-lg"" href=""https://xuanthulab.net/lap-trinh-c-co-ban/"" role=""button"">Xem thêm</a> | ||
</div> | ||
</div> | ||
"; | ||
|
||
} | ||
|
||
// Mở rộng String, phát sinh thẻ HTML với nội dụng là String | ||
// Ví dụ: | ||
// "content".HtmlTag() => <p>content</p> | ||
// "content".HtmlTag("div", "text-danger") => <div class="text-danger">content</div> | ||
public static string HtmlTag(this string content, string tag = "p", string _class = null) { | ||
string cls = (_class != null) ? $" class=\"{_class}\"":null; | ||
return $"<{tag + cls}>{content}</{tag}>"; | ||
} | ||
public static string td(this string content, string _class = null) { | ||
return content.HtmlTag("td", _class); | ||
} | ||
public static string tr(this string content, string _class = null) { | ||
return content.HtmlTag("tr", _class); | ||
} | ||
public static string table(this string content, string _class = null) { | ||
return content.HtmlTag("table", _class); | ||
} | ||
|
||
|
||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,10 @@ | ||
public class TestOptions | ||
{ | ||
public string opt_key1 {set; get;} | ||
public SubTestOption opt_key2 {set; get;} | ||
|
||
} | ||
public class SubTestOption { | ||
public string k1 {set; get;} | ||
public string k2 {set; get;} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Threading.Tasks; | ||
using Microsoft.AspNetCore.Hosting; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.Hosting; | ||
using Microsoft.Extensions.Logging; | ||
|
||
namespace _06.Config | ||
{ | ||
public class Program | ||
{ | ||
public static void Main(string[] args) | ||
{ | ||
CreateHostBuilder(args).Build().Run(); | ||
} | ||
|
||
public static IHostBuilder CreateHostBuilder(string[] args) => | ||
Host.CreateDefaultBuilder(args) | ||
.ConfigureWebHostDefaults(webBuilder => | ||
{ | ||
webBuilder.UseStartup<Startup>(); | ||
}); | ||
} | ||
} |
Oops, something went wrong.