Show Menu
Cheatography

CS 3500 Final Notes Cheat Sheet (DRAFT) by

CS 3500 Final Exam notes.

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Networking

Key Networking Issues -Data Arrival
You never know how much data will arrive at any given time Some or all may “Show up” - What does arrive will be in order Therefore: all data concat­ena­ted­/stored Search “all data” for messages Protocol of “what is a message?” Newlin­e/P­eri­od/etc.
Key Parts to Networking Object
Callbacks -This is how the network code commun­icates state to the “user” program TcpCli­ent­/Tc­pLi­stener objects -The main object you will be using See Simple­Cha­t[C­lie­nt/­Ser­ver­]Tc­pClient code ID -A unique identifier for the connection Settable (default → socket)

DataBase Principles - SQL and C# Interface to DB

 

Good Software Practices

GSPs refer to tools, techni­ques, processes, etc., that are used to ensure our code is:
Easier to maintain Contains fewer defects
Examples include:
Versioning (git/g­ith­ub/­github projects) Design Patterns System Archit­ecture decisions (e.g., MVC) SOLID, DRY Diagra­mmi­ng/UML Testing Unit Testing, Integr­ation Testing, open/c­los­ed-box testing, C# test syntax, e.g., TestCl­ass­()]…)
Self Docume­nting Code
“Self-­doc­ume­nting code is ostensibly written using human-­rea­dable names, typically consisting of a phrase in a human language which reflects the symbol’s meaning…”
Refact­oring
Changing code (often automa­tic­ally) to be more mainta­inable
Refact­oring Techniques 1
Inline Temp That being said: Extract Variable (Self-­Doc­ume­nting Code) Decomp­ose­-co­ndi­tional Split-­tem­por­ary­-va­riable Self-e­nca­psu­lat­e-field
Refact­oring Techniques 2
Extrac­t-i­nte­rface Extrac­t-m­ethod Consol­ida­te-­dup­lic­ate­-co­ndi­tio­nal­-fr­agments
Refact­oring Techniques 3
Hide-m­ethod Replac­e-e­xce­pti­on-­wit­h-test Extrac­t-class What SOLID is this?
Visual Studio (to the rescue!?!)
Visual Studio support… None – Some operations will be done by hand Some – Some operat­ions, like renaming can be done quickly. A lot – Some operat­ions, like method extrac­tion, can be done comple­tely!
Visual Studio (to the rescue!?!) Continued
Note: you cannot extract private methods to an interface… this doesn’t make sense as interfaces expose functi­ona­lity. Note 2: Phase1 and Phase2 are probably poor examples of where you would create an interface.
Code Analysis
Apply computer programs to Analyze and Improve computer progra­mming Code Analysis Tools Complexity Analysis - e.g., how many lines of code Duplicate Code Analysis - e.g., could be refactored into methods Style Guides - e.g., put spaces around parameters Code Cleanup - e.g., remove unused using statements
Code Analysis Continued
Code Analysis is run upon compil­ation Shown as warnin­gs/­mes­sages in Error List
Code Cleanup
Auto-Tools for “cleaning up” code base E.G., remove unnece­ssary usings Many of the “sugge­stions” you see with the underline squigglys Note: All “styles” should be agreed upon by team at start of develo­pment
Design Patterns
Design Patterns Well understood and beneficial ways to effect­ively solve recurring problems Anti-P­atterns Common ways of solving problems that have unintended side effects. Examples included: Iterator, and Null object
Design Pattern -Iterator
collection = new List( … ) Foreach (var x in collec­tion) collection = new Dictio­nary( … ) Foreach (var x in collec­tion) collection = new Tree( … ) Foreach (var x in collec­tion) They all work and collection Type can even be changed without changing the loop! We don’t care how the Data Structure iterates, just that it does Aside: How does a Dictionary iterate?
Design Pattern -Null Object
// BAD Logger logger = null; If (logger != null) logger.Lo­gDe­bug­(...); // GOOD Logger logger = NullLo­gge­r.I­nst­ance; logger.Lo­gDebug( … )
Anti-P­attern: Hard Coded Constants
All constants in your code should be replaced by named consta­nts­/re­ad-only variables What is difference between read only and const? All loops/­dat­a-s­tru­ctu­res­/etc., should be able to handle “any size” of data.
Anti-P­attern: Premature Optimi­zation
Don’t write complex code to speed up a potential bottle­neck. _DO_ use well known data structures and worry about Big O (Compl­exity). Optimize when you have empirical evidence that what you think is the bottle­neck, actually is. Next Lecture → Profiling
Rigor
Docume­nting Subdiv­iding (separ­ation of concerns) Big methods broken into multiple small methods Big tasks broken into multiple small tasks Hard Tasks “appro­xim­ated” first Naming Debugging
Software Practice Principles
Understand the problem you are trying to solve Seek clarif­ication of requir­ements early Approach each step in isolation Toy programs Separation of concerns Iterate - small steps Use versioning often
 

