Week 1 Day 4

¡Supera tus tareas y exámenes ahora con Quizwiz!

Predicate<T> Delegate

A Predicate <T> variable represents a method that defines a set of criteria and determines whether the specified object meets those criteria. This type parameter is contravariant (of the type specified or less derived). Returns Boolean true if the obj meets the criteria defined within the method represented by this delegate; otherwise, false. It's customary (and much more common) to use a lambda expression rather than to explicitly define a delegate of type Predicate<T>. Each element of the points array is passed to the lambda expression until the expression finds an element that meets the search criteria. The lambda expression returns true if the product of the X and Y fields is greater than 100,000.

S: Single Responsibility Principle

A class should only have one responsibility. Changes to a part of the software should only be able to affect the specification of one class.

What do you need for XML Serialization?

For XML serialization, you need: • to apply the SerializableAttribute attribute • to the type to avoid an exception. • the object which will be serialized • a stream to contain the serialized object • a System.Runtime.Serialization.Formatter instance

Errors - Usage Errors

Usage errors occur due to faulty program logic and should be addressed though correction of the code rather than in handling an exception when it's thrown.

Exceptions Try/Catch/Finally

Usage of try/catch/finally block is to: • obtain and use resources in a try block • deal with exceptional circumstances in a catch block • release the resources in the finally block The finally block always runs.

O: Open-Closed Principle

"A class should be open for extensions but closed to modifications". Modules and classes must be designed in such a way that new functionality can be added when new requirements are generated. We can use inheritance and implement interfaces to do this.

Delegate - Step by Step

1. Create a method to assign to a delegate. 2. Create a delegate type (named Del) with the same return type and argument. 3. Instantiate a delegate type variable and assign to it the chosen function (DelegateMethod). The delegate variable is what gets passed to a function. 4. Invoke the delegate variable. If the original method (DelegateMethod) returns a value, it will be returned through the delegate variabel (handler).

Events - Subscribing

1. Define an event handler method whose signature matches the delegate signature for the event. 2. Use the addition assignment operator (+=) to attach an event handler to the event.

Delegate - Multicasting

A delegate can call more than one method when invoked. This is referred to as multicasting. To add an extra method to the delegate's (ordered) method invocation list use the addition assignment operators ('+' or '+='). • Reference arguments are passed sequentially to each method in turn. Any changes by one method are visible to the next method. • If any method in the method invocation list throws an uncaught exception, execution stops and the exception is passed to the caller of the delegate. • If the delegate has a return value and/or out parameters, it returns the return value and/or out parameters of the last method invoked. •To remove a method from the invocation list, use the subtraction or subtraction assignment operators (- or -=).

What can a query do?

A query can: 1. Retrieve a subset of the elements to produce a new sequence without modifying the individual elements. The query may then sort or group the returned sequence in various ways 2. Retrieve a sequence of elements but transform them to a new type of object. 3. Retrieve a singleton value about the source data, such as: • The number of elements that match a certain condition. • The element that has the greatest or least value. • The first element that matches a condition, or the sum of particular values in a specified set of elements.

LINQ - Query Expression Basics

A query is a set of instructions that describes what data to retrieve from a given data source (or sources) and what type and organization the returned data should have. A query expression is a query expressed in query syntax. The source data is organized logically as a sequence of elements of the same kind. For example: • a SQL database table contains a sequence of rows. • In an XML file, there is a "sequence" of XML elements • An 'in-memory' collection contains a sequence of objects. A query expression must begin with a from clause and must end with a select or group clause. Between the first from clause and the last select or group clause, it can contain one or more of: where, orderby, join, let and even more from clauses. You can also use the into keyword to enable the result of a join or group clause to serve as the source for additional query clauses in the same query expression. From an application's viewpoint, the specific type and structure of the original source data is not important. The application always sees the source data as an IEnumerable<T> or IQueryable<T> collection

LINQ - Query Variables

A query variable is any variable that stores a query instead of the result of a query. A query variable is always an enumerable type that will produce a sequence of elements when it is iterated over in a foreach statement or a direct call to its IEnumerator.MoveNext method.

Exceptions - Throw

A throw statement can be used in a catch block to re-throw the exception that is caught by the catch statement to that the next method up the stack receives it, too. You can catch one exception and throw a different exception. When you do this, specify the exception that you caught as the inner exception.

Events - Publishing Based on the EventHandler Pattern

