0% found this document useful (0 votes)
48 views9 pages

Code Thuyết Trình

Uploaded by

thanh.trinh06k4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views9 pages

Code Thuyết Trình

Uploaded by

thanh.trinh06k4
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

Bài 44

using System;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;

namespace NetworkUtilities
{
class Program
{
static void Main(string[] args)
{

string url = "https://xuanthulab.net/lap-trinh/csharp/?page=3#acff";


var uri = new Uri(url);
var uritype = typeof(Uri);

Console.WriteLine("Thông tin các thuộc tính của Uri:");


uritype.GetProperties().ToList().ForEach(property =>
{
Console.WriteLine($"{property.Name, 15} {property.GetValue(uri)}");
});
Console.WriteLine($"Segments: {string.Join(",", uri.Segments)}");

Console.WriteLine("\nThông tin về host từ Dns:");


string dnsUrl = "https://www.bootstrapcdn.com/";
var dnsUri = new Uri(dnsUrl);
var hostEntry = Dns.GetHostEntry(dnsUri.Host);
Console.WriteLine($"Host {dnsUri.Host} có các IP:");
hostEntry.AddressList.ToList().ForEach(ip => Console.WriteLine(ip));

Console.WriteLine("\nKiểm tra kết nối với máy từ xa qua Ping:");


var ping = new Ping();
var pingReply = ping.Send("google.com.vn");
Console.WriteLine($"Trạng thái Ping: {pingReply.Status}");
if (pingReply.Status == IPStatus.Success)
{
Console.WriteLine($"Thời gian phản hồi: {pingReply.RoundtripTime} ms");
Console.WriteLine($"Địa chỉ IP: {pingReply.Address}");
}
}
}
}

Bài 45
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

public class HttpClientExample


{

public static void ShowHeaders(HttpHeaders headers)


{
Console.WriteLine("CÁC HEADER:");
foreach (var header in headers)
{
foreach (var value in header.Value)
{
Console.WriteLine($"{header.Key,25} : {value}");
}
}
Console.WriteLine();
}

public static async Task<string> GetWebContentAsync(string url)


{
using var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml+json");

try
{
HttpResponseMessage response = await httpClient.GetAsync(url);
ShowHeaders(response.Headers);
response.EnsureSuccessStatusCode();

string content = await response.Content.ReadAsStringAsync();


return content;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}

public static async Task<string> PostFormUrlEncodedAsync(string url)


{
using var httpClient = new HttpClient();

var parameters = new List<KeyValuePair<string, string>>


{
new KeyValuePair<string, string>("key1", "value1"),
new KeyValuePair<string, string>("key2", "value2")
};

var content = new FormUrlEncodedContent(parameters);


HttpResponseMessage response = await httpClient.PostAsync(url, content);

return await response.Content.ReadAsStringAsync();


}

public static async Task<string> PostJsonAsync(string url)


{
using var httpClient = new HttpClient();

string json = "{\"key1\": \"value1\", \"key2\": \"value2\"}";


var content = new StringContent(json, Encoding.UTF8, "application/json");
HttpResponseMessage response = await httpClient.PostAsync(url, content);

return await response.Content.ReadAsStringAsync();


}

public static async Task<string> PostMultipartAsync(string url, string filePath)


{
using var httpClient = new HttpClient();

var content = new MultipartFormDataContent();


using var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
content.Add(new StreamContent(fileStream), "fileupload", Path.GetFileName(filePath));
content.Add(new StringContent("value1"), "key1");

HttpResponseMessage response = await httpClient.PostAsync(url, content);

return await response.Content.ReadAsStringAsync();


}

public static async Task Main(string[] args)


{
string url = "https://postman-echo.com/post";
string content = await GetWebContentAsync("https://www.example.com");
Console.WriteLine(content);

string formResponse = await PostFormUrlEncodedAsync(url);


Console.WriteLine("Form Response: " + formResponse);

string jsonResponse = await PostJsonAsync(url);


Console.WriteLine("JSON Response: " + jsonResponse);

string multipartResponse = await PostMultipartAsync(url, "path/to/your/file.txt");


Console.WriteLine("Multipart Response: " + multipartResponse);
}
}

Bài 46
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

public class MyHttpClientHandler : HttpClientHandler


{
public MyHttpClientHandler(CookieContainer cookieContainer)
{
CookieContainer = cookieContainer;
AllowAutoRedirect = false;
AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
UseCookies = true;
}

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,


CancellationToken cancellationToken)
{
Console.WriteLine("Bắt đầu kết nối " + request.RequestUri);
var response = await base.SendAsync(request, cancellationToken);
Console.WriteLine("Hoàn thành tải dữ liệu");
return response;
}
}

public class ChangeUri : DelegatingHandler


{
public ChangeUri(HttpMessageHandler innerHandler) : base(innerHandler) { }

protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,


CancellationToken cancellationToken)
{
var host = request.RequestUri.Host.ToLower();
Console.WriteLine($"Check in ChangeUri - {host}");
if (host.Contains("google.com"))
{
request.RequestUri = new Uri("https://github.com/");
}
return base.SendAsync(request, cancellationToken);
}
}