MAUI/GUI

Dispatcher
Dispatcher Puts requests for GUI changes into a queue When the GUI thread “has a chance”, take care of requests in queue Always runs on GUI thread Warning - More than one thread (GUI + networ­kin­g(s)): LOCKING!!! If your GUI thread deals with an object that a networking thread also uses, you must protect the code using locks!
MVC in A7
Tendency is to write all of our logic together Assignment 7 Server “logics” Networking ← Model GUI ← View/C­ont­roller Connected Clients ← Model
Separation of concerns GUI server
Everything to do with storing multiple clients should be “abstr­acted” (i.e., put into a model class) Everything to do with Networking should be put into the Networking class Everything to do with the GUI should stay in the GUI class
GUI/Ne­twork Multi-­thr­eading
Guis are generally multi-­thr­eaded, -unless your GUI doesnt do any processing that requires time, you must use a BG worker to do the work so the GUI remains respon­sive. Networking code is multi-­thr­eaded.
Invalidate
Invalidate i.e., PlaySu­rfa­ce.I­nv­ali­date(); Can be called anywhere (not just on GUI thread) Tell GUI Thread: At next opport­unity, redraw the affected region Suggested Options Always (inside Draw Scene) → BAD :( “Burns” cycles On Message Received → Locked with Server → Okay Timer → X times per second → Good as well Especially if your client did “inter­pol­ation”!
Dispat­ching
All GUI updates must be done on the GUI thread (thread 1) When there are multiple threads in your program Any access to the GUI should be through the Dispat­cher.

Basic Web Server ideas, e.g. HTTP/H­TML/CSS

Web Server
Simply a program that listens on a port for a connection (e.g., from a web browser) and sends back web pages Using HTTP Hypertext transport protocol
HTTP Sequence
Point browser to a web server, e.g., http:/­/ww­w.w­ebp­age.com Browser opens socket to address Server accepts socket Browser sends text: “GET / HTTP/1.1” + stuff Server replies with text: “HTTP/1.1 200 OK …” + “<h­tml­>…<­/ht­ml>” Server closes socket – every HTTP request uses a new connection
Protocol
hwww.k­han­aca­dem­y.org hypert­ext­-tr­ans­fer­-pr­oto­col­-http Just a bunch of strings sent through sockets on the net… Request, e.g., GET / HTTP/1.1 Host: www.cs.ut­ah.edu Response, e.g., HTTP/1.1 200 OK Conten­t-Type: text/html; charse­t-UTF-8
HTTP Web Response
Just a string that follows the protocol, e.g., Header [New Line] Body. Example: HTTP/1.1 200 OK\n Connec­tion: close\n Conten­t-Type: text/html; charse­t=U­TF-8\n \n <text or html>
HTML Body Example
<!D­OCTYPE html> <!-- From w3schools –> <ht­ml> <bo­dy> <h1­>My First Headin­g</­h1> <p>My first paragr­aph.</­p> </b­ody> </h­tml>
URL
Uniform Resource Locator scheme­://­hos­t:p­ort­/pa­th?­query scheme → protocol (e.g. ftp, http, https) host → server name or address e.g. www.cs.ut­ah.edu Port → 80/443 by default We will continue to use 11000
HTML Keywords
HTML very similar to XML Headers → h1, h2, h3, … Paragraph → <p> … </p> Image → <img src=”url” alt=”e­ngl­ish­”/> Format → <b> bold, <u> underline, etc. Logical Divisions → <di­v> Document → <do­cty­pe> Link -> <a …> Many more
URL -Path
scheme­://­hos­t:p­ort­/path path → file/d­ire­cto­ry/page to access Optional Default is assumed to be file “index.html” Interp­reting path is entirely up to the server www.cs.ut­ah.edu/germain www.tw­itt­er.c­om­/search https:­//w­ww.g­oo­gle.co­m/s­ear­ch?­q=a­bc&oq­=ab­c&­aqs­=ch­rom­e..6­9i­57j­0l6­j46.55­2j0­j7&so­urc­eid­=ch­rom­e&­ie=­UTF-8

C#

Compiler Optimi­zation in C#
In C#, we don’t have much control Optimi­zation is done by the runtime (JIT) And partly by the CIL compiler https:­//w­ww.g­ee­ksf­org­eek­s.o­rg/­wha­t-i­s-j­ust­-in­-ti­me-­jit­-co­mpi­ler­-in­-do­t-net/ This is fine for most purposes C# is not the language of choice for (super) high perfor­mance…
Micro Optimi­zation - Data Access
Accessing data in certain patterns (order) can be faster than others Caching Memory system Prefet­ching
When to "­Micro Optimi­ze"
If you’ve picked all the right algori­thms… …and profiled everything …and it’s still not fast enough Then maybe start micro-­opt­imizing Learn more about this in CS 4400 Games and graphics need a lot of this
Profiling
First, determine where our program spends time. Every once-i­n-a­-while, stop the program and examine where it is executing (Sampling) Accumulate samples over time – attribute them to methods “Once-­in-­a-w­hile” is on the order of millis­econds
 

Logging

Logging Definition
Logging is the act of recording inform­ation about the what is happening during the run time of your program
Logs can be sent to one or more of the following:
Console Debug Display in Visual Studio GUI Files Databases Windows Event Log Etc.
Log Levels
Some inform­ation is more important (to certain people) than other. Too much inform­ation is often not useful. Log Levels Refers to how much and how “high a level” (or low) the inform­ation is E.g. Debug vs Critical Error
0 Trace
every little detail.. way too much inform­ati­on... turn this off most of the time Stakeh­older: Developer - Something really odd is going on… Show me all the mouse X,Y values as the mouse traverses the screen
1 Debug
standard detail level... usually too much info to store... use this for develo­pment Stakeh­older: Developer - Standard Develo­pment Cycle Show me every collision between two objects in the game
2 Inform­ation
high level inform­ati­on... for example "when a client connec­ts"... use this to understand "­met­a-l­eve­l" of applic­ation Stakeh­older: Develo­per­/Site Admini­strator Show me who logged into the system.
3 Warning
something is probably going wrong, but we haven't handled it yet Stakeh­older: Develo­per­/Site Admini­strator Show me when an unauth­orized user attempts to access data
4 Error
something has gone wrong and we didn't know how to (or didn't want to spend the time) to handle it Stakeh­olders: Site Admini­str­ators, Project Lead, (Devel­oper) Bank software cannot transfer to another bank
5 Critical
the applic­ation is about to die... can we do it gracef­ully? Stakeh­olders: Site Admini­str­ator, Project Lead Bank software “died” because database is not accessible
6 None
turn off messaging. Reasons to do: My code is perfect. Disk space is very expensive. (Note: neither of these are a reason to do this, nor are they true)
Where in Code to place Logging
Any “big” action Connection on the net Any “compl­icated” action For debugging complete message building Any “catas­tro­phic” event Let developer manager know where to go back to look for problem
Example of levels to log messages at
Position of mouse _logge­r.L­ogT­race($ “{Mous­ePo­sit­ion}” ); Partial messages coming over internet _logge­r.L­ogD­ebug( $”Data Receive: {data}” ); Inform­ation (or maybe just warning) New Chat Client Connected _logge­r.L­ogI­nfo­rma­tion( $” {name} connected from {ip_ad­dress}” );
Setting Up Logger on a C# program
To (corre­ctly) use Loggers and Dependency Injection, you must instrument the following places of your code: The Main Program The Class Constr­uctor Class Methods