All events in the .NET Framework class library are based on the EventHandler delegate. The standard signature of an eventHandler delegate defines a method that returns void. This method's first parameter is of type Object and refers to the instance that raises the event. Its second parameter is derived from type EventArgs and holds the event data. It is recommended that all events be based on the .NET Framework pattern by using EventHandler. The object that raises the event is called the event sender. The event is typically a member (method) of the event sender. To define an event, use the event keyword in the signature of your event class and specify the type of delegate for the event. Add a method that is marked as protected and virtual, conventionally named 'On[EventName]()' ('OnDataReceived()'). The method should take one parameter of object type EventArgs (or a derived type). Derived classes can override this method to change the logic for raising the event. A derived class should always call the 'On[EventName]()' method of the base class to ensure that registered delegates receive the event.

Exception Class - Hierarchy

All exceptions inherit from the Exception Class. All run-time exceptions inherit from the SystemException Class.

JSON - Deserialization (Sync and Async)

Deserialize from a file by using synchronous code. Read the file into a string. To deserialize from a file by using asynchronous code. Call the DeserializeAsync method.

LINQ - Method Expressions

As a rule when you write LINQ queries, it is recommended to use query syntax whenever possible and method syntax whenever necessary. Some queries must be expressed as method calls. Such as: • to retrieve the number of elements that match a specified condition. • to retrieve the element that has the maximum value in a source sequence

Binding - Overview

Binding - This process establishes a connection between an app UI and the data it displays. When the data changes its value, the elements (in memory) that are bound to the data reflect changes automatically. • Early Binding (AKA Static Binding, Static Dispatch, or Compile-Time Binding) - The compiler (or linker) directly associates a stack memory address to the function call. It replaces the call with a machine language instruction that tells the mainframe to leap to the address of the function. • Late Binding (AKA Dynamic Binding, Dynamic Dispatch, Dynamic Linkage, or Run-Time Binding) - is when an algorithm is created that uses a caller-supplied method that implements part of the algorithm (function pointers in C++). In .NET, late binding refers to overriding a virtual method. The compiler builds virtual tables for every virtual or interface method call which is used at run-time to determine the implementation to execute.

Delegate - Overview

Delegates are used to pass methods as arguments to other methods. This ability to refer to a method as a parameter makes delegates ideal for defining callback methods. A delegate is a type that represents references to methods with a defined parameter list and return type. When you instantiate a delegate, you can associate its instance with any method with a compatible signature and return type. You can invoke (call) the method through the delegate instance. Any accessible method or struct that matches the delegate type and return type can be assigned to the delegate. Delegates are object-oriented, type safe, and secure.

L: Liskov Substitution Principle

Derived classes must implement all the methods and fields of their parent. After implementing the methods and fields of the parent, you will be able to use any derived class instead of a parent class and it will behave in the same manner. This ensures that a derived class does not affect the behavior of the parent class. A derived class must be substitutable for its base class. Functions that use pointers of references to base classes must be able to use objects of derived classes without knowing it.

I: Interface Segregation Principle

Each interface should have a specific purpose or responsibility. A class shouldn't be forced to implement an interface when the class doesn't share the interfaces purpose. Large interfaces are more likely to include methods that not all classes can implement. Clients should not be forced to depend upon interfaces whose methods they don't use.

Events - Overview

Events enable a class or object to notify other classes or objects when something of interest occurs. The class that sends (or raises) the event is called the publisher and the classes that receive (or handle) the event are called subscribers. Events are a special kind of multicast delegate that can only be invoked from within the class or struct where they are declared (the "publisher" class). If other classes or structs subscribe to the event, their event handler methods will be called when the publisher class raises the event. To register for, and trigger an event: 1. the recipient creates a method designed to handle the event, then 2. creates a delegate for that method and 3. passes the delegate to the event source. 4. The source calls the delegate when the event occurs. 5. The delegate then calls the event handling method on the recipient, delivering the event data. The delegate type for a given event is defined by the event source.

Lambda Expression Form

Expression lambdas are used extensively in the construction of expression trees. An expression lambda returns the result of the expression. • Zero input parameters have empty ( ). • >2 input parameters are separated by commas enclosed in ( ). • You can optionally specify the types explicitly. • Input parameter types must be all explicit or all implicit. ex: (input-parameters) => expression

D: Dependency Inversion Principle

