SlideShare a Scribd company logo
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

More Related Content

Similar to 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-files
cskvsmi44
 
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
noahjamessss
 
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
Idan Sheinberg
 
Python with Firebird: FDB driver 101
Python with Firebird: FDB driver 101Python with Firebird: FDB driver 101
Python with Firebird: FDB driver 101
Marius 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 Katzir
Wix Engineering
 
File handling
File handlingFile handling
File handling
prateekgemini
 
00-intro-to-classes.pdf
00-intro-to-classes.pdf00-intro-to-classes.pdf
00-intro-to-classes.pdf
TamiratDejene1
 
The Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony BarcelonaThe Naked Bundle - Symfony Barcelona
The Naked Bundle - Symfony Barcelona
Matthias 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
 
using System.docx
using System.docxusing System.docx
using System.docx
KunalkishorSingh4
 
C # (C Sharp).pptx
C # (C Sharp).pptxC # (C Sharp).pptx
C # (C Sharp).pptx
SnapeSever
 
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
bupbechanhgmail
 
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
Felipe 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 2014
Matthias Noback
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
Matthias Noback
 
Java - Processing input and output
Java - Processing input and outputJava - Processing input and output
Java - Processing input and output
Riccardo Cardin
 
Technical Report Vawtrak v2
Technical Report Vawtrak v2Technical Report Vawtrak v2
Technical Report Vawtrak v2
Blueliv
 
Dynamic Proxy by Java
Dynamic Proxy by JavaDynamic Proxy by Java
Dynamic Proxy by Java
Kan-Han (John) Lu
 
W3C HTML5 KIG-Typed Arrays
W3C HTML5 KIG-Typed ArraysW3C HTML5 KIG-Typed Arrays
W3C HTML5 KIG-Typed Arrays
Changhwan Yi
 

Similar to 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
 

More from 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 Effects
Nick Pruehs
 
Unreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User InterfaceUnreal Engine Basics 05 - User Interface
Unreal Engine Basics 05 - User Interface
Nick Pruehs
 
Unreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior TreesUnreal Engine Basics 04 - Behavior Trees
Unreal Engine Basics 04 - Behavior Trees
Nick Pruehs
 
Unreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - GameplayUnreal Engine Basics 03 - Gameplay
Unreal Engine Basics 03 - Gameplay
Nick Pruehs
 
Unreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal EditorUnreal Engine Basics 02 - Unreal Editor
Unreal Engine Basics 02 - Unreal Editor
Nick Pruehs
 
Unreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game FrameworkUnreal Engine Basics 01 - Game Framework
Unreal Engine Basics 01 - Game Framework
Nick Pruehs
 
Game Programming - Cloud Development
Game Programming - Cloud DevelopmentGame Programming - Cloud Development
Game Programming - Cloud Development
Nick Pruehs
 
Game Programming - Git
Game Programming - GitGame Programming - Git
Game Programming - Git
Nick 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 Game
Nick 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 Pony
Nick Pruehs
 
Game Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance OptimizationGame Programming 13 - Debugging & Performance Optimization
Game Programming 13 - Debugging & Performance Optimization
Nick 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 Teams
Nick 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 Do
Nick 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 Basics
Nick Pruehs
 
Tool Development A - Git
Tool Development A - GitTool Development A - Git
Tool Development A - Git
Nick Pruehs
 
Game Programming 11 - Game Physics
Game Programming 11 - Game PhysicsGame Programming 11 - Game Physics
Game Programming 11 - Game Physics
Nick Pruehs
 
Game Programming 09 - AI
Game Programming 09 - AIGame Programming 09 - AI
Game Programming 09 - AI
Nick Pruehs
 
Game Development Challenges
Game Development ChallengesGame Development Challenges
Game Development Challenges
Nick Pruehs
 
Game Programming 08 - Tool Development
Game Programming 08 - Tool DevelopmentGame Programming 08 - Tool Development
Game Programming 08 - Tool Development
Nick Pruehs
 

More from 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
 

Recently uploaded

Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
UiPathCommunity
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
FilipTomaszewski5
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
christinelarrosa
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
DianaGray10
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
Pablo Gómez Abajo
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
ScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking ReplicationScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking Replication
ScyllaDB
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
Miro Wengner
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
Mydbops
 
From Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMsFrom Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMs
Sease
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
christinelarrosa
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
ScyllaDB
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
Ivo Velitchkov
 

Recently uploaded (20)

Session 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdfSession 1 - Intro to Robotic Process Automation.pdf
Session 1 - Intro to Robotic Process Automation.pdf
 
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeckPoznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
Poznań ACE event - 19.06.2024 Team 24 Wrapup slidedeck
 
Christine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptxChristine's Supplier Sourcing Presentaion.pptx
Christine's Supplier Sourcing Presentaion.pptx
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
What is an RPA CoE? Session 1 – CoE Vision
What is an RPA CoE?  Session 1 – CoE VisionWhat is an RPA CoE?  Session 1 – CoE Vision
What is an RPA CoE? Session 1 – CoE Vision
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
Mutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented ChatbotsMutation Testing for Task-Oriented Chatbots
Mutation Testing for Task-Oriented Chatbots
 
Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
ScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking ReplicationScyllaDB Tablets: Rethinking Replication
ScyllaDB Tablets: Rethinking Replication
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
JavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green MasterplanJavaLand 2024: Application Development Green Masterplan
JavaLand 2024: Application Development Green Masterplan
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
Must Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during MigrationMust Know Postgres Extension for DBA and Developer during Migration
Must Know Postgres Extension for DBA and Developer during Migration
 
From Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMsFrom Natural Language to Structured Solr Queries using LLMs
From Natural Language to Structured Solr Queries using LLMs
 
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptxPRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
PRODUCT LISTING OPTIMIZATION PRESENTATION.pptx
 
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyFreshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-Efficiency
 
Apps Break Data
Apps Break DataApps Break Data
Apps Break Data
 

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