Skip to content

Commit

Permalink
Attribute
Browse files Browse the repository at this point in the history
  • Loading branch information
XuanThuLab committed Aug 20, 2020
1 parent a4a4257 commit ac9c91a
Show file tree
Hide file tree
Showing 8 changed files with 222 additions and 0 deletions.
27 changes: 27 additions & 0 deletions CS026_Attribute/.vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
{
// 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 (console)",
"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/CS026_Attribute.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}
42 changes: 42 additions & 0 deletions CS026_Attribute/.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}/CS026_Attribute.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "publish",
"command": "dotnet",
"type": "process",
"args": [
"publish",
"${workspaceFolder}/CS026_Attribute.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
},
{
"label": "watch",
"command": "dotnet",
"type": "process",
"args": [
"watch",
"run",
"${workspaceFolder}/CS026_Attribute.csproj",
"/property:GenerateFullPaths=true",
"/consoleloggerparameters:NoSummary"
],
"problemMatcher": "$msCompile"
}
]
}
8 changes: 8 additions & 0 deletions CS026_Attribute/CS026_Attribute.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

</Project>
28 changes: 28 additions & 0 deletions CS026_Attribute/Employer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
using System;
using System.ComponentModel.DataAnnotations;

namespace CS026_Attribute {

public class Employer {
[Required (ErrorMessage = "Employee {0} is required")]
[StringLength (100, MinimumLength = 3, ErrorMessage = "Tên từ 3 đến 100 ký tự")]
[DataType (DataType.Text)]
public string Name { get; set; }

[Range (18, 99, ErrorMessage = "Age should be between 18 and 99")]
public int Age { get; set; }


[DataType (DataType.PhoneNumber)]
[Phone]
public string PhoneNumber { set; get; }

[DataType (DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }

}



}
13 changes: 13 additions & 0 deletions CS026_Attribute/MotaAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
using System;

namespace CS026_Attribute {

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Method)]
public class MotaAttribute : Attribute // có thể đặt tên Mota thay cho MotaAttribute
{
public MotaAttribute(string v) => Description = v;

public string Description {set; get;}
}

}
48 changes: 48 additions & 0 deletions CS026_Attribute/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace CS026_Attribute {
class Program {
public class MyClass {

[Obsolete ("Phương thức này lỗi thời, hãy dùng phương thức Abc")]
public static void Method1 () {
Console.WriteLine ("Phương thức chạy");
}
}
public static void checkValidationContext()
{
Employer user = new Employer();
user.Name = "AF";
user.Age = 6;
user.PhoneNumber = "1234as";
user.Email = "test@re";


ValidationContext context = new ValidationContext(user, null, null);
// results - lưu danh sách ValidationResult, kết quả kiểm tra
List<ValidationResult> results = new List<ValidationResult>();
// thực hiện kiểm tra dữ liệu
bool valid = Validator.TryValidateObject(user, context, results, true);

if (!valid)
{
// Duyệt qua các lỗi và in ra
foreach (ValidationResult vr in results)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.Write($"{vr.MemberNames.First(), 13}");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($" {vr.ErrorMessage}");
}
}
}
static void Main (string[] args) {
// MyClass.Method1();
// TestReadAttribute.test();
checkValidationContext();
}
}
}
41 changes: 41 additions & 0 deletions CS026_Attribute/TestReadAttribute.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using System;

namespace CS026_Attribute {
class TestReadAttribute {
public static void test () {
var a = new User ();

// Đọc các Attribute của lớp
foreach (Attribute attr in a.GetType ().GetCustomAttributes (false)) {
MotaAttribute mota = attr as MotaAttribute;
if (mota != null) {
Console.WriteLine ($"{a.GetType().Name,10} : {mota.Description}");
}
}

// Đọc Attribute của từng thuộc tính lớp
foreach (var thuoctinh in a.GetType ().GetProperties ()) {
foreach (Attribute attr in thuoctinh.GetCustomAttributes (false)) {
MotaAttribute mota = attr as MotaAttribute;
if (mota != null) {
Console.WriteLine ($"{thuoctinh.Name,10} : {mota.Description}");
}
}
}

// Đọc Attribute của phương thức
foreach (var m in a.GetType ().GetMethods ()) {
foreach (Attribute attr in m.GetCustomAttributes (false)) {
MotaAttribute mota = attr as MotaAttribute;
if (mota != null) {
Console.WriteLine ($"{m.Name,10} : {mota.Description}");
}
}
}



}

}
}
15 changes: 15 additions & 0 deletions CS026_Attribute/User.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
using System;

namespace CS026_Attribute {

[Mota("Lớp biểu diễn người dùng")] // thêm Attribute cho lớp
public class User
{
[Mota("Thuộc tính lưu tuổi")] // thêm Attribute cho thuộc tính lớp
public int age {set; get;}

[Mota("Phương thức này hiện thị age")] // thêm Attribute cho phương thức
public void ShowAge() {}
}

}

0 comments on commit ac9c91a

Please sign in to comment.