Accessories for Web Objects
Accessories for Web Objects
The Properties of an Object
Introduction
A property is a characteristic of an object, such as a descriptive piece of information. Because an object is a result of a class, a property is created from a class. You can create the property in a class created in a code file or a class created in a Razor Page.
There are various types of properties. A complete property starts from a private field.
A Property Writer
A property writer is a property that has only a set clause. In its body, assign value to the field. Here is an example:
@functions{
public class Square
{
private double s;
public double Side
{
set
{
s = value;
}
}
}
}
In the body of the property, you can write more code, including conditional statements, to perform any operations you judge necessary.
If your property writer includes a single-line expression, you can omit the body of the clause and replace it with the => operator. Here is an example:
@functions{
public class Employee
{
private string code;
public string ContractIdentifier
{
set => code = value;
}
}
}
A Property Reader
A property reader is a property that includes only a get clause in which you return the field you had created. Here is an example:
@functions{
public class Square
{
private double s;
public double Side
{
get
{
return s;
}
}
}
}
Once again, in the body of the property, you can perform any operations you judge necessary, including conditional statements.
If you have a get clause that uses a simple return value, you can replace the return keyword with the => operator, Here is an example:
@functions{
class Season
{
int temp;
public int MeanTemperature
{
get => temp;
}
}
}
To initialize a property reader, you can use a constructor of the class. The clients of the class can then get the value of the property but they cannot change it. Here is an example:
@page
@model PracticalLearning.Pages.TimeSheetModel
@{
Square sq = new(248.731);
}
@functions{
public class Square
{
private double _side;
public double Side
{
get
{
return _side;
}
}
public Square(double s)
{
_side = s;
}
}
}
<pre>=========================
Geometry - Square
-------------------------
Side: @sq.Side
=========================</pre>
This would produce:
========================= Geometry - Square ------------------------- Side: 248.731 =========================
A Read/Write Property
A read/write property is a complete property with a field, a set, and a get clause. Here is an example:
@functions{
public class Square
{
private double s;
public double Side
{
set
{
s = value;
}
get
{
return s;
}
}
}
}
You can simplify the code of a read/write property with a expression bodies. Here is an example:
@functions{ public class Employee { private string code; public string ContractIdentifier { get => code; set => code = value; } } }
An Automatic Property
A complete property with a field, a set, and a get clause allows you to perform some operations on the value of the property when its class communicates with other objects. If you want a property that doesn't need any primary operations, you can create it as an automatic property.
A read-only automatic property includes only a get accessor. Here is an example:
@functions{
public class Book
{
public string ISBN { get; }
}
}
A read/write automatic property has a simple { get; set; } section after its name. Here is an example:
@functions{
class Rectangle
{
public double Width { get; set; }
}
}
Page Models, Razor Pages, and Properties
Introduction
In a Page Model, you can create a property. If the property primarily doesn't hold a known value, you can make it a null property. To do this, write a question mark after its data type. If you are creating a property that is associated with a field, the field also must be null. Here is an example of a null property:
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Valuable.Pages
{
public class VanityModel : PageModel
{
public int? len;
public int? Length
{
get
{
return len;
}
set
{
len = value;
}
}
public void OnGet()
{
}
}
}
You can also create the property as an automatic one. Here is an example:
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Operations.Pages
{
public class AdditionModel : PageModel
{
public int Number { get; set; }
}
}
After creating a property, you can use it as you see fit. You should first initialize the property. You can do it where the property is created. Here is an example:
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Valuable.Pages
{
public class ExerciseModel : PageModel
{
public double? Distance { get; set; } = 628.47;
public void OnGet()
{
}
}
}
If the property is an automatic one, you can initialize it with an expression. Here is an example
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Valuable.Pages
{
public class ExerciseModel : PageModel
{
public string Equation { get; set; } = "3x + 6 = 18";
}
}
As seen with fields, you can also initialize an automatic property in a constructor or you can assign a value to it in a method of the class. Here is an example that initializes a property in a constructor:
using Microsoft.AspNetCore.Mvc.RazorPages; namespace Valuable.Pages { public class VanityModel : PageModel { public double? Distance { get; set; } public ExerciseModel() { Distance = 9_283_749.697; } public void OnGet() { } } }
A Property in a Razor Page
Once you have created a property in a Page Model class, to access the property in the corresponding Razor Page, use the @Model object.
A Required Initialized Property
Introduction
We already know that we can create a complete property. Since the property has a set clause, we can initialize it. Here is an example:
@page
@model Valuable.Pages.ExerciseModel
@{
House residence = new();
residence.MarketValue = 450_000;
}
@functions
{
public class House
{
int price;
public int MarketValue
{
get { return price; }
set { price = value; }
}
}
}
<pre>Market Value: @residence.MarketValue</pre>
This would produce:
Market Value: 450000
A Property Initializer
Instead of the set contextual keyword, an alternative to create a property reader is with the init contextual keyword. You primarily use it the same way you would proceed to create a set clause. This time, you must initialize the property before using it. To initialize the property, you can use a constructor. Here is an example:
@page @model Valuable.Pages.ExerciseModel @{ House residence = new House(450_000); } @functions { public class House { int price; public int MarketValue { get { return price; } init { price = value; } } public House(int cost) { price = cost; } } } <pre>Market Value: @residence.MarketValue</pre>
This would produce:
Market Value: 450000
An Automatic Property Initializer
Just like you can create an automatic read-write property with get and set clauses, you can create an automatic property that includes a get and an init clauses. Here is an example:
@page
@model Valuable.Pages.ExerciseModel
@{
}
@functions
{
public class House
{
public int MarketValue
{
get;
init;
}
}
}
This time, if you want to initialize the property, you can (must) use a constructor that uses a parameter that you will assign to the property. Here is an example:
@page @model Valuable.Pages.ExerciseModel @{ House residence = new House(450_000); } @functions{ public class House { public int MarketValue { get; init; } public House(int price) { MarketValue = price; } } } <pre>Market Value: @residence.MarketValue</pre>
Practical Learning: Introducing Nullity
body { } .bold { font-weight: bold; } .align-right { text-align: right; } .common-font { font-family: Garamond, Georgia, 'Times New Roman', serif; }
namespace PayrollPreparation2.Models { public class DayWork { protected double tm; protected double hsal; public DayWork(double salary, double time) { tm = time; hsal = salary; } public double HourlySalary { get { return hsal; } init { hsal = value; } } public double TimeWorked { get { return tm; } init { tm = value; } } public double RegularTime { get { if (tm is <= 8.00) return tm; else return 8.00; } } public double Overtime { get { if (tm is <= 8.00) return 0.00; else return tm - 8.00; } } public double RegularPay { get { return hsal * RegularTime; } } public double OvertimePay { get { return hsal * 1.50 * Overtime; } } public double NetPay { get { return RegularPay + OvertimePay; } } } }
@page @model PayrollPreparation2.Pages.PayEvaluationModel @using PayrollPreparation2.Models @{ string firstName = ""; string lastName = ""; string strMonday = "0.00"; string strHourlySalary = "0.00"; string strRegularTime = "0.00"; string strOvertime = "0.00"; string strRegularPay = "0.00"; string strOvertimePay = "0.00"; string strNetPay = "0.00"; DayWork dwMonday; if (Request.HasFormContentType) { double hSalary; double monday; firstName = Request.Form["txtFirstName"]; lastName = Request.Form["txtLastName"]; hSalary = double.Parse(Request.Form["txtHourlySalary"]); monday = double.Parse(Request.Form["txtMonday"]); dwMonday = new(hSalary, monday); strHourlySalary = $"{hSalary:F}"; strMonday = $"{monday:F}"; strRegularTime = $"{dwMonday.RegularTime:F}"; strOvertime = $"{dwMonday.Overtime:F}"; strRegularPay = $"{dwMonday.RegularPay:F}"; strOvertimePay = $"{dwMonday.OvertimePay:F}"; strNetPay = $"{dwMonday.NetPay:F}"; } } <h1 class="common-font text-center bold">Payroll Preparation</h1> <hr /> <form name="PayrollEvaluation" method="post" class="common-font"> <h3 class="text-center bold">Employee Time Sheet</h3> <hr /> <table style="width: 625px" align="center"> <tr> <td style="width: 125px">@Html.Label("txtFirstName", "First Name:", new { @class = "bold" })</td> <td>@Html.TextBox("txtFirstName", @firstName, new { @class = "form-control" })</td> <td>@Html.Label("txtLastName", "Last Name:", new { @class = "bold" })</td> <td>@Html.TextBox("txtLastName", @lastName, new { @class = "form-control" })</td> </tr> <tr> <td></td> <td></td> <td class="bold">Hourly Salary:</td> <td>@Html.TextBox("txtHourlySalary", @strHourlySalary, new { @class = "form-control" })</td> </tr> </table> <hr /> <table style="width: 625px" align="center"> <tr> <td style="width: 125px"> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td class="bold">Time Worked:</td> <td>@Html.TextBox("txtMonday", @strMonday, new { @class="form-control" })</td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Evaluate Payroll" name="btnEvaluatePayroll" style="width: 150px" /></td> </tr> </table> <hr /> <table style="width: 225px" align="center"> <tr style="border-bottom: 1px solid black"> <td class="bold">Pay Summary - Monday</td> <td> </td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Regular Time:</td> <td style="text-align: right">@strRegularTime</td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Overtime:</td> <td style="text-align: right">@strOvertime</td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Regular Pay:</td> <td style="text-align: right">@strRegularPay</td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Overtime Pay:</td> <td style="text-align: right">@strOvertimePay</td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Net Pay:</td> <td style="text-align: right">@strNetPay</td> </tr> </table> </form>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - Payroll Preparation</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/PayrollPreparation.css" asp-append-version="true" /> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3"> <div class="container"> <a class="navbar-brand" asp-area="" asp-page="/Index">Payroll Preparation</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-page="/PayEvaluation">Pay Evaluation</a> </li> <li class="nav-item"> <a class="nav-link text-dark" asp-area="" asp-page="/Privacy">Privacy</a> </li> </ul> </div> </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> <p class="text-center common-font">© 2022 - Payroll Preparation - <a asp-area="" asp-page="/Privacy">Privacy</a></p> </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
First Name: Patricia Last Name: Clarenden Hourly Salary: 24.63 Time Worked: 10.5
A Property of a Class Type
Introduction
You can create a property whose type is a class. If you want a full property, you can start by creating a field of the class type.
If you want a property reader, create a get clause that returns the field of the class type. Here is an example:
@functions{
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
private Camera cmr;
public Camera Recorder
{
get
{
return cmr;
}
}
}
}
If you want to get a property-writer, create a set clause. Here is an example:
@functions{
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
private Camera cmr;
public Camera Recorder
{
set
{
cmr = value;
}
}
}
}
If you want a complete property, create a set and a get clauses in it.
An Automatic Property of a Class Type
If you want a simple property that only produces an object, you can create the property as an automatic one with only get. If you want a simple but complete property, create it an automatic one.
Using a Property of a Class Type
Probably the biggest issue with a property of a class type is that you must initialize that property before accessing the members of its type. You have many options.
Before using a property of a class, you can first initialize it from an object of the class. Here is an example:
@page @model Valuable.Pages.FoundationsModel @{ TrafficTicket tt = new TrafficTicket(); tt.Recorder = new Camera(); tt.Recorder.Location = "Freemont Drive and Winchester Road"; } @functions{ public class Camera { public string Location { get; set; } } public class TrafficTicket { public Camera Recorder { get; set; } } } <p>Infraction Location: @tt.Recorder.Location</p>
This would produce:
Infraction Location: Freemont Drive and Winchester Road
An alternative is to initialize the property when creating it. Here is an example:
@page
@model Valuable.Pages.FoundationsModel
@{
TrafficTicket tt = new TrafficTicket();
tt.Recorder.Location = "Freemont Drive and Winchester Road";
}
@functions{
public class Camera
{
public string Location { get; set; }
}
public class TrafficTicket
{
public Camera Recorder
{
get;
set;
} = new Camera();
}
}
<p>Infraction Location: @tt.Recorder.Location</p>
Attributes
Introduction
In .NET programming, an attribute is information that assists the compiler in making a decision about a certain programmatic operation that must be performed on a value (a variable, a field, a property, etc), a procedure (a function or a method), or an object (of a class, an enumeration, a structure, an interface, a generic type, a record, etc).
Applying an Attribute
Although you can create an attribute from scratch, the .NET Framework already provides most of the attributes you will need for your application. you can simply and directly use those attributes. You will first need to know what operation you are trying to perform. You must then identify the attribute that can perform the operation you want.
To apply an attribute, before the item that needs the attribute, type the name of the attribute included in curly brackets.
Nullity and Classes
A Null Object
When you have just declared a variable of a class, its object is said to be null. You can explicitly indicate that your object is null. To do this, you can use the null keyword. Here is an example:
Microwave machine = null;
On the other hand, at any time, you can reset an object to nullity by assigning null to it. Here is an example:
@page
@model PracticalLearning.Pages.NullityModel
@{
Microwave machine = new Microwave()
{
Make = "Farberware",
Model = "FMO12AHTBSG",
Capacity = 1.2,
MenuOptions = 9,
Price = 108.65
};
}
@functions{
public class Microwave
{
public string Make { get; set; }
public string Model { get; set; }
public double Capacity { get; set; }
public int MenuOptions { get; set; }
public double Price { get; set; }
}
}
<pre>Microwave Oven
---------------------------------------
Make and Model: @machine.Make @machine.Model
Capacity: @machine.Capacity cubic-foot
Menu Options: @machine.MenuOptions
Price: @machine.Price
=======================================</pre>
@{
machine = null;
}
This would produce:
Microwave Oven --------------------------------------- Make and Model: Farberware FMO12AHTBSG Capacity: 1.2 cubic-foot Menu Options: 9 Price: 108.65 =======================================
To find out is an object is null, you can compare it to by using the equality operator, ==. Here is an example:
@page @model PracticalLearning.Pages.NullityModel @functions{ public class MicrowaveOven { public string Make { get; set; } public string Model { get; set; } public double Capacity { get; set; } public int MenuOptions { get; set; } public double Price { get; set; } } } @{ MicrowaveOven machine = null; } @if(mo == null) { <p>The object is null.</p> <p>=======================================</p> } else { <p>Microwave Oven</p> <p>---------------------------------------</p> <p>Make and Model: @machine.Make @machine.Model</p> <p>Capacity: @machine.Capacity cubic-foot</p> <p>Menu Options: @machine.MenuOptions</p> <p>Price: @machine.Price</p> <p>=======================================</p> } @{ machine = new MicrowaveOven() { Make = "Farberware", Model = "FMO12AHTBSG", Capacity = 1.2, MenuOptions = 9, Price = 108.65 }; } @if(mo == null) { <p>The object is null.</p> <p>=======================================</p> } else { <p>Microwave Oven</p> <p>---------------------------------------</p> <p>Make and Model: @machine.Make @machine.Model</p> <p>Capacity: @machine.Capacity cubic-foot</p> <p>Menu Options: @machine.MenuOptions</p> <p>Price: @machine.Price</p> <p>=======================================</p> }
This would produce:
The object is null. ======================================= Microwave Oven --------------------------------------- Make and Model: Farberware FMO12AHTBSG Capacity: 1.2 cubic-foot Menu Options: 9 Price: 108.65 =======================================
On the other hand, to find out whether an object is not null, you can use the != operator with the null keyword as the right operand. Here is an example:
@page @model PracticalLearning.Pages.NullityModel @{ MicrowaveOven machine = new MicrowaveOven() { Make = "Farberware", Model = "FMO12AHTBSG", Capacity = 1.2, MenuOptions = 9, Price = 108.65 }; } @functions{ public class MicrowaveOven { public string Make { get; set; } public string Model { get; set; } public double Capacity { get; set; } public int MenuOptions { get; set; } public double Price { get; set; } } } @if(machine != null) { <p>Microwave Oven</p> <p>---------------------------------------</p> <p>Make and Model: @machine.Make @machine.Model</p> <p>Capacity: @machine.Capacity cubic-foot</p> <p>Menu Options: @machine.MenuOptions</p> <p>Price: @machine.Price</p> <p>=======================================</p> } else { <p>The object is null.</p> <p>=======================================</p> } @if(machine != null) { <p>The object is null.</p> <p>=======================================</p> } else { <p>Microwave Oven</p> <p>---------------------------------------</p> <p>Make and Model: @machine.Make @machine.Model</p> <p>Capacity: @machine.Capacity cubic-foot</p> <p>Menu Options: @machine.MenuOptions</p> <p>Price: @machine.Price</p> <p>=======================================</p> }
This would produce:
Microwave Oven --------------------------------------- Make and Model: Farberware FMO12AHTBSG Capacity: 1.2 cubic-foot Menu Options: 9 Price: 108.65 ======================================= The object is null. =======================================
Checking the Compatibility of an Object
An application deals with various types of values. Tind out whether a certain object is compatible with another, you can use the is operator. You can combine it with the null value as in is null. Here is an example:
@page
@model PracticalLearning.Pages.NullityModel
@{
MicrowaveOven machine = new()
{
Make = "Aicok",
Model = "EM131A5C-BS",
Capacity = 1.1,
MenuOptions = 11,
Price = 79.95
};
}
@functions{
public class MicrowaveOven
{
public string Make { get; set; }
public string Model { get; set; }
public double Capacity { get; set; }
public int MenuOptions { get; set; }
public double Price { get; set; }
}
}
@if(machine is null)
{
<p>There is no machine to show.</p>
<p>=======================================</p>
}
else
{
<p>Microwave Oven</p>
<p>-------------------------------------------------</p>
<p>Make and Model: @machine.Make @machine.Model</p>
<p>Capacity: @machine.Capacity cubic-foot</p>
<p>Menu Options: @machine.MenuOptions</p>
<p>Price: @machine.Price</p>
<p>=============================</p>
}
This would produce:
Microwave Oven --------------------------------------- Make and Model: Aicok EM131A5C-BS Capacity: 1.1 cubic-foot Menu Options: 11 Price: 79.95 =======================================
Nullity Operators
The Null-Conditional Operator
The null-conditional operator represented as ?. checks whether the variable on its left is currently holding a null value. If it is, nothing happens. If it doesn't, then the member on its right is accessed and the operation that must be performed proceeds.
The Null Coalescing Operator
The ?. operator is used to check the nullity of a variable. You must apply the subsequent statement separately. To combine the ?. operation and its subsequent statement, you use the null coalescent operator represented as ?? (Two question marks). To apply it, type it after the condition followed by the desired statement. Here is an example:
int ?beds = -1;
Description desc = new Description();
House habitat = null;
beds = habitat?.Bedrooms ?? 0;
This code states that if the habitat object is null, the beds variable should be assigned 0. If the habitat object is not null, then the beds variable should receive a value from the designated property of the House class.
Practical Learning: Using the Nullity Values
namespace PayrollPreparation2.Models { public class DayWork { protected double? tm; protected double? hsal; public DayWork(double? salary, double? time) { tm = time; hsal = salary; } public double? HourlySalary { get { return hsal; } init { hsal = value; } } public double? TimeWorked { get { return tm; } init { tm = value; } } public double? RegularTime { get { if (tm is <= 8.00) return tm; else return 8.00; } } public double? Overtime { get { if (tm is <= 8.00) return 0.00; else return tm - 8.00; } } public double? RegularPay { get { return hsal * RegularTime; } } public double? OvertimePay { get { return hsal * 1.50 * Overtime; } } public double? NetPay { get { return RegularPay + OvertimePay; } } } }
@page @model PayrollPreparation2.Pages.PayEvaluationModel @using PayrollPreparation2.Models @{ string? firstName = null; string? lastName = null; string? strHourlySalary = null; string? strMonday = null; string? strTuesday = null; string? strWednesday = null; string? strThursday = null; string? strFriday = null; string? strMondayRegularTime = null; string? strTuesdayRegularTime = null; string? strWednesdayRegularTime = null; string? strThursdayRegularTime = null; string? strFridayRegularTime = null; string? strMondayOvertime = null; string? strTuesdayOvertime = null; string? strWednesdayOvertime = null; string? strThursdayOvertime = null; string? strFridayOvertime = null; string? strMondayRegularPay = null; string? strTuesdayRegularPay = null; string? strWednesdayRegularPay = null; string? strThursdayRegularPay = null; string? strFridayRegularPay = null; string? strMondayOvertimePay = null; string? strTuesdayOvertimePay = null; string? strWednesdayOvertimePay = null; string? strThursdayOvertimePay = null; string? strFridayOvertimePay = null; string? strMondayNetPay = null; string? strTuesdayNetPay = null; string? strWednesdayNetPay = null; string? strThursdayNetPay = null; string? strFridayNetPay = null; string? strGrossSalary = null; DayWork? dwMonday = null; DayWork? dwTuesday = null; DayWork? dwWednesday = null; DayWork? dwThursday = null; DayWork? dwFriday = null; if (Request.HasFormContentType) { double? hSalary = null; double? monday = null; double? tuesday = null; double? wednesday = null; double? thursday = null; double? friday = null; firstName = Request.Form["txtFirstName"]; lastName = Request.Form["txtLastName"]; hSalary = double.Parse(Request.Form["txtHourlySalary"]); monday = double.Parse(Request.Form["txtMonday"]); tuesday = double.Parse(Request.Form["txtTuesday"]); wednesday = double.Parse(Request.Form["txtWednesday"]); thursday = double.Parse(Request.Form["txtThursday"]); friday = double.Parse(Request.Form["txtFriday"]); dwMonday = new(hSalary, monday); dwTuesday = new(hSalary, tuesday); dwWednesday = new(hSalary, wednesday); dwThursday = new(hSalary, thursday); dwFriday = new(hSalary, friday); strHourlySalary = $"{hSalary:F}"; strMonday = $"{monday:F}"; strTuesday = $"{tuesday:F}"; strWednesday = $"{wednesday:F}"; strThursday = $"{thursday:F}"; strFriday = $"{friday:F}"; strMondayRegularTime = $"{dwMonday.RegularTime:F}"; strTuesdayRegularTime = $"{dwTuesday.RegularTime:F}"; strWednesdayRegularTime = $"{dwWednesday.RegularTime:F}"; strThursdayRegularTime = $"{dwThursday.RegularTime:F}"; strFridayRegularTime = $"{dwFriday.RegularTime:F}"; strMondayOvertime = $"{dwMonday.Overtime:F}"; strTuesdayOvertime = $"{dwTuesday.Overtime:F}"; strWednesdayOvertime = $"{dwWednesday.Overtime:F}"; strThursdayOvertime = $"{dwThursday.Overtime:F}"; strFridayOvertime = $"{dwFriday.Overtime:F}"; strMondayRegularPay = $"{dwMonday.RegularPay:F}"; strTuesdayRegularPay = $"{dwTuesday.RegularPay:F}"; strWednesdayRegularPay = $"{dwWednesday.RegularPay:F}"; strThursdayRegularPay = $"{dwThursday.RegularPay:F}"; strFridayRegularPay = $"{dwFriday.RegularPay:F}"; strMondayOvertimePay = $"{dwMonday.OvertimePay:F}"; strTuesdayOvertimePay = $"{dwTuesday.OvertimePay:F}"; strWednesdayOvertimePay = $"{dwWednesday.OvertimePay:F}"; strThursdayOvertimePay = $"{dwThursday.OvertimePay:F}"; strFridayOvertimePay = $"{dwFriday.OvertimePay:F}"; strMondayNetPay = $"{dwMonday.NetPay:F}"; strTuesdayNetPay = $"{dwTuesday.NetPay:F}"; strWednesdayNetPay = $"{dwWednesday.NetPay:F}"; strThursdayNetPay = $"{dwThursday.NetPay:F}"; strFridayNetPay = $"{dwFriday.NetPay:F}"; strGrossSalary = $"{(dwMonday.NetPay + dwTuesday.NetPay + dwWednesday.NetPay + dwThursday.NetPay + dwFriday.NetPay):F}"; } } <h1 class="common-font text-center bold">Payroll Preparation</h1> <hr /> <form name="PayrollEvaluation" method="post" class="common-font"> <h3 class="text-center bold">Employee Time Sheet</h3> <hr /> <table style="width: 625px" align="center"> <tr> <td style="width: 125px">@Html.Label("txtFirstName", "First Name:", new { @class = "bold" })</td> <td>@Html.TextBox("txtFirstName", @firstName, new { @class = "form-control" })</td> <td>@Html.Label("txtLastName", "Last Name:", new { @class = "bold" })</td> <td>@Html.TextBox("txtLastName", @lastName, new { @class = "form-control" })</td> </tr> <tr> <td></td> <td></td> <td class="bold">Hourly Salary:</td> <td>@Html.TextBox("txtHourlySalary", @strHourlySalary, new { @class = "form-control" })</td> </tr> </table> <hr /> <table style="width: 625px" align="center"> <tr> <td style="width: 125px"> </td> <td> </td> <td> </td> <td> </td> <td> </td> <td> </td> </tr> <tr> <td class="bold">Time Worked:</td> <td>@Html.TextBox("txtMonday", @strMonday, new { @class="form-control align-right" })</td> <td>@Html.TextBox("txtTuesday", @strTuesday, new { @class="form-control align-right" })</td> <td>@Html.TextBox("txtWednesday", @strWednesday, new { @class="form-control align-right" })</td> <td>@Html.TextBox("txtThursday", @strThursday, new { @class="form-control align-right" })</td> <td>@Html.TextBox("txtFriday", @strFriday, new { @class="form-control align-right" })</td> </tr> </table> <hr /> <table style="width: 300px" align="center"> <tr> <td style="width: 50px"> </td> <td><input type="submit" value="Evaluate Payroll" name="btnEvaluatePayroll" style="width: 150px" /></td> </tr> </table> <hr /> <table style="width: 625px" align="center"> <tr style="border-bottom: 1px solid black"> <td class="bold">Pay Summary</td> <td class="text-center bold">Monday</td> <td class="text-center bold">Tuesday</td> <td class="text-center bold">Wednesday</td> <td class="text-center bold">Thursday</td> <td class="text-center bold">Friday</td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Regular Time:</td> <td class="text-center">@strMondayRegularTime</td> <td class="text-center">@strTuesdayRegularTime</td> <td class="text-center">@strWednesdayRegularTime</td> <td class="text-center">@strThursdayRegularTime</td> <td class="text-center">@strFridayRegularTime</td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Overtime:</td> <td class="text-center">@strMondayOvertime</td> <td class="text-center">@strTuesdayOvertime</td> <td class="text-center">@strWednesdayOvertime</td> <td class="text-center">@strThursdayOvertime</td> <td class="text-center">@strFridayOvertime</td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Regular Pay:</td> <td class="text-center">@strMondayRegularPay</td> <td class="text-center">@strTuesdayRegularPay</td> <td class="text-center">@strWednesdayRegularPay</td> <td class="text-center">@strThursdayRegularPay</td> <td class="text-center">@strFridayRegularPay</td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Overtime Pay:</td> <td class="text-center">@strMondayOvertimePay</td> <td class="text-center">@strTuesdayOvertimePay</td> <td class="text-center">@strWednesdayOvertimePay</td> <td class="text-center">@strThursdayOvertimePay</td> <td class="text-center">@strFridayOvertimePay</td> </tr> <tr style="border-bottom: 1px solid black"> <td class="bold">Net Pay:</td> <td class="text-center">@strMondayNetPay</td> <td class="text-center">@strTuesdayNetPay</td> <td class="text-center">@strWednesdayNetPay</td> <td class="text-center">@strThursdayNetPay</td> <td class="text-center">@strFridayNetPay</td> </tr> <tr style="border-bottom: 1px solid black"> <td> </td> <td> </td> <td> </td> <td> </td> <td class="bold">Gross Salary:</td> <td class="text-center">@strGrossSalary</td> </tr> </table> </form>
First Name: Victor Last Name: Schroeder Hourly Salary: 28.05 Monday: 6.5 Tuesday: 9 Wednesday: 8 Thursday 7.5 Friday: 10.5
Enumerations
Introduction
An enumeration is a group of names where each name represents a constant number (integer). To create an enumeration, use the enum keyword. If you are working in a Razor Page, create the enumeration in an @functions{} section. Here is an example:
@page
@model Valuable.Pages.ExerciseModel
@{
}
@functions{
enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
}
You can also create an enumeration in the body of a class. If you are planning to use an enumeration from only one class, create it inside that class without specifying its access level or by applying private. Here is an example:
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace PracticalLearning.Pages
{
private enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
public class EnumerationsModel : PageModel
{
public void OnGet()
{
}
}
}
Using an Enumeration
You can declare a variable of an enumeration type. Here is an example:
@page
@model PracticalLearning.Pages.EnumerationsModel
@{
PropertyType type;
}
@functions{
enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
}
After declaring the variable, you can initialize it. You can display a member of an enumeration to the user. To do that, if you are working in a razor page, create an HTML tab, type @ followed by the name of the variable. Here is an example:
@page @model PracticalLearning.Pages.EnumerationsModel @{ PropertyType type = PropertyType.SingleFamily; } @functions{ enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium } public class RealEstate { PropertyType type; } public class Exercise { PropertyType category; } } <p>Property Type: @type</p>
This would produce:
Property Type: SingleFamily
Other than that, an enumeration is used as done in C#. For example, you can declare an enumeration variable in the body of a class. This means that you can create a field of an enumeration. Here is an example:
@page @model PracticalLearning.Pages.EnumerationsModel @{ } @functions{ public enum HouseType { Unknown, SingleFamily, TownHouse, Condominium } public class House { HouseType propertyType; } }
You can create a function or method that returns a member of an enumeration. You can use an enumeration as a parameter type. Here is an example:
@page
@model PracticalLearning.Pages.EnumerationsModel
@{
PropertyType type = PropertyType.Condominium;
}
@functions{
enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
void Build(PropertyType prop)
{
}
}
You can create a property of an enumeration type. Here is an example:
@page
@model PracticalLearning.Pages.EnumerationsModel
@{
RealEstate reside = new();
reside.Type = PropertyType.SingleFamily;
}
@functions{
public enum PropertyType { Unknown, SingleFamily, TownHouse, Condominium }
public class RealEstate
{
PropertyType pt;
public PropertyType Type
{
get
{
return pt;
}
set
{
pt = value;
}
}
}
}
<p>Property Type: @reside.Type</p>
Tuples
Introduction
A tuple is a combination of values with the group considered as a variable. Each value, also called an item, member, or element, can be one of a primitive type (int, bool, double, or string). The types of items can be the same or different.
To create a tuple, open some parentheses. In the parentheses, type the data type of each value. Separate them with commas. Outside the parentheses, give a name to the tuple as done for a variable. Here are examples:
@{ // A tuple made of integral numbers only (int, int) coordinates; // A tuple made of strings only (string, string, string) employeeName; // A tuple made of various types of values (int, string, double) definition; }
To initialize a tuple, assign some parentheses to the variable. In the parentheses, specify the value of each item in the order the types appear in the declaration. Here is an example:
@{
(string, string, string) students = ("Aaron", "Jennifer", "Yerimah");
}
Using a Tuple
To use a tuple in a razor page, create an HTML tag and use an @ symbol to access the variable. Here is an example:
@page @model PracticalLearning.Pages.HumanResourcesModel @{ (string, string) employee = ("Robert", "Ewell"); } <p>Employee: @employee</p>
This would produce:
Employee: (Robert, Ewell)
Other than that, create and use tuples as done in C#. For example, you can declare a tuple variable using the var keyword. You can then access the elements of the tuple. Here are examples:
@page @model PracticalLearning.Pages.TuplesModel @{ var staff = (392507, "Gertrude", "Ngovayang", 96275); } <pre>Employee Record ----------------------------- Employee #: @staff.Item1 First Name: @staff.Item2 Last Name: @staff.Item3 Yearly Salary: @staff.Item4 =============================</pre>
This would produce:
Employee Record ------------------------ Employee #: 392507 First Name: Gertrude Last Name: Ngovayang Yearly Salary: 96275 ========================
To specify the name of an element, in the parentheses, type that name, a colon, and the value of the element. You can then access an element either by its ordinal name or the name you had given it, if any. Here are examples:
@page @model PracticalLearning.Pages.TuplesModel @{ var staff = (emplNumber: 394806, "Denis", lastName: "Merchand", 96275, fullTime: true); } <pre>Employee Record ----------------------------- Employee #: @staff.Item1 First Name: @staff.Item2 Last Name: @staff.lastName Yearly Salary: @staff.Item4 Employed Full-Time: @staff.Item5 =============================</pre>
This would produce:
Employee Record ----------------------------- Employee #: 394806 First Name: Denis Last Name: Merchand Yearly Salary: 96275 Employed Full-Time: True =============================
Tuples and Conditional Statements
In a tuple, since each item can be accessed on its own, you can perform a comparison on it. Here is an example:
@page
@model PracticalLearning.Pages.TuplesModel
@{
(int memNbr, string name, string category, int fee) member;
member.memNbr = 938_405;
member.name = "Matthew Groeder";
member.category = "Adult";
member.fee = -1;
if (member.category == "Child")
member.fee = 0;
if (member.category == "Yound Adult")
member.fee = 15;
if (member.category == "Adult")
member.fee = 45;
if (member.category == "Senior")
member.fee = 25;
}
<pre>+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=
Club Membership
==============================================
Member Information
----------------------------------------------
Membership #: @member.memNbr
Member Name: @member.name
Membership Type: @member.category
----------------------------------------------
Membership Fee: @member.fee
==============================================</pre>
This would produce:
+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+= Club Membership ============================================== Member Information ---------------------------------------------- Membership #: 938405 Member Name: Matthew Groeder Membership Type: Adult ---------------------------------------------- Membership Fee: $45 ==============================================
Tuples with Functions and Methods
You can create a function or method that returns a value, you can call that function and assign its return value to a variable, then use that variable as an item of a tuple. Here is the example we used:
@page @model PracticalLearning.Pages.TuplesModel @{ double EvaluateSalary(double hourly) { return hourly * 40; } int emplNbr = 138_475; double weeklySalary = 22.27; string fName = "Christoffer"; string lName = "Prize"; double sal = EvaluateSalary(weeklySalary); (int emplNumber, string fullName, double salary) employee = (emplNbr, fName + " " + lName, sal); } <pre>Employee Record ---------------------------------- Employee #: @employee.emplNumber Full Name: @employee.fullName Weekly Salary: @employee.salary ==================================</pre>
This would produce:
Employee Record ---------------------------------- Employee #: 138475 Full Name: Christoffer Prize Weekly Salary: 890.8 ==================================
A parameter of a function or method can be a tuple type. Here is an example:
@page @model PracticalLearning.Pages.TuplesModel @{ (double price, int reduction) itemInfo; (int number, string name, double price, int days) storeItem; storeItem.number = 9370592; storeItem.name = "Summer Casual V-Neck Floral Dress"; storeItem.days = 38; storeItem.price = 98.85; int discountRate = EvaluateDiscountRate(storeItem.days); itemInfo.price = storeItem.price; itemInfo.reduction = discountRate; double discountedAmount = EvaluateDiscountAmount(itemInfo); double markedPrice = storeItem.price - discountedAmount; string strOriginalPrice = $"{storeItem.price:f}"; string strDiscountAmount = $"{discountedAmount:f}"; string strMarkedPrice = $"{markedPrice:f}"; } @functions{ int EvaluateDiscountRate(int days) { int discountRate = 0; if (days > 70) discountRate = 70; else if (days > 50) discountRate = 50; else if (days > 30) discountRate = 35; else if (days > 15) discountRate = 15; return discountRate; } double EvaluateDiscountAmount((double cost, int rate) value) { double discountAmount = value.cost * value.rate / 100.00; return discountAmount; } } <pre>=================================================== Fun Department Store --------------------------------------------------- Item #: @storeItem.number Item Name: @storeItem.name Days in Store: @storeItem.days Original Price: @strOriginalPrice --------------------------------------------------- Discount Rate: @discountRate% Discount Amount: @strDiscountAmount Marked Price: @strMarkedPrice ===================================================</pre>
This produce:
=================================================== Fun Department Store --------------------------------------------------- Item #: 9370592 Item Name: Summer Casual V-Neck Floral Dress Days in Store: 38 Original Price: 98.85 --------------------------------------------------- Discount Rate: 35% Discount Amount: 34.60 Marked Price: 64.25 ===================================================
Tuples and Properties
The type of a property can be a tuple. Here is an example:
@functions { public class Trapezoid { private double _top_; public double Bottom { get; set; } public double Height { get; set; } public Trapezoid(double bottom, double height) { (Bottom, Height) = (bottom, height); } public Trapezoid(double bottom, double top, double height) { (Bottom, Top, Height) = (bottom, top, height); } public double Top { get { if (_top_ == 0.00) return Bottom * .75; return _top_; } set { _top_ = value; } } public double Area { get { return ((Bottom + Top) / 2.00) * Height; } } } }
When creating an object, you can use the constructor you want and specify the appropriate values for the parameters. Here are two examples that call each constructor:
@page @model PracticalDistribution.Pages.ExerciseModel @{ Trapezoid trap = new Trapezoid(708.83, 140.07); } <pre>Trapezoid --------------------------- Top: @trap.Top Bottom: @trap.Bottom Height: @trap.Height --------------------------- Area: @trap.Area ===========================</pre> @{ trap = new Trapezoid(708.83, 486.39, 140.07); } <pre>Trapezoid" --------------------------- Top: @trap.Top Bottom: @trap.Bottom Height: @trap.Height --------------------------- Area: @trap.Area ===========================</pre>
This would produce:
Trapezoid --------------------------- Top: 531.6225000000001 Bottom: 708.83 Height: 140.07 --------------------------- Area: 86875.0908375); =========================== Trapezoid" --------------------------- Top: 486.39 Bottom: 708.83 Height: 140.07 --------------------------- Area: 83707.2327
Practical Learning: Introducing Exception Handling
body { } .delimiter { margin: auto; width: 450px; } .top-bar { border-bottom: 6px solid blue; background-color: #022d50 !important; } .common-font { font-family: Georgia, Garamond, 'Times New Roman', serif; } .navbar-light .navbar-brand { color: white; } .navbar-light .navbar-brand:hover { color: yellow; } .navbar-light .navbar-brand:focus { color: khaki; } .navbar-light .navbar-brand { font-family: Georgia, Garamond, 'Times New Roman', serif; } .nav-link { font-family: Georgia, Garamond, 'Times New Roman', serif; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>@ViewData["Title"] - DeltaX Services</title> <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" /> <link rel="stylesheet" href="~/css/site.css" asp-append-version="true" /> <link rel="stylesheet" href="~/css/TaxPreparation.css" asp-append-version="true" /> </head> <body> <header> <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-white border-bottom box-shadow mb-3 top-bar"> <div class="container"> <a class="navbar-brand" asp-area="" asp-page="/Index">DeltaX Home</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between"> <ul class="navbar-nav flex-grow-1"> <li class="nav-item"> <a class="nav-link text-white" asp-area="" asp-page="/Index">Home</a> </li> <li class="nav-item"> <a class="nav-link text-white" asp-area="" asp-page="/Privacy">Privacy</a> </li> </ul> </div> </div> </nav> </header> <div class="container"> <main role="main" class="pb-3"> @RenderBody() </main> </div> <footer class="border-top footer text-muted"> <div class="container"> <p class="text-center common-font">© 2022 - DeltaX Services - <a asp-area="" asp-page="/Privacy">Privacy</a></p> </div> </footer> <script src="~/lib/jquery/dist/jquery.min.js"></script> <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script> <script src="~/js/site.js" asp-append-version="true"></script> @await RenderSectionAsync("Scripts", required: false) </body> </html>
@page @model IndexModel @{ ViewData["Title"] = "Home page"; } @{ /* New York State and New York City * https://www.tax.ny.gov/pdf/current_forms/it/it2105i.pdf */ string strNetPay = "0.00"; string strTaxAmount = "0.00"; double taxRateExcess = 0.00; double amountInExcess = 0.00; string strGrossSalary = "0.00"; if (Request.HasFormContentType) { double excess; double taxAmount; double grossSalary = double.Parse(Request.Form["txtGrossSalary"]); // Married Filing Jointly and Qualifying Widow(er) if(grossSalary is (>= 0.00) and (<= 17_150)) { taxRateExcess = 4.00; amountInExcess = 0.00; taxAmount = grossSalary * 4.00 / 100.00; } else if(grossSalary is (> 17_150) and (<= 23_600)) { taxRateExcess = 4.50; amountInExcess = 686; excess = (grossSalary - 17_150) * 4.5 / 100.00; taxAmount = excess + 686; } else if(grossSalary is (> 23_600) and (<= 27_900)) { taxRateExcess = 5.25; amountInExcess = 976; excess = (grossSalary - 23_600) * 5.25 / 100.00; taxAmount = excess + 976; } else if(grossSalary is (> 27_900) and (<= 161_550)) { taxRateExcess = 5.85; amountInExcess = 1_202; excess = (grossSalary - 27_900) * 5.85 / 100.00; taxAmount = excess + 1_202; } else if(grossSalary is (> 161_550) and (<= 323_200)) { taxRateExcess = 6.25; amountInExcess = 9_021; excess = (grossSalary - 161_550) * 6.25 / 100.00; taxAmount = excess + 9_021; } else if(grossSalary is (> 323_200) and (<= 2_155_350)) { taxRateExcess = 6.85; amountInExcess = 19_124; excess = (grossSalary - 323_200) * 6.85 / 100.00; taxAmount = excess + 19_124; } else if(grossSalary is (> 2_155_350) and (<= 5_000_000)) { taxRateExcess = 9.65; amountInExcess = 144_626; excess = (grossSalary - 2_155_350) * 9.65 / 100.00; taxAmount = excess + 144_626; } else if(grossSalary is (> 5_000_000) and (<= 25_000_000)) { taxRateExcess = 10.3; amountInExcess = 419_135; excess = (grossSalary - 5_000_000) * 10.3 / 100.00; taxAmount = excess + 419_135; } else // if(grossSalary is > 25_000_000) { taxRateExcess = 10.9; amountInExcess = 2_479_135; excess = (grossSalary - 25_000_000) * 10.9 / 100.00; taxAmount = excess + 2_479_135; } strGrossSalary = $"{grossSalary:F}"; strTaxAmount = $"{taxAmount:F}"; strNetPay = $"{(grossSalary - taxAmount):F}"; } } <h1 class="text-center common-font">- DeltaX - Tax Preparation Services -</h1> <hr /> <h2 class="text-center common-font">- New York State - State Income Tax -</h2> <hr /> <div class="delimiter common-font"> <form name="frmTaxPreparation" method="post"> <table class="table common-font"> <tr> <td width="150">@Html.Label("txtGrossSalary", "Gross Salary:", new { @class = "" })</td> <td>@Html.TextBox("txtGrossSalary", @strGrossSalary, new { @class = "form-control" })</td> </tr> <tr> <td></td> <td class="pcenter"><input type="submit" value="Evaluate Taxes" class="btn-primary" /></td> </tr> </table> </form> <table class="table"> <tr> <td width="250">Gross Salary:</td> <td>@strGrossSalary</td> </tr> <tr> <td>Tax Rate in Excess:</td> <td>@taxRateExcess%</td> </tr> <tr> <td>Amount Added in Excess:</td> <td>@amountInExcess</td> </tr> <tr> <td>Tax Amount from Income:</td> <td>@strTaxAmount</td> </tr> <tr> <td>Net Pay:</td> <td>@strNetPay</td> </tr> </table> </div>
Delegates
Introduction
A delegate is a function or method that is treated as an object.
Creating a Delegate
To create a delegate, you use the delegate keyword. Normally, you start with some options such new, public, private, protected, or internal. This is followed by the return type, a name for the delegate, and at least the parentheses. Here is an example:
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace Exercises.Pages
{
delegate void Observation();
public class ExerciseModel : PageModel
{
public void OnGet()
{
}
}
}
You can then create a function or method to which you will associate the delegate. After creating the function or method, you can declare a variable of the delegate type, using the new or the dynamic keyword, and pass the name of the function or method as argument. Here are examples:
@page @model Exercises.Pages.ExerciseModel @using static System.Console @{ // A Var variable for a delegate var qt = new Quote(Create); // A dynamic variable dynamic talk = new Quote(Create); } @functions{ void Create() { WriteLine("A man with one watch knows what time it is; a man with two watches is never quite sure. - Lee Segall -"); } }
After this declaration, to use the delegate, you can call the variable as when calling a function or method.
Characteristics of Delegates
A delegate is a type of object between a function/method and a class/structure/record. As a function/method, a delegate can use one or more parameters, in which you would call it with arguments. As a type, a delegate can be returned from a function or method and a delegate can be passed as argument.
Lambda Expressions
A lambda expression is a series of techniques to simplify the way delegates are created and used.
.NET Delegates
While the concept of delegates is huge and completely supported in C#, the .NET Framework has its own, huge support for delegate. This support starts with a series of classes.
The functions or methods that don't return a value (void) are supported by the Action delegate. The Action delegate is overloaded with many versions that each takes a different number of argumements.
The functions or methods that must return a value or object are supported in the .NET Framework by the Func delegate. The Funct delegate too is overloaded with many versions that each takes a certain number of arguments.
|
|||
Previous | Copyright © 2001-2023, C# Key | Saturday 17 December 2022 | Next |
|