SlideShare ist ein Scribd-Unternehmen logo
1 von 40
Downloaden Sie, um offline zu lesen
Tool Development
Chapter 06: Binary Serialization, Worker Threads
Nick Prühs
Assignment Solution #5
DEMO
2 / 58
Objectives
• To learn how to properly read and write binary files
• To understand how to use worker threads in order
to create reactive UIs
3 / 58
Binary Serialization
• Sometimes you’ll want to serialize data in a format
other than plain text
• As we have learned, this can basically be achieved
using the BinaryReader and BinaryWriter classes
in .NET
4 / 58
Writing Binary Data To Files
C#
5 / 58
// Collect information on the file to create.
FileInfo fileInfo = new FileInfo("newFile.dat");
// Create new file.
FileStream fileStream = fileInfo.Create();
// Create new binary writer.
BinaryWriter binaryWriter = new BinaryWriter(fileStream);
// Write data.
binaryWriter.Write(23);
binaryWriter.Write(true);
binaryWriter.Write(0.4f);
// Close file stream and release all resources.
binaryWriter.Close();
Reading From Binary Files
C#
6 / 58
// Collect information on the file to read from.
FileInfo fileInfo = new FileInfo("newFile.dat");
// Open file for reading.
FileStream fileStream = fileInfo.OpenRead();
// Create new binary reader.
BinaryReader binaryReader = new BinaryReader(fileStream);
// Read data.
int i = binaryReader.ReadInt32();
bool b = binaryReader.ReadBoolean();
float f = binaryReader.ReadSingle();
// Close file stream and release all resources.
binaryReader.Close();
Binary Serialization
• However, writing and reading binary data in the
right order can be tedious and very error-prone.
• In most cases you’ll need arbitrary data to be read and
written.
• Even worse, your type hierarchy will evolve during
development.
• We’ll take a look at two more generic approaches
that try to ensure mostly error-free binary
serialization.
7 / 58
Initial Situation
C#
8 / 58
public class Address
{
public string PostCode;
public string City;
}
public class OrderItem
{
public string Name;
public float Price;
}
public class Order
{
public OrderItem Item;
public Address ShipTo;
}
Challenge
• In order to be able to automatically serialize and
deserialize objects of type Order,
• we need to recursively serialize and deserialize objects
of type Address and OrderItem,
• we must be able to read and write field values of
primitive types (such as string or float),
• and we must do so in the right order!
9 / 58
Binary Serialization
via Interfaces
• All serializable classes implement a new interface
IBinarySerializable.
• Interface enforces methods for reading and writing
binary data.
• These methods can be called for all types that are
referenced by serialized types.
• Reading and writing data in the correct order relies on a
correct implementation of the interface.
10 / 58
Interface
IBinarySerializable
C#
11 / 58
public interface IBinarySerializable
{
void WriteBinary(BinaryWriter writer);
void ReadBinary(BinaryReader reader);
}
Interface Implementations
C#
12 / 58
public class Address : IBinarySerializable
{
public string PostCode;
public string City;
public void WriteBinary(BinaryWriter writer)
{
writer.Write(this.PostCode);
writer.Write(this.City);
}
public void ReadBinary(BinaryReader reader)
{
this.PostCode = reader.ReadString();
this.City = reader.ReadString();
}
}
Interface Implementations
C#
13 / 58
public class OrderItem : IBinarySerializable
{
public string Name;
public float Price;
public void WriteBinary(BinaryWriter writer)
{
writer.Write(this.Name);
writer.Write(this.Price);
}
public void ReadBinary(BinaryReader reader)
{
this.Name = reader.ReadString();
this.Price = reader.ReadSingle();
}
}
Interface Implementations
C#
14 / 58
public class Order : IBinarySerializable
{
public OrderItem Item;
public Address ShipTo;
public void WriteBinary(BinaryWriter writer)
{
this.Item.WriteBinary(writer);
this.ShipTo.WriteBinary(writer);
}
public void ReadBinary(BinaryReader reader)
{
this.Item = new OrderItem();
this.Item.ReadBinary(reader);
this.ShipTo = new Address();
this.ShipTo.ReadBinary(reader);
}
}
Writing Binary Data
C#
15 / 58
// Collect information on the file to create.
FileInfo fileInfo = new FileInfo("newFile.dat");
// Create new file.
FileStream fileStream = fileInfo.Create();
// Create new binary writer.
BinaryWriter binaryWriter = new BinaryWriter(fileStream);
// Write data.
order.WriteBinary(binaryWriter);
// Close file stream and release all resources.
binaryWriter.Close();
Reading Binary Data
C#
16 / 58
// Collect information on the file to read from.
FileInfo fileInfo = new FileInfo("newFile.dat");
// Open file for reading.
FileStream fileStream = fileInfo.OpenRead();
// Create new binary reader.
BinaryReader binaryReader = new BinaryReader(fileStream);
// Read data.
Order order = new Order();
order.ReadBinary(binaryReader);
// Close file stream and release all resources.
binaryReader.Close();
Binary Serialization
via Interfaces - Evaluation
• Delegating the task of serialization to serialized
classes increases code readability and makes
debugging easier
• However, every time a new type is introduced, you need
to implement the interface again.
• Reading and writing data in the correct order relies on a
correct implementation of the interface.
• Strictly spoken, this approach violates the principle of
separation of concerns.
17 / 58
Binary Serialization
via Reflection
• We create a new serialization class called
BinarySerializer.
• Similar to XmlSerializer, this class provides
Serialize and Deserialize methods that reflect the
fields of a given type.
18 / 58
Class BinarySerializer
C#
19 / 58
public void Serialize(BinaryWriter writer, object obj)
{
if (obj == null)
{
return;
}
// Reflect object fields.
Type type = obj.GetType();
FieldInfo[] fields = type.GetFields
(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// ...
Class BinarySerializer
C#
20 / 58
// ...
foreach (FieldInfo field in fields)
{
// Check how the field value has to be serialized.
object fieldValue = field.GetValue(obj);
if (field.FieldType == typeof(string))
{
writer.Write((string)fieldValue);
}
else if (field.FieldType == typeof(float))
{
writer.Write((float)fieldValue);
}
else if (field.FieldType == typeof(int))
{
writer.Write((int)fieldValue);
}
// ...
}
}
Class BinarySerializer
C#
21 / 58
foreach (FieldInfo field in fields)
{
// ...
else if (!field.FieldType.IsPrimitive)
{
// Recursively serialize referenced types.
this.Serialize(writer, fieldValue);
}
else
{
throw new ArgumentException(
string.Format("Unsupported type for binary serialization: {0}.
Cannot serialize fields of type {1}.", type, field.FieldType), "obj");
}
}
}
Class BinarySerializer
C#
22 / 58
public object Deserialize(BinaryReader reader, Type type)
{
// Create object instance.
object obj = Activator.CreateInstance(type);
// Reflect object fields.
FieldInfo[] fields = type.GetFields
(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// ...
Class BinarySerializer
C#
23 / 58
// ...
foreach (FieldInfo field in fields)
{
object fieldValue;
// Check how the field value has to be deserialized.
if (field.FieldType == typeof(string))
{
fieldValue = reader.ReadString();
}
else if (field.FieldType == typeof(float))
{
fieldValue = reader.ReadSingle();
}
else if (field.FieldType == typeof(int))
{
fieldValue = reader.ReadInt32();
}
// ...
}
}
Class BinarySerializer
C#
24 / 58
foreach (FieldInfo field in fields)
{
// ...
else if (!field.FieldType.IsPrimitive)
{
// Recursively deserialize referenced types.
fieldValue = this.Deserialize(reader, field.FieldType);
}
else
{
throw new ArgumentException(
string.Format("Unsupported type for binary deserialization: {0}.
Cannot deserialize fields of type {1}.", type, field.FieldType), "type");
}
// Set field value.
field.SetValue(obj, fieldValue);
}
return obj;
}
Writing Binary Data
C#
25 / 58
// Collect information on the file to create.
FileInfo fileInfo = new FileInfo("newFile.dat");
// Create new file.
FileStream fileStream = fileInfo.Create();
// Create new binary writer.
BinaryWriter binaryWriter = new BinaryWriter(fileStream);
// Write data.
BinarySerializer serializer = new BinarySerializer();
serializer.Serialize(binaryWriter, order);
// Close file stream and release all resources.
binaryWriter.Close();
Reading Binary Data
C#
26 / 58
// Collect information on the file to read from.
FileInfo fileInfo = new FileInfo("newFile.dat");
// Open file for reading.
FileStream fileStream = fileInfo.OpenRead();
// Create new binary reader.
BinaryReader binaryReader = new BinaryReader(fileStream);
// Read data.
BinarySerializer serializer = new BinarySerializer();
Order order = (Order)serializer.Deserialize(binaryReader, typeof(Order));
// Close file stream and release all resources.
binaryReader.Close();
Binary Serialization
via Reflection - Evaluation
• Newly created types don’t need to implement any
interfaces.
• Special cases (enums, nullable types, generics)
need to be considered only once.
• Serialization code is limited to very few lines, which
in turn can be found in a single class.
• However, serialization via reflection is significantly
slower than via interfaces.
• Reading and writing data in the correct order depends
on the order the fields are declared in serialized types!
27 / 58
Hint
Never stop improving your error
handling while developing!
(e.g. missing default constructor,
unexpected enum value, etc.)
29 / 78
Background Workers
• Time-consuming operations like downloads and
database transactions can cause your UI to seem as
though it has stopped responding while they are
running.
• BackgroundWorker class allows you to run an
operation on a separate, dedicated thread.
30 / 78
Background Workers 101
1. Create new BackgroundWorker object.
2. Add event handlers.
1. Perform your time-consuming operation in DoWork.
2. Set WorkerReportsProgress to true and receive
notifications of progress updates in ProgressChanged.
3. Receive a notification when the operation is
completed in RunWorkerCompleted.
3. Call RunWorkerAsync on the worker object.
31 / 78
Gotcha!
Don’t to manipulate any UI objects
in your DoWork event handler!
32 / 78
Background Worker and UI
33 / 78
Reporting Progress
• Calling ReportProgress on the background worker
object causes the ProgressChanged event handler
to be called in the UI thread.
• In that event handler, the reported progress is
available through the property
ProgressChangedEventArgs.ProgressPercentage.
34 / 58
Passing Parameters
• If your background operation requires a parameter,
call RunWorkerAsync with your parameter.
• Inside the DoWork event handler, you can extract
the parameter from the
DoWorkEventArgs.Argument property.
35 / 58
Returning Results
• If your background operation needs to return a
result, set the DoWorkEventArgs.Result property in
your DoWork event handler after your operation is
finished.
• Inside the RunWorkerCompleted event handler of
your UI thread, you can access the result from the
RunWorkerCompletedEventArgs.Result property.
36 / 58
Assignment #6
1. Status Bar
Add a StatusBar with a TextBlock and a ProgressBar
to your MainWindow.
37 / 58
Assignment #6
2. Worker Threads
1. Modify your application and make creating new maps
happen in a background worker thread.
2. Your status text and progress bar should reflect the
progress of the map creation.
38 / 58
References
• MSDN. BackgroundWorker Class.
http://msdn.microsoft.com/en-
us/library/system.componentmodel.backgroundwo
rker%28v=vs.110%29.aspx, May 2016.
39 / 58
Thank you!
http://www.npruehs.de
https://github.com/npruehs
@npruehs
dev@npruehs.de
5 Minute Review Session
• What are two possible approaches for binary
serialization?
• What are the advantages and disadvantages of binary
serialization via interfaces?
• What are the advantages and disadvantages of binary
serialization via reflection?
• Why and when should you use a Background Worker in
your UI?
• How do you work with Background Workers?
• How do you pass data to and from Background
Workers?
41 / 58

Weitere ähnliche Inhalte

Ähnlich wie Tool Development 06 - Binary Serialization, Worker Threads

Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesnoahjamessss
 
Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filescskvsmi44
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worthIdan Sheinberg
 
Python with Firebird: FDB driver 101
Python with Firebird: FDB driver 101Python with Firebird: FDB driver 101
Python with Firebird: FDB driver 101Marius Adrian Popa
 
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...CanSecWest
 
TDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirTDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirWix Engineering
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdfTamiratDejene1
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaMatthias Noback
 
Defcon 27 - Writing custom backdoor payloads with C#
Defcon 27 - Writing custom backdoor payloads with C#Defcon 27 - Writing custom backdoor payloads with C#
Defcon 27 - Writing custom backdoor payloads with C#Mauricio Velazco
 
C # (C Sharp).pptx
C # (C Sharp).pptxC # (C Sharp).pptx
C # (C Sharp).pptxSnapeSever
 
Db2 version 9 for linux, unix, and windows
Db2 version 9 for linux, unix, and windowsDb2 version 9 for linux, unix, and windows
Db2 version 9 for linux, unix, and windowsbupbechanhgmail
 
DEF CON 27 - workshop - MAURICIO VELAZCO - writing custom paylods
DEF CON 27 - workshop - MAURICIO VELAZCO - writing  custom paylodsDEF CON 27 - workshop - MAURICIO VELAZCO - writing  custom paylods
DEF CON 27 - workshop - MAURICIO VELAZCO - writing custom paylodsFelipe Prado
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumMatthias Noback
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and outputRiccardo Cardin
 
Technical Report Vawtrak v2
Technical Report Vawtrak v2Technical Report Vawtrak v2
Technical Report Vawtrak v2Blueliv
 
W3C HTML5 KIG-Typed Arrays
W3C HTML5 KIG-Typed ArraysW3C HTML5 KIG-Typed Arrays
W3C HTML5 KIG-Typed ArraysChanghwan Yi
 

Ähnlich wie Tool Development 06 - Binary Serialization, Worker Threads (20)

Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-files
 
Devry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-filesDevry cis-170-c-i lab-7-of-7-sequential-files
Devry cis-170-c-i lab-7-of-7-sequential-files
 
JNA - Let's C what it's worth
JNA - Let's C what it's worthJNA - Let's C what it's worth
JNA - Let's C what it's worth
 
Python with Firebird: FDB driver 101
Python with Firebird: FDB driver 101Python with Firebird: FDB driver 101
Python with Firebird: FDB driver 101
 
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
CSW2017 Henry li how to find the vulnerability to bypass the control flow gua...
 
TDD With Typescript - Noam Katzir
TDD With Typescript - Noam KatzirTDD With Typescript - Noam Katzir
TDD With Typescript - Noam Katzir
 
File handling
File handlingFile handling
File handling
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdf
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony Barcelona
 
Defcon 27 - Writing custom backdoor payloads with C#
Defcon 27 - Writing custom backdoor payloads with C#Defcon 27 - Writing custom backdoor payloads with C#
Defcon 27 - Writing custom backdoor payloads with C#
 
using System.docx
using System.docxusing System.docx
using System.docx
 
C # (C Sharp).pptx
C # (C Sharp).pptxC # (C Sharp).pptx
C # (C Sharp).pptx
 
Db2 version 9 for linux, unix, and windows
Db2 version 9 for linux, unix, and windowsDb2 version 9 for linux, unix, and windows
Db2 version 9 for linux, unix, and windows
 
DEF CON 27 - workshop - MAURICIO VELAZCO - writing custom paylods
DEF CON 27 - workshop - MAURICIO VELAZCO - writing  custom paylodsDEF CON 27 - workshop - MAURICIO VELAZCO - writing  custom paylods
DEF CON 27 - workshop - MAURICIO VELAZCO - writing custom paylods
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
 
Technical Report Vawtrak v2
Technical Report Vawtrak v2Technical Report Vawtrak v2
Technical Report Vawtrak v2
 
Dynamic Proxy by Java
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by Java
 
W3C HTML5 KIG-Typed Arrays
W3C HTML5 KIG-Typed ArraysW3C HTML5 KIG-Typed Arrays
W3C HTML5 KIG-Typed Arrays
 

Mehr von Nick Pruehs

Unreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsUnreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsNick Pruehs
 
Unreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceUnreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceNick Pruehs
 
Unreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesUnreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesNick Pruehs
 
Unreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayUnreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayNick Pruehs
 
Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorNick Pruehs
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkNick Pruehs
 
Game Programming - Cloud Development
Game Programming - Cloud DevelopmentGame Programming - Cloud Development
Game Programming - Cloud DevelopmentNick Pruehs
 
Game Programming - Git
Game Programming - GitGame Programming - Git
Game Programming - GitNick Pruehs
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameNick Pruehs
 
Designing an actor model game architecture with Pony
Designing an actor model game architecture with PonyDesigning an actor model game architecture with Pony
Designing an actor model game architecture with PonyNick Pruehs
 
Game Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationGame Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationNick Pruehs
 
Scrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsScrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsNick Pruehs
 
Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Nick Pruehs
 
What Would Blizzard Do
What Would Blizzard DoWhat Would Blizzard Do
What Would Blizzard DoNick Pruehs
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsNick Pruehs
 
Tool Development A - Git
Tool Development A - GitTool Development A - Git
Tool Development A - GitNick Pruehs
 
Game Programming 11 - Game Physics
Game Programming 11 - Game PhysicsGame Programming 11 - Game Physics
Game Programming 11 - Game PhysicsNick Pruehs
 
Game Programming 09 - AI
Game Programming 09 - AIGame Programming 09 - AI
Game Programming 09 - AINick Pruehs
 
Game Development Challenges
Game Development ChallengesGame Development Challenges
Game Development ChallengesNick Pruehs
 
Game Programming 08 - Tool Development
Game Programming 08 - Tool DevelopmentGame Programming 08 - Tool Development
Game Programming 08 - Tool DevelopmentNick Pruehs
 

Mehr von Nick Pruehs (20)

Unreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual EffectsUnreal Engine Basics 06 - Animation, Audio, Visual Effects
Unreal Engine Basics 06 - Animation, Audio, Visual Effects
 
Unreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceUnreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User Interface
 
Unreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesUnreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior Trees
 
Unreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayUnreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - Gameplay
 
Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal Editor
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game Framework
 
Game Programming - Cloud Development
Game Programming - Cloud DevelopmentGame Programming - Cloud Development
Game Programming - Cloud Development
 
Game Programming - Git
Game Programming - GitGame Programming - Git
Game Programming - Git
 
Eight Rules for Making Your First Great Game
Eight Rules for Making Your First Great GameEight Rules for Making Your First Great Game
Eight Rules for Making Your First Great Game
 
Designing an actor model game architecture with Pony
Designing an actor model game architecture with PonyDesigning an actor model game architecture with Pony
Designing an actor model game architecture with Pony
 
Game Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationGame Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance Optimization
 
Scrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small TeamsScrum - but... Agile Game Development in Small Teams
Scrum - but... Agile Game Development in Small Teams
 
Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)Component-Based Entity Systems (Demo)
Component-Based Entity Systems (Demo)
 
What Would Blizzard Do
What Would Blizzard DoWhat Would Blizzard Do
What Would Blizzard Do
 
School For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine BasicsSchool For Games 2015 - Unity Engine Basics
School For Games 2015 - Unity Engine Basics
 
Tool Development A - Git
Tool Development A - GitTool Development A - Git
Tool Development A - Git
 
Game Programming 11 - Game Physics
Game Programming 11 - Game PhysicsGame Programming 11 - Game Physics
Game Programming 11 - Game Physics
 
Game Programming 09 - AI
Game Programming 09 - AIGame Programming 09 - AI
Game Programming 09 - AI
 
Game Development Challenges
Game Development ChallengesGame Development Challenges
Game Development Challenges
 
Game Programming 08 - Tool Development
Game Programming 08 - Tool DevelopmentGame Programming 08 - Tool Development
Game Programming 08 - Tool Development
 

Kürzlich hochgeladen

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 

Kürzlich hochgeladen (20)

Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 

Tool Development 06 - Binary Serialization, Worker Threads

  • 1. Tool Development Chapter 06: Binary Serialization, Worker Threads Nick Prühs
  • 3. Objectives • To learn how to properly read and write binary files • To understand how to use worker threads in order to create reactive UIs 3 / 58
  • 4. Binary Serialization • Sometimes you’ll want to serialize data in a format other than plain text • As we have learned, this can basically be achieved using the BinaryReader and BinaryWriter classes in .NET 4 / 58
  • 5. Writing Binary Data To Files C# 5 / 58 // Collect information on the file to create. FileInfo fileInfo = new FileInfo("newFile.dat"); // Create new file. FileStream fileStream = fileInfo.Create(); // Create new binary writer. BinaryWriter binaryWriter = new BinaryWriter(fileStream); // Write data. binaryWriter.Write(23); binaryWriter.Write(true); binaryWriter.Write(0.4f); // Close file stream and release all resources. binaryWriter.Close();
  • 6. Reading From Binary Files C# 6 / 58 // Collect information on the file to read from. FileInfo fileInfo = new FileInfo("newFile.dat"); // Open file for reading. FileStream fileStream = fileInfo.OpenRead(); // Create new binary reader. BinaryReader binaryReader = new BinaryReader(fileStream); // Read data. int i = binaryReader.ReadInt32(); bool b = binaryReader.ReadBoolean(); float f = binaryReader.ReadSingle(); // Close file stream and release all resources. binaryReader.Close();
  • 7. Binary Serialization • However, writing and reading binary data in the right order can be tedious and very error-prone. • In most cases you’ll need arbitrary data to be read and written. • Even worse, your type hierarchy will evolve during development. • We’ll take a look at two more generic approaches that try to ensure mostly error-free binary serialization. 7 / 58
  • 8. Initial Situation C# 8 / 58 public class Address { public string PostCode; public string City; } public class OrderItem { public string Name; public float Price; } public class Order { public OrderItem Item; public Address ShipTo; }
  • 9. Challenge • In order to be able to automatically serialize and deserialize objects of type Order, • we need to recursively serialize and deserialize objects of type Address and OrderItem, • we must be able to read and write field values of primitive types (such as string or float), • and we must do so in the right order! 9 / 58
  • 10. Binary Serialization via Interfaces • All serializable classes implement a new interface IBinarySerializable. • Interface enforces methods for reading and writing binary data. • These methods can be called for all types that are referenced by serialized types. • Reading and writing data in the correct order relies on a correct implementation of the interface. 10 / 58
  • 11. Interface IBinarySerializable C# 11 / 58 public interface IBinarySerializable { void WriteBinary(BinaryWriter writer); void ReadBinary(BinaryReader reader); }
  • 12. Interface Implementations C# 12 / 58 public class Address : IBinarySerializable { public string PostCode; public string City; public void WriteBinary(BinaryWriter writer) { writer.Write(this.PostCode); writer.Write(this.City); } public void ReadBinary(BinaryReader reader) { this.PostCode = reader.ReadString(); this.City = reader.ReadString(); } }
  • 13. Interface Implementations C# 13 / 58 public class OrderItem : IBinarySerializable { public string Name; public float Price; public void WriteBinary(BinaryWriter writer) { writer.Write(this.Name); writer.Write(this.Price); } public void ReadBinary(BinaryReader reader) { this.Name = reader.ReadString(); this.Price = reader.ReadSingle(); } }
  • 14. Interface Implementations C# 14 / 58 public class Order : IBinarySerializable { public OrderItem Item; public Address ShipTo; public void WriteBinary(BinaryWriter writer) { this.Item.WriteBinary(writer); this.ShipTo.WriteBinary(writer); } public void ReadBinary(BinaryReader reader) { this.Item = new OrderItem(); this.Item.ReadBinary(reader); this.ShipTo = new Address(); this.ShipTo.ReadBinary(reader); } }
  • 15. Writing Binary Data C# 15 / 58 // Collect information on the file to create. FileInfo fileInfo = new FileInfo("newFile.dat"); // Create new file. FileStream fileStream = fileInfo.Create(); // Create new binary writer. BinaryWriter binaryWriter = new BinaryWriter(fileStream); // Write data. order.WriteBinary(binaryWriter); // Close file stream and release all resources. binaryWriter.Close();
  • 16. Reading Binary Data C# 16 / 58 // Collect information on the file to read from. FileInfo fileInfo = new FileInfo("newFile.dat"); // Open file for reading. FileStream fileStream = fileInfo.OpenRead(); // Create new binary reader. BinaryReader binaryReader = new BinaryReader(fileStream); // Read data. Order order = new Order(); order.ReadBinary(binaryReader); // Close file stream and release all resources. binaryReader.Close();
  • 17. Binary Serialization via Interfaces - Evaluation • Delegating the task of serialization to serialized classes increases code readability and makes debugging easier • However, every time a new type is introduced, you need to implement the interface again. • Reading and writing data in the correct order relies on a correct implementation of the interface. • Strictly spoken, this approach violates the principle of separation of concerns. 17 / 58
  • 18. Binary Serialization via Reflection • We create a new serialization class called BinarySerializer. • Similar to XmlSerializer, this class provides Serialize and Deserialize methods that reflect the fields of a given type. 18 / 58
  • 19. Class BinarySerializer C# 19 / 58 public void Serialize(BinaryWriter writer, object obj) { if (obj == null) { return; } // Reflect object fields. Type type = obj.GetType(); FieldInfo[] fields = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); // ...
  • 20. Class BinarySerializer C# 20 / 58 // ... foreach (FieldInfo field in fields) { // Check how the field value has to be serialized. object fieldValue = field.GetValue(obj); if (field.FieldType == typeof(string)) { writer.Write((string)fieldValue); } else if (field.FieldType == typeof(float)) { writer.Write((float)fieldValue); } else if (field.FieldType == typeof(int)) { writer.Write((int)fieldValue); } // ... } }
  • 21. Class BinarySerializer C# 21 / 58 foreach (FieldInfo field in fields) { // ... else if (!field.FieldType.IsPrimitive) { // Recursively serialize referenced types. this.Serialize(writer, fieldValue); } else { throw new ArgumentException( string.Format("Unsupported type for binary serialization: {0}. Cannot serialize fields of type {1}.", type, field.FieldType), "obj"); } } }
  • 22. Class BinarySerializer C# 22 / 58 public object Deserialize(BinaryReader reader, Type type) { // Create object instance. object obj = Activator.CreateInstance(type); // Reflect object fields. FieldInfo[] fields = type.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); // ...
  • 23. Class BinarySerializer C# 23 / 58 // ... foreach (FieldInfo field in fields) { object fieldValue; // Check how the field value has to be deserialized. if (field.FieldType == typeof(string)) { fieldValue = reader.ReadString(); } else if (field.FieldType == typeof(float)) { fieldValue = reader.ReadSingle(); } else if (field.FieldType == typeof(int)) { fieldValue = reader.ReadInt32(); } // ... } }
  • 24. Class BinarySerializer C# 24 / 58 foreach (FieldInfo field in fields) { // ... else if (!field.FieldType.IsPrimitive) { // Recursively deserialize referenced types. fieldValue = this.Deserialize(reader, field.FieldType); } else { throw new ArgumentException( string.Format("Unsupported type for binary deserialization: {0}. Cannot deserialize fields of type {1}.", type, field.FieldType), "type"); } // Set field value. field.SetValue(obj, fieldValue); } return obj; }
  • 25. Writing Binary Data C# 25 / 58 // Collect information on the file to create. FileInfo fileInfo = new FileInfo("newFile.dat"); // Create new file. FileStream fileStream = fileInfo.Create(); // Create new binary writer. BinaryWriter binaryWriter = new BinaryWriter(fileStream); // Write data. BinarySerializer serializer = new BinarySerializer(); serializer.Serialize(binaryWriter, order); // Close file stream and release all resources. binaryWriter.Close();
  • 26. Reading Binary Data C# 26 / 58 // Collect information on the file to read from. FileInfo fileInfo = new FileInfo("newFile.dat"); // Open file for reading. FileStream fileStream = fileInfo.OpenRead(); // Create new binary reader. BinaryReader binaryReader = new BinaryReader(fileStream); // Read data. BinarySerializer serializer = new BinarySerializer(); Order order = (Order)serializer.Deserialize(binaryReader, typeof(Order)); // Close file stream and release all resources. binaryReader.Close();
  • 27. Binary Serialization via Reflection - Evaluation • Newly created types don’t need to implement any interfaces. • Special cases (enums, nullable types, generics) need to be considered only once. • Serialization code is limited to very few lines, which in turn can be found in a single class. • However, serialization via reflection is significantly slower than via interfaces. • Reading and writing data in the correct order depends on the order the fields are declared in serialized types! 27 / 58
  • 28. Hint Never stop improving your error handling while developing! (e.g. missing default constructor, unexpected enum value, etc.) 29 / 78
  • 29. Background Workers • Time-consuming operations like downloads and database transactions can cause your UI to seem as though it has stopped responding while they are running. • BackgroundWorker class allows you to run an operation on a separate, dedicated thread. 30 / 78
  • 30. Background Workers 101 1. Create new BackgroundWorker object. 2. Add event handlers. 1. Perform your time-consuming operation in DoWork. 2. Set WorkerReportsProgress to true and receive notifications of progress updates in ProgressChanged. 3. Receive a notification when the operation is completed in RunWorkerCompleted. 3. Call RunWorkerAsync on the worker object. 31 / 78
  • 31. Gotcha! Don’t to manipulate any UI objects in your DoWork event handler! 32 / 78
  • 32. Background Worker and UI 33 / 78
  • 33. Reporting Progress • Calling ReportProgress on the background worker object causes the ProgressChanged event handler to be called in the UI thread. • In that event handler, the reported progress is available through the property ProgressChangedEventArgs.ProgressPercentage. 34 / 58
  • 34. Passing Parameters • If your background operation requires a parameter, call RunWorkerAsync with your parameter. • Inside the DoWork event handler, you can extract the parameter from the DoWorkEventArgs.Argument property. 35 / 58
  • 35. Returning Results • If your background operation needs to return a result, set the DoWorkEventArgs.Result property in your DoWork event handler after your operation is finished. • Inside the RunWorkerCompleted event handler of your UI thread, you can access the result from the RunWorkerCompletedEventArgs.Result property. 36 / 58
  • 36. Assignment #6 1. Status Bar Add a StatusBar with a TextBlock and a ProgressBar to your MainWindow. 37 / 58
  • 37. Assignment #6 2. Worker Threads 1. Modify your application and make creating new maps happen in a background worker thread. 2. Your status text and progress bar should reflect the progress of the map creation. 38 / 58
  • 38. References • MSDN. BackgroundWorker Class. http://msdn.microsoft.com/en- us/library/system.componentmodel.backgroundwo rker%28v=vs.110%29.aspx, May 2016. 39 / 58
  • 40. 5 Minute Review Session • What are two possible approaches for binary serialization? • What are the advantages and disadvantages of binary serialization via interfaces? • What are the advantages and disadvantages of binary serialization via reflection? • Why and when should you use a Background Worker in your UI? • How do you work with Background Workers? • How do you pass data to and from Background Workers? 41 / 58