Fix typos

This commit is contained in:
Marcello 2021-09-20 19:35:32 +02:00
parent 76550dfa3c
commit 5c0799df7f
118 changed files with 1150 additions and 1602 deletions

View file

@ -73,7 +73,7 @@ namespace App
// or
services.AddControllers(); // controllers w/o views
//or
sevices.AddControllersWithViews(); // MVC Controllers
services.AddControllersWithViews(); // MVC Controllers
//or
services.AddServerSideBlazor(); // needs Razor Pages
@ -147,7 +147,7 @@ Connection Strings & Secrets.
## `launchsettings.json`
Launch Settings & Deployement Settings.
Launch Settings & Deployment Settings.
```json
{

View file

@ -16,7 +16,7 @@ The component class is usually written in the form of a Razor markup page with a
## Project Structure & Important Files
### Blazor Server Project Stucture
### Blazor Server Project Structure
```txt
Project
@ -45,7 +45,7 @@ Project
|- App.razor --> component root of the app
|
|- appsettings.json --> application settings
|- Program.cs --> App entrypoint
|- Program.cs --> App entry-point
|- Startup.cs --> services and middleware configs
```
@ -78,7 +78,7 @@ Project
|- App.razor --> component root of the app
|
|- appsettings.json --> application settings
|- Program.cs --> App entrypoint
|- Program.cs --> App entry-point
```
### Blazor PWA Project Structure

View file