public class DenyAccessFacebook : DelegatingHandler


{
public DenyAccessFacebook(HttpMessageHandler innerHandler) : base(innerHandler) { }

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,


CancellationToken cancellationToken)
{
var host = request.RequestUri.Host.ToLower();
Console.WriteLine($"Check in DenyAccessFacebook - {host}");
if (host.Contains("facebook.com"))
{
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(Encoding.UTF8.GetBytes("Không được truy cập"))
};
return await Task.FromResult(response);
}
return await base.SendAsync(request, cancellationToken);
}
}

public class Program


{
public static async Task Main(string[] args)
{
var url = "https://www.facebook.com/xuanthulab";

CookieContainer cookies = new CookieContainer();

var bottomHandler = new MyHttpClientHandler(cookies);


var changeUriHandler = new ChangeUri(bottomHandler);
var denyAccessFacebook = new DenyAccessFacebook(changeUriHandler);

using var httpClient = new HttpClient(denyAccessFacebook);


httpClient.DefaultRequestHeaders.Add("Accept", "text/html,application/xhtml+xml+json");
httpClient.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0");

try
{
HttpResponseMessage response = await httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
string htmltext = await response.Content.ReadAsStringAsync();
Console.WriteLine(htmltext);
}
catch (HttpRequestException ex)
{
Console.WriteLine("Request error: " + ex.Message);
}
}
}
Bài 47
using System;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;