High-level modules/classes implement business rules or logic in a system (front-end). Low-level modules/classes deal with more detailed operations. They may deal with writing information to databases or passing messages to the operating system or services. When a class too closely uses the design and implementation of another class, it raises the risk that changes to one class will break the other class. So we must keep these high-level and low-level modules/classes loosely coupled as much as possible. To do that, we need to make both of them dependent on abstractions instead of knowing each other.

Errors - Program Errors

May reflect a routine error condition. Avoid using exception handling to deal with program errors. Instead prevent the exception by trying the action first. USE => DateTime.TryParseExact (returns a Boolean) DO NOT USE => DateTime.ParseExact (throws a FormatException exception)

Exceptions vs. Errors

Run-time errors can occur for a variety of reasons. Not all errors should be handled as exceptions in your code. There are three main types of run-time errors: • Usage Errors • An error in program logic that should be addressed not through exception handling but by modifying the faulty code. • Program Errors • a run-time error that cannot necessarily be avoided by writing bug-free code. • System Failures • a run-time error that cannot be handled programmatically in a meaningful way

S.O.L.I.D. - Overview

SOLID Principles is a coding standard that helps developers avoid bad design in software development. When applied properly, it makes code more extensible, more logical, and easier to read. Badly designed software can become inflexible and brittle. Small changes in the software can result in bugs that break other parts of the code.

Serialization - Uses

Serialization allows you to save and then recreate the state of an object. This allows storage of objects as well as data exchange. Serialization is useful when: • Sending the object to a remote application by using a web service • Passing an object from one domain to another • Passing an object through a firewall as a JSON or XML string • Maintaining security or user-specific information across applications

Errors - System Errors

Should not be handled by using exception handling. Any method can throw an OutOfMemoryException exception if the CLR is unable to allocate additional memory. You may be able to use an event such as AppDomain.UnhandledException and call the Environment.FailFast method notify the user before the application terminates

Func<TResult> Delegate

TResult is the type of the return value of the method that the Func<TResult> delegate encapsulates. This type parameter is covariant (use your specified type or a more derived type). Use Func<TResult> delegate to represent a method that can be passed as a parameter without explicitly declaring a custom delegate. The encapsulated method must correspond to the method signature that is defined by this delegate.

Exception Class

The Exception Class is the base class for all exceptions. When any error occurs, the system or the application throws an exception that contains information about the error. When an exception is thrown by a method far down the call stack, the CLR will unwind the stack, looking for a method with a catch block for that specific exception type and execute the first such catch block that it finds. If it finds no catch block in the call stack, it terminates the process and display a message to the user.

JSON - How-To

The System.Text.Json namespace contains classes for JSON serialization and deserialization. JSON Serialization serializes the public properties of an object into a string, byte array, or stream that conforms to the RFC 8259 JSON specification. To control the way JsonSerializer serializes or deserializes an instance of the class: • Use a JsonSerializerOptions object • Apply attributes from the System.Text.Json.Serialization namespace to classes or properties

Lambda Statement Form

The body of a statement lambda can consist of any number of statements. Statement lambdas cannot be used to create expression trees. ex: (input-parameters) => { <sequence-of-statements> }

Lambda Expression

There are two Lambda expression forms •Expression Lambda •Statement Lambda Specify input parameters to the left of the => and an expression or statement block to the right.

User-Defined Exceptions

To create custom exceptions, you must: • create your own exception classes • Derive(inherit) from the Exception class. • End the class name with the word "Exception". • Implement the three common constructors.

Events - Unsubscribing and Garbage Collection

To prevent your event handler from being invoked when the event is raised, unsubscribe from the event. In order to prevent resource leaks, you should unsubscribe from events before you dispose of a subscriber object. Until you unsubscribe from an event, the multicast delegate that underlies the event in the publishing object has a reference to the delegate that encapsulates the subscriber's event handler. As long as the publishing object holds that reference, garbage collection will not delete your subscriber object. When all subscribers have unsubscribed from an event, the event instance in the publisher class is set to null.

LINQ - Overview

Traditionally, queries against data (in a DB or file) have been expressed as simple strings without type-checking at compile time or IntelliSense. You'd have to learn a different query language for each type of data source: • SQL databases, • XML documents, • various Web services, etc. • With LINQ, a query is a language construct, just like classes, methods, events. • Query expressions are written in a declarative query syntax. • You can perform filtering, ordering, and grouping operations on data sources with minimum code. • You use the same basic query expression patterns to query and transform data in SQL databases, ADO.NET Datasets, XML documents and streams, and .NET collections. A complete LINQ query operation includes: • creating a data source, • defining the query expression, and • executing the query in a foreach statement. There are two Query Expression syntaxes: • Query Syntax • Method-Based Syntax