Threading

Async
Async methods should do “somet­hing” that may take a long time E.g., DB lookup, network connec­tion, big comput­ation
Await
await keyword tells program to “yield” cpu to other tasks while the long running operation completes Then resume at the given line when task is done WARNING: may be on a different thread
Networking and GUI → Threads
Network commun­ica­tions come in “Async” Handled on DIFFERENT threads GUI work MUST BE DONE on the GUI thread Solution: Dispat­che­r.D­isp­atch( ( ) => { Messag­esA­ndS­tat­us.Text = $"Server Shutdo­wn!­" + Enviro­nme­nt.N­ew­Line; }
Which thread is running
Use: Enviro­nme­nt.C­ur­ren­tMa­nag­edT­hreadId Print this next to every log message to help you understand what is going on. If value != 1, then not the GUI thread! Also Remember: Debug Window Parallel Stacks
Race Condition
The Clients list is “shared” by all threads, thus becoming a Race Condition How do we fix this? Answer: locking! Warning for Server: Don’t “hold on to” client list while doing lots of work (e.g., sending messages to all clients) Copy client list (while locked) Then iterate over the copied list!
Race Condition Continued
GUI and Networking code use Threads to execute Any object that is referenced in methods that may be executing simult­ane­ously in two or more threads MUST lock the data * Why is “lock the data” misleading in the statement above?

Dependency Injection

Key Ideas:
Code (objects) need other Code (objects) to work (or to be more effective) Databases, Loggers, UserMa­nagers, etc.,
Where do those other objects come from?
Static Globals? Parame­ters?
Summary
Objects that need other objects to help do their job Want to be able to use different objects without modifying source code: Define functi­onality as an interface Pass object in at constr­uction time (and save in class field) Important: only works for classes that the “system” builds for you E.g., you MAUI program MainPage!
 

JSON/S­eri­ali­zation

JSON Serial­ization -Default Option
What constr­uctor is used BEFORE data put in: Default constr­uctor What is serial­ized? Public properties What is not serial­ized? Fields, private properties How do we change that? Attributes (Metadata Tags)
JSON Serial­ization "­Rec­urs­ion­"
Is it recursive? Yes - all objects inside public Properties are also serial­ized. Deep Copy (not shallow copy) “Cloning” ?? Circular References ??
JSON De/Ser­ial­ization
Reflection Runtime - inspect code Deseri­ali­zation Calls default constr­uctor *(or constr­uctor that matches field names in JSON string). “Finds” the names of the properties Reads the JSON looking for matching names Puts data directly into properties Serial­ization “Finds” names of properties and auto-g­ene­rates json string
JSON Attribute Tags and Options
[JsonC­ons­tru­ctor] Specify the specific constr­uctor to use Constr­uctor parameters must match names of Json Fields [JsonI­nclude] Force property to be part of the serial­ization [JsonI­gnore] For property to not be part of the serial­ization [JsonR­equire] If field _not_ there then error
Parsing JSON ex
Food f = new Food(); List<F­ood> list = new(); list.A­dd(f); message = JsonSe­ria­liz­er.S­er­ialize( list ); JsonSe­ria­liz­er.D­eS­eri­ali­ze<­Lis­t<F­ood­>>( message ); DeSeri­ali­ze(­mes­sage, new List<F­ood­>().Ty­pe()) {CMD_F­ood­}[{­X:5­0,Y­:50­,ID­:5..},...]
JSON – Message Passing Optimi­zation
Content of message (JSON string) is “too big” for value, i.e., we can compress the inform­ation in the JSON string into _far_ fewer bytes. What are we doing to do about it? Answer: Nothing

MVC

MVC for Agario
World status should be its own class (Model) GameClient intera­ctions should be its own class Have important methods like: Handle­Mes­sag­eFr­omS­erver( … ) SendMo­veR­equ­est­ToS­erver( … ) Uses a World object Networking code Updates client with messages GUI code Reads client’s World inform­ation and draws it Need to make all references to client­/world Thread Saf
MVC for Agario Continued
Start simple. Put most/all code in MainPa­ge.x­aml.cs As you start to see patterns, build helper classes to handle them Then in the later stages of develo­pment review code such that MainPa­ge.x­aml.cs is very short. See “refac­toring” idea of extracting methods.

SQL

 

CS 3500

Purpose of CS 3500
What is it you are supposed to learning in CS 3500? CS 3500 is primarily about learning to: Solve complex problems with software Afterall, software rules the world And that, that software should Contains fewer defects Be more mainta­inable
Mainta­ina­ble­/Te­stable Software
Simple (as possible) Organi­zed­/Ar­chi­tected (e.g., MVC) SOLID (e.g., Separation of Concer­ns/­Single Respon­sib­ility) DRY Docume­nte­d/C­omm­ent­ed/­Des­cri­bable READMEs Pictur­es/­Fig­ure­s/UML Testable
Teamwork
Working with another developer Versio­ning, e.g., git usage Iterating Asking questions Discussing
Components software systems will need
Databases Networking (e.g., client­/server archit­ecture) Multi-­thr­eading GUI Logging
IDE
IDE support - Visual Studio Debug tools Optimi­zation tools Database interface tools Multi-­Arc­hit­ecture Deployment (e.g., MAUI) Intell­isense Copilot?, GPT? XML docume­ntation
C# Progra­mming
C# is one of many choice (albeit a good one) it could have been C++, or Ruby, or Python, or Java, or Go, or …. What are elements of the language that support GSPs? Long winded essay question possib­ility: “Describe multiple reasons we should use C# on our next project to support making mainta­inable software?”
Some Niceties of the C# Language
Functions as Values - Delegates, Event Handlers, etc. Lambdas, Closures Events - Design code around events “happe­ning” Threading OOL, Library support Exceptions Garbage collection GUI Support Much much more.