Elysia Tools
Navigation mobile
C#
Sérialisation Windows - Exemples C#
Exemples complets de sérialisation C# pour plateforme Windows incluant JSON, XML, sérialisation binaire et transformation de données
Exemples
Entrées de cette collection
Sérialisation et Désérialisation JSON
Travailler avec des données JSON en utilisant System.Text.Json pour la sérialisation et désérialisation d'objets
Difficulté
4/10
Temps estimé
20 min
Étiquettes
csharp, json, serialization, windows
Prérequis
C# basics, Object-oriented programming, JSON concepts
using System;
using System.Collections.Generic;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.IO;
public class Person
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Email { get; set; }
public DateTime BirthDate { get; set; }
public List<string> Hobbies { get; set; }
public Address Address { get; set; }
}
public class Address
{
public string Street { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string PostalCode { get; set; }
}
class JSONSerialization
{
// 1. Basic JSON serialization
public static void BasicJSONSerialization()
{
Console.WriteLine("=== Basic JSON Serialization ===");
// Create a sample object
var person = new Person
{
Id = 1,
FirstName = "John",
LastName = "Doe",
Age = 30,
Email = "[email protected]",
BirthDate = new DateTime(1993, 5, 15),
Hobbies = new List<string> { "Reading", "Swimming", "Programming" },
Address = new Address
{
Street = "123 Main St",
City = "New York",
Country = "USA",
PostalCode = "10001"
}
};
// Serialize to JSON string
string jsonString = JsonSerializer.Serialize(person, new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
Console.WriteLine("Serialized JSON:");
Console.WriteLine(jsonString);
// Save to file
File.WriteAllText("person.json", jsonString);
Console.WriteLine("\nJSON saved to person.json file");
}
// 2. Basic JSON deserialization
public static void BasicJSONDeserialization()
{
Console.WriteLine("\n=== Basic JSON Deserialization ===");
try
{
// Read from file
string jsonString = File.ReadAllText("person.json");
Console.WriteLine("Reading JSON from file...");
// Deserialize to object
Person person = JsonSerializer.Deserialize<Person>(jsonString);
Console.WriteLine("\nDeserialized Person object:");
Console.WriteLine($"ID: {person.Id}");
Console.WriteLine($"Name: {person.FirstName} {person.LastName}");
Console.WriteLine($"Age: {person.Age}");
Console.WriteLine($"Email: {person.Email}");
Console.WriteLine($"Birth Date: {person.BirthDate:yyyy-MM-dd}");
Console.WriteLine($"Hobbies: {string.Join(", ", person.Hobbies)}");
Console.WriteLine($"Address: {person.Address.Street}, {person.Address.City}, {person.Address.Country}");
}
catch (Exception ex)
{
Console.WriteLine($"Error deserializing JSON: {ex.Message}");
}
}
// 3. Advanced JSON serialization with custom options
public static void AdvancedJSONSerialization()
{
Console.WriteLine("\n=== Advanced JSON Serialization ===");
var employees = new List<Employee>
{
new Employee
{
Id = 1,
Name = "Alice Johnson",
Position = "Software Engineer",
Salary = 75000.50m,
HireDate = new DateTime(2020, 3, 15),
IsActive = true,
Department = "Engineering"
},
new Employee
{
Id = 2,
Name = "Bob Smith",
Position = "Project Manager",
Salary = 85000.00m,
HireDate = new DateTime(2019, 7, 1),
IsActive = true,
Department = "Management"
},
new Employee
{
Id = 3,
Name = "Carol White",
Position = "UX Designer",
Salary = 65000.00m,
HireDate = new DateTime(2021, 1, 10),
IsActive = false,
Department = "Design"
}
};
// Configure JSON serializer options
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
NumberHandling = JsonNumberHandling.AllowReadingFromString,
Converters = { new JsonStringEnumConverter() }
};
// Serialize list of employees
string employeesJson = JsonSerializer.Serialize(employees, options);
Console.WriteLine("Advanced JSON Serialization (Employees):");
Console.WriteLine(employeesJson);
// Save to file
File.WriteAllText("employees.json", employeesJson);
Console.WriteLine("\nEmployees JSON saved to employees.json");
}
// 4. Working with anonymous objects and dynamic JSON
public static void DynamicJSONOperations()
{
Console.WriteLine("\n=== Dynamic JSON Operations ===");
// Create anonymous object
var orderData = new
{
OrderId = "ORD-2023-001",
Customer = new
{
Name = "Jane Doe",
Email = "[email protected]",
Phone = "+1-555-0123"
},
Items = new[]
{
new { ProductId = "PROD-001", Name = "Laptop", Quantity = 1, Price = 999.99m },
new { ProductId = "PROD-002", Name = "Mouse", Quantity = 2, Price = 25.50m },
new { ProductId = "PROD-003", Name = "Keyboard", Quantity = 1, Price = 75.00m }
},
TotalAmount = 1125.99m,
OrderDate = DateTime.Now,
Status = "Pending"
};
// Serialize anonymous object
string orderJson = JsonSerializer.Serialize(orderData, new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase
});
Console.WriteLine("Anonymous Object Serialization:");
Console.WriteLine(orderJson);
// Parse to JsonDocument for dynamic access
using (JsonDocument document = JsonDocument.Parse(orderJson))
{
JsonElement root = document.RootElement;
Console.WriteLine("\nDynamic JSON Access:");
Console.WriteLine($"Order ID: {root.GetProperty("orderId").GetString()}");
Console.WriteLine($"Customer Name: {root.GetProperty("customer").GetProperty("name").GetString()}");
Console.WriteLine($"Total Amount: ${root.GetProperty("totalAmount").GetDecimal():F2}");
Console.WriteLine("\nOrder Items:");
foreach (JsonElement item in root.GetProperty("items").EnumerateArray())
{
string name = item.GetProperty("name").GetString();
int quantity = item.GetProperty("quantity").GetInt32();
decimal price = item.GetProperty("price").GetDecimal();
Console.WriteLine($"- {name}: {quantity} x ${price:F2}");
}
}
}
// 5. JSON with custom serialization attributes
public static void CustomAttributeSerialization()
{
Console.WriteLine("\n=== Custom Attribute Serialization ===");
var product = new Product
{
ProductId = "PROD-001",
ProductName = "Wireless Headphones",
Description = "High-quality wireless headphones with noise cancellation",
Price = 149.99m,
InStock = true,
Categories = new List<string> { "Electronics", "Audio", "Wireless" },
Metadata = new Dictionary<string, object>
{
["Brand"] = "TechSound",
["Model"] = "WH-1000XM4",
["Weight"] = 254,
["BatteryLife"] = "30 hours",
["WaterResistant"] = true
}
};
// Serialize with custom attributes
var options = new JsonSerializerOptions
{
WriteIndented = true,
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault
};
string productJson = JsonSerializer.Serialize(product, options);
Console.WriteLine("Product with Custom Attributes:");
Console.WriteLine(productJson);
// Deserialize
Product deserializedProduct = JsonSerializer.Deserialize<Product>(productJson, options);
Console.WriteLine("\nDeserialized Product:");
Console.WriteLine($"ID: {deserializedProduct.ProductId}");
Console.WriteLine($"Name: {deserializedProduct.ProductName}");
Console.WriteLine($"Price: ${deserializedProduct.Price:F2}");
Console.WriteLine($"In Stock: {deserializedProduct.InStock}");
Console.WriteLine($"Categories: {string.Join(", ", deserializedProduct.Categories)}");
Console.WriteLine($"Brand: {deserializedProduct.Metadata["Brand"]}");
}
public static void RunAllExamples()
{
Console.WriteLine("JSON Serialization Examples");
Console.WriteLine("===========================");
BasicJSONSerialization();
BasicJSONDeserialization();
AdvancedJSONSerialization();
DynamicJSONOperations();
CustomAttributeSerialization();
Console.WriteLine("\nJSON serialization examples completed!");
}
}
public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public string Position { get; set; }
public decimal Salary { get; set; }
public DateTime HireDate { get; set; }
public bool IsActive { get; set; }
public string Department { get; set; }
}
public class Product
{
[JsonPropertyName("productId")]
public string ProductId { get; set; }
[JsonPropertyName("productName")]
public string ProductName { get; set; }
[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
public string Description { get; set; }
[JsonPropertyName("price")]
[JsonConverter(typeof(DecimalConverter))]
public decimal Price { get; set; }
[JsonPropertyName("inStock")]
public bool InStock { get; set; }
[JsonPropertyName("categories")]
public List<string> Categories { get; set; }
[JsonPropertyName("metadata")]
public Dictionary<string, object> Metadata { get; set; }
}
public class DecimalConverter : JsonConverter<decimal>
{
public override decimal Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return reader.GetDecimal();
}
public override void Write(Utf8JsonWriter writer, decimal value, JsonSerializerOptions options)
{
writer.WriteNumberValue(Math.Round(value, 2));
}
}Sérialisation et Analyse XML
Gestion de données XML en utilisant XmlDocument, XDocument et XmlSerializer pour le traitement de données structurées
Difficulté
6/10
Temps estimé
25 min
Étiquettes
csharp, xml, serialization, linq, windows
Prérequis
C# basics, XML concepts, LINQ basics
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using System.Linq;
[XmlRoot("BookStore")]
public class BookStore
{
[XmlElement("StoreName")]
public string StoreName { get; set; }
[XmlElement("Location")]
public string Location { get; set; }
[XmlElement("Books")]
public List<Book> Books { get; set; } = new List<Book>();
[XmlAttribute("Version")]
public string Version { get; set; } = "1.0";
}
public class Book
{
[XmlElement("Title")]
public string Title { get; set; }
[XmlElement("Author")]
public string Author { get; set; }
[XmlElement("ISBN")]
public string ISBN { get; set; }
[XmlElement("Price")]
public decimal Price { get; set; }
[XmlElement("PublishedDate")]
public DateTime PublishedDate { get; set; }
[XmlElement("Genre")]
public string Genre { get; set; }
[XmlAttribute("BookId")]
public int BookId { get; set; }
[XmlElement("Tags")]
public List<string> Tags { get; set; } = new List<string>();
}
class XMLSerialization
{
// 1. XML Serialization using XmlSerializer
public static void XMLSerializationExample()
{
Console.WriteLine("=== XML Serialization Example ===");
// Create bookstore with sample data
var bookstore = new BookStore
{
StoreName = "Tech Books Emporium",
Location = "San Francisco, CA",
Version = "2.1",
Books = new List<Book>
{
new Book
{
BookId = 1,
Title = "C# Programming Basics",
Author = "John Smith",
ISBN = "978-1-234567-89-0",
Price = 39.99m,
PublishedDate = new DateTime(2023, 1, 15),
Genre = "Programming",
Tags = new List<string> { "C#", "Programming", "Beginner" }
},
new Book
{
BookId = 2,
Title = "Advanced Design Patterns",
Author = "Jane Johnson",
ISBN = "978-0-987654-32-1",
Price = 54.99m,
PublishedDate = new DateTime(2022, 8, 20),
Genre = "Software Engineering",
Tags = new List<string> { "Design Patterns", "Architecture", "Advanced" }
},
new Book
{
BookId = 3,
Title = "Web Development with ASP.NET",
Author = "Mike Wilson",
ISBN = "978-1-555555-55-5",
Price = 49.99m,
PublishedDate = new DateTime(2023, 3, 10),
Genre = "Web Development",
Tags = new List<string> { "ASP.NET", "Web", "Backend" }
}
}
};
// Serialize to XML
var xmlSerializer = new XmlSerializer(typeof(BookStore));
using (var stringWriter = new StringWriter())
{
xmlSerializer.Serialize(stringWriter, bookstore);
string xmlString = stringWriter.ToString();
Console.WriteLine("Serialized XML:");
Console.WriteLine(xmlString);
// Save to file
File.WriteAllText("bookstore.xml", xmlString);
Console.WriteLine("\nXML saved to bookstore.xml file");
}
}
// 2. XML Deserialization
public static void XMLDeserializationExample()
{
Console.WriteLine("\n=== XML Deserialization Example ===");
try
{
// Read XML from file
string xmlString = File.ReadAllText("bookstore.xml");
Console.WriteLine("Reading XML from file...");
var xmlSerializer = new XmlSerializer(typeof(BookStore));
using (var stringReader = new StringReader(xmlString))
{
BookStore bookstore = (BookStore)xmlSerializer.Deserialize(stringReader);
Console.WriteLine("\nDeserialized BookStore:");
Console.WriteLine($"Store Name: {bookstore.StoreName}");
Console.WriteLine($"Location: {bookstore.Location}");
Console.WriteLine($"Version: {bookstore.Version}");
Console.WriteLine($"Total Books: {bookstore.Books.Count}");
Console.WriteLine("\nBooks:");
foreach (var book in bookstore.Books)
{
Console.WriteLine($"\nBook ID: {book.BookId}");
Console.WriteLine($"Title: {book.Title}");
Console.WriteLine($"Author: {book.Author}");
Console.WriteLine($"ISBN: {book.ISBN}");
Console.WriteLine($"Price: ${book.Price:F2}");
Console.WriteLine($"Published: {book.PublishedDate:yyyy-MM-dd}");
Console.WriteLine($"Genre: {book.Genre}");
Console.WriteLine($"Tags: {string.Join(", ", book.Tags)}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error deserializing XML: {ex.Message}");
}
}
// 3. Working with XDocument (LINQ to XML)
public static void XDocumentOperations()
{
Console.WriteLine("\n=== XDocument Operations (LINQ to XML) ===");
// Create XML document using XDocument
XDocument doc = new XDocument(
new XElement("Employees",
new XElement("Employee",
new XAttribute("Id", "1"),
new XElement("Name", "Alice Johnson"),
new XElement("Department", "Engineering"),
new XElement("Position", "Senior Developer"),
new XElement("Salary", "95000"),
new XElement("HireDate", "2020-01-15"),
new XElement("Skills",
new XElement("Skill", "C#"),
new XElement("Skill", "JavaScript"),
new XElement("Skill", "SQL")
)
),
new XElement("Employee",
new XAttribute("Id", "2"),
new XElement("Name", "Bob Smith"),
new XElement("Department", "Marketing"),
new XElement("Position", "Marketing Manager"),
new XElement("Salary", "85000"),
new XElement("HireDate", "2019-06-01"),
new XElement("Skills",
new XElement("Skill", "SEO"),
new XElement("Skill", "Analytics"),
new XElement("Skill", "Content Strategy")
)
),
new XElement("Employee",
new XAttribute("Id", "3"),
new XElement("Name", "Carol White"),
new XElement("Department", "Engineering"),
new XElement("Position", "UX Designer"),
new XElement("Salary", "75000"),
new XElement("HireDate", "2021-03-10"),
new XElement("Skills",
new XElement("Skill", "UI Design"),
new XElement("Skill", "User Research"),
new XElement("Skill", "Prototyping")
)
)
)
);
Console.WriteLine("Created XDocument:");
Console.WriteLine(doc.ToString());
// Save to file
doc.Save("employees.xml");
Console.WriteLine("\nXDocument saved to employees.xml");
// Query the XML document
Console.WriteLine("\n=== Querying XML with LINQ ===");
// Load the document
XDocument loadedDoc = XDocument.Load("employees.xml");
// Find all employees in Engineering department
var engineeringEmployees = loadedDoc.Descendants("Employee")
.Where(e => e.Element("Department").Value == "Engineering")
.Select(e => new
{
Id = e.Attribute("Id").Value,
Name = e.Element("Name").Value,
Position = e.Element("Position").Value,
Salary = decimal.Parse(e.Element("Salary").Value)
});
Console.WriteLine("Engineering Department Employees:");
foreach (var emp in engineeringEmployees)
{
Console.WriteLine($"- {emp.Name} ({emp.Position}): ${emp.Salary:N0}");
}
// Find employees with specific skills
var csharpDevelopers = loadedDoc.Descendants("Employee")
.Where(e => e.Descendants("Skill").Any(s => s.Value == "C#"))
.Select(e => e.Element("Name").Value);
Console.WriteLine("\nC# Developers:");
foreach (var dev in csharpDevelopers)
{
Console.WriteLine($"- {dev}");
}
}
// 4. XmlDocument operations (traditional XML DOM)
public static void XmlDocumentOperations()
{
Console.WriteLine("\n=== XmlDocument Operations ===");
// Create XmlDocument
XmlDocument xmlDoc = new XmlDocument();
// Create root element
XmlElement root = xmlDoc.CreateElement("Products");
xmlDoc.AppendChild(root);
// Add products
var products = new[]
{
new { Id = "1", Name = "Laptop", Category = "Electronics", Price = "999.99", Stock = "50" },
new { Id = "2", Name = "Mouse", Category = "Electronics", Price = "25.50", Stock = "200" },
new { Id = "3", Name = "Keyboard", Category = "Electronics", Price = "75.00", Stock = "100" },
new { Id = "4", Name = "Monitor", Category = "Electronics", Price = "299.99", Stock = "75" }
};
foreach (var product in products)
{
XmlElement productElement = xmlDoc.CreateElement("Product");
productElement.SetAttribute("Id", product.Id);
XmlElement nameElement = xmlDoc.CreateElement("Name");
nameElement.InnerText = product.Name;
productElement.AppendChild(nameElement);
XmlElement categoryElement = xmlDoc.CreateElement("Category");
categoryElement.InnerText = product.Category;
productElement.AppendChild(categoryElement);
XmlElement priceElement = xmlDoc.CreateElement("Price");
priceElement.InnerText = product.Price;
productElement.AppendChild(priceElement);
XmlElement stockElement = xmlDoc.CreateElement("Stock");
stockElement.InnerText = product.Stock;
productElement.AppendChild(stockElement);
root.AppendChild(productElement);
}
Console.WriteLine("Created XmlDocument:");
Console.WriteLine(xmlDoc.OuterXml);
// Save to file
xmlDoc.Save("products.xml");
Console.WriteLine("\nXmlDocument saved to products.xml");
// Read and manipulate
Console.WriteLine("\n=== Reading and Manipulating XmlDocument ===");
XmlDocument loadedDoc = new XmlDocument();
loadedDoc.Load("products.xml");
// Get all product nodes
XmlNodeList productNodes = loadedDoc.GetElementsByTagName("Product");
Console.WriteLine($"Found {productNodes.Count} products:");
decimal totalValue = 0;
foreach (XmlNode node in productNodes)
{
string name = node["Name"].InnerText;
decimal price = decimal.Parse(node["Price"].InnerText);
int stock = int.Parse(node["Stock"].InnerText);
Console.WriteLine($"- {name}: ${price:F2} (Stock: {stock})");
totalValue += price * stock;
}
Console.WriteLine($"\nTotal inventory value: ${totalValue:N2}");
// Modify an element
XmlNode firstProduct = productNodes[0];
firstProduct["Stock"].InnerText = "45";
Console.WriteLine("\nUpdated first product stock to 45");
// Add a new attribute
XmlElement firstProductElement = (XmlElement)firstProduct;
firstProductElement.SetAttribute("Status", "Available");
Console.WriteLine("Added Status attribute to first product");
// Save changes
loadedDoc.Save("products_modified.xml");
Console.WriteLine("\nModified XmlDocument saved to products_modified.xml");
}
// 5. XML transformation and validation
public static void XMLTransformation()
{
Console.WriteLine("\n=== XML Transformation ===");
// Create source XML
string sourceXml = @"
<Orders>
<Order OrderId='ORD-001'>
<Customer>
<Name>John Doe</Name>
<Email>[email protected]</Email>
</Customer>
<Items>
<Item ProductId='PROD-001' Name='Laptop' Quantity='1' Price='999.99' />
<Item ProductId='PROD-002' Name='Mouse' Quantity='2' Price='25.50' />
</Items>
</Order>
<Order OrderId='ORD-002'>
<Customer>
<Name>Jane Smith</Name>
<Email>[email protected]</Email>
</Customer>
<Items>
<Item ProductId='PROD-003' Name='Keyboard' Quantity='1' Price='75.00' />
<Item ProductId='PROD-004' Name='Monitor' Quantity='1' Price='299.99' />
</Items>
</Order>
</Orders>";
XDocument sourceDoc = XDocument.Parse(sourceXml);
// Transform to a summary format
var transformedData = sourceDoc.Descendants("Order")
.Select(order => new
{
OrderId = order.Attribute("OrderId").Value,
CustomerName = order.Element("Customer").Element("Name").Value,
CustomerEmail = order.Element("Customer").Element("Email").Value,
Items = order.Descendants("Item").Count(),
TotalAmount = order.Descendants("Item")
.Sum(item => decimal.Parse(item.Attribute("Price").Value) *
int.Parse(item.Attribute("Quantity").Value))
});
// Create transformed XML
XDocument transformedDoc = new XDocument(
new XElement("OrderSummary",
new XElement("GeneratedDate", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")),
new XElement("TotalOrders", transformedData.Count()),
new XElement("Orders",
transformedData.Select(order => new XElement("Order",
new XElement("OrderId", order.OrderId),
new XElement("Customer", order.CustomerName),
new XElement("Email", order.CustomerEmail),
new XElement("ItemCount", order.Items),
new XElement("TotalAmount", order.TotalAmount.ToString("F2"))
))
)
)
);
Console.WriteLine("Transformed XML:");
Console.WriteLine(transformedDoc.ToString());
// Save transformation
transformedDoc.Save("order_summary.xml");
Console.WriteLine("\nTransformed XML saved to order_summary.xml");
// Calculate statistics
decimal grandTotal = transformedData.Sum(order => order.TotalAmount);
double averageOrder = (double)grandTotal / transformedData.Count();
Console.WriteLine("\n=== Order Statistics ===");
Console.WriteLine($"Total Orders: {transformedData.Count()}");
Console.WriteLine($"Grand Total: ${grandTotal:F2}");
Console.WriteLine($"Average Order Value: ${averageOrder:F2}");
}
public static void RunAllExamples()
{
Console.WriteLine("XML Serialization Examples");
Console.WriteLine("==========================");
XMLSerializationExample();
XMLDeserializationExample();
XDocumentOperations();
XmlDocumentOperations();
XMLTransformation();
Console.WriteLine("\nXML serialization examples completed!");
}
}Sérialisation Binaire et Personnalisée
Sérialisation binaire, formateurs personnalisés et patterns de sérialisation avancés pour applications critiques en performance
Difficulté
8/10
Temps estimé
30 min
Étiquettes
csharp, binary, serialization, performance, windows
Prérequis
C# advanced, Serialization concepts, Performance optimization
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.Json;
[Serializable]
public class Product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public int Stock { get; set; }
public DateTime CreatedDate { get; set; }
public List<string> Categories { get; set; }
[NonSerialized]
public string InternalCode; // This won't be serialized
public Product()
{
Categories = new List<string>();
InternalCode = Guid.NewGuid().ToString("N");
}
public override string ToString()
{
return $"Product {ProductId}: {Name} - ${Price:F2} (Stock: {Stock})";
}
}
[Serializable]
public class Order
{
public int OrderId { get; set; }
public string CustomerName { get; set; }
public string CustomerEmail { get; set; }
public DateTime OrderDate { get; set; }
public List<OrderItem> Items { get; set; }
public decimal TotalAmount { get; set; }
public string Status { get; set; }
public Order()
{
Items = new List<OrderItem>();
}
public void CalculateTotal()
{
TotalAmount = 0;
foreach (var item in Items)
{
TotalAmount += item.Price * item.Quantity;
}
}
}
[Serializable]
public class OrderItem
{
public string ProductId { get; set; }
public string ProductName { get; set; }
public int Quantity { get; set; }
public decimal Price { get; set; }
[NonSerialized]
public decimal Discount; // Won't be serialized
}
class BinarySerialization
{
// 1. Basic Binary Serialization
public static void BasicBinarySerialization()
{
Console.WriteLine("=== Basic Binary Serialization ===");
try
{
// Create sample products
var products = new List<Product>
{
new Product
{
ProductId = 1,
Name = "Laptop Pro",
Description = "High-performance laptop for professionals",
Price = 1299.99m,
Stock = 25,
CreatedDate = DateTime.Now.AddDays(-30),
Categories = new List<string> { "Electronics", "Computers", "Professional" }
},
new Product
{
ProductId = 2,
Name = "Wireless Mouse",
Description = "Ergonomic wireless mouse",
Price = 49.99m,
Stock = 150,
CreatedDate = DateTime.Now.AddDays(-15),
Categories = new List<string> { "Electronics", "Accessories", "Wireless" }
},
new Product
{
ProductId = 3,
Name = "Mechanical Keyboard",
Description = "RGB mechanical keyboard",
Price = 129.99m,
Stock = 75,
CreatedDate = DateTime.Now.AddDays(-7),
Categories = new List<string> { "Electronics", "Input Devices", "Gaming" }
}
};
// Binary serialization
IFormatter formatter = new BinaryFormatter();
using (var stream = new FileStream("products.bin", FileMode.Create))
{
formatter.Serialize(stream, products);
Console.WriteLine("Products serialized to binary file");
}
// Get file size for comparison
FileInfo fileInfo = new FileInfo("products.bin");
Console.WriteLine($"Binary file size: {fileInfo.Length} bytes");
// Display products before serialization
Console.WriteLine("\nOriginal Products:");
foreach (var product in products)
{
Console.WriteLine($"- {product} (Internal Code: {product.InternalCode})");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in binary serialization: {ex.Message}");
}
}
// 2. Binary Deserialization
public static void BasicBinaryDeserialization()
{
Console.WriteLine("\n=== Binary Deserialization ===");
try
{
IFormatter formatter = new BinaryFormatter();
using (var stream = new FileStream("products.bin", FileMode.Open))
{
var deserializedProducts = (List<Product>)formatter.Deserialize(stream);
Console.WriteLine($"Deserialized {deserializedProducts.Count} products");
Console.WriteLine("\nDeserialized Products:");
foreach (var product in deserializedProducts)
{
Console.WriteLine($"- {product} (Internal Code: {product.InternalCode ?? "NULL"})");
Console.WriteLine($" Categories: {string.Join(", ", product.Categories)}");
Console.WriteLine($" Created: {product.CreatedDate:yyyy-MM-dd HH:mm:ss}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in binary deserialization: {ex.Message}");
}
}
// 3. Performance comparison: Binary vs JSON
public static void SerializationPerformanceComparison()
{
Console.WriteLine("\n=== Serialization Performance Comparison ===");
// Create a large dataset
var largeDataSet = new List<Order>();
var random = new Random();
for (int i = 1; i <= 1000; i++)
{
var order = new Order
{
OrderId = i,
CustomerName = $"Customer {i}",
CustomerEmail = $"customer{i}@example.com",
OrderDate = DateTime.Now.AddDays(-random.Next(0, 365)),
Status = "Processing"
};
// Add random items to each order
int itemCount = random.Next(1, 6);
for (int j = 1; j <= itemCount; j++)
{
order.Items.Add(new OrderItem
{
ProductId = $"PROD-{random.Next(1, 100):000}",
ProductName = $"Product {random.Next(1, 500)}",
Quantity = random.Next(1, 5),
Price = (decimal)(random.NextDouble() * 500 + 10)
});
}
order.CalculateTotal();
largeDataSet.Add(order);
}
Console.WriteLine($"Created dataset with {largeDataSet.Count} orders");
// Binary serialization performance
var binaryStopwatch = System.Diagnostics.Stopwatch.StartNew();
long binarySize = 0;
using (var stream = new MemoryStream())
{
IFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, largeDataSet);
binarySize = stream.Length;
}
binaryStopwatch.Stop();
// JSON serialization performance
var jsonStopwatch = System.Diagnostics.Stopwatch.StartNew();
long jsonSize = 0;
var jsonOptions = new JsonSerializerOptions
{
WriteIndented = false // Minified for fair comparison
};
string jsonString = JsonSerializer.Serialize(largeDataSet, jsonOptions);
jsonSize = System.Text.Encoding.UTF8.GetByteCount(jsonString);
jsonStopwatch.Stop();
Console.WriteLine("\nPerformance Results:");
Console.WriteLine($"Binary Serialization:");
Console.WriteLine($" Time: {binaryStopwatch.ElapsedMilliseconds} ms");
Console.WriteLine($" Size: {binarySize:N0} bytes");
Console.WriteLine($"JSON Serialization:");
Console.WriteLine($" Time: {jsonStopwatch.ElapsedMilliseconds} ms");
Console.WriteLine($" Size: {jsonSize:N0} bytes");
double sizeRatio = (double)jsonSize / binarySize;
double timeRatio = (double)jsonStopwatch.ElapsedMilliseconds / binaryStopwatch.ElapsedMilliseconds;
Console.WriteLine($"\nComparison:");
Console.WriteLine($" Size Ratio (JSON/Binary): {sizeRatio:F2}");
Console.WriteLine($" Time Ratio (JSON/Binary): {timeRatio:F2}");
}
// 4. Custom serialization with ISerializable
public static void CustomSerialization()
{
Console.WriteLine("\n=== Custom Serialization Example ===");
try
{
// Create a custom serializable object
var sensitiveData = new SensitiveDocument
{
DocumentId = "DOC-001",
Title = "Confidential Report",
Content = "This is sensitive information that should be encrypted",
Author = "John Doe",
CreatedDate = DateTime.Now.AddDays(-10),
AccessLevel = 5,
Tags = new List<string> { "Confidential", "Internal", "Restricted" }
};
Console.WriteLine("Original SensitiveDocument:");
Console.WriteLine($"ID: {sensitiveData.DocumentId}");
Console.WriteLine($"Title: {sensitiveData.Title}");
Console.WriteLine($"Content: {sensitiveData.Content}");
Console.WriteLine($"Author: {sensitiveData.Author}");
Console.WriteLine($"Access Level: {sensitiveData.AccessLevel}");
// Serialize using custom method
IFormatter formatter = new BinaryFormatter();
using (var stream = new FileStream("sensitive_doc.bin", FileMode.Create))
{
formatter.Serialize(stream, sensitiveData);
Console.WriteLine("\nSensitiveDocument serialized with custom logic");
}
// Deserialize
using (var stream = new FileStream("sensitive_doc.bin", FileMode.Open))
{
var deserializedDoc = (SensitiveDocument)formatter.Deserialize(stream);
Console.WriteLine("\nDeserialized SensitiveDocument:");
Console.WriteLine($"ID: {deserializedDoc.DocumentId}");
Console.WriteLine($"Title: {deserializedDoc.Title}");
Console.WriteLine($"Content: {deserializedDoc.Content}");
Console.WriteLine($"Author: {deserializedDoc.Author}");
Console.WriteLine($"Access Level: {deserializedDoc.AccessLevel}");
Console.WriteLine($"Deserialization Count: {deserializedDoc.DeserializationCount}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in custom serialization: {ex.Message}");
}
}
// 5. Streaming serialization for large datasets
public static void StreamingSerialization()
{
Console.WriteLine("\n=== Streaming Serialization Example ===");
try
{
// Create large dataset
var sensorData = new List<SensorReading>();
var random = new Random();
Console.WriteLine("Generating sensor data...");
for (int i = 0; i < 10000; i++)
{
sensorData.Add(new SensorReading
{
Timestamp = DateTime.Now.AddSeconds(-i),
SensorId = $"SENSOR-{(i % 10 + 1):D2}",
Temperature = 20 + random.NextDouble() * 15,
Humidity = 30 + random.NextDouble() * 40,
Pressure = 980 + random.NextDouble() * 50,
Location = $"Location-{(i % 5 + 1)}"
});
}
Console.WriteLine($"Generated {sensorData.Count} sensor readings");
// Stream serialization
Console.WriteLine("\nPerforming streaming serialization...");
var streamingStopwatch = System.Diagnostics.Stopwatch.StartNew();
using (var stream = new FileStream("sensor_data_stream.bin", FileMode.Create))
{
using (var writer = new BinaryWriter(stream))
{
// Write header
writer.Write(sensorData.Count);
writer.Write(DateTime.Now.ToBinary());
// Stream each reading individually
foreach (var reading in sensorData)
{
writer.Write(reading.Timestamp.ToBinary());
writer.Write(reading.SensorId ?? string.Empty);
writer.Write(reading.Temperature);
writer.Write(reading.Humidity);
writer.Write(reading.Pressure);
writer.Write(reading.Location ?? string.Empty);
}
}
}
streamingStopwatch.Stop();
var streamSize = new FileInfo("sensor_data_stream.bin").Length;
Console.WriteLine($"Streaming serialization completed in {streamingStopwatch.ElapsedMilliseconds} ms");
Console.WriteLine($"Stream size: {streamSize:N0} bytes");
// Stream deserialization
Console.WriteLine("\nPerforming streaming deserialization...");
streamingStopwatch.Restart();
var deserializedReadings = new List<SensorReading>();
using (var stream = new FileStream("sensor_data_stream.bin", FileMode.Open))
{
using (var reader = new BinaryReader(stream))
{
// Read header
int count = reader.ReadInt32();
DateTime createdDate = DateTime.FromBinary(reader.ReadInt64());
// Read each reading
for (int i = 0; i < count; i++)
{
deserializedReadings.Add(new SensorReading
{
Timestamp = DateTime.FromBinary(reader.ReadInt64()),
SensorId = reader.ReadString(),
Temperature = reader.ReadDouble(),
Humidity = reader.ReadDouble(),
Pressure = reader.ReadDouble(),
Location = reader.ReadString()
});
}
}
}
streamingStopwatch.Stop();
Console.WriteLine($"Streaming deserialization completed in {streamingStopwatch.ElapsedMilliseconds} ms");
Console.WriteLine($"Deserialized {deserializedReadings.Count} readings");
// Show sample data
Console.WriteLine("\nSample readings:");
for (int i = 0; i < Math.Min(5, deserializedReadings.Count; i++)
{
var reading = deserializedReadings[i];
Console.WriteLine($" {reading.Timestamp:HH:mm:ss} - {reading.SensorId}: {reading.Temperature:F1}°C, {reading.Humidity:F1}%");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error in streaming serialization: {ex.Message}");
}
}
public static void RunAllExamples()
{
Console.WriteLine("Binary and Custom Serialization Examples");
Console.WriteLine("=========================================");
BasicBinarySerialization();
BasicBinaryDeserialization();
SerializationPerformanceComparison();
CustomSerialization();
StreamingSerialization();
Console.WriteLine("\nBinary serialization examples completed!");
}
}
[Serializable]
public class SensitiveDocument : ISerializable
{
public string DocumentId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public string Author { get; set; }
public DateTime CreatedDate { get; set; }
public int AccessLevel { get; set; }
public List<string> Tags { get; set; }
[NonSerialized]
public int DeserializationCount;
public SensitiveDocument()
{
Tags = new List<string>();
}
// Custom serialization constructor
protected SensitiveDocument(SerializationInfo info, StreamingContext context)
{
DocumentId = info.GetString("DocumentId");
Title = info.GetString("Title");
Author = info.GetString("Author");
CreatedDate = info.GetDateTime("CreatedDate");
AccessLevel = info.GetInt32("AccessLevel");
Tags = (List<string>)info.GetValue("Tags", typeof(List<string>));
// Custom logic: "encrypt" content during serialization
string encryptedContent = info.GetString("EncryptedContent");
Content = DecryptContent(encryptedContent);
DeserializationCount++;
}
// Custom serialization method
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("DocumentId", DocumentId);
info.AddValue("Title", Title);
info.AddValue("Author", Author);
info.AddValue("CreatedDate", CreatedDate);
info.AddValue("AccessLevel", AccessLevel);
info.AddValue("Tags", Tags);
// Custom logic: "encrypt" sensitive content
string encryptedContent = EncryptContent(Content);
info.AddValue("EncryptedContent", encryptedContent);
}
private string EncryptContent(string content)
{
// Simple "encryption" for demonstration (XOR with a key)
char[] chars = content.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
chars[i] = (char)(chars[i] ^ 0x55);
}
return new string(chars);
}
private string DecryptContent(string encryptedContent)
{
// Reverse the encryption
char[] chars = encryptedContent.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
chars[i] = (char)(chars[i] ^ 0x55);
}
return new string(chars);
}
}
[Serializable]
public class SensorReading
{
public DateTime Timestamp { get; set; }
public string SensorId { get; set; }
public double Temperature { get; set; }
public double Humidity { get; set; }
public double Pressure { get; set; }
public string Location { get; set; }
}Outils
Outils souvent utilisés avec cet exemple
Associé