XML Serialization

XML Serialization serializes the public fields and properties of an object (or the parameters and return values of methods) into an XML stream that conforms to a specific XML Schema definition language (XSD) document. System.Xml.Serialization contains classes for serializing and deserializing XML. You apply attributes to classes and class members to control the way the XmlSerializer serializes or deserializes. • Apply the SerializableAttribute attribute to the property/field even if the class also implements the ISerializable interface. • When SerializableAttribute attribute is applied, all private and public fields are serialized. • XML serialization does not include type information. • You can control serialization by implementing the ISerializable interface to override the serialization process. • Exclude fields from serialization by applying NonSerializedAttribute to the field. • If a field of a serializable type contains a data structure that cannot be reconstituted in a different environment, apply the NonSerializedAttribute attribute to that field

Lambda Async/Await

You can easily create lambda expressions and statements that incorporate asynchronous processing by using the async and await keywords. For example, the following Windows Forms example contains an event handler that calls and awaits an async method, ExampleMethodAsync. public partial class Form1 : Form { public Form1() { InitializeComponent(); button1.Click += button1_Click; } private async void button1_Click(object sender, EventArgs e) { await ExampleMethodAsync(); textBox1.Text += "\r\nControl returned to Click event handler.\n"; } private async Task ExampleMethodAsync() { // The following line simulates a task-returning asynchronous process. await Task.Delay(1000); } }

Action and Action<T> Delegate

You can use an Action delegate to pass a method as a parameter without explicitly declaring a custom delegate. Action Delegates always return void. The encapsulated method must correspond to the parameter list defined by the Action delegate and return void.

JSON - Deserialization Behavior

• By default, property name matching is case-sensitive. You can specify case-insensitivity. • read-only properties are ignored. No exception is thrown. • Deserialization to reference types without a parameter-less constructor is not supported. • Deserialization to immutable objects or read-only properties isn't supported. • By default, enums are supported as numbers. You can serialize enum names as strings. • Fields aren't supported. • Comments or trailing commas in the JSON throw exceptions. You can explicitly allow comments and trailing commas. • The default maximum depth is 64. • Learn to "Pretty-Print" your JSON

Exceptions - Try/Catch Block

• Generally, when an exception is thrown, the CLR unwinds the stack looking for the appropriate catch statement. If no catch block is found, then the CLR displays an unhandled exception message to the user and stops execution of the program. • The try/catch statement consists of a try block followed by one or more catch clauses, which specify handlers for different exceptions. The try block contains the guarded code that may cause the exception. The block is executed until an exception is thrown or it is completed successfully. • Using multiple catch arguments is a way to filter for the exceptions you want to handle.

Events - Properties

• publisher - determines when an event is raised; the subscribers determine what action is taken in response to the event. • event - can have multiple subscribers. A subscriber can handle multiple events from multiple publishers. • Events are typically used to signal user actions such as button clicks or menu selections in graphical user interfaces. • When an event has multiple subscribers, the event handlers are invoked synchronously. • In the .NET Framework class library, events are based on the EventHandler delegate and the EventArgs base class.

Lambda Conversion to Delegate

•Any lambda expression can be converted to a delegate type. •The delegate type to which a lambda expression can be converted is defined by the types of its parameters and return value. •If a lambda expression doesn't return a value, a) it can be converted to one of the Action<> delegate types. a1) A lambda expression that has two parameters and returns void can be converted to an Action<T1,T2> delegate. •If a lambda expression returns a value, a) it can be converted to a Func<> delegate type. a1) A lambda expression that has one parameter and returns a value can be converted to a Func<T,TResult> delegate.

JSON - JavaScript Object Notation

•JSON is a popular type of serialization provided in .NET by the System.Text.Json namespace. •All public properties are serialized and you can specify which properties to exclude. •JSON is by default 'minified', but you can 'pretty-print' it. •Casing of JSON names matches the .NET model names. You can customize JSON name casing. •Circular references are detected and exceptions thrown. •Fields are excluded.


Conjuntos de estudio relacionados

The Growth of Industrial Prosperity: The Second Industrial Revolution

View Set

Lippencott chapter 2 complications of pregnancy, missed questions, maternity

View Set

Odyssey American Government Ch 3 section 3

View Set

PHARM HESI PRACTICE QUESTIONS (SAUNDERS)

View Set