class SimpleHttpServer
{
private readonly HttpListener listener;

public SimpleHttpServer(params string[] prefixes)


{
if (!HttpListener.IsSupported) throw new Exception("Máy không hỗ trợ HttpListener.");
listener = new HttpListener();
foreach (string prefix in prefixes) listener.Prefixes.Add(prefix);
}

public async Task StartAsync()


{
listener.Start();
Console.WriteLine("Server started...");
while (listener.IsListening)
{
var context = await listener.GetContextAsync();
await HandleRequest(context);
}
}

private async Task HandleRequest(HttpListenerContext context)


{
var request = context.Request;
var response = context.Response;
response.ContentType = "text/html";

string responseBody = request.Url.AbsolutePath switch


{
"/" => "Hello, world!",
"/stop" => StopServer(),
"/json" => JsonConvert.SerializeObject(new { Name = "Macbook Pro", Price = 2000, Manufacturer =
"Apple" }),
"/requestinfo" => GenerateRequestInfoHtml(request),
_ => "NOT FOUND"
};

byte[] buffer = Encoding.UTF8.GetBytes(responseBody);


response.ContentLength64 = buffer.Length;
await response.OutputStream.WriteAsync(buffer, 0, buffer.Length);
response.OutputStream.Close();
}

private string StopServer()


{
listener.Stop();
return "Server stopped";
}

private string GenerateRequestInfoHtml(HttpListenerRequest request)


{
var headers = string.Join("", request.Headers.AllKeys.Select(key => $"<div>{key}:
{request.Headers[key]}</div>"));
return $"<html><body><h1>Request Info</h1><h2>Headers</h2>{headers}</body></html>";
}
}

static async Task Main(string[] args)


{
var server = new SimpleHttpServer("http://*:8080/");
await server.StartAsync();
}

Bài 48
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace NetworkExample
{
class Program
{
public static void ShowUriInfo(string url)
{
Uri uri = new Uri(url);
Console.WriteLine($"URL : {url}");
Console.WriteLine($"Scheme : {uri.Scheme}");
Console.WriteLine($"Host : {uri.Host}");
Console.WriteLine($"Port : {uri.Port}");
Console.WriteLine($"Fragment : {uri.Fragment}");
Console.WriteLine($"Query : {uri.Query}");
Console.WriteLine($"Path : {uri.LocalPath}");
foreach (var seg in uri.Segments)
Console.WriteLine($"Segment : {seg}");
}

public static void IPAddressExample(string ips)


{
if (IPAddress.TryParse(ips, out IPAddress ipaddress))
{
Console.WriteLine($"Loopback : {IPAddress.Loopback}");
Console.WriteLine($"AddressFamily : {ipaddress.AddressFamily}");
Console.WriteLine($"IPv4 : {ipaddress.MapToIPv4()}");
Console.WriteLine($"IPv6 : {ipaddress.MapToIPv6()}");
}
}

public static async Task TcpClientExample(string host, int port)


{
using (var client = new TcpClient())
{
await client.ConnectAsync(host, port);
Console.WriteLine("Connected to server");

var stream = client.GetStream();


byte[] message = Encoding.UTF8.GetBytes("Hello from client");
await stream.WriteAsync(message, 0, message.Length);

byte[] buffer = new byte[256];


int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
Console.WriteLine($"Received: {Encoding.UTF8.GetString(buffer, 0, bytesRead)}");
}
}

static async Task Main(string[] args)


{
string url = "https://example.com/path/page.html?query=1#fragment";
ShowUriInfo(url);

string ip = "192.168.1.1";
IPAddressExample(ip);

string tcpHost = "localhost";


int tcpPort = 8080;
await TcpClientExample(tcpHost, tcpPort);
}
}
}

Bài 49
using System;
using System.Data;
using System.Data.SqlClient;
public class DatabaseConnectionExample
{
public static void ConnectAndQuery()
{
var connectionString = "Data Source=127.0.0.1,1433;Initial Catalog=xtlab;User
ID=SA;Password=Password123";
using var connection = new SqlConnection(connectionString);

connection.StatisticsEnabled = true;

connection.StateChange += (sender, e) =>


{
Console.WriteLine($"Trạng thái thay đổi: {e.CurrentState}, trước đó: {e.OriginalState}");
};

try
{

connection.Open();
Console.WriteLine("Kết nối thành công.");

using var command = connection.CreateCommand();


command.CommandText = "SELECT TOP(5) * FROM Sanpham";
using var reader = command.ExecuteReader();

Console.WriteLine("Dữ liệu từ bảng Sanpham:");


while (reader.Read())
{
Console.WriteLine($"ID: {reader["SanphamID"]}, Tên sản phẩm: {reader["TenSanpham"]}");
}
}
catch (SqlException ex)
{
Console.WriteLine($"Lỗi SQL: {ex.Message}");
}
finally
{

connection.Close();
Console.WriteLine("Kết nối đã đóng.");
}
var stats = connection.RetrieveStatistics();
Console.WriteLine("Thống kê kết nối:");
foreach (var key in stats.Keys)
{
Console.WriteLine($"{key}: {stats[key]}");
}
}

static void Main(string[] args)


{
ConnectAndQuery();
}
}

Bài 50
using System;
using System.Data;
using System.Data.SqlClient;

namespace SqlCommandExamples
{
class Program
{
static void Main(string[] args)
{
ExecuteScalarExample();
ExecuteNonQueryExample();
ExecuteReaderExample();
CallStoredProcedure();
}

static void ExecuteScalarExample()


{
string sqlconnectStr = @"Data Source=localhost,1433;Initial Catalog=xtlab;User
ID=SA;Password=Password123";
using SqlConnection connection = new SqlConnection(sqlconnectStr);
connection.Open();

string queryString = @"INSERT INTO Shippers (Hoten, Sodienthoai) VALUES (@Hoten, @Sodienthoai);
SELECT CAST(scope_identity() AS int)";
using SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@Hoten", "Abc");
command.Parameters.AddWithValue("@Sodienthoai", 123456);

var shipperId = command.ExecuteScalar();


Console.WriteLine($"Thêm mới Shipper, ID = {shipperId}");

connection.Close();
}

static void ExecuteNonQueryExample()


{
string sqlconnectStr = @"Data Source=localhost,1433;Initial Catalog=xtlab;User
ID=SA;Password=Password123";
using SqlConnection connection = new SqlConnection(sqlconnectStr);
connection.Open();

string queryString = "DELETE FROM Shippers WHERE ShipperID = @ShipperID";


using SqlCommand command = new SqlCommand(queryString, connection);
command.Parameters.AddWithValue("@ShipperID", 4);

int rowsAffected = command.ExecuteNonQuery();


Console.WriteLine($"Số dòng ảnh hưởng = {rowsAffected}");

connection.Close();
}
static void ExecuteReaderExample()
{
string sqlconnectStr = @"Data Source=localhost,1433;Initial Catalog=xtlab;User
ID=SA;Password=Password123";
using SqlConnection connection = new SqlConnection(sqlconnectStr);
connection.Open();

string queryString = "SELECT DanhmucID, TenDanhMuc, MoTa FROM Danhmuc";


using SqlCommand command = new SqlCommand(queryString, connection);
using SqlDataReader reader = command.ExecuteReader();

if (reader.HasRows)
{
while (reader.Read())
{
int danhmuc = reader.GetInt32(0);
string tendanhmuc = reader["TenDanhMuc"].ToString();
string mota = reader["MoTa"].ToString();

Console.WriteLine($"{danhmuc,4} - {tendanhmuc,-20} - {mota}");


}
}
else
{
Console.WriteLine("Không có dữ liệu trả về");
}

connection.Close();
}

static void CallStoredProcedure()


{
string sqlconnectStr = @"Data Source=localhost,1433;Initial Catalog=xtlab;User
ID=SA;Password=Password123";
using SqlConnection connection = new SqlConnection(sqlconnectStr);
connection.Open();

using SqlCommand cmd = new SqlCommand("getproduct", connection);


cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter
{
ParameterName = "@id",
SqlDbType = SqlDbType.Int,
Value = 10
});

using SqlDataReader reader = cmd.ExecuteReader();


while (reader.Read())
{
var ten = reader["TenSanpham"];
var gia = reader["Gia"];
Console.WriteLine($"{ten}\t{gia}");
}

connection.Close();
}
}
}

You might also like