Skip to content

Commit

Permalink
Session
Browse files Browse the repository at this point in the history
  • Loading branch information
XuanThuLab committed Aug 29, 2020
1 parent a4a4257 commit a2a03e4
Show file tree
Hide file tree
Showing 24 changed files with 8,522 additions and 0 deletions.
36 changes: 36 additions & 0 deletions ASP_NET_CORE/05.Session/.vscode/launch.json
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}"
}
]
}
42 changes: 42 additions & 0 deletions ASP_NET_CORE/05.Session/.vscode/tasks.json
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"
}
]
}
14 changes: 14 additions & 0 deletions ASP_NET_CORE/05.Session/05.Session.csproj
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>05.Session</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>
106 changes: 106 additions & 0 deletions ASP_NET_CORE/05.Session/Controller/ProductController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
using System;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

namespace _05.Session {
public class ProductController {
IListProductName lsPhone;
IListProductName lsLaptop;

// Inject hai dịch vụ qua phương thức khởi tạo
public ProductController (IListProductName lsphone, LaptopName lslaptop) {
Console.WriteLine (this.GetType ().Name + " created");
this.lsPhone = lsphone;
this.lsLaptop = lslaptop;
}

// 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 (lsPhoneHTML);

sb.Append ("Danh sách Laptop".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;
}

}
}
142 changes: 142 additions & 0 deletions ASP_NET_CORE/05.Session/HtmlHelper.cs
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);
}


}
26 changes: 26 additions & 0 deletions ASP_NET_CORE/05.Session/Program.cs
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 _05.Session
{
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>();
});
}
}
Loading

0 comments on commit a2a03e4

Please sign in to comment.