IIIC 2026 0830 Programación Avanzada Sesión Virtual 2
Introduction to Tutorial 2 of Advanced Programming
Overview of the Session
- The tutorial is led by José Miguel Avendaño and runs from 6 to 8 p.m., with a recording planned for later publication on the UNED Systems Technology Chair's YouTube channel.
Recording Protocol
- Participants implicitly authorize their contributions to be recorded, including names, text, and audio for academic purposes.
- There are no geographic restrictions or time limits on the validity of this authorization.
Privacy Considerations
- Participants wishing to maintain privacy should use only first names or initials and keep microphones muted if they do not want their voices recorded.
Ethical Use of Artificial Intelligence at UNED
Guidelines for AI Usage
- AI should serve as a support tool rather than a substitute for personal reasoning or programming skills.
- Students must understand and defend their code; ethical use includes respecting human rights and data protection.
Permitted vs. Non-Permitted Uses
- AI can assist in brainstorming, research, writing improvement, and best practices but cannot replace full project development or lead to plagiarism.
Topics Covered in This Session
Key Topics
- The session will cover multi-threading, databases with ADO.NET, generic collections, and networking.
Project Submission Guidelines
Submission Requirements
- Ensure projects compile and execute correctly before submission; check that all necessary files are included.
Evaluation Criteria
- Projects that do not compile or execute correctly may receive a zero grade; exceptions apply only under justified circumstances.
Questions Regarding Project Development
Clarifications on Project Structure
- A student confirms understanding that projects should be developed separately as client-server applications per instructions provided by the professor.
Database Connection Discussion
Connecting Databases with Visual Studio
- The professor agrees to review database connection issues using an existing project as an example during the session.
Overview of Multi-threading Concepts
Important Definitions
- Key concepts include processes, multiprocessing, multithreading, threads, monitors, concurrency, and shared resources.
Thread Management Insights
Operating System Functionality
- Multitasking allows multiple processes theoretically running simultaneously through time-sharing by processors.
Attributes of Threads
Priority and State
- Threads have attributes such as priority (importance level assigned by the processor), which affects processing time allocation.
Lifecycle States of Threads
Understanding Thread States
- Running: actively executing tasks.
- Stopped: completed execution.
- Sleeping: waiting for resources (join).
- Blocked: waiting for resource availability.
Mutual Exclusion in Multi-threading
Resource Access Conflicts
- Mutual exclusion occurs when two threads attempt simultaneous access to a single resource (e.g., file writing).
Locking Mechanisms Explained
Preventing Resource Conflicts
- Locking ensures exclusive access to resources while one thread is using them; others must wait until it’s released.
Semaphore Utilization in Thread Management
Controlling Concurrent Access
- Semaphores limit how many threads can access a resource simultaneously; useful when dealing with slow servers like databases.
Importance of Thread Execution Order
Processor Handling Dynamics
- Execution order is determined by processor management based on thread priority rather than creation order.
Interface Management in Multi-threaded Applications
Parent vs Child Threads
- UI changes must be executed within the parent thread due to restrictions placed on child threads accessing UI elements directly.
Delegate Functions in UI Updates
Updating UI Elements Safely
- Delegate functions allow safe updates from child threads back to the main thread without causing application freezes.
Practical Examples of Thread Implementation
Console Application Demonstration
- An example shows how numbers are printed sequentially using both single-threaded and multi-threaded approaches demonstrating differences in execution flow.
Parameterized Thread Execution
Passing Parameters Between Threads
- Using parameterized thread start allows passing values into threads dynamically during execution enhancing functionality.
Resource Competition Issues
Managing Shared Resources Effectively
- When multiple threads compete for shared variables without proper management leads to inconsistent results requiring locks or semaphores for resolution.
Setting Thread Priorities
Impact on Execution Flow
- Assigning different priorities helps manage which thread executes first but does not resolve underlying resource competition issues alone.
Implementing Locks for Resource Protection
Ensuring Data Integrity
- Locks prevent concurrent access issues ensuring that once one thread accesses a critical section others must wait until it's released maintaining data integrity throughout operations.
Semaphore Example Demonstration
Controlling Access Through Semaphores
– An example illustrates semaphore usage where limited numbers of threads can enter critical sections at any given time preventing overload situations effectively managing system performance .
Overview of Thread Creation and Sub-processes
Creating Threads and Sub-processes
- The interface initiates thread creation, executing a method that generates sub-processes.
- A loop is established to create five sub-processes, each receiving a counter as a parameter.
Semaphore Functionality in Writing Output
Semaphore Usage
- A random number is generated and written to an output file using semaphore control.
- The semaphore indicates when the process is waiting to enter and when it has exited.
Introduction to Database Integration
Transitioning to Database Use
- Discussion shifts towards integrating a relational database into the project.
- Emphasis on briefly explaining database concepts without delving deeply into theory.
Understanding Relational Databases
Key Concepts of Relational Databases
- Relational databases organize data in tables with rows, columns, primary keys, and referential integrity.
- Relationships can be one-to-one, one-to-many (1:N), or many-to-many (N:M).
SQL Operations for Database Interaction
Common SQL Commands
- Essential SQL operations include SELECT and INSERT commands for data retrieval and insertion.
- Additional commands like WHERE, ORDER BY, and INNER JOIN are also mentioned for more complex queries.
Programming Namespaces for Database Access
Required Namespaces
- Important namespaces include System.Data along with OLEDB and SQL Client for database interaction.
Example Project Review
Revisiting Previous Examples
- An example from a previous session is revisited where employees can be added or checked through an interface.
Transitioning from Vectors to Lists
Data Structure Changes
- The current implementation uses vectors which need to be replaced with lists for better functionality.
Introduction to Collections
Understanding Lists
- Lists are generic collections that require specifying the data type upon definition (e.g., list of strings).
Types of Lists
Generic vs Non-generic Lists
- Focus will primarily be on generic collections due to their utility in the project context.
Defining Lists in Code
Implementation Details
- The transition from vector definitions to list definitions is demonstrated within the code structure.
Utilizing Autocomplete Features
Coding Efficiency
- Autocomplete features in coding environments help streamline list definitions by suggesting relevant code snippets.
Error Handling During List Implementation
Resolving Static Errors
- Errors arise due to static definitions; adjustments are made by removing unnecessary static declarations.
Simplifying List Additions
Adding Elements Efficiently
- Unlike vectors requiring positional specifications, lists allow direct additions without index references.
Business Logic Adjustments
Addressing Logical Errors
- Issues arise during employee consultation due to static class calls; instances must now be created correctly.
Correcting Return Types
Ensuring Proper Returns
- Functions must return lists instead of vectors; necessary changes are implemented throughout the codebase.
Finalizing Employee Addition Logic
Streamlining Employee Addition
- Manual entries previously included need removal so only database entries appear after corrections are made.
Interface Updates
Synchronizing Changes Across Interfaces
- Interface updates reflect backend changes ensuring consistency between user input fields and underlying logic.
Optimizing Combo Box Data Sources
Enhancing User Experience
- Instead of traditional loops, combo boxes utilize direct data sources improving efficiency in displaying ID types.
Establishing Database Connections
Configuration File Setup
- Connection strings must be defined within configuration files located at the presentation layer for effective database access.
Configuring Connection Strings
Setting Up Connection Parameters
- Proper connection string setup involves specifying server addresses accurately based on local configurations.
Implementing Constructor Logic
Saving Connection Strings
- Constructors should initialize connection strings effectively while managing potential errors during setup processes.
Finalizing Connection Setup
Installing Necessary Packages
- Ensure all required packages such as System.Data.SqlClient are installed properly before proceeding with connections.
Command Execution Preparation
- Define SQL commands clearly indicating what actions will be executed against the database once connected.
Using Statements Effectively
- Utilize 'using' statements efficiently ensuring automatic closure of connections post-execution enhancing resource management.
Reading Results from Database
- Implement reading mechanisms via SQL Data Readers capturing results returned from executed commands effectively.
Updating UI Based on DB Entries
- Ensure UI reflects accurate data pulled from databases eliminating any hardcoded values previously used.
Conclusion & Next Steps
- Prepare additional examples showcasing complete functionalities including both fetching & saving records within databases effectively.
Overview of Server and Client Connection
Introduction to Server and Client
- The session begins with a demonstration of how the server operates, highlighting its role in listening for client connections.
- The server starts listening at IP address 127.0.0.1 on port 3000, indicating readiness to accept client connections.
Connecting Clients
- A client connects using an identifier (123), which is logged by the server along with the connection timestamp.
- A second client instance is opened, connecting with identifier (789), further demonstrating multiple simultaneous connections.
Programming the Server
Server Configuration
- The server's programming involves defining an IP address and port number, setting it to listen for incoming clients.
- A thread is instantiated for continuous listening, ensuring that the server can handle multiple requests without blocking.
Handling Connections
- The state label updates to indicate that the server is actively listening; buttons are disabled during this process.
- An infinite loop allows the TCP listener to continuously check for incoming messages from clients.
Understanding Client Functionality
Client Connection Process
- The client's connect method validates user input before attempting a connection to ensure an identifier has been entered.
- Upon validation, a connection request is sent using predefined parameters such as IP address and port number.
Message Transmission
- After establishing a connection, a message indicating intent to connect is prepared and serialized into JSON format for transmission over the network.
Server Message Reception
Processing Incoming Messages
- When a message arrives at the server, it triggers a new thread dedicated to processing that specific message.
- The server deserializes incoming messages from JSON format back into C# objects for further handling.
Executing Commands
- Based on received parameters, commands are executed; in this case, logging connected clients or performing business logic checks occurs here.
Debugging Techniques
Setting Breakpoints
- Debugging involves placing breakpoints within both client and server code to observe execution flow and data handling in real-time.
Observing Execution Flow
- As breakpoints are hit during execution, developers can trace through each step of connecting clients and processing messages effectively.
Querying Data Example
Transitioning from Connection to Data Retrieval
- Moving beyond simple connections, an example demonstrates querying books by author where data transmission becomes bidirectional between client and server.
Implementing Queries
- In this scenario, methods like
get authorsare defined on the server side which execute SQL queries against a database to retrieve relevant information based on client requests.
Framework Recommendations
Choosing .NET Versions
- Discussion emphasizes using consistent framework versions across all project components (e.g., .NET 8 recommended).
Importance of Compatibility
- Ensuring all parts of a project use compatible framework versions prevents compilation errors due to mismatched dependencies.
Turn any video into a summary like this
YouTube links, meetings, lectures. With transcripts, search, and chat.