@ -1,6 +1,6 @@
# [Filters](https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/filters)
**Filters** in ASP.NET Core allow code to be run *before* or *after* specific stages in the request processing pipeline.
**Filters** in ASP.NET Core allow code to be run _before_ or _after_ specific stages in the request processing pipeline.
Built-in filters handle tasks such as:
@ -11,7 +11,7 @@ Custom filters can be created to handle cross-cutting concerns. Examples of cros
## **How filters work**
Filters run within the *ASP.NET Core action invocation pipeline*, sometimes referred to as the *filter pipeline*. The filter pipeline runs after ASP.NET Core selects the action to execute.
Filters run within the _ASP.NET Core action invocation pipeline_, sometimes referred to as the _filter pipeline_. The filter pipeline runs after ASP.NET Core selects the action to execute.
![filter-pipeline-1](../../.images/dotnet_filter-pipeline-1.png)
![filter-pipeline-2](../../.images/dotnet_filter-pipeline-2.png)
@ -20,18 +20,18 @@ Filters run within the *ASP.NET Core action invocation pipeline*, sometimes ref
Each filter type is executed at a different stage in the filter pipeline:
- **Authorization filters** run first and are used to determine whether the user is authorized for the request. Authorization filters short-circuit the pipeline if the request is not authorized.
- **Authorization filters** run first and are used to determine whether the user is authorized for the request. Authorization filters short-circuit the pipeline if the request is not authorized.
- **Resource filters**:
- Run after authorization.
- `OnResourceExecuting` runs code before the rest of the filter pipeline. For example, `OnResourceExecuting` runs code before model binding.
- `OnResourceExecuting` runs code before the rest of the filter pipeline. For example, `OnResourceExecuting` runs code before model binding.
- `OnResourceExecuted` runs code after the rest of the pipeline has completed.
- **Action filters**:
- Run code immediately before and after an action method is called.
- Can change the arguments passed into an action.
- Can change the result returned from the action.
- Are **not** supported in Razor Pages.
- **Exception filters** apply global policies to unhandled exceptions that occur before the response body has been written to.
- **Result filters** run code immediately before and after the execution of action results. They run only when the action method has executed successfully. They are useful for logic that must surround view or formatter execution.
- Are **not** supported in Razor Pages.
- **Exception filters** apply global policies to unhandled exceptions that occur before the response body has been written to.
- **Result filters** run code immediately before and after the execution of action results. They run only when the action method has executed successfully. They are useful for logic that must surround view or formatter execution.
## **Implementation**
@ -44,7 +44,7 @@ Interfaces for multiple filter stages can be implemented in a single class.
## **Built-in filter attributes**
ASP.NET Core includes built-in *attribute-based* filters that can be subclassed and customized.
ASP.NET Core includes built-in _attribute-based_ filters that can be subclassed and customized.
Several of the filter interfaces have corresponding attributes that can be used as base classes for custom implementations.
Filter attributes:
@ -58,12 +58,12 @@ Filter attributes:
## **Filter scopes**
A filter can be added to the pipeline at one of three *scopes*:
A filter can be added to the pipeline at one of three *scopes*:
- Using an attribute on a controller action. Filter attributes cannot be applied to Razor Pages handler methods.
```cs
// services.AddScoped<CustomActionFilterAttibute>();
// services.AddScoped<CustomActionFilterAttribute>();
[ServiceFilter(typeof(CustomActionFilterAttribute))]
public IActionResult Index()
{
@ -101,14 +101,14 @@ public void ConfigureServices(IServiceCollection services)
When there are multiple filters for a particular stage of the pipeline, scope determines the default order of filter execution. Global filters surround class filters, which in turn surround method filters.
As a result of filter nesting, the *after* code of filters runs in the reverse order of the *before* code. The filter sequence:
As a result of filter nesting, the *after* code of filters runs in the reverse order of the *before* code. The filter sequence:
- The *before* code of global filters.
- The *before* code of controller and Razor Page filters.
- The *before* code of action method filters.
- The *after* code of action method filters.
- The *after* code of controller and Razor Page filters.
- The *after* code of global filters.
- The *before* code of global filters.
- The *before* code of controller and Razor Page filters.
- The *before* code of action method filters.
- The *after* code of action method filters.
- The *after* code of controller and Razor Page filters.
- The *after* code of global filters.
### Cancellation and Short-Circuiting

View file

@ -42,7 +42,7 @@ Project
| |-HomeController.cs
|
|- appsettings.json
|- Program.cs --> App entrypoiny
|- Program.cs --> App entry-point
|- Startup.cs --> App config
```
@ -70,7 +70,7 @@ namespace App.Controllers
// GET /Controller/Index
public IActionResult Index()
{
IEnumerable<Entity> enities = _db.Entities;
IEnumerable<Entity> entities = _db.Entities;
return View(Entities); // pass data to the @model
}
@ -83,7 +83,7 @@ namespace App.Controllers
// POST /Controller/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Entity entity) // recieve data from the @model
public IActionResult Create(Entity entity) // receive data from the @model
{
_db.Entities.Add(entity);
_db.SaveChanges();
@ -104,7 +104,7 @@ namespace App.Controllers
return NotFound();
}
return View(entity); // return pupulated form for updating
return View(entity); // return populated form for updating
}
// POST /Controller/Edit
@ -136,7 +136,7 @@ namespace App.Controllers
return NotFound();
}
return View(entity); // return pupulated form for confirmation
return View(entity); // return populated form for confirmation
}
// POST /Controller/Delete
@ -197,7 +197,7 @@ In `View.cshtml`;
<div class="col-8">
<input asp-for="IntProp" class="form-control"/>
<span asp-validation-for="IntProp" class="text-danger"></span> // error message displyed here
<span asp-validation-for="IntProp" class="text-danger"></span> // error message displayed here
</div>
</div>
</form>
@ -230,7 +230,7 @@ namespace App.Controllers
// GET /Controller/Index
public IActionResult Index()
{
IEnumerable<Entity> enities = _db.Entities;
IEnumerable<Entity> entities = _db.Entities;
return View(Entities); // pass data to the @model
}
@ -243,7 +243,7 @@ namespace App.Controllers
// POST /Controller/Create
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(Entity entity) // recieve data from the @model
public IActionResult Create(Entity entity) // receive data from the @model
{
if (ModelState.IsValid) // all rules in model have been met
{

View file

@ -7,13 +7,13 @@ Middleware is software that's assembled into an app pipeline to handle requests
Request delegates are used to build the request pipeline. The request delegates handle each HTTP request.
Request delegates are configured using [Run][Run_docs], [Map][Map_docs], and [Use][Use_docs] extension methods.
Request delegates are configured using [Run][Run_docs], [Map][Map_docs], and [Use][Use_docs] extension methods.
An individual request delegate can be specified in-line as an anonymous method (called in-line middleware), or it can be defined in a reusable class.
These reusable classes and in-line anonymous methods are *middleware*, also called *middleware components*.
These reusable classes and in-line anonymous methods are *middleware*, also called *middleware components*.
Each middleware component in the request pipeline is responsible for invoking the next component in the pipeline or short-circuiting the pipeline.
When a middleware short-circuits, it's called a *terminal middleware* because it prevents further middleware from processing the request.
When a middleware short-circuits, it's called a *terminal middleware* because it prevents further middleware from processing the request.
[Use_docs]: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.useextensions.use
[Run_docs]: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.builder.runextensions.run
@ -166,10 +166,10 @@ namespace <App>
The middleware class **must** include:
- A public constructor with a parameter of type [RequestDelegate][RequestDelegate_docs].
- A public method named `Invoke` or `InvokeAsync`. This method must:
- Return a `Task`.
- Accept a first parameter of type [HttpContext][HttpConrext_Docs].
- A public constructor with a parameter of type [RequestDelegate][RequestDelegate_docs].
- A public method named `Invoke` or `InvokeAsync`. This method must:
- Return a `Task`.
- Accept a first parameter of type [HttpContext][HttpConrext_Docs].
[RequestDelegate_docs]: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.requestdelegate
[HttpConrext_Docs]: https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.httpcontext

View file

@ -2,8 +2,8 @@
## Data Transfer Objects (DTOs)
A **DTO** is an object that defines how the data will be sent and recieved over the network (usually as JSON).
Without a DTO the JSON response (or reqest) could contain irrilevant, wrong or unformatted data.
A **DTO** is an object that defines how the data will be sent and received over the network (usually as JSON).
Without a DTO the JSON response (or request) could contain irrelevant, wrong or unformatted data.
Moreover, by decoupling the JSON response from the actual data model, it's possible to change the latter without breaking the API.
DTOs must be mapped to the internal methods.
@ -50,7 +50,7 @@ namespace <Namespace>.Profiles
## Controller (No View)
Uses [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) to recieve a suitable implementation of `IEntityRepo`,
Uses [Dependency Injection](https://en.wikipedia.org/wiki/Dependency_injection) to receive a suitable implementation of `IEntityRepo`,
### Service Lifetimes

View file

@ -33,7 +33,7 @@ Project
| |- ...
|
|- appsettings.json --> application settings
|- Program.cs --> App entrypoint
|- Program.cs --> App entry-point
|- Startup.cs
```
@ -88,17 +88,17 @@ namespace App.Pages
{
private readonly ApplicationDbContext _db; // EF DB Context
// Get DBContex through DI
// Get DBContext through DI
public IndexModel(ApplicationDbContext db)
{
_db = db;
}
[BindProperty] // assumed to be recieved on POST
[BindProperty] // assumed to be received on POST
public IEnumerable<Entity> Entities { get; set; }
// HTTP Method Handler
public aysnc Task OnGet()
public async Task OnGet()
{
// get data from DB (example operation)
Entities = await _db.Entities.ToListAsync();
@ -131,12 +131,12 @@ Rules:
- URL maps to a physical file on disk
- Razor paged needs a root folder (Default "Pages")
- file extension not included in URL
- `Index.cshtml` is enrtypoint and default document (missing file in URL redirects to index)
- `Index.cshtml` is entry-point and default document (missing file in URL redirects to index)
| URL | Maps TO |
|------------------------|----------------------------------------------------|
| www.domain.com | /Pages/Index.cshtml |
| www.doamin.com/Index | /Pages/Index.html |
| www.domain.com/Index | /Pages/Index.html |
| www.domain.com/Account | /Pages/Account.cshtml, /Pages/Account/Index.cshtml |
## Data Validation
@ -179,7 +179,7 @@ In `View.cshtml`;
<div class="col-8">
<input asp-for="IntProp" class="form-control"/>
<span asp-validation-for="IntProp" class="text-danger"></span> // error message displyed here
<span asp-validation-for="IntProp" class="text-danger"></span> // error message displayed here
</div>
</div>
</form>

View file

@ -10,14 +10,14 @@
@* razor comment *@
// substituite @variable with it's value
// substitute @variable with it's value
<tag>@variable</tag>
@{
// razor code block
// can contain C# or HTML
Model // acces to passed @model (MVC)
Model // access to passed @model (MVC)
}
@if (condition) { }
@ -58,7 +58,7 @@ The first parameter after `@addTagHelper` specifies the Tag Helpers to load (`*`
It's possible to disable a Tag Helper at the element level with the Tag Helper opt-out character (`!`)
```cshtml
<!-- disable email vaidation -->
<!-- disable email validation -->
<!span asp-validation-for="Email" ></!span>
```
@ -86,7 +86,7 @@ The `@tagHelperPrefix` directive allows to specify a tag prefix string to enable
@Model.EntityProp
<from>
// use the property as the label, eventyally w/ [DysplayName("...")]
// use the property as the label, eventually w/ [DisplayName("...")]
<label asp-for="EntityProp"></label>
@Html.LabelFor()
@ -131,7 +131,7 @@ In `View.cs`
<form asp-controller="Controller" asp-action="PostAction">
<select asp-for"EntityId" asp-items="Model.Enities">
<select asp-for"EntityId" asp-items="Model.Entities">
</select>
<button type="submit">Send<button>
@ -145,7 +145,7 @@ public IActionResult GetAction()
{
var vm = new ViewModel();
vm.Entities = new SelectList(_context.Enities, "Id", "Text"); // fill SelectList
vm.Entities = new SelectList(_context.Entities, "Id", "Text"); // fill SelectList
vm.EntityId = value; // set selected option (OPTIONAL)
return View(vm);

View file

@ -52,9 +52,9 @@ public class CustomHub : Hub
return Clients.Caller.SendAsync("CLientMethod", args);
// trigger function on clients of a group and pass args to it
return Clients.Group("GoupName").SendAsync("CLientMethod", args);
return Clients.Group("GroupName").SendAsync("CLientMethod", args);
// other opeations
// other operations
}
}
```
@ -149,7 +149,7 @@ Reference the SignalR JavaScript client in the `<script>` element. For example:
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hub/endpoint")
.configureLogging(signalR.LogLevel.Information)
.withAutomaticreconnect() // optional
.withAutomaticReconnect() // optional
.build();
// async/await connection start

View file

@ -2,7 +2,7 @@
## `Page.aspx`
The fist loaded page is `Default.aspx` and its undelying code.
The fist loaded page is `Default.aspx` and its underlying code.
```html
<!-- directive -->
@ -76,7 +76,7 @@ namespace Project
}
protected void Control_Event(object sender, EventAtgs e)
protected void Control_Event(object sender, EventArgs e)
{
// actions on event trigger
}

View file

@ -17,7 +17,7 @@ namespace Project
}
protected void Control_Event(object sender, EventAtgs e)
protected void Control_Event(object sender, EventArgs e)
{
// actions on event trigger
}

View file

@ -1,6 +1,6 @@
# Page.aspx
The fist loaded page is `Default.aspx` and its undelying code.
The fist loaded page is `Default.aspx` and its underlying code.
```html
<!-- directive -->
@ -38,7 +38,7 @@ The fist loaded page is `Default.aspx` and its undelying code.
```xml
<asp:Control ID="" runat="server" ...></asp:Control>
<!-- Label: empty text will diplay ID, use empty space as text for empty label -->
<!-- Label: empty text will display ID, use empty space as text for empty label -->
<asp:Label ID="lbl_" runat="server" Text=" "></asp:Label>
<!-- TextBox -->
<asp:TextBox ID="txt_" runat="server"></asp:TextBox>

View file

@ -2,9 +2,9 @@
## Arrays
An array is an object that contains multiple elements of a particular type. The number of elements is fixed for the lifetime of the array, so it must be specied when the array is created.
An array is an object that contains multiple elements of a particular type. The number of elements is fixed for the lifetime of the array, so it must be specified when the array is created.
An array type is always a reference type, regardless of the element type. Nonetheless, the choice between reference type and value type elements makes a significant difference in an arrays behavior.
An array type is always a reference type, regardless of the element type. Nonetheless, the choice between reference type and value type elements makes a significant difference in an array's behavior.
```cs
type[] array = new type[dimension];
@ -14,9 +14,9 @@ type[] array = {value1, value2, ..., valueN}; // initializer
var array = new type[] {value1, value2, ..., valueN}; // initializer (var type needs new operator)
var array = new[] {value1, value2, ..., valueN}; // initializer w/ element type inference (var type needs new operator), can be used as method arg
array[index]; // value acces
array[index] = value; // value assignement
array.Lenght; // dimension of the array
array[index]; // value access
array[index] = value; // value assignment
array.Length; // dimension of the array
// from IEnumerable<T>
array.OfType<Type>(); // filter array based on type, returns IEnumerable<Type>
@ -27,17 +27,17 @@ array.OfType<Type>(); // filter array based on type, returns IEnumerable<Type>
```cs
// overloaded search methods
Array.IndexOf(array, item); // return index of searched item in passed array
Array.LastIndexOf(array, item); // return index of searched item staring from the end of the arrary
Array.LastIndexOf(array, item); // return index of searched item staring from the end of the array
Array.FindIndex(array, Predicate<T>) // returns the index of the first item matching the predicate (can be lambda function)
Array.FindLastIndex(array, Predicate<T>) // returns the index of the last item matching the predicate (can be lambda function)
Array.Find(array, Predicate<T>) // returns the value of the first item matching the predicate (can be lambda function)
Array.FindLast(array, Predicate<T>) // returns the value of the last item matvhing the predicate (can be lambda function)
Array.FindLast(array, Predicate<T>) // returns the value of the last item matching the predicate (can be lambda function)
Array.FindAll(array, Predicate<T>) // returns array of all items matching the predicate (can be lambda function)
Array.BinarySearch(array, value) // Searches a SORTED array for a value, using a binary search algorithm; retuns the index of the found item
Array.BinarySearch(array, value) // Searches a SORTED array for a value, using a binary search algorithm; returns the index of the found item
Array.Sort(array);
Array.Reverse(array); // reverses the order of array elements
Array.Clear(start_index, x); //removes reference to x elements starting at start index. Dimension of array uncanged (cleared elements value is set tu null)
Array.Clear(start_index, x); //removes reference to x elements starting at start index. Dimension of array unchanged (cleared elements value is set tu null)
Array.Resize(ref array, target_dimension); //expands or shrinks the array dimension. Shrinking drops trailing values. Array passed by reference.
// Copies elements from an Array starting at the specified index and pastes them to another Array starting at the specified destination index.
@ -78,8 +78,8 @@ type[,] matrix = new type[n, m]; // n * m matrix
type[,] matrix = {{}, {}, {}, ...}; // {} for each row to initialize
type[, ,] tensor = new type[n, m, o] // n * m * o tensor
matrix.Length; // total numeber of elements (n * m)
matrix.GetLenght(int dimension); // get the size of a particular direction
matrix.Length; // total number of elements (n * m)
matrix.GetLength(int dimension); // get the size of a particular direction
// row = 0, column = 1, ...
```
@ -102,13 +102,13 @@ list.Insert(index, item); // insert an item at the specified index
list.InsertRange(index, item); // insert items at the specified index
list.IndexOf(item); // return index of searched item in passed list
list.LastIndexOf(item); // return index of searched item staring from the end of the arrary
list.LastIndexOf(item); // return index of searched item staring from the end of the array
list.FindIndex(Predicate<T>) // returns the index of the first item matching the predicate (can be lambda function)
list.FindLastIndex(Predicate<T>) // returns the index of the last item matching the predicate (can be lambda function)
list.Find(Predicate<T>) // returns the value of the first item matching the predicate (can be lambda function)
list.FindLast(Predicate<T>) // returns the value of the last item matvhing the predicate (can be lambda function)
list.FindLast(Predicate<T>) // returns the value of the last item matching the predicate (can be lambda function)
list.FindAll(Predicate<T>) // returns list of all items matching the predicate (can be lambda function)
list.BinarySearch(value) // Searches a SORTED list for a value, using a binary search algorithm; retuns the index of the found item
list.BinarySearch(value) // Searches a SORTED list for a value, using a binary search algorithm; returns the index of the found item
list.Remove(item); // remove item from list
list.RemoveAt(index); // remove item at specified position
@ -138,7 +138,7 @@ When a `yield return` statement is reached, the current location in code is reme
It's possible to use a `yield break` statement or exception to end the iteration.
**Note**: Since an iteartor returns an `IEnumerable<T>` is can be used to implement a `GetEnumerator()`.
**Note**: Since an iterator returns an `IEnumerable<T>` is can be used to implement a `GetEnumerator()`.
```cs
// simple iterator
@ -159,7 +159,7 @@ Exposes the enumerator, which supports a simple iteration over a collection of a
```cs
public interface IEnumerable<out T> : IEnumerable
{
IEnumerator<T> GetEnumerator(); // retrun an enumerator
IEnumerator<T> GetEnumerator(); // return an enumerator
}
// iterate through a collection
@ -227,7 +227,7 @@ Span<T> slice = array[start..end];
ReadOnlySpan<T> slice = array[start..end];
```
## [Dictioanaries](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2)
## [Dictionaries](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2)
[ValueCollection](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.valuecollection)
[KeyCollection](https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2.keycollection)
@ -258,10 +258,10 @@ Dictionary<TKey, TValue> dict =
}
// indexer access
dict[key]; // read value associted with key (throws KeyNotFoundException if key does not exist)
dict[key] = value; // modify value associted with key (throws KeyNotFoundException if key does not exist)
dict[key]; // read value associated with key (throws KeyNotFoundException if key does not exist)
dict[key] = value; // modify value associated with key (throws KeyNotFoundException if key does not exist)
dict.Count; // numer of key-value pair stored in the dict
dict.Count; // number of key-value pair stored in the dict
dict.Keys; // Dictionary<TKey,TValue>.KeyCollection containing the keys of the dict
dict.Values; // Dictionary<TKey,TValue>.ValueCollection containing the values of the dict

View file

@ -11,7 +11,7 @@ LINQ to Objects will be used when any `IEnumerable<T>` is specified as the sourc
### Query Expressions
All query expressions are required to begin with a `from` clause, which specifies the source of the query.
The final part of the query is a `select` (or `group`) clause. This determines the final output of the query and its sytem type.
The final part of the query is a `select` (or `group`) clause. This determines the final output of the query and its system type.
```cs
// query expression
@ -21,10 +21,10 @@ var result = from item in enumerable select item;
var result = from item in enumerable where condition select item;
// ordering
var result = from item in enumerable orderby item.property select item; // ordered IEnumerble
var result = from item in enumerable orderby item.property select item; // ordered IEnumerable
// let clause, assign expression to variable to avoid re-evaluetion on each cycle
var result = from item in enumerable let tmp = <sub-expr> ... // BEWARE: compiled code has a lot of overhead to satisfy let caluse
// let clause, assign expression to variable to avoid re-evaluation on each cycle
var result = from item in enumerable let tmp = <sub-expr> ... // BEWARE: compiled code has a lot of overhead to satisfy let clause
// grouping (difficult to re-implement to obtain better performance)
var result = from item in enumerable group item by item.property; // returns IEnumerable<IGrouping<TKey,TElement>>
@ -63,7 +63,7 @@ IEnumerable<T>.Any(Func<T, bool> predicate); // check if condition is true for
IEnumerable<T>.Concat(IEnumerable<T> enumerable);
// Applies a specified function to the corresponding elements of two sequences, producing a sequence of the results.
IEnumerable<TFirst>.Zip(IEnumerable<TSecond> enumerable, Func<TFirst, TSecoind, TResult> func);
IEnumerable<TFirst>.Zip(IEnumerable<TSecond> enumerable, Func<TFirst, TSecond, TResult> func);
IEnumerable<TFirst>.Zip(IEnumerable<TSecond> enumerable); // Produces a sequence of tuples with elements from the two specified sequences.
```

View file

@ -3,7 +3,7 @@
The **Reactive Extensions** for .NET, or **Rx**, are designed for working with asynchronous and event-based sources of information.
Rx provides services that help orchestrate and synchronize the way code reacts to data from these kinds of sources.
Rxs fundamental abstraction, `IObservable<T>`, represents a sequence of items, and its operators are defined as extension methods for this interface.
Rx's fundamental abstraction, `IObservable<T>`, represents a sequence of items, and its operators are defined as extension methods for this interface.
This might sound a lot like LINQ to Objects, and there are similarities, not only does `IObservable<T>` have a lot in common with `IEnumerable<T>`, but Rx also supports almost all of the standard LINQ operators.

View file

@ -22,7 +22,7 @@ The `ADO.NET` classes are found in `System.Data.dll`, and are integrated with th
### [SQLite](https://www.connectionstrings.com/sqlite/)
- Basic: `Data Source: path\to\db.sqlite3; Version=3;`
- In-Memory Dataabse: `Data Source=:memory:; Version=3; New=True`
- In-Memory Database: `Data Source=:memory:; Version=3; New=True`
- With Password: `Data Source: path\to\db.sqlite3; Version=3; Password=<password>`
## Connection to DB
@ -59,7 +59,7 @@ namespace <namespace>
using (SqlConnection connection = new SqlConnection())
{
connection.ConnectionString = connectionString.ConnectionString;
connection.Open(); // start comunication w/ sql server
connection.Open(); // start communication w/ sql server
}
// more compact
@ -106,7 +106,7 @@ using (SqlDataReader cursor = command.ExecuteReader()) // object to get data fr
// check for null before retrieving the value
if(!cursor.IsDBNull(n))
{
sqlreader.Get<SystemType>(index); // retrieve data form the n-th column
cursor.Get<SystemType>(index); // retrieve data form the n-th column
}
}
}

View file

@ -67,7 +67,7 @@ namespace <Project>.Model
Create & Update DB Schema if necessary.
In Packge Manager Shell:
In Package Manager Shell:
```ps1
PM> Add-Migration <migration_name>

View file

@ -2,14 +2,14 @@
## Rigidbody Component
Enables physycs on the game objects.
Enables physics on the game objects.
Rigidbodies collide with other objects instead of going through them.
Avoid obejct rotation on colisions:
Avoid object rotation on collisions:
1. Assign `Rigidbody` component to object
2. Enable Freeze Rotaion in Rigidbody > Constraints
2. Enable Freeze Rotation in Rigidbody > Constraints
```cs
using UnityEngine;
@ -21,19 +21,19 @@ public class GameObject : MonoBehaviour {
void Start()
{
rigidbody = GetComponenet<Rigidbody>(); // get rigidbody reference
rigidbody = GetComponent<Rigidbody>(); // get rigidbody reference
}
void Update()
{
}
// FixedUpdate is calles every x seconds (not influenced by FPS instability)
// used for physics calculations which sould be FPS independant
// FixedUpdate is calls every x seconds (not influenced by FPS instability)
// used for physics calculations which should be FPS independent
void FixedUpdate()
{
Time.fixedDeltaTime; // fixed amount of time
Time.timeDelta; // if called inside FIxedUpadate() behaves like fixedDeltaTime
Time.timeDelta; // if called inside FIxedUpdate() behaves like fixedDeltaTime
}
}
@ -44,8 +44,8 @@ public class GameObject : MonoBehaviour {
Enable `Is Trigger` to register the collision but avoid blocking the movement of the objects.
The trigger can generate a event to signal the contact with the object.
One of the collidng GameObjects *must have* the `Rigidbody` component and the other `Is Trigger` enabled.
To detect the collison but avoid computing the physycs `Is Kinematic` must be enabled in the `Rigidbody` component.
One of the colliding GameObjects *must have* the `Rigidbody` component and the other `Is Trigger` enabled.
To detect the collision but avoid computing the physics `Is Kinematic` must be enabled in the `Rigidbody` component.
```cs
using UnityEngine;
@ -57,21 +57,21 @@ public class GameObject : MonoBehaviour {
void Start()
{
rigidbody = GetComponenet<Rigidbody>(); // get rigidbody reference
rigidbody = GetComponent<Rigidbody>(); // get rigidbody reference
}
// FixedUpdate is calles every x seconds (not influenced by FPS instability)
// used for physics calculations which sould be FPS independant
// FixedUpdate is calls every x seconds (not influenced by FPS instability)
// used for physics calculations which should be FPS independent
void FixedUpdate()
{
Time.fixedDeltaTime; // fixed amount of time
Time.timeDelta; // if called inside FIxedUpadate() behaves like fixedDeltaTime
Time.timeDelta; // if called inside FixedUpdate() behaves like fixedDeltaTime
}
// called on box collision.
void OnTriggerEnter(Collider triggerCollider) {
// detect a collison with a perticular GameObject(must have a TAG)
// detect a collision with a particular GameObject(must have a TAG)
if (triggerCollider.tag = "tag") {
Destroy(triggerCollider.gameObject); // destroy tagged item on collision
//or

View file

@ -2,7 +2,7 @@
[Coroutines - Unity manual](https://docs.unity3d.com/Manual/Coroutines.html)
When you call a function, it runs to completion before returning. This effectively means that any action taking place in a function must happen *within a single frame update*; a function call cant be used to contain a procedural animation or a sequence of events over time.
When you call a function, it runs to completion before returning. This effectively means that any action taking place in a function must happen *within a single frame update*; a function call can't be used to contain a procedural animation or a sequence of events over time.
A coroutine is like a function that has the ability to pause execution and return control to Unity but then to continue where it left off on the following frame.
@ -22,7 +22,7 @@ IEnumerator coroutine()
// or
yeld return StartCoroutine(coroutine()); // wait for anothe coroitine to finish before starting
yeld return StartCoroutine(coroutine()); // wait for another coroutine to finish before starting
}
StartCoroutine(coroutine()); // start the coroutine

View file

@ -4,7 +4,7 @@ The Input Manager uses the following types of controls:
- **Key** refers to any key on a physical keyboard, such as `W`, `Shift`, or the `space bar`.
- **Button** refers to any button on a physical controller (for example, gamepads), such as the `X` button on an Xbox One controller.
- A **virtual axis** (plural: axes) is mapped to a **control**, such as a button or a key. When the user activates the control, the axis receives a value in the range of `[1..1]`.
- A **virtual axis** (plural: axes) is mapped to a **control**, such as a button or a key. When the user activates the control, the axis receives a value in the range of `[-1..1]`.
## Virtual axes
@ -30,8 +30,8 @@ The Input Manager uses the following types of controls:
Axis values can be:
- Between `1` and `1` for joystick and keyboard input. The neutral position for these axes is `0`. Some types of controls, such as buttons on a keyboard, arent sensitive to input intensity, so they cant produce values other than `1`, `0`, or `1`.
- Mouse delta (how much the mouse has moved during the last frame) for mouse input. The values for mouse input axes can be larger than `1` or smaller than `1` when the user moves the mouse quickly.
- Between `-1` and `1` for joystick and keyboard input. The neutral position for these axes is `0`. Some types of controls, such as buttons on a keyboard, aren't sensitive to input intensity, so they can't produce values other than `-1`, `0`, or `1`.
- Mouse delta (how much the mouse has moved during the last frame) for mouse input. The values for mouse input axes can be larger than `1` or smaller than `-1` when the user moves the mouse quickly.
```cs
//Define the speed at which the object moves.

View file

@ -1,8 +1,8 @@
# Prefabs
Prefabs are a blueprint for GameObcets and any change made to the prefab is inherited by all it's instances.
Prefabs are a blueprint for GameObjects and any change made to the prefab is inherited by all it's instances.
## Script Instantation
## Script Instantiation
```cs

View file

@ -1,6 +1,6 @@
# Raycasting Notes
A raycast is conceptually like a laser beam that is fired from a point in space along a particular directuin. Any object making contact with the beam can be detected and reported.
A raycast is conceptually like a laser beam that is fired from a point in space along a particular direction. Any object making contact with the beam can be detected and reported.
## 3D Raycasting
@ -16,13 +16,13 @@ void Update()
hitInfo.transform // transform og the hit object
hitInfo.collider.gameObject // reference to the object hit by the ray
hitInfo.collider.gameObject // reference to the object hit by the ray
hitInfo.normal // normal bector og the hit surface
hitInfo.normal // normal vector og the hit surface
hitInfo.point // actual point of collision
// static method, object must haave a collider dot the collision to happen, returns a BOOL
// static method, object must have a collider dot the collision to happen, returns a BOOL
Physics.Raycast(ray, out hitInfo); // update hitInfo based on ray collisions
Physics.Raycast(ray, out hitInfo, float maxRayDistance); // limit the ray length
Physics.Raycast(ray, out hitInfo, Mask mask); // specify with which layers the ray can interact, layer must be allpied to object's mask
Physics.Raycast(ray, out hitInfo, Mask mask); // specify with which layers the ray can interact, layer must be applied to object's mask
Physics.Raycast(ray, out hitInfo, Mask mask, QueryTriggerInteraction.Ignore); // ignore collision if "is trigger" is enabled on other objects
// detect a collision
@ -30,12 +30,12 @@ void Update()
{
//collision happened
// draw the ray ingame for debuggng
// draw the ray in game for debugging
Debug.DrawLine(ray.origin, hitInfo.point, Color.red); // draw red line if collision happens
}
else
{
Debug.DrawLine(ray.origin, ray.origin + ray.direction * 100, Color.blue); // draw blue line if collision happens, arrival point is 100 units from the origin sinche the ray goes to infinity
Debug.DrawLine(ray.origin, ray.origin + ray.direction * 100, Color.blue); // draw blue line if collision happens, arrival point is 100 units from the origin since the ray goes to infinity
}
}
```
@ -47,8 +47,8 @@ public Camera gameCamera;
void Update()
{
// ray goint ftom cametra through a screen point
Ray ray = gameCamera.ScreenPointToRay(Input.mousePosition); // Input.mousePosition is the postion of the mouse in pixels (screen points)
// ray going from camera through a screen point
Ray ray = gameCamera.ScreenPointToRay(Input.mousePosition); // Input.mousePosition is the position of the mouse in pixels (screen points)
RaycastHit hitInfo; // place pointed by the mouse
Physics.Raycast(ray, out hitInfo) // update pointed position
@ -61,12 +61,12 @@ void Update()
void Start()
{
Physisc2D.queriesStartColliders = false; // avoid collision with collider of the ray generator gameObject
Physics2D.queriesStartColliders = false; // avoid collision with collider of the ray generator gameObject
}
void Update()
{
// returns a RaycastHit2D, needs an origin and direction separatedly
// returns a RaycastHit2D, needs an origin and direction separately
Raycast2D hitInfo = Physics2D.Raycast(Vector2 origin, Vector2 direction);
Raycast2D hitInfo = Physics2D.Raycast(Vector2 origin, Vector2 direction, float maxRayDistance);
Raycast2D hitInfo = Physics2D.Raycast(Vector2 origin, Vector2 direction, float maxRayDistance);

View file

@ -24,25 +24,25 @@ public class ClassName : MonoBehaviour {
Time.deltaTime; // time since last frame
}
// FixedUpdate is calles every x seconds (not influenced by FPS instability)
// used for physics calculations which sould be FPS independant
// FixedUpdate is calls every x seconds (not influenced by FPS instability)
// used for physics calculations which should be FPS independent
void FixedUpdate()
{
Time.fixedDeltaTime; // fixed amount of time
Time.timeDelta; // if called inside FIxedUpadate() behaves like fixedDeltaTime
Time.timeDelta; // if called inside FIxedUpdate() behaves like fixedDeltaTime
}
}
```
### Script comunication
### Script communication
Referencing data in a sctipt from another.
Referencing data in a script from another.
```cs
//example of a script to be referenced in another
Using System;
public class Player : MonoBheaviour {
public class Player : MonoBehaviour {
public float health = 10;
public event Action OnPlayerDeath; //event of type Action, needs using System
@ -55,7 +55,7 @@ public class Player : MonoBheaviour {
if (health <= 0) {
if (OnPlayerDeath != null) {
OnPleyerDeath(); // invoke Action (if no subscribers event will be NULL, can cause errors)
OnPlayerDeath(); // invoke Action (if no subscribers event will be NULL, can cause errors)
}
Destroy(GameObject); // needs to be notified
@ -68,7 +68,7 @@ public class Player : MonoBheaviour {
// example of script needing a reference to another
public class GameUI : MonoBehaviour {
Player player; //instance of referenced GameObject to be founf by its type
Player player; //instance of referenced GameObject to be found by its type
void Start(){
GameObject playerObj = GameObject.Find("Player"); //reference to game object
@ -77,7 +77,7 @@ public class GameUI : MonoBehaviour {
player = FindObjectOfType<Player>(); // get reference to an object
// on event invocation all subscribet methods will be called
// on event invocation all subscriber methods will be called
player.OnPlayerDeath += GameOver; // subscribe method to event
}
@ -85,7 +85,7 @@ public class GameUI : MonoBehaviour {
DrawHealthBar(plyer.health); // call method passing data of player GameObject
}
void DrawHealthbar(float playerHealth) {
void DrawHealthBar(float playerHealth) {
// implementation
}
@ -100,9 +100,9 @@ public class GameUI : MonoBehaviour {
### 2D Screen Measures
Aspect Ratio = `(screen_width [px]) / (screen_height [px])`
Orhograpic Size `[world units]` = `(screen_height [world units] / 2)`
Aspect Ratio * Orhograpic Size = `(screen_width [world units] / 2)`
Screen Width `[world units]` = `(AspectRatio * OrhograpicSize * 2)`
Orthographic Size `[world units]` = `(screen_height [world units] / 2)`
Aspect Ratio * Orthographic Size = `(screen_width [world units] / 2)`
Screen Width `[world units]` = `(AspectRatio * OrthographicSize * 2)`
```cs
screenWidth = Camera.main.aspect * Camera.main.orthographicSize * 2;
@ -123,7 +123,7 @@ public class ScriptableObjectName : ScriptableObject {
### Game Object Serialization
```c#
[SeralizeField] type variable; //access game object from code
[SerializeField] type variable; //access game object from code
```
### Game Object Data Access

View file

@ -1,4 +1,4 @@
# Vector, Tranfrorm, Space
# Vector, Transform, Space
## Vector2, Vector3, Vector4
@ -33,8 +33,8 @@ Vector3.one // Vector3(1, 1, 1)
### Operations
```cs
Vector3(x, y, z) * n = Vecotr3(xn, yn, yz);
Vector3(x, y, z) / n = Vecotr3(x / n, y / n, y / z);
Vector3(x, y, z) * n = Vector3(xn, yn, yz);
Vector3(x, y, z) / n = Vector3(x / n, y / n, y / z);
Vector3(x1, y1, z1) + Vector3(x2, y2, z2) = Vector3(x1 + x2, y1 + y2, z1 + z2);
Vector3(x1, y1, z1) - Vector3(x2, y2, z2) = Vector3(x1 - x2, y1 - y2, z1 - z2);
@ -54,11 +54,11 @@ MovementInFrame = Speed * timeSinceLastFrame
[Transform Docs](https://docs.unity3d.com/ScriptReference/Transform.html)
```cs
// propetries
transfrom.position // Vector3 - global position
transfrom.localPosition // Vector3 - local position
// properties
transform.position // Vector3 - global position
transform.localPosition // Vector3 - local position
transform.rotation // Quaternion - global rotation
transfrom.parent // Transform - parent of the object
transform.parent // Transform - parent of the object
transform.localScale = Vector3; // set object dimensions
@ -67,21 +67,21 @@ transform.Rotate(Vector3 * Time.deltaTime * speed, Space); // set rotation usin
transform.Translate(Vector3 * Time.deltaTime * speed, Space); // set movement in selected space
```
### Local, GLobal & Object Spcace
### Local, GLobal & Object Space
**Local Space**: Applies transformation relative to the *local* coordinate system (`Space.Self`).
**Global Space**: Applies transformation relative to the *world* coordinate system (`Space.World`)
### Parenting
Changing the parent will make position, scale and rotation of the child object retalive to the parent but keep the world space's position, rotation and scale the same.
Changing the parent will make position, scale and rotation of the child object relative to the parent but keep the world space's position, rotation and scale the same.
Setting the parentele by script:
```cs
public class ParentScript : MonoBehaviour {
public Transform childTransform; // reference to the child object transfrom
public Transform childTransform; // reference to the child object transform
childTrandform.parent = transfrom; // when evaluated at runtime sets current object as parent of another
childTransform.parent = transform; // when evaluated at runtime sets current object as parent of another
}
```

View file

@ -13,7 +13,7 @@ The word *winfx* refers to a name once used for the .NET Framework 3.0, which in
The `x:Class` attribute can appear only on the root element of a XAML file. It specifies the .NET namespace and name of a derived class. The base class of this derived class is the root element.
In other words, this `x:Class` specification indicates that the `App` class in the `AppName` namespace derives from `Application`.
Thats exactly the same information as the `App` class definition in the `App.xaml.cs` file.
That's exactly the same information as the `App` class definition in the `App.xaml.cs` file.
```xml
<?xml version="1.0" encoding="utf-8" ?>
@ -31,7 +31,7 @@ Thats exactly the same information as the `App` class definition in the `App.
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="AppName.App">
<!-- collection of shared resources definiions -->
<!-- collection of shared resources definitions -->
<Application.Resources>
<!-- Application resource dictionary -->
@ -42,7 +42,7 @@ Thats exactly the same information as the `App` class definition in the `App.
<!-- define a reusable style -->
<Style x:Key="Style Name" TargetType="Element Type">
<!-- set poperties of the style -->
<!-- set properties of the style -->
<Setter Property="PropertyName" Value="PropertyValue">
</Style>

View file

@ -52,7 +52,7 @@ The term *view* in Xamarin.Forms denotes familiar types of presentation and inte
- StackLayout: Organizes views linearly, either horizontally or vertically.
- AbsoluteLayout: Organizes views by setting coordinates & size in terms of absolute values or ratios.
- RelativeLayout: Organizes views by setting constraints relative to their parents dimensions & position.
- RelativeLayout: Organizes views by setting constraints relative to their parent's dimensions & position.
- Grid: Organizes views in a grid of Rows and Columns
- FlexLayout: Organizes views horizontally or vertically with wrapping.
- ScrollView: Layout that's capable of scrolling its content.
@ -60,7 +60,7 @@ The term *view* in Xamarin.Forms denotes familiar types of presentation and inte
### Grid Layout
```xml
<!-- "<num>*" makes the dimesions proportional -->
<!-- "<num>*" makes the dimensions proportional -->
<Gird.RowDefinitions>
<!-- insert a row in the layout -->
<RowDefinition Height="2*"/>
@ -76,11 +76,11 @@ The term *view* in Xamarin.Forms denotes familiar types of presentation and inte
```xml
<Image Source="" BackgroundColor="" [LayoutPosition]/>
<!-- source contains reference to imagefile in Xamarin.[OS]/Resources/drawable -->
<!-- source contains reference to image file in Xamarin.[OS]/Resources/drawable -->
<!-- box to insert text -->
<Editor Placeholder="placeholder text" [LayoutPosition]/>
<!-- clickable button -->
<Button Text="button text" BackgroundColor="" Clicked="function_to_call" [LayoytPosition]/>
<Button Text="button text" BackgroundColor="" Clicked="function_to_call" [LayoutPosition]/>
```

View file

@ -27,7 +27,7 @@ namespace AppName.ViewModels
field = value;
var args = new PropertyChangedEventArgs(nameof(Property)); // EVENT: let view know that the Property has changed
PropertyChanged?.Invoke(this, args); // Ivoke event to notify the view
PropertyChanged?.Invoke(this, args); // Invoke event to notify the view
}
}
}