Learning Path Details
Complete Foundation in C# Course Series from Tim Corey
Description:
The Complete Foundation in C# Course Series is a series of 10 modular courses; it is the predecessor to Tim Corey's current C# Mastercourse. Please see the individual course modules for information specific to each module.
Key Takeaways:
Completing the course series, I have the skills to be a junior to mid-level C# developer.
Technologies Learned:
- .NET;
- .NET Core;
- .NET Core 3.0;
- .NET Core 3.1;
- .NET Framework;
- .NET Framework 4.5;
- .NET Framework 4.6.1;
- .NET Framework 4.7;
- .NET Framework 4.7.2;
- .NET Framework 4.8;
- .NET Standard;
- .NET Standard 2.0;
- Abstract Classes;
- Access Modifiers;
- Application Design;
- arrays;
- ASP.NET Core Web API;
- ASP.NET Core Web Application (Model-View-Controller);
- ASP.NET Core Web Application (Razor Pages);
- booleans;
- C#;
- Child Classes of the Exception Class;
- Class Library;
- Classes;
- Console Application;
- CosmosDB;
- Dapper;
- Debugging;
- decimal floating point values;
- Dictionaries;
- do/while loops;
- double-precision floating point values;
- Entity Framework;
- Event Handlers;
- Event Listeners;
- Events;
- Exceptions (Class);
- Extension Methods;
- for loops;
- foreach loops;
- Generics;
- Handling Exceptions;
- if/else;
- Inheritance;
- Instatiated Classes;
- integer values;
- Interfaces;
- Lambda Expressions;
- LINQ;
- Lists;
- Method Overrides;
- methods;
- Mongo DB;
- Multiple Catch statements;
- MySQL;
- Namespaces;
- Object-Oriented Programming;
- Overloaded Methods;
- Properties;
- SQL;
- SQL Server Database Project;
- SQLite;
- Static Classes;
- string interpolation;
- strings;
- switch/case;
- Testing;
- Text File Data Access;
- try/catch;
- try/catch/finally;
- type conversion;
- Unit Tests;
- Using Breakpoints;
- Visual Studio Debugger;
- while loops;
- Windows Forms Application;
- WOULD Framework;
- WPF Application;
- XAML;
- xUnit Test Project;
This learning resource was completed on 12/31/2021.
Find the Resource here:
Practice Projects
Hotel Management App
Description:
The homework from Module 9, Hotel Management App, of the Complete Foundation in C# Course Series from Tim Corey. We have been commissioned to create a hotel management application. We need a web portal that allows people to book an available room. We also need a desktop app for when they check in.
We need to create a minimum viable product (MVP) that will allow the customer to get going and to identify what features should be added later.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- .NET Core Web Application (Razor Pages);
- .NET Standard;
- .NET Standard 2.1;
- C#;
- Class Library;
- SQL;
- SQL Server Database Project;
- SQLite;
- WPF Application;
Find the Project here:
Code Snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using HotelAppLibrary.Databases;
using HotelAppLibrary.Models;
namespace HotelAppLibrary.Data
{
public class SqlData : IDatabaseData
{
private readonly ISqlDataAccess _db;
private const string connectionStringName = "SqlDb";
public SqlData(ISqlDataAccess db)
{
_db = db;
}
public List<RoomTypeModel> GetAvailableRoomTypes(DateTime startDate, DateTime endDate)
{
return _db.LoadData<RoomTypeModel, dynamic>("dbo.spRoomTypes_GetAvailableTypes",
new { startDate, endDate },
connectionStringName,
true);
}
public void BookGuest(string firstName, string lastName, DateTime startDate, DateTime endDate, int roomTypeId)
{
GuestModel guest = _db.LoadData<GuestModel, dynamic>("dbo.spGuests_InsertGuest",
new { firstName, lastName },
connectionStringName,
true).First();
RoomTypeModel roomType = _db.LoadData<RoomTypeModel, dynamic>("SELECT * FROM dbo.RoomTypes where Id = @Id",
new { Id = roomTypeId },
connectionStringName,
false).First();
TimeSpan timeStaying = endDate.Date.Subtract(startDate.Date);
List<RoomModel> availableRooms = _db.LoadData<RoomModel, dynamic>("dbo.spRooms_GetAvailableRooms",
new { startDate, endDate, roomTypeId },
connectionStringName,
true);
_db.SaveData("dbo.spBookings_Insert",
new
{
roomId = availableRooms.First().Id,
guestId = guest.Id,
startDate,
endDate,
totalCost = timeStaying.Days * roomType.Price
},
connectionStringName,
true);
}
public List<BookingFullModel> SearchBookings(string lastName)
{
return _db.LoadData<BookingFullModel, dynamic>("dbo.spBookings_Search",
new { lastName, startDate = DateTime.Now.Date },
connectionStringName,
true);
}
public void CheckInGuest(int bookingId)
{
_db.SaveData("dbo.spBookings_CheckIn", new { Id = bookingId }, connectionStringName, true);
}
public RoomTypeModel GetRoomTypeById(int id)
{
return _db.LoadData<RoomTypeModel, dynamic>("dbo.spRoomTypes_GetById",
new { id },
connectionStringName,
true).FirstOrDefault();
}
}
}
Entity Framework Core
Description:
The homework from Lesson 14, Entity Framework Core, of Module 8, Data Access, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a simple database using code first. Create models for People, Addresses, and Employers. Make sure it builds and that you can load and save data.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Class Library;
- Console Application;
- Entity Framework;
Find the Project here:
https://github.com/Spartan-CSharp/DataAccess-EntityFrameworkCore
Code Snippet:
using System.Collections.Generic;
using System.Linq;
using DataAccessLibrary.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace DataAccessLibrary.EFDataAccess
{
public class EFCrud : ICrud
{
private readonly IConfiguration _configuration;
private readonly string _connectionStringName;
public EFCrud(IConfiguration configuration, string connectionStringName)
{
_configuration = configuration;
_connectionStringName = connectionStringName;
}
public void CreatePerson(Person person)
{
using ( EFContext db = new EFContext() )
{
_ = db.People.Add(person);
_ = db.SaveChanges();
}
}
public void CreateEmployer(Employer employer)
{
using ( EFContext db = new EFContext() )
{
_ = db.Employers.Add(employer);
_ = db.SaveChanges();
}
}
public void CreateAddress(Address address)
{
using ( EFContext db = new EFContext() )
{
_ = db.Addresses.Add(address);
_ = db.SaveChanges();
}
}
public List<Person> RetrieveAllPeople()
{
using ( EFContext db = new EFContext() )
{
List<Person> output = db.People.Include(e => e.Employer).Include(a => a.Addresses).ToList();
return output;
}
}
public Person RetrievePersonById(int id)
{
using ( EFContext db = new EFContext() )
{
Person output = db.People.Include(e => e.Employer).Include(a => a.Addresses).Where(p => p.Id == id).First();
return output;
}
}
public List<Person> RetrievePeopleByEmployerId(int employerId)
{
using ( EFContext db = new EFContext() )
{
List<Person> output = db.People.Include(e => e.Employer).Include(a => a.Addresses).Where(p => p.Employer.Id == employerId).ToList();
return output;
}
}
public List<Employer> RetrieveAllEmployers()
{
using ( EFContext db = new EFContext() )
{
List<Employer> output = db.Employers.Include(a => a.Addresses).ToList();
return output;
}
}
public Employer RetrieveEmployerById(int id)
{
using ( EFContext db = new EFContext() )
{
Employer output = db.Employers.Include(a => a.Addresses).Where(e => e.Id == id).First();
return output;
}
}
public List<Address> RetrieveAllAddresses()
{
using ( EFContext db = new EFContext() )
{
List<Address> output = db.Addresses.ToList();
return output;
}
}
public Address RetrieveAddressById(int id)
{
using ( EFContext db = new EFContext() )
{
Address output = db.Addresses.Where(a => a.Id == id).First();
return output;
}
}
public void UpdatePerson(Person person)
{
using ( EFContext db = new EFContext() )
{
Person record = db.People.Include(e => e.Employer).Include(a => a.Addresses).Where(p => p.Id == person.Id).First();
record.FirstName = person.FirstName;
record.LastName = person.LastName;
record.IsActive = person.IsActive;
record.Addresses.Clear();
foreach ( Address item in person.Addresses )
{
record.Addresses.Add(item);
}
record.Employer = person.Employer;
_ = db.SaveChanges();
}
}
public void UpdateEmployer(Employer employer)
{
using ( EFContext db = new EFContext() )
{
Employer record = db.Employers.Include(a => a.Addresses).Where(e => e.Id == employer.Id).First();
record.CompanyName = employer.CompanyName;
record.Addresses.Clear();
foreach ( Address item in employer.Addresses )
{
record.Addresses.Add(item);
}
_ = db.SaveChanges();
}
}
public void UpdateAddress(Address address)
{
using ( EFContext db = new EFContext() )
{
Address record = db.Addresses.Where(a => a.Id == address.Id).First();
record.StreetAddress = address.StreetAddress;
record.City = address.City;
record.State = address.State;
record.ZipCode = address.ZipCode;
_ = db.SaveChanges();
}
}
public void DeletePerson(Person person)
{
using ( EFContext db = new EFContext() )
{
Person record = db.People.Include(e => e.Employer).Include(a => a.Addresses).Where(p => p.Id == person.Id).First();
_ = db.People.Remove(record);
_ = db.SaveChanges();
}
}
public void DeleteEmployer(Employer employer)
{
using ( EFContext db = new EFContext() )
{
Employer record = db.Employers.Include(a => a.Addresses).Where(e => e.Id == employer.Id).First();
_ = db.Employers.Remove(record);
_ = db.SaveChanges();
}
}
public void DeleteAddress(Address address)
{
using ( EFContext db = new EFContext() )
{
Address record = db.Addresses.Where(a => a.Id == address.Id).First();
_ = db.Addresses.Remove(record);
_ = db.SaveChanges();
}
}
}
}
Linq/Lambdas
Description:
The homework from Lesson 13, Linq/Lambdas, of Module 8, Data Access, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a list of PersonModel. Filter the list twice – once using the query syntax and once using the method syntax. Perform at least a filter and sort each time.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using LinqLambdaConsoleAppUI.Models;
namespace LinqLambdaConsoleAppUI
{
internal class Program
{
private static void Main()
{
Console.WriteLine("Query Syntax:");
RunQueries();
Console.WriteLine();
Console.WriteLine("Method Syntax:");
RunMethods();
Console.WriteLine();
Console.WriteLine("Done Processing!");
_ = Console.ReadLine();
}
private static void RunQueries()
{
List<PersonModel> people = SampleData.GeneratePersonModels();
List<EmployerModel> employers = SampleData.GenerateEmployerModels();
List<AddressModel> addresses = SampleData.GenerateAddressModels();
IOrderedEnumerable<PersonModel> results = from p in people where p.Addresses.Count() > 1 orderby p.LastName select p;
foreach ( PersonModel item in results )
{
Console.WriteLine($"{item.FirstName} {item.LastName} - {item.Addresses.Count()}");
}
}
private static void RunMethods()
{
List<PersonModel> people = SampleData.GeneratePersonModels();
List<EmployerModel> employers = SampleData.GenerateEmployerModels();
List<AddressModel> addresses = SampleData.GenerateAddressModels();
IOrderedEnumerable<PersonModel> results = people.Where(x => x.Addresses.Count > 1).OrderBy(x => x.LastName).ThenBy(x => x.FirstName);
foreach ( PersonModel item in results )
{
Console.WriteLine($"{item.FirstName} {item.LastName} - {item.Addresses.Count()}");
}
}
}
}
APIs
Description:
The homework from Lesson 12, APIs, of Module 8, Data Access, of the Complete Foundation in C# Course Series from Tim Corey. We are to call the SWAPI (https://swapi.co) for a person and load models for the person and then load the models for each film they were in.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- ASP.NET Web Application (Razor Pages);
- C#;
Find the Project here:
Code Snippet:
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using SWAPIWebApplication.Models;
namespace SWAPIWebApplication.Pages
{
public class SWAPIModel : PageModel
{
private readonly ILogger<SWAPIModel> _logger;
private readonly HttpClient _httpClient;
public PersonModel Person { get; set; }
public List<FilmModel> Films { get; set; } = new List<FilmModel>();
public SWAPIModel(ILogger<SWAPIModel> logger, IHttpClientFactory httpClientFactory)
{
_logger = logger;
_httpClient = httpClientFactory.CreateClient();
_httpClient.DefaultRequestHeaders.Clear();
_httpClient.DefaultRequestHeaders.Accept.Clear();
_httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task OnGetAsync()
{
_logger.LogInformation("OnGetAsync SWAPI Page");
Person = await GetPersonAsync("https://swapi.dev/api/people/1");
foreach ( string filmUrl in Person.Films )
{
FilmModel film = await GetFilmAsync(filmUrl);
Films.Add(film);
}
}
private async Task<PersonModel> GetPersonAsync(string personUrl)
{
using ( HttpResponseMessage response = await _httpClient.GetAsync(personUrl) )
{
if ( response.IsSuccessStatusCode )
{
JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
string responseText = await response.Content.ReadAsStringAsync();
PersonModel person = JsonSerializer.Deserialize<PersonModel>(responseText, options);
return person;
}
else
{
throw new ApplicationException(response.ReasonPhrase);
}
}
}
private async Task<FilmModel> GetFilmAsync(string filmUrl)
{
using ( HttpResponseMessage response = await _httpClient.GetAsync(filmUrl) )
{
if ( response.IsSuccessStatusCode )
{
JsonSerializerOptions options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
};
string responseText = await response.Content.ReadAsStringAsync();
FilmModel film = JsonSerializer.Deserialize<FilmModel>(responseText, options);
return film;
}
else
{
throw new ApplicationException(response.ReasonPhrase);
}
}
}
}
}
Text Files
Description:
The homework from Lesson 11, Text Files, of Module 8, Data Access, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a CSV file that holds Person information. Load the file into models in C# and save the data from C# back into the CSV file.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Class Library;
- Console Application;
Find the Project here:
Code Snippet:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using DataAccessLibrary.Models;
namespace DataAccessLibrary.TextFileDataAccess
{
public class TextFileCRUD : ICrud
{
private readonly string _filePath;
public TextFileCRUD(string fileName)
{
string filePath = Directory.GetCurrentDirectory();
_filePath = filePath + "\\" + fileName;
}
public void CreatePerson(PersonModel person)
{
List<string> addresses = new List<string>();
foreach ( AddressModel address in person.Addresses )
{
addresses.Add($"{address.StreetAddress}|{address.City}|{address.State}|{address.ZipCode}");
}
string addressString = string.Join(";", addresses);
string employerString = string.Empty;
if ( person.Employer != null )
{
employerString += person.Employer.CompanyName + "^";
List<string> employerAddresses = new List<string>();
foreach ( AddressModel address in person.Addresses )
{
employerAddresses.Add($"{address.StreetAddress}|{address.City}|{address.State}|{address.ZipCode}");
}
employerString += string.Join(";", employerAddresses);
}
string personString = $"{person.Id},{person.FirstName},{person.LastName},{person.IsActive},{employerString},{addressString}";
List<string> existingLines = TextFileDataAccess.ReadAllCSVEntries(_filePath);
existingLines.Add(personString);
TextFileDataAccess.WriteAllCSVEntries(_filePath, existingLines);
}
public void DeletePerson(PersonModel person)
{
List<PersonModel> people = RetrieveAllPeople();
people.RemoveAt(people.FindIndex(x => x.Id == person.Id));
List<string> updateList = new List<string>();
foreach ( PersonModel p in people )
{
List<string> addresses = new List<string>();
foreach ( AddressModel address in p.Addresses )
{
addresses.Add($"{address.StreetAddress}|{address.City}|{address.State}|{address.ZipCode}");
}
string addressString = string.Join(";", addresses);
string employerString = string.Empty;
if ( p.Employer != null )
{
employerString += p.Employer.CompanyName + "^";
List<string> employerAddresses = new List<string>();
foreach ( AddressModel address in p.Addresses )
{
employerAddresses.Add($"{address.StreetAddress}|{address.City}|{address.State}|{address.ZipCode}");
}
employerString += string.Join(";", employerAddresses);
}
string personString = $"{p.Id},{p.FirstName},{p.LastName},{p.IsActive},{employerString},{addressString}";
updateList.Add(personString);
}
TextFileDataAccess.WriteAllCSVEntries(_filePath, updateList);
}
public List<PersonModel> RetrieveAllPeople()
{
List<PersonModel> output = new List<PersonModel>();
List<string> existingLines = TextFileDataAccess.ReadAllCSVEntries(_filePath);
foreach ( string line in existingLines )
{
string[] cols = line.Split(',');
if ( cols.Length != 6 )
{
throw new ApplicationException($"Bad Line in CSV File {_filePath}: {line}");
}
PersonModel person = new PersonModel
{
Id = new Guid(cols[0]),
FirstName = cols[1],
LastName = cols[2],
IsActive = cols[3].ToLower() == "true"
};
if ( cols[4].Length > 0 )
{
// split out the employer data
string[] employerCols = cols[4].Split('^');
if ( employerCols.Length != 2 )
{
throw new ApplicationException($"Bad Employer in CSV File {_filePath} Line {line}: {cols[4]}");
}
person.Employer = new EmployerModel
{
CompanyName = employerCols[0]
};
string[] addresses = employerCols[1].Split(';');
foreach ( string address in addresses )
{
string[] addressCols = address.Split('|');
if ( addressCols.Length != 4 )
{
throw new ApplicationException($"Bad Employer Address in CSV File {_filePath} Line {line}, Employer {cols[4]}: {address}");
}
AddressModel addressModel = new AddressModel
{
StreetAddress = addressCols[0],
City = addressCols[1],
State = addressCols[2],
ZipCode = addressCols[3]
};
person.Employer.Addresses.Add(addressModel);
}
}
if ( cols[5].Length > 0 )
{
string[] addresses = cols[5].Split(';');
foreach ( string address in addresses )
{
string[] addressCols = address.Split('|');
if ( addressCols.Length != 4 )
{
throw new ApplicationException($"Bad Address in CSV File {_filePath} Line {line}: {address}");
}
AddressModel addressModel = new AddressModel
{
StreetAddress = addressCols[0],
City = addressCols[1],
State = addressCols[2],
ZipCode = addressCols[3]
};
person.Addresses.Add(addressModel);
}
}
output.Add(person);
}
return output;
}
public PersonModel RetrievePersonById(Guid id)
{
PersonModel output = RetrieveAllPeople().FirstOrDefault(x => x.Id == id);
return output ?? throw new ApplicationException($"Person with Id of {id} not found in file {_filePath}");
}
public void UpdatePerson(PersonModel person)
{
List<PersonModel> people = RetrieveAllPeople();
PersonModel personToUpdate = people.FirstOrDefault(x => x.Id == person.Id) ?? throw new ApplicationException($"Person with Id of {person.Id} not found in file {_filePath}");
personToUpdate = person;
List<string> updateList = new List<string>();
foreach ( PersonModel p in people )
{
List<string> addresses = new List<string>();
foreach ( AddressModel address in p.Addresses )
{
addresses.Add($"{address.StreetAddress}|{address.City}|{address.State}|{address.ZipCode}");
}
string addressString = string.Join(";", addresses);
string employerString = string.Empty;
if ( p.Employer != null )
{
employerString += p.Employer.CompanyName + "^";
List<string> employerAddresses = new List<string>();
foreach ( AddressModel address in p.Addresses )
{
employerAddresses.Add($"{address.StreetAddress}|{address.City}|{address.State}|{address.ZipCode}");
}
employerString += string.Join(";", employerAddresses);
}
string personString = $"{p.Id},{p.FirstName},{p.LastName},{p.IsActive},{employerString},{addressString}";
updateList.Add(personString);
}
TextFileDataAccess.WriteAllCSVEntries(_filePath, updateList);
}
}
}
CosmosDB
Description:
The homework from the Lesson 10, CosmosDB, of Module 8, Data Access, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a simple database in CosmosDB that holds People, Addresses, and Employers. Make sure it builds and that you can load and save data in C#.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Class Library;
- Console Application;
- CosmosDB;
Find the Project here:
Code Snippet:
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using DataAccessLibrary.Models;
using Microsoft.Azure.Cosmos;
namespace DataAccessLibrary.CosmosDBDataAccess
{
public class CosmosDBCrud : ICrud
{
private readonly Database _database;
public CosmosDBCrud(string endpointUri, string primaryKey, string databaseName)
{
CosmosClient cosmosClient = new CosmosClient(endpointUri, primaryKey);
_database = cosmosClient.GetDatabase(databaseName);
}
public async Task CreateAddressAsync(AddressModel address)
{
await _database.CreateRecordAsync("Addresses", address);
}
public async Task CreateEmployerAsync(EmployerModel employer)
{
await _database.CreateRecordAsync("Employers", employer);
}
public async Task CreatePersonAsync(PersonModel person)
{
await _database.CreateRecordAsync("People", person);
}
public async Task DeleteAddressAsync(AddressModel address)
{
await _database.DeleteRecordAsync<AddressModel>("Addresses", address.Id.ToString(), new PartitionKey(address.ZipCode));
}
public async Task DeleteEmployerAsync(EmployerModel employer)
{
await _database.DeleteRecordAsync<AddressModel>("Employers", employer.Id.ToString(), new PartitionKey(employer.CompanyName));
}
public async Task DeletePersonAsync(PersonModel person)
{
await _database.DeleteRecordAsync<AddressModel>("People", person.Id.ToString(), new PartitionKey(person.LastName));
}
public async Task<AddressModel> RetrieveAddressByIdAsync(Guid id)
{
AddressModel output = await _database.RetrieveRecordByIdAsync<AddressModel>("Addresses", id.ToString());
return output;
}
public async Task<List<AddressModel>> RetrieveAllAddressesAsync()
{
List<AddressModel> output = await _database.RetrieveRecordsAsync<AddressModel>("Addresses");
return output;
}
public async Task<List<EmployerModel>> RetrieveAllEmployersAsync()
{
List<EmployerModel> output = await _database.RetrieveRecordsAsync<EmployerModel>("Employers");
return output;
}
public async Task<List<PersonModel>> RetrieveAllPeopleAsync()
{
List<PersonModel> output = await _database.RetrieveRecordsAsync<PersonModel>("People");
return output;
}
public async Task<EmployerModel> RetrieveEmployerByIdAsync(Guid id)
{
EmployerModel output = await _database.RetrieveRecordByIdAsync<EmployerModel>("Employers", id.ToString());
return output;
}
public async Task<List<PersonModel>> RetrievePeopleByEmployerIdAsync(Guid employerId)
{
List<PersonModel> output = (await RetrieveAllPeopleAsync()).FindAll(x => x.Employer?.Id == employerId);
return output;
}
public async Task<PersonModel> RetrievePersonByIdAsync(Guid id)
{
PersonModel output = await _database.RetrieveRecordByIdAsync<PersonModel>("People", id.ToString());
return output;
}
public async Task UpdateAddressAsync(AddressModel address)
{
await _database.UpdateRecordAsync("Addresses", address);
}
public async Task UpdateEmployerAsync(EmployerModel employer)
{
await _database.UpdateRecordAsync("Employers", employer);
}
public async Task UpdatePersonAsync(PersonModel person)
{
await _database.UpdateRecordAsync("People", person);
}
}
}
MongoDB
Description:
The homework from the Lesson 9, MongoDB, of Module 8, Data Access, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a simple database in MongoDB that holds People, Addresses, and Employers. Make sure it builds and that you can load and save data in C#.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Class Library;
- Console Application;
- MongoDB;
Find the Project here:
Code Snippet:
using System;
using System.Collections.Generic;
using DataAccessLibrary.Models;
using MongoDB.Driver;
namespace DataAccessLibrary.MongoDBDataAccess
{
public class MongoDBCrud : ICrud
{
private readonly IMongoDatabase _mongoDatabase;
public MongoDBCrud(string databaseName, string connectionString)
{
MongoClient client = new MongoClient(connectionString);
_mongoDatabase = client.GetDatabase(databaseName);
}
public void CreateAddress(AddressModel address)
{
_mongoDatabase.CreateRecord("Addresses", address);
}
public void CreateEmployer(EmployerModel employer)
{
_mongoDatabase.CreateRecord("Employers", employer);
}
public void CreatePerson(PersonModel person)
{
_mongoDatabase.CreateRecord("People", person);
}
public void DeleteAddress(AddressModel address)
{
_mongoDatabase.DeleteRecord<AddressModel>("Addresses", address.Id);
}
public void DeleteEmployer(EmployerModel employer)
{
_mongoDatabase.DeleteRecord<EmployerModel>("Employers", employer.Id);
}
public void DeletePerson(PersonModel person)
{
_mongoDatabase.DeleteRecord<PersonModel>("People", person.Id);
}
public AddressModel RetrieveAddressById(Guid id)
{
AddressModel output = _mongoDatabase.RetrieveRecordById<AddressModel>("Addresses", id);
return output;
}
public List<AddressModel> RetrieveAllAddresses()
{
List<AddressModel> output = _mongoDatabase.RetrieveRecords<AddressModel>("Addresses");
return output;
}
public List<EmployerModel> RetrieveAllEmployers()
{
List<EmployerModel> output = _mongoDatabase.RetrieveRecords<EmployerModel>("Employers");
return output;
}
public List<PersonModel> RetrieveAllPeople()
{
List<PersonModel> output = _mongoDatabase.RetrieveRecords<PersonModel>("People");
return output;
}
public EmployerModel RetrieveEmployerById(Guid id)
{
EmployerModel output = _mongoDatabase.RetrieveRecordById<EmployerModel>("Employers", id);
return output;
}
public List<PersonModel> RetrievePeopleByEmployerId(Guid employerId)
{
List<PersonModel> output = RetrieveAllPeople().FindAll(x => x.Employer?.Id == employerId);
return output;
}
public PersonModel RetrievePersonById(Guid id)
{
PersonModel output = _mongoDatabase.RetrieveRecordById<PersonModel>("People", id);
return output;
}
public void UpdateAddress(AddressModel address)
{
_mongoDatabase.UpdateRecord("Addresses", address.Id, address);
}
public void UpdateEmployer(EmployerModel employer)
{
_mongoDatabase.UpdateRecord("Employers", employer.Id, employer);
}
public void UpdatePerson(PersonModel person)
{
_mongoDatabase.UpdateRecord("People", person.Id, person);
}
}
}
MySQL
Description:
The homework from the Lesson 7, MySQL, of Module 8, Data Access, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a simple database in MySQL that holds People, Addresses, and Employers. Make sure it builds and that you can load and save data in C#.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Class Library;
- Console Application;
- MySQL;
Find the Project here:
Code Snippet:
using System.Collections.Generic;
using System.Linq;
using Dapper;
using DataAccessLibrary.Models;
namespace DataAccessLibrary.MySQLDataAccess
{
public class MySQLCrud : ICrud
{
private readonly string _connectionString;
public MySQLCrud(string connectionString)
{
_connectionString = connectionString;
}
public void CreatePerson(PersonBaseModel person)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@FirstName", person.FirstName);
parameters.Add("@LastName", person.LastName);
parameters.Add("@IsActive", person.IsActive);
parameters.Add("@EmployerId", person.EmployerId);
string sqlstatement = "INSERT INTO People (FirstName, LastName, IsActive, EmployerId) VALUES (@FirstName, @LastName, @IsActive, @EmployerId);";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM People WHERE FirstName = @FirstName AND LastName = @LastName AND IsActive = @IsActive AND EmployerId = @EmployerId;";
person.Id = MySQLDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreateEmployer(EmployerBaseModel employer)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@CompanyName", employer.CompanyName);
string sqlstatement = "INSERT INTO Employers (CompanyName) VALUES (@CompanyName);";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM Employers WHERE CompanyName = @CompanyName;";
employer.Id = MySQLDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreateAddress(AddressModel address)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@StreetAddress", address.StreetAddress);
parameters.Add("@City", address.City);
parameters.Add("@State", address.State);
parameters.Add("@ZipCode", address.ZipCode);
string sqlstatement = "INSERT INTO Addresses (StreetAddress, City, State, ZipCode) VALUES (@StreetAddress, @City, @State, @ZipCode);";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM Addresses WHERE StreetAddress = @StreetAddress AND City = @City AND State = @State AND ZipCode = @ZipCode;";
address.Id = MySQLDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreatePersonAddress(PersonAddressBaseModel personAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@PersonId", personAddress.PersonId);
parameters.Add("@AddressId", personAddress.AddressId);
string sqlstatement = "INSERT INTO PersonAddresses (PersonId, AddressId) VALUES (@PersonId, @AddressId);";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM PersonAddresses WHERE PersonId = @PersonId AND AddressId = @AddressId;";
personAddress.Id = MySQLDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreateEmployerAddress(EmployerAddressBaseModel employerAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@EmployerId", employerAddress.EmployerId);
parameters.Add("@AddressId", employerAddress.AddressId);
string sqlstatement = "INSERT INTO EmployerAddresses (EmployerId, AddressId) VALUES (@EmployerId, @AddressId);";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM EmployerAddresses WHERE EmployerId = @EmployerId AND AddressId = @AddressId;";
employerAddress.Id = MySQLDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public List<PersonBaseModel> RetrieveAllPeople()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, FirstName, LastName, IsActive, EmployerId FROM People;";
List<PersonBaseModel> output = MySQLDataAccess.ReadData<PersonBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public PersonBaseModel RetrievePersonById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, FirstName, LastName, IsActive, EmployerId FROM People WHERE Id = @Id;";
PersonBaseModel output = MySQLDataAccess.ReadData<PersonBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<PersonBaseModel> RetrievePeopleByEmployerId(int employerId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@EmployerId", employerId);
string sqlstatement = "SELECT Id, FirstName, LastName, IsActive, EmployerId FROM People WHERE EmployerId = @EmployerId;";
List<PersonBaseModel> output = MySQLDataAccess.ReadData<PersonBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<EmployerBaseModel> RetrieveAllEmployers()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, CompanyName FROM Employers;";
List<EmployerBaseModel> output = MySQLDataAccess.ReadData<EmployerBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public EmployerBaseModel RetrieveEmployerById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, CompanyName FROM Employers WHERE Id = @Id;";
EmployerBaseModel output = MySQLDataAccess.ReadData<EmployerBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<AddressModel> RetrieveAllAddresses()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, StreetAddress, City, State, ZipCode FROM Addresses;";
List<AddressModel> output = MySQLDataAccess.ReadData<AddressModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public AddressModel RetrieveAddressById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, StreetAddress, City, State, ZipCode FROM Addresses WHERE Id = @Id;";
AddressModel output = MySQLDataAccess.ReadData<AddressModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<PersonAddressBaseModel> RetrieveAllPersonAddresses()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, PersonId, AddressId FROM PersonAddresses;";
List<PersonAddressBaseModel> output = MySQLDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public PersonAddressBaseModel RetrievePersonAddressById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, PersonId, AddressId FROM PersonAddresses WHERE Id = @Id;";
PersonAddressBaseModel output = MySQLDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<PersonAddressBaseModel> RetrievePersonAddressByPersonId(int personId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@PersonId", personId);
string sqlstatement = "SELECT Id, PersonId, AddressId FROM PersonAddresses WHERE PersonId = @PersonId;";
List<PersonAddressBaseModel> output = MySQLDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<PersonAddressBaseModel> RetrievePersonAddressByAddressId(int addressId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@AddressId", addressId);
string sqlstatement = "SELECT Id, PersonId, AddressId FROM PersonAddresses WHERE AddressId = @AddressId;";
List<PersonAddressBaseModel> output = MySQLDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<EmployerAddressBaseModel> RetrieveAllEmployerAddresses()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, EmployerId, AddressId FROM EmployerAddresses;";
List<EmployerAddressBaseModel> output = MySQLDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public EmployerAddressBaseModel RetrieveEmployerAddressById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, EmployerId, AddressId FROM EmployerAddresses WHERE Id = @Id;";
EmployerAddressBaseModel output = MySQLDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<EmployerAddressBaseModel> RetrieveEmployerAddressByEmployerId(int employerId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@EmployerId", employerId);
string sqlstatement = "SELECT Id, EmployerId, AddressId FROM EmployerAddresses WHERE EmployerId = @EmployerId;";
List<EmployerAddressBaseModel> output = MySQLDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<EmployerAddressBaseModel> RetrieveEmployerAddressByAddressId(int addressId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@AddressId", addressId);
string sqlstatement = "SELECT Id, EmployerId, AddressId FROM EmployerAddresses WHERE AddressId = @AddressId;";
List<EmployerAddressBaseModel> output = MySQLDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public void UpdatePerson(PersonBaseModel person)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", person.Id);
parameters.Add("@FirstName", person.FirstName);
parameters.Add("@LastName", person.LastName);
parameters.Add("@IsActive", person.IsActive);
parameters.Add("@EmployerId", person.EmployerId);
string sqlstatement = "UPDATE People SET FirstName = @FirstName, LastName = @LastName, IsActive = @IsActive, EmployerId = @EmployerId WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdateEmployer(EmployerBaseModel employer)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employer.Id);
parameters.Add("@CompanyName", employer.CompanyName);
string sqlstatement = "UPDATE Employers SET CompanyName = @CompanyName WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdateAddress(AddressModel address)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", address.Id);
parameters.Add("@StreetAddress", address.StreetAddress);
parameters.Add("@City", address.City);
parameters.Add("@State", address.State);
parameters.Add("@ZipCode", address.ZipCode);
string sqlstatement = "UPDATE Addresses SET StreetAddress = @StreetAddress, City = @City, State = @State, ZipCode = @ZipCode WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdatePersonAddress(PersonAddressBaseModel personAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", personAddress.Id);
parameters.Add("@PersonId", personAddress.PersonId);
parameters.Add("@AddressId", personAddress.AddressId);
string sqlstatement = "UPDATE PersonAddresses SET PersonId = @PersonId, AddresId = @AddressId WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdateEmployerAddress(EmployerAddressBaseModel employerAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employerAddress.Id);
parameters.Add("@EmployerId", employerAddress.EmployerId);
parameters.Add("@AddressId", employerAddress.AddressId);
string sqlstatement = "UPDATE EmployerAddresses SET EmployerId = @EmployerId, AddresId = @AddressId WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeletePerson(PersonBaseModel person)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", person.Id);
string sqlstatement = "DELETE FROM People WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeleteEmployer(EmployerBaseModel employer)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employer.Id);
string sqlstatement = "DELETE FROM Employers WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeleteAddress(AddressModel address)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", address.Id);
string sqlstatement = "DELETE FROM Addresses WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeletePersonAddress(PersonAddressBaseModel personAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", personAddress.Id);
string sqlstatement = "DELETE FROM PersonAddresses WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeleteEmployerAddress(EmployerAddressBaseModel employerAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employerAddress.Id);
string sqlstatement = "DELETE FROM EmployerAddresses WHERE Id = @Id;";
MySQLDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
}
}
SQLite
Description:
The homework from the Lesson 6, SQLite, of Module 8, Data Access, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a simple database in SQLite that holds People, Addresses, and Employers. Make sure it builds and that you can load and save data in C#.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Class Library;
- Console Application;
- SQLite;
Find the Project here:
Code Snippet:
using System.Collections.Generic;
using System.Linq;
using Dapper;
using DataAccessLibrary.Models;
namespace DataAccessLibrary.SQLiteDataAccess
{
public class SQLiteCrud : ICrud
{
private readonly string _connectionString;
public SQLiteCrud(string connectionString)
{
_connectionString = connectionString;
}
public void CreatePerson(PersonBaseModel person)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@FirstName", person.FirstName);
parameters.Add("@LastName", person.LastName);
parameters.Add("@IsActive", person.IsActive);
parameters.Add("@EmployerId", person.EmployerId);
string sqlstatement = "INSERT INTO People (FirstName, LastName, IsActive, EmployerId) VALUES (@FirstName, @LastName, @IsActive, @EmployerId);";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM People WHERE FirstName = @FirstName AND LastName = @LastName AND IsActive = @IsActive AND EmployerId = @EmployerId;";
person.Id = SQLiteDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreateEmployer(EmployerBaseModel employer)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@CompanyName", employer.CompanyName);
string sqlstatement = "INSERT INTO Employers (CompanyName) VALUES (@CompanyName);";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM Employers WHERE CompanyName = @CompanyName;";
employer.Id = SQLiteDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreateAddress(AddressModel address)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@StreetAddress", address.StreetAddress);
parameters.Add("@City", address.City);
parameters.Add("@State", address.State);
parameters.Add("@ZipCode", address.ZipCode);
string sqlstatement = "INSERT INTO Addresses (StreetAddress, City, State, ZipCode) VALUES (@StreetAddress, @City, @State, @ZipCode);";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM Addresses WHERE StreetAddress = @StreetAddress AND City = @City AND State = @State AND ZipCode = @ZipCode;";
address.Id = SQLiteDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreatePersonAddress(PersonAddressBaseModel personAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@PersonId", personAddress.PersonId);
parameters.Add("@AddressId", personAddress.AddressId);
string sqlstatement = "INSERT INTO PersonAddresses (PersonId, AddressId) VALUES (@PersonId, @AddressId);";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM PersonAddresses WHERE PersonId = @PersonId AND AddressId = @AddressId;";
personAddress.Id = SQLiteDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreateEmployerAddress(EmployerAddressBaseModel employerAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@EmployerId", employerAddress.EmployerId);
parameters.Add("@AddressId", employerAddress.AddressId);
string sqlstatement = "INSERT INTO EmployerAddresses (EmployerId, AddressId) VALUES (@EmployerId, @AddressId);";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT Id FROM EmployerAddresses WHERE EmployerId = @EmployerId AND AddressId = @AddressId;";
employerAddress.Id = SQLiteDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public List<PersonBaseModel> RetrieveAllPeople()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, FirstName, LastName, IsActive, EmployerId FROM People;";
List<PersonBaseModel> output = SQLiteDataAccess.ReadData<PersonBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public PersonBaseModel RetrievePersonById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, FirstName, LastName, IsActive, EmployerId FROM People WHERE Id = @Id;";
PersonBaseModel output = SQLiteDataAccess.ReadData<PersonBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<PersonBaseModel> RetrievePeopleByEmployerId(int employerId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@EmployerId", employerId);
string sqlstatement = "SELECT Id, FirstName, LastName, IsActive, EmployerId FROM People WHERE EmployerId = @EmployerId;";
List<PersonBaseModel> output = SQLiteDataAccess.ReadData<PersonBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<EmployerBaseModel> RetrieveAllEmployers()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, CompanyName FROM Employers;";
List<EmployerBaseModel> output = SQLiteDataAccess.ReadData<EmployerBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public EmployerBaseModel RetrieveEmployerById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, CompanyName FROM Employers WHERE Id = @Id;";
EmployerBaseModel output = SQLiteDataAccess.ReadData<EmployerBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<AddressModel> RetrieveAllAddresses()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, StreetAddress, City, State, ZipCode FROM Addresses;";
List<AddressModel> output = SQLiteDataAccess.ReadData<AddressModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public AddressModel RetrieveAddressById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, StreetAddress, City, State, ZipCode FROM Addresses WHERE Id = @Id;";
AddressModel output = SQLiteDataAccess.ReadData<AddressModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<PersonAddressBaseModel> RetrieveAllPersonAddresses()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, PersonId, AddressId FROM PersonAddresses;";
List<PersonAddressBaseModel> output = SQLiteDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public PersonAddressBaseModel RetrievePersonAddressById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, PersonId, AddressId FROM PersonAddresses WHERE Id = @Id;";
PersonAddressBaseModel output = SQLiteDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<PersonAddressBaseModel> RetrievePersonAddressByPersonId(int personId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@PersonId", personId);
string sqlstatement = "SELECT Id, PersonId, AddressId FROM PersonAddresses WHERE PersonId = @PersonId;";
List<PersonAddressBaseModel> output = SQLiteDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<PersonAddressBaseModel> RetrievePersonAddressByAddressId(int addressId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@AddressId", addressId);
string sqlstatement = "SELECT Id, PersonId, AddressId FROM PersonAddresses WHERE AddressId = @AddressId;";
List<PersonAddressBaseModel> output = SQLiteDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<EmployerAddressBaseModel> RetrieveAllEmployerAddresses()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT Id, EmployerId, AddressId FROM EmployerAddresses;";
List<EmployerAddressBaseModel> output = SQLiteDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public EmployerAddressBaseModel RetrieveEmployerAddressById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT Id, EmployerId, AddressId FROM EmployerAddresses WHERE Id = @Id;";
EmployerAddressBaseModel output = SQLiteDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<EmployerAddressBaseModel> RetrieveEmployerAddressByEmployerId(int employerId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@EmployerId", employerId);
string sqlstatement = "SELECT Id, EmployerId, AddressId FROM EmployerAddresses WHERE EmployerId = @EmployerId;";
List<EmployerAddressBaseModel> output = SQLiteDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<EmployerAddressBaseModel> RetrieveEmployerAddressByAddressId(int addressId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@AddressId", addressId);
string sqlstatement = "SELECT Id, EmployerId, AddressId FROM EmployerAddresses WHERE AddressId = @AddressId;";
List<EmployerAddressBaseModel> output = SQLiteDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public void UpdatePerson(PersonBaseModel person)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", person.Id);
parameters.Add("@FirstName", person.FirstName);
parameters.Add("@LastName", person.LastName);
parameters.Add("@IsActive", person.IsActive);
parameters.Add("@EmployerId", person.EmployerId);
string sqlstatement = "UPDATE People SET FirstName = @FirstName, LastName = @LastName, IsActive = @IsActive, EmployerId = @EmployerId WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdateEmployer(EmployerBaseModel employer)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employer.Id);
parameters.Add("@CompanyName", employer.CompanyName);
string sqlstatement = "UPDATE Employers SET CompanyName = @CompanyName WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdateAddress(AddressModel address)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", address.Id);
parameters.Add("@StreetAddress", address.StreetAddress);
parameters.Add("@City", address.City);
parameters.Add("@State", address.State);
parameters.Add("@ZipCode", address.ZipCode);
string sqlstatement = "UPDATE Addresses SET StreetAddress = @StreetAddress, City = @City, State = @State, ZipCode = @ZipCode WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdatePersonAddress(PersonAddressBaseModel personAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", personAddress.Id);
parameters.Add("@PersonId", personAddress.PersonId);
parameters.Add("@AddressId", personAddress.AddressId);
string sqlstatement = "UPDATE PersonAddresses SET PersonId = @PersonId, AddresId = @AddressId WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdateEmployerAddress(EmployerAddressBaseModel employerAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employerAddress.Id);
parameters.Add("@EmployerId", employerAddress.EmployerId);
parameters.Add("@AddressId", employerAddress.AddressId);
string sqlstatement = "UPDATE EmployerAddresses SET EmployerId = @EmployerId, AddresId = @AddressId WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeletePerson(PersonBaseModel person)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", person.Id);
string sqlstatement = "DELETE FROM People WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeleteEmployer(EmployerBaseModel employer)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employer.Id);
string sqlstatement = "DELETE FROM Employers WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeleteAddress(AddressModel address)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", address.Id);
string sqlstatement = "DELETE FROM Addresses WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeletePersonAddress(PersonAddressBaseModel personAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", personAddress.Id);
string sqlstatement = "DELETE FROM PersonAddresses WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeleteEmployerAddress(EmployerAddressBaseModel employerAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employerAddress.Id);
string sqlstatement = "DELETE FROM EmployerAddresses WHERE Id = @Id;";
SQLiteDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
}
}
SQL Server
Description:
The homework from the Lesson 5, SQL Server, of Module 8, Data Access, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a simple database in SQL that holds People, Addresses, and Employers. Make sure it builds and that you can load and save data in C#.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Class Library;
- Console Application;
- SQL Server Database Project;
Find the Project here:
Code Snippet:
using System.Collections.Generic;
using System.Linq;
using Dapper;
using DataAccessLibrary.Models;
namespace DataAccessLibrary.SQLDataAccess
{
public class SqlCrud : ICrud
{
private readonly string _connectionString;
public SqlCrud(string connectionString)
{
_connectionString = connectionString;
}
public void CreatePerson(PersonBaseModel person)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@FirstName", person.FirstName);
parameters.Add("@LastName", person.LastName);
parameters.Add("@IsActive", person.IsActive);
parameters.Add("@EmployerId", person.EmployerId);
string sqlstatement = "INSERT INTO [dbo].[People] ([FirstName], [LastName], [IsActive], [EmployerId]) VALUES (@FirstName, @LastName, @IsActive, @EmployerId);";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT [Id] FROM [dbo].[People] WHERE [FirstName] = @FirstName AND [LastName] = @LastName AND [IsActive] = @IsActive AND [EmployerId] = @EmployerId;";
person.Id = SqlDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreateEmployer(EmployerBaseModel employer)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@CompanyName", employer.CompanyName);
string sqlstatement = "INSERT INTO [dbo].[Employers] ([CompanyName]) VALUES (@CompanyName);";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT [Id] FROM [dbo].[Employers] WHERE [CompanyName] = @CompanyName;";
employer.Id = SqlDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreateAddress(AddressModel address)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@StreetAddress", address.StreetAddress);
parameters.Add("@City", address.City);
parameters.Add("@State", address.State);
parameters.Add("@ZipCode", address.ZipCode);
string sqlstatement = "INSERT INTO [dbo].[Addresses] ([StreetAddress], [City], [State], [ZipCode]) VALUES (@StreetAddress, @City, @State, @ZipCode);";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT [Id] FROM [dbo].[Addresses] WHERE [StreetAddress] = @StreetAddress AND [City] = @City AND [State] = @State AND [ZipCode] = @ZipCode;";
address.Id = SqlDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreatePersonAddress(PersonAddressBaseModel personAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@PersonId", personAddress.PersonId);
parameters.Add("@AddressId", personAddress.AddressId);
string sqlstatement = "INSERT INTO [dbo].[PersonAddresses] ([PersonId], [AddressId]) VALUES (@PersonId, @AddressId);";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT [Id] FROM [dbo].[PersonAddresses] WHERE [PersonId] = @PersonId AND [AddressId] = @AddressId;";
personAddress.Id = SqlDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public void CreateEmployerAddress(EmployerAddressBaseModel employerAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@EmployerId", employerAddress.EmployerId);
parameters.Add("@AddressId", employerAddress.AddressId);
string sqlstatement = "INSERT INTO [dbo].[EmployerAddresses] ([EmployerId], [AddressId]) VALUES (@EmployerId, @AddressId);";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
sqlstatement = "SELECT [Id] FROM [dbo].[EmployerAddresses] WHERE [EmployerId] = @EmployerId AND [AddressId] = @AddressId;";
employerAddress.Id = SqlDataAccess.ReadData<int, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
}
public List<PersonBaseModel> RetrieveAllPeople()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT [Id], [FirstName], [LastName], [IsActive], [EmployerId] FROM [dbo].[People];";
List<PersonBaseModel> output = SqlDataAccess.ReadData<PersonBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public PersonBaseModel RetrievePersonById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT [Id], [FirstName], [LastName], [IsActive], [EmployerId] FROM [dbo].[People] WHERE Id = @Id;";
PersonBaseModel output = SqlDataAccess.ReadData<PersonBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<PersonBaseModel> RetrievePeopleByEmployerId(int employerId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@EmployerId", employerId);
string sqlstatement = "SELECT [Id], [FirstName], [LastName], [IsActive], [EmployerId] FROM [dbo].[People] WHERE EmployerId = @EmployerId;";
List<PersonBaseModel> output = SqlDataAccess.ReadData<PersonBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<EmployerBaseModel> RetrieveAllEmployers()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT [Id], [CompanyName] FROM [dbo].[Employers];";
List<EmployerBaseModel> output = SqlDataAccess.ReadData<EmployerBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public EmployerBaseModel RetrieveEmployerById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT [Id], [CompanyName] FROM [dbo].[Employers] WHERE Id = @Id;";
EmployerBaseModel output = SqlDataAccess.ReadData<EmployerBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<AddressModel> RetrieveAllAddresses()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT [Id], [StreetAddress], [City], [State], [ZipCode] FROM [dbo].[Addresses];";
List<AddressModel> output = SqlDataAccess.ReadData<AddressModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public AddressModel RetrieveAddressById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT [Id], [StreetAddress], [City], [State], [ZipCode] FROM [dbo].[Addresses] WHERE Id = @Id;";
AddressModel output = SqlDataAccess.ReadData<AddressModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<PersonAddressBaseModel> RetrieveAllPersonAddresses()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT [Id], [PersonId], [AddressId] FROM [dbo].[PersonAddresses];";
List<PersonAddressBaseModel> output = SqlDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public PersonAddressBaseModel RetrievePersonAddressById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT [Id], [PersonId], [AddressId] FROM [dbo].[PersonAddresses] WHERE Id = @Id;";
PersonAddressBaseModel output = SqlDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<PersonAddressBaseModel> RetrievePersonAddressByPersonId(int personId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@PersonId", personId);
string sqlstatement = "SELECT [Id], [PersonId], [AddressId] FROM [dbo].[PersonAddresses] WHERE PersonId = @PersonId;";
List<PersonAddressBaseModel> output = SqlDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<PersonAddressBaseModel> RetrievePersonAddressByAddressId(int addressId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@AddressId", addressId);
string sqlstatement = "SELECT [Id], [PersonId], [AddressId] FROM [dbo].[PersonAddresses] WHERE AddressId = @AddressId;";
List<PersonAddressBaseModel> output = SqlDataAccess.ReadData<PersonAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<EmployerAddressBaseModel> RetrieveAllEmployerAddresses()
{
DynamicParameters parameters = new DynamicParameters();
string sqlstatement = "SELECT [Id], [EmployerId], [AddressId] FROM [dbo].[EmployerAddresses];";
List<EmployerAddressBaseModel> output = SqlDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public EmployerAddressBaseModel RetrieveEmployerAddressById(int id)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", id);
string sqlstatement = "SELECT [Id], [EmployerId], [AddressId] FROM [dbo].[EmployerAddresses] WHERE Id = @Id;";
EmployerAddressBaseModel output = SqlDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString).First();
return output;
}
public List<EmployerAddressBaseModel> RetrieveEmployerAddressByEmployerId(int employerId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@EmployerId", employerId);
string sqlstatement = "SELECT [Id], [EmployerId], [AddressId] FROM [dbo].[EmployerAddresses] WHERE EmployerId = @EmployerId;";
List<EmployerAddressBaseModel> output = SqlDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public List<EmployerAddressBaseModel> RetrieveEmployerAddressByAddressId(int addressId)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@AddressId", addressId);
string sqlstatement = "SELECT [Id], [EmployerId], [AddressId] FROM [dbo].[EmployerAddresses] WHERE AddressId = @AddressId;";
List<EmployerAddressBaseModel> output = SqlDataAccess.ReadData<EmployerAddressBaseModel, DynamicParameters>(sqlstatement, parameters, _connectionString);
return output;
}
public void UpdatePerson(PersonBaseModel person)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", person.Id);
parameters.Add("@FirstName", person.FirstName);
parameters.Add("@LastName", person.LastName);
parameters.Add("@IsActive", person.IsActive);
parameters.Add("@EmployerId", person.EmployerId);
string sqlstatement = "UPDATE [dbo].[People] SET [FirstName] = @FirstName, [LastName] = @LastName, [IsActive] = @IsActive, [EmployerId] = @EmployerId WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdateEmployer(EmployerBaseModel employer)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employer.Id);
parameters.Add("@CompanyName", employer.CompanyName);
string sqlstatement = "UPDATE [dbo].[Employers] SET [CompanyName] = @CompanyName WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdateAddress(AddressModel address)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", address.Id);
parameters.Add("@StreetAddress", address.StreetAddress);
parameters.Add("@City", address.City);
parameters.Add("@State", address.State);
parameters.Add("@ZipCode", address.ZipCode);
string sqlstatement = "UPDATE [dbo].[Addresses] SET [StreetAddress] = @StreetAddress, [City] = @City, [State] = @State, [ZipCode] = @ZipCode WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdatePersonAddress(PersonAddressBaseModel personAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", personAddress.Id);
parameters.Add("@PersonId", personAddress.PersonId);
parameters.Add("@AddressId", personAddress.AddressId);
string sqlstatement = "UPDATE [dbo].[PersonAddresses] SET [PersonId] = @PersonId, [AddresId] = @AddressId WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void UpdateEmployerAddress(EmployerAddressBaseModel employerAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employerAddress.Id);
parameters.Add("@EmployerId", employerAddress.EmployerId);
parameters.Add("@AddressId", employerAddress.AddressId);
string sqlstatement = "UPDATE [dbo].[EmployerAddresses] SET [EmployerId] = @EmployerId, [AddresId] = @AddressId WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeletePerson(PersonBaseModel person)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", person.Id);
string sqlstatement = "DELETE FROM [dbo].[People] WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeleteEmployer(EmployerBaseModel employer)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employer.Id);
string sqlstatement = "DELETE FROM [dbo].[Employers] WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeleteAddress(AddressModel address)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", address.Id);
string sqlstatement = "DELETE FROM [dbo].[Addresses] WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeletePersonAddress(PersonAddressBaseModel personAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", personAddress.Id);
string sqlstatement = "DELETE FROM [dbo].[PersonAddresses] WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
public void DeleteEmployerAddress(EmployerAddressBaseModel employerAddress)
{
DynamicParameters parameters = new DynamicParameters();
parameters.Add("@Id", employerAddress.Id);
string sqlstatement = "DELETE FROM [dbo].[EmployerAddresses] WHERE [Id] = @Id;";
SqlDataAccess.WriteData(sqlstatement, parameters, _connectionString);
}
}
}
ASP.NET Core API Mini Project
Description:
The homework from the Lesson 15, Mini Project - ASP.NET Core API, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a WebAPI Core application with two POST commands. Create a POST that takes in a person's info and another that takes in address info.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- ASP.NET Core Web API;
- C#;
- Class Library;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-ASP.NETCoreAPIMiniProject
Code Snippet:
using System.Collections.Generic;
using ClassLibrary;
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace APIWebApplicationUI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PersonController : ControllerBase
{
private readonly PersonModel _person;
public PersonController(PersonModel person)
{
_person = person;
}
// GET: api/Person
[HttpGet]
public IEnumerable<PersonModel> Get()
{
List<PersonModel> people = new List<PersonModel>();
if ( !string.IsNullOrWhiteSpace(_person.FirstName) && !string.IsNullOrWhiteSpace(_person.LastName) )
{
people.Add(_person);
}
return people;
}
// GET api/Person/5
[HttpGet("{id}")]
public PersonModel Get(int id)
{
return _person;
}
// POST api/Person
[HttpPost]
public void Post([FromBody] PersonModel value)
{
_person.FirstName = value.FirstName;
_person.LastName = value.LastName;
_person.IsActive = value.IsActive;
_person.Addresses = value.Addresses;
}
// PUT api/Person/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] PersonModel value)
{
_person.FirstName = value.FirstName;
_person.LastName = value.LastName;
_person.IsActive = value.IsActive;
_person.Addresses = value.Addresses;
}
// DELETE api/<PersonController>/5
[HttpDelete("{id}")]
public void Delete(int id)
{
_person.FirstName = "";
_person.LastName = "";
_person.IsActive = false;
_person.Addresses.Clear();
}
}
}
ASP.NET Core API
Description:
The homework from the Lesson 14, ASP.NET Core API Project Type, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a Web API Application that has a GET call that takes in a First Name and Last Name and it returns "Hi {FN} {LN}".
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- ASP.NET Core Web API;
- C#;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-ASP.NETCoreAPI
Code Snippet:
using Microsoft.AspNetCore.Mvc;
// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
namespace SayHi.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class PersonController : ControllerBase
{
// GET: api/Person
[HttpGet]
public string Get(string firstName, string lastName)
{
return $"Hi {firstName} {lastName}!";
}
}
}
ASP.NET Core MVC Mini Project
Description:
The homework from the Lesson 13, Mini Project - ASP.NET Core MVC, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a Core MVC application with two pages. Create a page that takes in a person's info and another that takes in address info (no need to associate it).
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- ASP.NET Core Web Application (Model-View-Controller);
- C#;
- Class Library;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-ASP.NETCoreMVCMiniProject
Code Snippet:
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using MVCWebApplicationUI.Models;
namespace MVCWebApplicationUI.Controllers
{
public class PersonController : Controller
{
private readonly ILogger<PersonController> _logger;
[BindProperty]
private PersonViewModel _person { get; set; }
public PersonController(ILogger<PersonController> logger, PersonViewModel person)
{
_logger = logger;
_person = person;
}
// GET: Person
public ActionResult Index()
{
List<PersonViewModel> people = new List<PersonViewModel>();
if ( !string.IsNullOrWhiteSpace(_person.FirstName) && !string.IsNullOrWhiteSpace(_person.LastName) )
{
people.Add(_person);
}
_logger.LogInformation("GET, Person Controller, Index View, Person View Model");
return View(people);
}
// GET: Person/Details/5
public ActionResult Details(int id)
{
_logger.LogInformation("GET, Person Controller, Details View, Person View Model with Id = {id}", id);
return View(_person);
}
// GET: Person/Create
public ActionResult Create()
{
_logger.LogInformation("GET, Person Controller, Details View, Person View Model");
_person.FirstName = "";
_person.LastName = "";
_person.IsActive = false;
_person.Addresses.Clear();
return View(_person);
}
// POST: Person/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PersonViewModel person)
{
_logger.LogInformation("POST, Person Controller, Details View, Person View Model with FirstName = {FirstName}, LastName = {LastName}, IsActive = {IsActive}, and {AddressCount} Addresses", person.FirstName, person.LastName, person.IsActive, person.Addresses.Count);
try
{
if ( ModelState.IsValid )
{
_person.FirstName = person.FirstName;
_person.LastName = person.LastName;
_person.IsActive = person.IsActive;
_person.Addresses.Clear();
foreach ( AddressViewModel address in person.Addresses )
{
_person.Addresses.Add(address);
}
return RedirectToAction(nameof(Details), new { id = 5 });
}
else
{
return View(person);
}
}
catch
{
return View(person);
}
}
// GET: Person/Edit/5
public ActionResult Edit(int id)
{
_logger.LogInformation("GET, Person Controller, Edit View, Person View Model with Id = {id}", id);
return View(_person);
}
// POST: Person/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(int id, PersonViewModel person)
{
_logger.LogInformation("POST, Person Controller, Edit View, Person View Model with Id = {id}, FirstName = {FirstName}, LastName = {LastName}, IsActive = {IsActive}, and {AddressCount} Addresses", id, person.FirstName, person.LastName, person.IsActive, person.Addresses.Count);
try
{
if ( ModelState.IsValid )
{
_person.FirstName = person.FirstName;
_person.LastName = person.LastName;
_person.IsActive = person.IsActive;
_person.Addresses.Clear();
foreach ( AddressViewModel address in person.Addresses )
{
_person.Addresses.Add(address);
}
return RedirectToAction(nameof(Details), new { id = 5 });
}
else
{
return View(person);
}
}
catch
{
return View(person);
}
}
// GET: Person/Delete/5
public ActionResult Delete(int id)
{
_logger.LogInformation("GET, Person Controller, Delete View, Person View Model with Id = {id}", id);
return View(_person);
}
// POST: Person/Delete/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Delete(int id, PersonViewModel person)
{
_logger.LogInformation("POST, Person Controller, Edit View, Person View Model with Id = {id}, FirstName = {FirstName}, LastName = {LastName}, IsActive = {IsActive}, and {AddressCount} Addresses", id, person.FirstName, person.LastName, person.IsActive, person.Addresses.Count);
try
{
_person.FirstName = "";
_person.LastName = "";
_person.IsActive = false;
_person.Addresses.Clear();
return RedirectToAction(nameof(Index));
}
catch
{
return View(person);
}
}
}
}
ASP.NET Core MVC
Description:
The homework from the Lesson 12, ASP.NET Core MVC Project Type, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a Core MVC Application that has a simple data-entry page with First and Last Name fields. Have a button say "Hi {FN} {LN}" when pressed.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- ASP.NET Core Web Application (Model-View-Controller);
- C#;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-ASP.NETCoreMVC
Code Snippet:
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SayHi.Models;
namespace SayHi.Controllers
{
public class SayHiController : Controller
{
private readonly ILogger<SayHiController> _logger;
[BindProperty]
private PersonModel Person { get; set; } = new PersonModel();
public SayHiController(ILogger<SayHiController> logger)
{
_logger = logger;
}
// GET: SayHi
public ActionResult Index()
{
_logger.LogInformation("GET, SayHi Controller, Index View, Person Model");
return View();
}
// GET: SayHi/Create
public ActionResult Create()
{
_logger.LogInformation("GET, Say Hi Controller, Create View, Person Model");
return View();
}
// GET: SayHi/Details
public ActionResult Details(PersonModel person)
{
_logger.LogInformation("GET, Say Hi Controller, Details View, PersonModel Model: {person}", person);
Person = person;
return View(Person);
}
// POST: SayHi/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(PersonModel person)
{
_logger.LogInformation("POST, Say Hi Controller, Create View, Person Model: {person}", person);
try
{
if ( ModelState.IsValid )
{
Person.FirstName = person.FirstName;
Person.LastName = person.LastName;
return RedirectToAction(nameof(Details), Person);
}
else
{
return RedirectToAction(nameof(Index));
}
}
catch
{
return View();
}
}
}
}
ASP.NET Core Razor Pages Mini Project
Description:
The homework from the Lesson 11, Mini Project - ASP.NET Core Razor Pages, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a Razor Pages application with two pages. Create a page that takes in a person's info and another that takes in address info (no need to associate it).
Technologies Used:
- .NET Core;
- .NET Core 3.1;
- ASP.NET Core Web Application (Razor Pages);
- C#;
- Class Library;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-ASP.NETCoreRazorPagesMiniProject
Code Snippet:
using System.Collections.Generic;
using ClassLibrary;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace RazorPagesWebApplicationUI.Pages
{
public class PersonEntryModel : PageModel
{
private readonly ILogger<PersonEntryModel> _logger;
private readonly PersonModel _person;
[BindProperty]
public string FirstName
{
get; set;
}
[BindProperty]
public string LastName
{
get; set;
}
[BindProperty]
public bool IsActive
{
get; set;
}
[BindProperty]
public List<AddressModel> Addresses
{
get; set;
} = new List<AddressModel>();
public PersonEntryModel(ILogger<PersonEntryModel> logger, PersonModel person)
{
_logger = logger;
_person = person;
}
public void OnGet()
{
FirstName = _person.FirstName;
LastName = _person.LastName;
IsActive = _person.IsActive != null && (bool)_person.IsActive;
Addresses = _person.Addresses;
_logger.LogInformation("On GET Person Entry Page, Person Entry Model");
}
public IActionResult OnPost()
{
_person.FirstName = FirstName;
_person.LastName = LastName;
_person.IsActive = IsActive;
_logger.LogInformation("On POST Person Entry Page, Person Entry Model, with First Name {FirstName}, Last Name {LastName}, Is Active {IsActive}, and {AddressCount} Addresses", _person.FirstName, _person.LastName, _person.IsActive, _person.Addresses.Count);
return RedirectToPage("./Index");
}
public IActionResult OnPostAdd()
{
_person.FirstName = FirstName;
_person.LastName = LastName;
_person.IsActive = IsActive;
_logger.LogInformation("On POST Person Entry Page to Add Address, Person Entry Model, with First Name {FirstName}, Last Name {LastName}, Is Active {IsActive}, and {AddressCount} Addresses", _person.FirstName, _person.LastName, _person.IsActive, _person.Addresses.Count);
return RedirectToPage("./AddressEntry");
}
}
}
ASP.NET Core Razor Pages
Description:
The homework from the Lesson 10, ASP.NET Core Razor Pages Project Type, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a Razor Pages Application that has a simple data-entry page with First and Last Name fields. Have a button say "Hi {FN} {LN}" when pressed.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- ASP.NET Core Web Application (Razor Pages);
- C#;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-ASP.NETCoreRazorPages
Code Snippet:
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
namespace SayHi.Pages
{
public class IndexModel : PageModel
{
[BindProperty]
public string FirstName
{
get; set;
}
[BindProperty]
public string LastName
{
get; set;
}
[BindProperty]
public string Greeting
{
get; set;
}
private readonly ILogger<IndexModel> _logger;
public IndexModel(ILogger<IndexModel> logger)
{
_logger = logger;
}
public void OnGet()
{
_logger.LogInformation("On GET Index Page, Index Model");
}
public IActionResult OnPost()
{
Greeting = $"Hi {FirstName} {LastName}!";
_logger.LogInformation("On POST Index Page, Index Model, with Greeting = {Greeting}", Greeting);
return Page();
}
}
}
WPF Core Mini Project
Description:
The homework from the Lesson 9, Mini Project - WPF Core, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a WPF application with two forms. Create a form that takes in a person's info and another that takes in address info (multiple per person).
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Class Library;
- WPF Application;
- XAML;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-WPFCoreMiniProject
Code Snippet:
<Window x:Name="personEntryWindow" x:Class="WPFCoreUI.PersonEntryWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:WPFCoreUI" mc:Ignorable="d" FontSize="24" Title="Person Entry Window" Height="600" Width="450" MinWidth="250" MinHeight="350">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" Grid.Column="1" Margin="0 5 5 5">First Name</TextBlock>
<TextBox x:Name="firstNameTextBox" Grid.Row="1" Grid.Column="2" MinWidth="150" Margin="5 5 0 5" Padding="5" />
<TextBlock Grid.Row="2" Grid.Column="1" Margin="0 5 5 5">Last Name</TextBlock>
<TextBox x:Name="lastNameTextBox" Grid.Row="2" Grid.Column="2" MinWidth="150" Margin="5 5 0 5" Padding="5" />
<TextBlock Grid.Row="3" Grid.Column="1" Margin="0 5 5 5">Active</TextBlock>
<CheckBox x:Name="activeChecBox" Grid.Row="3" Grid.Column="2" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="5 5 0 5" Padding="5" />
<TextBlock Grid.Row="4" Grid.Column="1" Margin="0 5 5 5">Addresses</TextBlock>
<Button x:Name="addAddressButton" Grid.Row="4" Grid.Column="2" Margin="5 5 0 5" Padding="5" Width="75" Height="40" HorizontalAlignment="Right" Click="AddAddressButton_Click">Add</Button>
<ListBox x:Name="addressesListBox" Grid.Row="5" Grid.Column="1" Grid.ColumnSpan="2" Margin="0 0 0 5" Padding="5">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Margin="0 2 2 2" Padding="1" Text="{Binding StreetAddress}" />
<TextBlock Margin="2 2 2 2" Padding="1" Text="{Binding City}" />
<TextBlock Margin="2 2 2 2" Padding="1" Text="{Binding State}" />
<TextBlock Margin="2 2 0 2" Padding="1" Text="{Binding ZipCode}" />
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Button x:Name="saveRecordButton" Grid.Row="6" Grid.Column="1" Grid.ColumnSpan="2" Margin="5" Padding="5" Width="200" Height="50" Click="SaveRecordButton_Click">Save</Button>
</Grid>
</Window>
WPF Core
Description:
The homework from the Lesson 8, WPF Core Project Type, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a WPF Application that has a simple data-entry screen with First and Last Name fields. Have a button say "Hi {FN} {LN}" when pressed.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- WPF Application;
- XAML;
Find the Project here:
Code Snippet:
<Window x:Class="SayHi.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:SayHi"
mc:Ignorable="d" Title="Say Hi!" Height="450" Width="800" FontSize="24">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="20" />
<RowDefinition Height="*" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
<RowDefinition Height="20" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="auto" />
<ColumnDefinition Width="*" />
<ColumnDefinition Width="20" />
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" Grid.Row="2" Grid.Column="2">
<TextBlock Margin="5">First Name:</TextBlock>
<TextBox x:Name="firstNameTextBox" MinWidth="100" MaxWidth="200" Padding="5"></TextBox>
</StackPanel>
<StackPanel Orientation="Horizontal" Grid.Row="2" Grid.Column="3">
<TextBlock Margin="5">Last Name:</TextBlock>
<TextBox x:Name="lastNameTextBox" MinWidth="100" MaxWidth="200" Padding="5"></TextBox>
</StackPanel>
<Button x:Name="sayHiButton" Grid.Row="3" Grid.Column="2" Grid.ColumnSpan="2" Click="SayHiButton_Click" Margin="10">Say Hi!</Button>
<TextBlock x:Name="sayHiTextBlock" Grid.Row="4" Grid.Column="2" Grid.ColumnSpan="2" Text="{Binding}" Margin="10" />
</Grid>
</Window>
WinForms Mini Project
Description:
The homework from the Lesson 7, Mini Project - WinForms of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a WinForms application with two forms. Create a form that takes in a person's info and another that takes in address info (multiple per person).
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Class Library;
- Windows Forms Application;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-WinFormsMiniProject
Code Snippet:
using System;
using System.ComponentModel;
using System.Windows.Forms;
using ClassLibrary;
namespace WindowsFormsUI
{
public partial class PersonEntry : Form, ISaveAddress
{
private string _firstName = "";
private string _lastName = "";
private readonly BindingList<AddressModel> _addressList = new BindingList<AddressModel>();
private readonly PersonModel _person = new PersonModel();
public PersonEntry()
{
InitializeComponent();
WireUpLists();
}
private void WireUpLists()
{
firstNameTextBox.Text = _firstName;
lastNameTextBox.Text = _lastName;
addressesListBox.DataSource = _addressList;
addressesListBox.DisplayMember = nameof(AddressModel.FormattedAddress);
}
private void AddAddressButton_Click(object sender, EventArgs e)
{
AddressEntry addressentry = new AddressEntry(this, _person.FullName);
addressentry.Show();
}
public void SaveAddress(AddressModel address)
{
_addressList.Add(address);
_person.Addresses.Add(address);
}
private void FirstNameTextBox_TextChanged(object sender, EventArgs e)
{
_firstName = firstNameTextBox.Text;
_person.FirstName = _firstName;
}
private void LastNameTextBox_TextChanged(object sender, EventArgs e)
{
_lastName = lastNameTextBox.Text;
_person.LastName = _lastName;
}
}
}
WinForms
Description:
The homework from the Lesson 6, WinForm Project Type, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a WinForms Application that has a simple data-entry screen with First and Last Name fields. Have a button say "Hi {FN} {LN}" when pressed.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Windows Forms Application;
Find the Project here:
Code Snippet:
using System;
using System.Windows.Forms;
namespace SayHi
{
public partial class SayHi : Form
{
public SayHi()
{
InitializeComponent();
}
private void SayHiButton_Click(object sender, EventArgs e)
{
if ( string.IsNullOrWhiteSpace(firstNameTextBox.Text) && string.IsNullOrWhiteSpace(lastNameTextBox.Text) )
{
_ = MessageBox.Show("You must enter both a First Name and a Last Name to Say Hi!", "First Name and Last Name Blank", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
_ = firstNameTextBox.Focus();
}
else if ( string.IsNullOrWhiteSpace(firstNameTextBox.Text) )
{
_ = MessageBox.Show("You must enter both a First Name to Say Hi!", "First Name Blank", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
_ = firstNameTextBox.Focus();
}
else if ( string.IsNullOrWhiteSpace(lastNameTextBox.Text) )
{
_ = MessageBox.Show("You must enter a Last Name to Say Hi!", "Last Name Blank", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
_ = lastNameTextBox.Focus();
}
else
{
_ = MessageBox.Show($"Hi {firstNameTextBox.Text} {lastNameTextBox.Text}!", "Hi there!", MessageBoxButtons.OK, MessageBoxIcon.None);
firstNameTextBox.Text = "";
lastNameTextBox.Text = "";
_ = firstNameTextBox.Focus();
}
}
}
}
Unit Test Mini Project
Description:
The homework from the Lesson 5, Mini Project - Unit Tests, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a Class Library (.NET Standard) with a class that does the basic math operations. Create unit tests for all methods.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- .NET Standard;
- .NET Standard 2.1;
- C#;
- Class Library;
- xUnit Test Project;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-UnitTestMiniProject
Code Snippet:
using Xunit;
namespace CalculationLibrary.Tests
{
public class CalculationsTests
{
[Fact]
public void BasicAddTest()
{
// Arrange
int expected = 7;
// Act
int actual = Calculations.Add(3, 4);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void BasicSubtractTest()
{
// Arrange
int expected = -1;
// Act
int actual = Calculations.Subtract(3, 4);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void BasicMultiplyTest()
{
// Arrange
int expected = 12;
// Act
int actual = Calculations.Multiply(3, 4);
// Assert
Assert.Equal(expected, actual);
}
[Fact]
public void BasicDivideTest()
{
// Arrange
int expected = 0;
// Act
int actual = Calculations.Divide(3, 4);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
// Arrange
[InlineData(-3, -4, -7)]
[InlineData(-3, 4, 1)]
[InlineData(3, -4, -1)]
[InlineData(3, 4, 7)]
[InlineData(4, -4, 0)]
[InlineData(4, 4, 8)]
[InlineData(0, -4, -4)]
[InlineData(0, 4, 4)]
[InlineData(0, 0, 0)]
[InlineData(-3, 0, -3)]
[InlineData(3, 0, 3)]
[InlineData(-4, -3, -7)]
[InlineData(4, -3, 1)]
[InlineData(-4, 3, -1)]
[InlineData(4, 3, 7)]
[InlineData(-4, 4, 0)]
[InlineData(-4, 0, -4)]
[InlineData(4, 0, 4)]
[InlineData(0, -3, -3)]
[InlineData(0, 3, 3)]
[InlineData(-8, -4, -12)]
[InlineData(-8, 4, -4)]
[InlineData(8, -4, 4)]
[InlineData(8, 4, 12)]
[InlineData(-8, 0, -8)]
[InlineData(8, 0, 8)]
[InlineData(-4, -8, -12)]
[InlineData(4, -8, -4)]
[InlineData(-4, 8, 4)]
[InlineData(4, 8, 12)]
[InlineData(0, -8, -8)]
[InlineData(0, 8, 8)]
[InlineData(1, -4, -3)]
[InlineData(1, 4, 5)]
[InlineData(1, 1, 2)]
[InlineData(-3, 1, -2)]
[InlineData(3, 1, 4)]
[InlineData(-4, 1, -3)]
[InlineData(4, 1, 5)]
[InlineData(1, -3, -2)]
[InlineData(1, 3, 4)]
[InlineData(-8, 1, -7)]
[InlineData(8, 1, 9)]
[InlineData(1, -8, -7)]
[InlineData(1, 8, 9)]
[InlineData(-1, -4, -5)]
[InlineData(-1, 4, 3)]
[InlineData(-1, -1, -2)]
[InlineData(-3, -1, -4)]
[InlineData(3, -1, 2)]
[InlineData(-4, -1, -5)]
[InlineData(4, -1, 3)]
[InlineData(-1, -3, -4)]
[InlineData(-1, 3, 2)]
[InlineData(-8, -1, -9)]
[InlineData(8, -1, 7)]
[InlineData(-1, -8, -9)]
[InlineData(-1, 8, 7)]
public void ComprehensiveAddTest(int x, int y, int expected)
{
// Act
int actual = Calculations.Add(x, y);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
// Arrange
[InlineData(-3, -4, 1)]
[InlineData(-3, 4, -7)]
[InlineData(3, -4, 7)]
[InlineData(3, 4, -1)]
[InlineData(4, -4, 8)]
[InlineData(4, 4, 0)]
[InlineData(0, -4, 4)]
[InlineData(0, 4, -4)]
[InlineData(0, 0, 0)]
[InlineData(-3, 0, -3)]
[InlineData(3, 0, 3)]
[InlineData(-4, -3, -1)]
[InlineData(4, -3, 7)]
[InlineData(-4, 3, -7)]
[InlineData(4, 3, 1)]
[InlineData(-4, 4, -8)]
[InlineData(-4, 0, -4)]
[InlineData(4, 0, 4)]
[InlineData(0, -3, 3)]
[InlineData(0, 3, -3)]
[InlineData(-8, -4, -4)]
[InlineData(-8, 4, -12)]
[InlineData(8, -4, 12)]
[InlineData(8, 4, 4)]
[InlineData(-8, 0, -8)]
[InlineData(8, 0, 8)]
[InlineData(-4, -8, 4)]
[InlineData(4, -8, 12)]
[InlineData(-4, 8, -12)]
[InlineData(4, 8, -4)]
[InlineData(0, -8, 8)]
[InlineData(0, 8, -8)]
[InlineData(1, -4, 5)]
[InlineData(1, 4, -3)]
[InlineData(1, 1, 0)]
[InlineData(-3, 1, -4)]
[InlineData(3, 1, 2)]
[InlineData(-4, 1, -5)]
[InlineData(4, 1, 3)]
[InlineData(1, -3, 4)]
[InlineData(1, 3, -2)]
[InlineData(-8, 1, -9)]
[InlineData(8, 1, 7)]
[InlineData(1, -8, 9)]
[InlineData(1, 8, -7)]
[InlineData(-1, -4, 3)]
[InlineData(-1, 4, -5)]
[InlineData(-1, -1, 0)]
[InlineData(-3, -1, -2)]
[InlineData(3, -1, 4)]
[InlineData(-4, -1, -3)]
[InlineData(4, -1, 5)]
[InlineData(-1, -3, 2)]
[InlineData(-1, 3, -4)]
[InlineData(-8, -1, -7)]
[InlineData(8, -1, 9)]
[InlineData(-1, -8, 7)]
[InlineData(-1, 8, -9)]
public void ComprehensiveSubtractTest(int x, int y, int expected)
{
// Act
int actual = Calculations.Subtract(x, y);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
// Arrange
[InlineData(-3, -4, 12)]
[InlineData(-3, 4, -12)]
[InlineData(3, -4, -12)]
[InlineData(3, 4, 12)]
[InlineData(4, -4, -16)]
[InlineData(4, 4, 16)]
[InlineData(0, -4, 0)]
[InlineData(0, 4, 0)]
[InlineData(0, 0, 0)]
[InlineData(-3, 0, 0)]
[InlineData(3, 0, 0)]
[InlineData(-4, -3, 12)]
[InlineData(4, -3, -12)]
[InlineData(-4, 3, -12)]
[InlineData(4, 3, 12)]
[InlineData(-4, 4, -16)]
[InlineData(-4, 0, 0)]
[InlineData(4, 0, 0)]
[InlineData(0, -3, 0)]
[InlineData(0, 3, 0)]
[InlineData(-8, -4, 32)]
[InlineData(-8, 4, -32)]
[InlineData(8, -4, -32)]
[InlineData(8, 4, 32)]
[InlineData(-8, 0, 0)]
[InlineData(8, 0, 0)]
[InlineData(-4, -8, 32)]
[InlineData(4, -8, -32)]
[InlineData(-4, 8, -32)]
[InlineData(4, 8, 32)]
[InlineData(0, -8, 0)]
[InlineData(0, 8, 0)]
[InlineData(1, -4, -4)]
[InlineData(1, 4, 4)]
[InlineData(1, 1, 1)]
[InlineData(-3, 1, -3)]
[InlineData(3, 1, 3)]
[InlineData(-4, 1, -4)]
[InlineData(4, 1, 4)]
[InlineData(1, -3, -3)]
[InlineData(1, 3, 3)]
[InlineData(-8, 1, -8)]
[InlineData(8, 1, 8)]
[InlineData(1, -8, -8)]
[InlineData(1, 8, 8)]
[InlineData(-1, -4, 4)]
[InlineData(-1, 4, -4)]
[InlineData(-1, -1, 1)]
[InlineData(-3, -1, 3)]
[InlineData(3, -1, -3)]
[InlineData(-4, -1, 4)]
[InlineData(4, -1, -4)]
[InlineData(-1, -3, 3)]
[InlineData(-1, 3, -3)]
[InlineData(-8, -1, 8)]
[InlineData(8, -1, -8)]
[InlineData(-1, -8, 8)]
[InlineData(-1, 8, -8)]
public void ComprehensiveMultiplyTest(int x, int y, int expected)
{
// Act
int actual = Calculations.Multiply(x, y);
// Assert
Assert.Equal(expected, actual);
}
[Theory]
// Arrange
[InlineData(-3, -4, 0)]
[InlineData(-3, 4, 0)]
[InlineData(3, -4, 0)]
[InlineData(3, 4, 0)]
[InlineData(4, -4, -1)]
[InlineData(4, 4, 1)]
[InlineData(0, -4, 0)]
[InlineData(0, 4, 0)]
//[InlineData(0, 0, 0)]
//[InlineData(-3, 0, 0)]
//[InlineData(3, 0, 0)]
[InlineData(-4, -3, 1)]
[InlineData(4, -3, -1)]
[InlineData(-4, 3, -1)]
[InlineData(4, 3, 1)]
[InlineData(-4, 4, -1)]
//[InlineData(-4, 0, 0)]
//[InlineData(4, 0, 0)]
[InlineData(0, -3, 0)]
[InlineData(0, 3, 0)]
[InlineData(-8, -4, 2)]
[InlineData(-8, 4, -2)]
[InlineData(8, -4, -2)]
[InlineData(8, 4, 2)]
//[InlineData(-8, 0, 0)]
//[InlineData(8, 0, 0)]
[InlineData(-4, -8, 0)]
[InlineData(4, -8, 0)]
[InlineData(-4, 8, 0)]
[InlineData(4, 8, 0)]
[InlineData(0, -8, 0)]
[InlineData(0, 8, 0)]
[InlineData(1, -4, 0)]
[InlineData(1, 4, 0)]
[InlineData(1, 1, 1)]
[InlineData(-3, 1, -3)]
[InlineData(3, 1, 3)]
[InlineData(-4, 1, -4)]
[InlineData(4, 1, 4)]
[InlineData(1, -3, 0)]
[InlineData(1, 3, 0)]
[InlineData(-8, 1, -8)]
[InlineData(8, 1, 8)]
[InlineData(1, -8, 0)]
[InlineData(1, 8, 0)]
[InlineData(-1, -4, 0)]
[InlineData(-1, 4, 0)]
[InlineData(-1, -1, 1)]
[InlineData(-3, -1, 3)]
[InlineData(3, -1, -3)]
[InlineData(-4, -1, 4)]
[InlineData(4, -1, -4)]
[InlineData(-1, -3, 0)]
[InlineData(-1, 3, 0)]
[InlineData(-8, -1, 8)]
[InlineData(8, -1, -8)]
[InlineData(-1, -8, 0)]
[InlineData(-1, 8, 0)]
public void ComprehensiveDivideTest(int x, int y, int expected)
{
// Act
int actual = Calculations.Divide(x, y);
// Assert
Assert.Equal(expected, actual);
}
}
}
Unit Tests
Description:
The homework from the Lesson 4, Unit Test Project Type, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a simple unit test project. Don't worry about testing any code yet. Just get the flow down (Arrange, Act, Assert).
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- C#;
- Class Library;
- xUnit Test Project;
Find the Project here:
Code Snippet:
using Xunit;
namespace GreetingLibrary.Test
{
public class GreetingGeneratorTests
{
[Theory]
[InlineData("Mr.", "Corey", 0, "Good night Mr. Corey")]
[InlineData("Mr.", "Corey", 1, "Good night Mr. Corey")]
[InlineData("Mr.", "Corey", 2, "Good night Mr. Corey")]
[InlineData("Mr.", "Corey", 3, "Good night Mr. Corey")]
[InlineData("Mr.", "Corey", 4, "Good night Mr. Corey")]
[InlineData("Mr.", "Corey", 5, "Good night Mr. Corey")]
[InlineData("Mr.", "Corey", 6, "Good morning Mr. Corey")]
[InlineData("Mr.", "Corey", 7, "Good morning Mr. Corey")]
[InlineData("Mr.", "Corey", 8, "Good morning Mr. Corey")]
[InlineData("Mr.", "Corey", 9, "Good morning Mr. Corey")]
[InlineData("Mr.", "Corey", 10, "Good morning Mr. Corey")]
[InlineData("Mr.", "Corey", 11, "Good morning Mr. Corey")]
[InlineData("Mrs.", "Corey", 12, "Good afternoon Mrs. Corey")]
[InlineData("Mrs.", "Corey", 13, "Good afternoon Mrs. Corey")]
[InlineData("Mrs.", "Corey", 14, "Good afternoon Mrs. Corey")]
[InlineData("Mrs.", "Corey", 15, "Good afternoon Mrs. Corey")]
[InlineData("Mrs.", "Corey", 16, "Good afternoon Mrs. Corey")]
[InlineData("Mrs.", "Corey", 17, "Good afternoon Mrs. Corey")]
[InlineData("Mr.", "Corey", 18, "Good evening Mr. Corey")]
[InlineData("Mr.", "Corey", 19, "Good evening Mr. Corey")]
[InlineData("Mr.", "Corey", 20, "Good evening Mr. Corey")]
[InlineData("Mr.", "Corey", 21, "Good evening Mr. Corey")]
[InlineData("Mr.", "Corey", 22, "Good evening Mr. Corey")]
[InlineData("Mr.", "Corey", 23, "Good evening Mr. Corey")]
public void GreetingGeneratorTest(string prefix, string lastName, int hourOfDay, string expected)
{
// Arrange
GreetingGenerator greetings = new GreetingGenerator();
// Act
string actual = greetings.GenerateGreeting(prefix, lastName, hourOfDay);
// Assert
Assert.Equal(expected, actual);
}
}
}
Class Libraries
Description:
The homework from the Lesson 3, Class Library Project Types, of Module 7, Common Project Types, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a .NET Standard Class Library and a Console Application. Put a couple calculation methods in it and call it from the Console.
Technologies Used:
- .NET;
- .NET Core;
- .NET Core 3.1;
- .NET Standard;
- .NET Standard 2.1;
- C#;
- Class Library;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/ProjectTypes-ClassLibraries
Code Snippet:
using System;
namespace StandardLibrary
{
public class Calculator
{
public int Add(int x, int y)
{
int output = x + y;
return output;
}
public int Subtract(int x, int y)
{
int output = x - y;
return output;
}
public int Multiply(int x, int y)
{
int output = x * y;
return output;
}
public int Divide(int x, int y)
{
int output = y != 0 ? x / y : throw new DivideByZeroException("You cannot divide by zero.");
return output;
}
public int Modulo(int x, int y)
{
int output = y != 0 ? x % y : throw new DivideByZeroException("You cannot divide by zero.");
return output;
}
}
}
Mini Project
Description:
The homework from the Lesson 14, Mini Project, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to recreate the project we jsut did without looking back a the video. Make sure to make small tweaks.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/OOP2-GenericsEventsMiniProject
Code Snippet:
using System;
using System.Collections.Generic;
namespace WrapUp
{
internal class Program
{
private static void Main()
{
DataAccess.BadEntryFound += DataAccess_BadEntryFound;
List<PersonModel> people = new List<PersonModel> {
new PersonModel { FirstName = "Tim", LastName = "Coreydarnit", Email = "tim@iamtimcorey.com"},
new PersonModel { FirstName = "Sue", LastName = "Storm", Email = "sue@stormy.com"},
new PersonModel { FirstName = "John", LastName = "Smith", Email = "John4537@aol.com"}
};
List<CarModel> cars = new List<CarModel> {
new CarModel { Manufacturer = "Toyota", Model = "DARNCorolla" },
new CarModel { Manufacturer = "Toyota", Model = "Highlander" },
new CarModel { Manufacturer = "Ford", Model = "heckMustang" }
};
people.SaveToCSV(@"D:\Pierre\source\repos\Complete Foundation in C# Course Series\6 Object Oriented Programming Part 2\Homework\WrapUpHomeworkApp\people.csv");
cars.SaveToCSV(@"D:\Pierre\source\repos\Complete Foundation in C# Course Series\6 Object Oriented Programming Part 2\Homework\WrapUpHomeworkApp\cars.csv");
_ = Console.ReadLine();
}
private static void DataAccess_BadEntryFound(object sender, string e)
{
if ( e == "WrapUpHomework.PersonModel" )
{
PersonModel person = (PersonModel)sender;
Console.WriteLine($"Bad Word(s) found in {e} {person.FirstName} {person.LastName}!");
}
else if ( e == "WrapUpHomework.CarModel" )
{
CarModel car = (CarModel)sender;
Console.WriteLine($"Bad Word(s) found in {e} {car.Manufacturer} {car.Model}!");
}
else
{
Console.WriteLine($"Bad Word(s) found in {e}!");
}
Console.WriteLine();
}
}
}
Events
Description:
The homework from the Lesson 13, Events, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to create an event in a class and then consume that class. Attach a listener to the event and have it write to the console.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace Events
{
internal class Program
{
private static void Main()
{
PersonModel person = new PersonModel("Tim", "Corey");
person.LastNameChanged += Person_LastNameChanged;
Console.WriteLine(person.FullName);
person.LastName = "Storm";
Console.WriteLine(person.FullName);
_ = Console.ReadLine();
}
private static void Person_LastNameChanged(object sender, string e)
{
PersonModel model = (PersonModel)sender;
Console.WriteLine();
Console.WriteLine($"{model.FullName}'s last name has changed: {e}");
Console.WriteLine();
}
}
public class PersonModel
{
public event EventHandler<string> LastNameChanged;
public string FirstName { get; set; }
private string _lastName;
public string LastName
{
get
{
return _lastName;
}
set
{
LastNameChanged?.Invoke(this, $"Last Name has been changed from {_lastName} to {value}.");
_lastName = value;
}
}
public string FullName
{
get
{
return $"{FirstName} {LastName}";
}
}
public PersonModel(string firstName, string lastName)
{
FirstName = firstName;
_lastName = lastName;
}
}
}
Generics
Description:
The homework from the Lesson 12, Generics, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a generic method that takes in an item and calls the ToString() method and prints that value to the Console.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace Generics
{
internal class Program
{
private static void Main()
{
string teststring = "A String";
int testint = 42;
bool testbool = false;
double testdouble = 98.6;
PersonModel testpersonmodel = new PersonModel { FirstName = "Tim", LastName = "Corey" };
string stringstringified = Stringify(teststring);
string intstringified = Stringify(testint);
string boolstringified = Stringify(testbool);
string doublestringified = Stringify(testdouble);
string personmodelstringified = Stringify(testpersonmodel);
Console.WriteLine($"{teststring} stringified is {stringstringified}");
Console.WriteLine($"{testint} stringified is {intstringified}");
Console.WriteLine($"{testbool} stringified is {boolstringified}");
Console.WriteLine($"{testdouble} stringified is {doublestringified}");
Console.WriteLine($"{testpersonmodel} stringified is {personmodelstringified}");
_ = Console.ReadLine();
}
private static string Stringify<T>(T item)
{
string output = item.ToString();
return output;
}
}
}
Mini-Project
Description:
The homework from the Lesson 11, Mini Project, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to recreate the project we did for this lesson but without looking back over what Tim did. Tweak it slightly as well.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/OOP2-ExtensionsOverloadsMiniProject
Code Snippet:
using System;
namespace ExtensionsOverloads
{
internal class Program
{
private static void Main()
{
PersonModel person = new PersonModel
{
FirstName = "What is your first name: ".RequestString(),
LastName = "What is your last name: ".RequestString(),
Age = "What is your age: ".RequestInt(1, 120),
Salary = "What is your salary: ".RequestDecimal()
};
_ = person.PrintInfo();
_ = Console.ReadLine();
}
}
}
Extension Methods
Description:
The homework from the Lesson 10, Extension Methods, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to create the following chain using extension methods: person.SetDefaultAge().PrintInfo();
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace ExtensionMethods
{
public static class PersonExtensions
{
public static PersonModel SetDefaultAge(this PersonModel person)
{
person.Age = 25;
return person;
}
public static PersonModel PrintInfo(this PersonModel person)
{
Console.WriteLine($"{person.FullName} is {person.Age} years old.");
return person;
}
}
}
Method Overloading
Description:
The homework from the Lesson 9, Method Overloading, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to create an EmployeeModel class. Create three different constructors that take in different amounts of data.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
namespace MethodOverload
{
public class EmployeeModel
{
public string FirstName
{
get; set;
}
public string LastName
{
get; set;
}
public string Email
{
get; set;
}
public decimal Salary
{
get; set;
}
public string FullName
{
get
{
return $"{FirstName} {LastName}";
}
}
public EmployeeModel()
{
}
public EmployeeModel(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
public EmployeeModel(string firstName, string lastName, string email)
{
FirstName = firstName;
LastName = lastName;
Email = email;
}
public EmployeeModel(string firstName, string lastName, decimal salary)
{
FirstName = firstName;
LastName = lastName;
Salary = salary;
}
}
}
Mini Project
Description:
The homework from the Lesson 8, Mini-Project, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a similar project to what we did here but change it just a bit so you are sure you understand it.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Class Library;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/OOP2-ModifierAbstractOverrideMiniProject
Code Snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using CardGameLibrary.Enums;
namespace CardGameLibrary.Models
{
public abstract class DeckModel
{
internal List<PlayingCardModel> _fullDeck = new List<PlayingCardModel>();
internal List<PlayingCardModel> _drawPile = new List<PlayingCardModel>();
internal List<PlayingCardModel> _discardPile = new List<PlayingCardModel>();
public void ShuffleDeck()
{
Random rnd = new Random();
_drawPile = _fullDeck.OrderBy(x => rnd.Next()).ToList();
}
public abstract List<PlayingCardModel> DealCards();
protected PlayingCardModel DrawOneCard()
{
PlayingCardModel output = _drawPile.First();
_ = _drawPile.Remove(output);
return output;
}
private protected void CreateDeck()
{
_fullDeck.Clear();
for ( int suit = 0; suit < 4; suit++ )
{
for ( int value = 0; value < 13; value++ )
{
PlayingCardModel card = new PlayingCardModel((CARDSUIT)suit, (CARDVALUE)value);
_fullDeck.Add(card);
}
}
}
}
}
Method Overriding
Description:
The homework from the Lesson 7, Method Overriding, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Person class and override the ToString method in it. Make it return the user's first and last name.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
namespace MethodOverride
{
public class PersonModel
{
public string FirstName
{
get; set;
}
public string LastName
{
get; set;
}
public override string ToString()
{
return $"{FirstName} {LastName}";
}
}
}
Abstract Classes
Description:
The homework from the Lesson 6, Abstract Classes, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to create an Abstract Class that has an Interface applied to it. When instantiating the child class, store it using the interface type.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace AbstractClass
{
public abstract class Vehicle : IInventoryItem
{
public decimal SellPrice
{
get; set;
}
public decimal PurchasePrice
{
get; set;
}
public int QuantityOnHand
{
get; set;
}
public string Manufacturer
{
get; set;
}
public string Model
{
get; set;
}
public string VIN
{
get; set;
}
public decimal CalculateGrossProfit()
{
throw new NotImplementedException();
}
public void SellItem()
{
throw new NotImplementedException();
}
}
}
Access Modifiers
Description:
The homework from the Lesson 5, Access Modifiers, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Class Library and a Console Application. Create a public class with members that have different modifiers. Try each out.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Class Library;
- Console Application;
Find the Project here:
Code Snippet:
using System;
using AccessModifiersLibrary;
namespace AccessModifiers
{
internal class Program
{
private static void Main()
{
Person person = new Person();
Manager manager = new Manager();
CEO ceo = new CEO();
// Class Pet not accessible as it is internal
Pet cat = new Pet();
// Class Dog not accessible as it is internal
Dog scruffy = new Dog();
// person.FirstName is accessible as it is public
Console.WriteLine($"{person.FirstName}");
// person.LastName is not accessible as it is protected
Console.WriteLine($"{person.LastName}");
// person.Age is not accessible as it is internal
Console.WriteLine($"{person.Age}");
// person.NetWorth is not accessible as it is protected internal
Console.WriteLine($"{person.NetWorth}");
// person.SSN is not accessible as it is private
Console.WriteLine($"{person.SSN}");
// person.Height is not accessible as it is private protected
Console.WriteLine($"{person.Height}");
// manager.FirstName is accessible as it is public
Console.WriteLine($"{manager.FirstName}");
// manager.LastName is not accessible as it is protected
Console.WriteLine($"{manager.LastName}");
// manager.Age is not accessible as it is internal
Console.WriteLine($"{manager.Age}");
// manager.NetWorth is not accessible as it is protected internal
Console.WriteLine($"{manager.NetWorth}");
// manager.SSN is not accessible as it is private
Console.WriteLine($"{manager.SSN}");
// manager.Height is not accessible as it is private protected
Console.WriteLine($"{manager.Height}");
// manager.PrintProperties is accessible as it is public
manager.PrintProperties();
// ceo.FirstName is accessible as it is public
Console.WriteLine($"{ceo.FirstName}");
// ceo.LastName is not accessible as it is protected
Console.WriteLine($"{ceo.LastName}");
// ceo.Age is not accessible as it is internal
Console.WriteLine($"{ceo.Age}");
// ceo.NetWorth is not accessible as it is protected internal
Console.WriteLine($"{ceo.NetWorth}");
// ceo.SSN is not accessible as it is private
Console.WriteLine($"{ceo.SSN}");
// ceo.Height is not accessible as it is private protected
Console.WriteLine($"{ceo.Height}");
// ceo.PrintProperties is accessible as it is public
ceo.PrintProperties();
_ = Console.ReadLine();
}
}
}
Mini-Project
Description:
The homework from the Lesson 4, Mini-Project, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a similar project to what we did here but change it just a bit so we are sure we understand it.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/OOP2-InheritanceInterfaceMiniProject
Code Snippet:
using System;
using System.Collections.Generic;
using InheritanceMiniProject.Interfaces;
using InheritanceMiniProject.Models;
namespace InheritanceMiniProject
{
internal class Program
{
private static void Main()
{
List<IRentable> rentables = new List<IRentable>();
List<IPurchaseable> purchaseables = new List<IPurchaseable>();
BeachBallModel beachball = new BeachBallModel { BallSize = 15, ItemName = "Wilson Beach Ball", PurchasePrice = 25.00M, QuantityInStock = 10 };
BookModel book = new BookModel { Author = "Charles Dickens", ItemName = "A Tale of Two Cities", NumberOfPages = 658, PurchasePrice = 7.99M, QuantityInStock = 3 };
CarModel car = new CarModel { ItemName = "Chevy Malibu", NumberOfSeats = 4, PurchasePrice = 25000.00M, QuantityInStock = 7, RentalPrice = 125.00M, VehicleIdentificationNumber = "2C56DFG66734A" };
ExcavatorModel excavator = new ExcavatorModel { ItemName = "Backhoe", QuantityInStock = 2, RentalPrice = 250.00M, VehicleIdentificationNumber = "14H34CAB23HE5" };
_ = new InventoryItemModel { ItemName = "Widget", QuantityInStock = 25000 };
MotorcycleModel motorcycle = new MotorcycleModel { ItemName = "Voodoo", PurchasePrice = 17000.00M, QuantityInStock = 1, RentalPrice = 99.75M, RideType = "Low Rider", VehicleIdentificationNumber = "2453DCGB7G45F" };
SunscreenModel sunscreen = new SunscreenModel { BottleSize = 3.4, ItemName = "Neutrogena Sunscreen", PurchasePrice = 9.99M, QuantityInStock = 200 };
TowelModel towel = new TowelModel { ItemName = "Beach Towel", PurchasePrice = 35.99M, QuantityInStock = 75, RentalPrice = 2.00M, TowelLength = 72, TowelWidth = 30 };
TruckModel truck = new TruckModel { BedLength = 6, ItemName = "Ram 1500", PurchasePrice = 35000.00M, QuantityInStock = 5, RentalPrice = 175.00M, VehicleIdentificationNumber = "ADF1234DK9E8D" };
VehicleModel vehicle = new VehicleModel { ItemName = "Moped", PurchasePrice = 2500.00M, QuantityInStock = 5, RentalPrice = 50.00M, VehicleIdentificationNumber = "1234ADBD5643D" };
rentables.Add(car);
rentables.Add(excavator);
rentables.Add(motorcycle);
rentables.Add(towel);
rentables.Add(truck);
rentables.Add(vehicle);
purchaseables.Add(beachball);
purchaseables.Add(book);
purchaseables.Add(car);
purchaseables.Add(motorcycle);
purchaseables.Add(sunscreen);
purchaseables.Add(towel);
purchaseables.Add(truck);
purchaseables.Add(vehicle);
Console.WriteLine("General Store");
Console.WriteLine();
string moretransactions;
do
{
Console.Write("Do you want to rent, buy, or return (rent/buy/return): ");
string rentorbuy = Console.ReadLine();
if ( rentorbuy.ToLower() == "rent" )
{
foreach ( IRentable rentable in rentables )
{
Console.Write($"Did you want to rent a {rentable.ItemName} for ${rentable.RentalPrice} (yes/no): ");
string wanttorent = Console.ReadLine();
if ( wanttorent.ToLower() == "yes" )
{
rentable.Rent();
Console.WriteLine();
}
}
Console.WriteLine();
}
else if ( rentorbuy.ToLower() == "buy" )
{
foreach ( IPurchaseable purchaseable in purchaseables )
{
Console.Write($"Did you want to purchase a {purchaseable.ItemName} for ${purchaseable.PurchasePrice} (yes/no): ");
string wanttobuy = Console.ReadLine();
if ( wanttobuy.ToLower() == "yes" )
{
purchaseable.Puchase();
Console.WriteLine();
}
}
Console.WriteLine();
}
else if ( rentorbuy.ToLower() == "return" )
{
foreach ( IRentable rentable in rentables )
{
Console.Write($"Did you want to return a {rentable.ItemName} (yes/no): ");
string wanttoreturn = Console.ReadLine();
if ( wanttoreturn.ToLower() == "yes" )
{
rentable.Return();
Console.WriteLine();
}
}
Console.WriteLine();
}
else
{
Console.WriteLine("I did not understand.");
Console.WriteLine();
}
Console.Write("Did you want to do anything else (yes/no): ");
moretransactions = Console.ReadLine();
} while ( moretransactions.ToLower() == "yes" );
_ = Console.ReadLine();
}
}
}
Interfaces
Description:
The homework from the Lesson 3, Interfaces, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to create an IRun Interface and apply it to a Person Class and an Animal Class. Store both types in a List
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
namespace ConsoleUI
{
public interface IRun
{
string StartRunning();
string StopRunning();
}
}
Inheritance
Description:
The homework from the Lesson 2, Inheritance, of Module 6, Object-Oriented Programming, Part 2, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Vehicle Class, a Car Class, a Boat Class, and a Motorcycle Class. Identify what inheritance should happen, if any, and wire it up.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
}
}
internal class Vehicle
{
internal int NumberOfSeats
{
get; set;
}
internal string Engine
{
get; set;
}
internal void StartEngine()
{
}
internal void StopEngine()
{
}
}
internal class Car : Vehicle
{
internal int NumberOfDoors
{
get; set;
}
internal int NumberOfWheels
{
get; set;
}
}
internal class Motorcycle : Vehicle
{
}
internal class Boat : Vehicle
{
}
}
Battleship Project
Description:
The homework from Module 4, Battleship Project, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a small, two-player console game that has its roots in the game Battleship from Mattel. There will be a 25-spot grid (A1 – E5). Each player will place five pegs on the board to represent their five ships. Players will then take turns firing on their opponent's ships. The first person to sink all five ships wins.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Class Library;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/BattleshipProject-BattleshipProject
Code Snippet:
using System;
using BattleshipLibrary;
using BattleshipLibrary.Models;
namespace BattleshipLite
{
internal class Program
{
private static void Main()
{
WelcomeMessage();
PlayerInfoModel activeplayer = CreatePlayer("Player 1");
PlayerInfoModel opponent = CreatePlayer("Player 2");
PlayerInfoModel winner = null;
do
{
DisplayShotGrid(activeplayer);
RecordPlayerShot(activeplayer, opponent);
bool doesgamecontinue = GameLogic.PlayerStillActive(opponent);
if ( doesgamecontinue == true )
{
// Swap positions
(activeplayer, opponent) = (opponent, activeplayer);
}
else
{
winner = activeplayer;
}
} while ( winner == null );
IdentifyWinner(winner);
_ = Console.ReadLine();
}
private static void IdentifyWinner(PlayerInfoModel winner)
{
Console.WriteLine($"Congratulations to {winner.UsersName} for winning!");
Console.WriteLine($"{winner.UsersName} took {GameLogic.GetShotCount(winner)} shots.");
}
private static void RecordPlayerShot(PlayerInfoModel activePlayer, PlayerInfoModel opponent)
{
string row = "";
int column = 0;
bool isvalidshot;
do
{
string shot = AskForShot(activePlayer);
try
{
(row, column) = GameLogic.SplitShotIntoRowAndColumn(shot);
isvalidshot = GameLogic.ValidateShot(activePlayer, row, column);
}
catch ( Exception )
{
isvalidshot = false;
}
if ( isvalidshot == false )
{
Console.WriteLine("Invalid Shot Location. Please try again.");
}
} while ( isvalidshot == false );
bool isahit = GameLogic.IdentifyShotResult(opponent, row, column);
GameLogic.MarkShotResult(activePlayer, row, column, isahit);
DisplayShotResults(row, column, isahit);
DisplayCurrentScore(activePlayer, opponent);
}
private static void DisplayCurrentScore(PlayerInfoModel activePlayer, PlayerInfoModel opponent)
{
int activeplayershipssunk = 0;
int opponentplayershipssunk = 0;
foreach ( GridSpotModel ship in activePlayer.ShipLocations )
{
if ( ship.Status == GRIDSPOTSTATUS.Sunk )
{
activeplayershipssunk++;
}
}
foreach ( GridSpotModel ship in opponent.ShipLocations )
{
if ( ship.Status == GRIDSPOTSTATUS.Sunk )
{
opponentplayershipssunk++;
}
}
Console.WriteLine($"{activePlayer.UsersName} has sunk {opponentplayershipssunk} of {opponent.UsersName}'s ships. {opponent.UsersName} has {5 - opponentplayershipssunk} ships left.");
Console.WriteLine($"{opponent.UsersName} has sunk {activeplayershipssunk} of {activePlayer.UsersName}'s ships. {activePlayer.UsersName} has {5 - activeplayershipssunk} ships left.");
Console.WriteLine();
}
private static void DisplayShotResults(string row, int column, bool isAHit)
{
if ( isAHit )
{
Console.WriteLine($"{row}{column} is a Hit!");
}
else
{
Console.WriteLine($"{row}{column} is a miss.");
}
Console.WriteLine();
}
private static string AskForShot(PlayerInfoModel player)
{
Console.Write($"{player.UsersName}, please enter your shot selection: ");
string output = Console.ReadLine();
return output;
}
private static void DisplayShotGrid(PlayerInfoModel activePlayer)
{
string currentrow = activePlayer.ShotGrid[0].SpotLetter;
foreach ( GridSpotModel gridspot in activePlayer.ShotGrid )
{
if ( gridspot.SpotLetter != currentrow )
{
Console.WriteLine();
currentrow = gridspot.SpotLetter;
}
if ( gridspot.Status == GRIDSPOTSTATUS.Empty )
{
Console.Write($" {gridspot.SpotLetter}{gridspot.SpotNumber} ");
}
else if ( gridspot.Status == GRIDSPOTSTATUS.Hit )
{
Console.Write(" X ");
}
else if ( gridspot.Status == GRIDSPOTSTATUS.Miss )
{
Console.Write(" O ");
}
else
{
Console.Write(" ? ");
}
}
Console.WriteLine();
Console.WriteLine();
}
private static void WelcomeMessage()
{
Console.WriteLine("Welcome to Battleship Lite");
Console.WriteLine("created by Tim Corey");
Console.WriteLine();
}
private static PlayerInfoModel CreatePlayer(string playerTitle)
{
PlayerInfoModel output = new PlayerInfoModel();
Console.WriteLine($"Player information for {playerTitle}");
// Ask the user for their name
output.UsersName = AskForUsersName();
// Load up the shot grid
GameLogic.InitializeGrid(output);
// Ask the user for their 5 ship placements
PlaceShips(output);
// Clear
Console.Clear();
return output;
}
private static string AskForUsersName()
{
Console.Write("What is your name: ");
string output = Console.ReadLine();
return output;
}
private static void PlaceShips(PlayerInfoModel model)
{
do
{
Console.Write($"Where do you want to place ship number {model.ShipLocations.Count + 1}: ");
string location = Console.ReadLine();
bool isvalidlocation = false;
try
{
isvalidlocation = GameLogic.PlaceShip(model, location);
}
catch ( Exception ex )
{
Console.WriteLine("Error: " + ex.Message);
}
if ( isvalidlocation == false )
{
Console.WriteLine("That was not a valid location. Please try again.");
}
} while ( model.ShipLocations.Count < 5 );
}
}
}
Mini Project
Description:
The homework from the Lesson 7, Mini-Project, of Module 4, Object-Oriented Programming, Part 1, of the Complete Foundation in C# Course Series from Tim Corey. We are to recreate the guest book project without looking back. Just take the concept and create the application.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Class Library;
- Console Application;
Find the Project here:
Code Snippet:
using System;
using System.Collections.Generic;
using GuestBookLibrary.Models;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
List<GuestModel> guestlist = new List<GuestModel>();
GetGuestInformation(guestlist);
PrintOutGuestList(guestlist);
_ = Console.ReadLine();
}
private static void PrintOutGuestList(List<GuestModel> guests)
{
foreach ( GuestModel guest in guests )
{
Console.WriteLine(guest.GuestMessage);
}
}
private static void GetGuestInformation(List<GuestModel> guests)
{
string moreguestcoming;
do
{
bool isagevalid;
GuestModel guest = new GuestModel
{
FirstName = GetInfoFromConsole("What is your first name: "),
LastName = GetInfoFromConsole("What is your last name: ")
};
do
{
string agetext = GetInfoFromConsole("How old are you: ");
isagevalid = int.TryParse(agetext, out int agenumber);
if ( !isagevalid )
{
Console.WriteLine("Please enter your age as a number.");
}
guest.Age = agenumber;
} while ( !isagevalid );
guest.Hometown = GetInfoFromConsole("What is your hometowm: ");
guest.MessageToHost = GetInfoFromConsole("What is your message for the host: ");
guests.Add(guest);
moreguestcoming = GetInfoFromConsole("Are more guest coming (yes/no): ");
Console.Clear();
} while ( moreguestcoming.ToLower() == "yes" );
}
private static string GetInfoFromConsole(string message)
{
string output;
Console.Write(message);
output = Console.ReadLine();
return output;
}
}
}
Class Libraries
Description:
The homework from the Lesson 6, Class Libraries, of Module 4, Object-Oriented Programming, Part 1, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Class Library that holds a Person Class. Use that Class in a Console Application.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Class Library;
- Console Application;
Find the Project here:
Code Snippet:
namespace DemoLibrary
{
public class PersonModel
{
public string FirstName
{
get; set;
}
public string LastName
{
get; set;
}
public string FullName
{
get
{
return $"{FirstName} {LastName}";
}
}
}
}
Namespaces
Description:
The homework from the Lesson 5, Namespaces, of Module 4, Object-Oriented Programming, Part 1, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Class file and change the Namespace to be something different. Call a method in that class.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
using ConsoleUI.Models;
using ConsoleUI.UserInteraction;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
PersonModel person = new PersonModel
{
FirstName = "Tim",
LastName = "Corey"
};
Messages.GreetPerson(person);
_ = Console.ReadLine();
}
}
}
Properties
Description:
The homework from the Lesson 4, Properties, of Module 4, Object-Oriented Programming, Part 1, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Class that has Properties for street address, city, state, and zip code. Then add a FullAddress property that is read-only.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
namespace ConsoleUI
{
internal class AddressModel
{
internal string StreetAddress
{
get; set;
}
internal string City
{
get; set;
}
internal string State
{
get; set;
}
internal string ZipCode
{
get; set;
}
internal string FullAddress
{
get
{
return $"{StreetAddress}, {City} {State} {ZipCode}";
}
}
internal AddressModel()
{
}
internal AddressModel(string streetAddress, string city, string state, string zipCode)
{
StreetAddress = streetAddress;
City = city;
State = state;
ZipCode = zipCode;
}
}
}
Instantiated Classes
Description:
The homework from the Lesson 3, Instantiated Classes, of Module 4, Object-Oriented Programming, Part 1, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Console Application that has a Person Class and an Address Class.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
namespace ConsoleUI
{
internal class PersonModel
{
internal string FirstName
{
get; set;
}
internal string LastName
{
get; set;
}
internal AddressModel Address
{
get; set;
}
}
internal class AddressModel
{
internal string StreetAddress
{
get; set;
}
internal string City
{
get; set;
}
internal string State
{
get; set;
}
internal string ZipCode
{
get; set;
}
}
}
Static Classes
Description:
The homework from the Lesson 2, Static Classes, of Module 4, Object-Oriented Programming, Part 1, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Console Application with a Static Class that handles calculaltions.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
namespace ConsoleUI
{
internal static class CalculateData
{
internal static double Operate(double x, double y, char opp)
{
double output = 0.0;
switch ( opp )
{
case '+':
output = Add(x, y);
break;
case '-':
output = Subtract(x, y);
break;
case '*':
output = Multiply(x, y);
break;
case '/':
output = Divide(x, y);
break;
default:
UserMessages.DisplayErrorMessage("That is not a valid operation.");
break;
}
return output;
}
private static double Add(double x, double y)
{
double output = x + y;
return output;
}
private static double Subtract(double x, double y)
{
double output = x - y;
return output;
}
private static double Multiply(double x, double y)
{
double output = x * y;
return output;
}
private static double Divide(double x, double y)
{
double output = 0.0;
if ( y != 0.0 )
{
output = x / y;
}
else
{
UserMessages.DisplayErrorMessage("We cannot divide by zero.");
}
return output;
}
}
}
Advanced Breakpoints
Description:
The homework from the Lesson 5, Advanced Breakpoints, of Module 3, Debugging, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Console Application that loops from 1 to 100. Throw an exception on 73. Use a breakpoint to break before the breaking situation.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
Find the Project here:
https://github.com/Spartan-CSharp/Debugging-AdvancedBreakpoints
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
Looper();
_ = Console.ReadLine();
}
private static void Looper()
{
int total = 0;
for ( int i = 1; i <= 100; i++ )
{
total += i;
if ( i == 73 )
{
throw new Exception();
}
}
}
}
}
Advanced Exceptions
Description:
The homework from the Lesson 4, Advanced Exceptions, of Module 3, Debugging, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Console Application that throws an exception in a method that we can catch in the main method.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/Debugging-AdvancedExceptions
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
try
{
ExceptionGenerator();
}
catch ( NotImplementedException ex )
{
Console.WriteLine("You did not implement a mathod.");
Console.WriteLine(ex);
}
catch ( Exception ex )
{
Console.WriteLine("A general exception occurred");
Console.WriteLine(ex);
}
finally
{
Console.WriteLine("Clean up code: I always run!");
}
_ = Console.ReadLine();
}
private static void ExceptionGenerator()
{
throw new NotImplementedException();
}
}
}
Handling Exceptions
Description:
The homework from the Lesson 3, Handling Exceptions, of Module 3, Debugging, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Console Application with a for loop that throws an exception after five iterations. Catch the exception.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/Debugging-HandlingExceptions
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
int[] numbers = new int[] { 1, 42, 34, 56, 13 };
for ( int i = 0; i <= numbers.Length; i++ )
{
try
{
Console.WriteLine($"The number at position {i} is {numbers[i]}");
}
catch ( Exception ex )
{
Console.WriteLine("We had an error");
Console.WriteLine(ex);
}
}
_ = Console.ReadLine();
}
}
}
Using Breakpoints
Description:
The homework from the Lesson 2, Using Breakpoints, of Module 3, Debugging, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Console Application with a for loop that multiplies a number by five and adds it to the total each time. Step through the code.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/Debugging-UsingBreakpoints
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
for ( int i = 1; i < 50; i *= 5 )
{
Console.WriteLine($"The value of i is {i}");
}
_ = Console.ReadLine();
}
}
}
Console Guest Book
Description:
The homework from the Lesson 13, Mini-Project, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to build a Console Guest Book. Ask the user for their name and how many are in their party. Keep track of how many people are at the party. At the end, print out the guest list and the total number of guests.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/CommonSyntax-ConsoleGuestBook
Code Snippet:
using System;
using System.Collections.Generic;
namespace ConsoleUI
{
internal class Program
{
private static void Main(string[] args)
{
//Start counting guests at 0
int totalguests = 0;
// Initialize guest list
List<string> guestlist = new List<string>();
// Initialize done checker
string done;
do
{
//Get user name
string guestname = GetGuestName();
//Add name to guest list
guestlist.Add(guestname);
//Get # of people in party
int partysize = GetPartySize();
//Add # of people to total guests
totalguests += partysize;
//Ask if done
Console.Write("Done (yes/no): ");
done = Console.ReadLine();
//If not done loop back to get user name
//If done move on
} while ( done.ToLower() != "yes" );
//Print out list of people
//Print out total # of people
DisplayGuestList(guestlist, totalguests);
_ = Console.ReadLine();
}
private static string GetGuestName()
{
Console.Write("What is the name of your party: ");
string output = Console.ReadLine();
return output;
}
private static int GetPartySize()
{
bool issizevalid;
int output;
do
{
Console.Write("How many people in your party: ");
string partysize = Console.ReadLine();
issizevalid = int.TryParse(partysize, out output);
if ( !issizevalid )
{
Console.WriteLine("Please enter the number using digits.");
}
} while ( !issizevalid );
return output;
}
private static void DisplayGuestList(List<string> guestList, int totalGuests)
{
Console.WriteLine("Party Guest List");
foreach ( string guest in guestList )
{
Console.WriteLine(guest);
}
Console.WriteLine($"Total Guests: {totalGuests}");
}
}
}
Methods
Description:
The homework from the Lesson 12, Methods, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a welcome method, a method to ask for the user's name, and another to tell that user "Hello __".
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
WelcomeUser();
string name = GetUserName();
SayHello(name);
_ = Console.ReadLine();
}
private static void WelcomeUser()
{
Console.WriteLine("Welcome to Foundation in C#!");
}
private static string GetUserName()
{
Console.Write("What is your first name: ");
string output = Console.ReadLine();
return output;
}
private static void SayHello(string firstName)
{
Console.WriteLine($"Hello {firstName}!");
}
}
}
Loops: foreach
Description:
The homework from the Lesson 11, Loops: foreach, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to ask the user for their first name. Continue asking for first names until there are no more. Then loop through each name using foreach and tell them hello.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
using System.Collections.Generic;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
List<string> firstnames = new List<string>();
string morenames;
do
{
Console.Write("Enter a first name: ");
firstnames.Add(Console.ReadLine());
Console.Write("Any more (yes/no)? ");
morenames = Console.ReadLine();
} while ( morenames.ToLower() != "no" );
foreach ( string firstname in firstnames )
{
Console.WriteLine($"Hello {firstname}!");
}
_ = Console.ReadLine();
}
}
}
Loops: for
Description:
The homework from the Lesson 10, Loops: for, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to ask the user for a comma-separated list of first names (no spaces). Split the string into a string array. Loop through the array and tell each person hello.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
Console.Write("Enter a comma-separated list of first names (no spaces): ");
string firstnamelist = Console.ReadLine();
string[] firstnames = firstnamelist.Split(',');
for ( int i = 0; i < firstnames.Length; i++ )
{
Console.WriteLine($"Hello {firstnames[i]}!");
}
_ = Console.ReadLine();
}
}
}
Sets: Dictionary
Description:
The homework from the Lesson 9, Sets: Dictionary, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Dictionary list of employee IDs and the name that goes with that ID. Fill it with a few records. Then ask the user for their ID and return their name.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/CommonSyntax-SetsDictionary
Code Snippet:
using System;
using System.Collections.Generic;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
Dictionary<int, string> employees = new Dictionary<int, string>
{
[1] = "Tim",
[2] = "Sue",
[3] = "Bob"
};
Console.Write("Enter your Employee ID: ");
string employeeidtext = Console.ReadLine();
bool isidvalid = int.TryParse(employeeidtext, out int employeeid);
if ( isidvalid && employeeid > 0 && employeeid < 4 )
{
Console.WriteLine($"Welcome {employees[employeeid]}!");
}
else
{
Console.WriteLine("That is not a valid ID.");
}
_ = Console.ReadLine();
}
}
}
Sets: Lists
Description:
The homework from the Lesson 8, Sets: Lists, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to add students to a class roster until there are no more students. Then print out the count of the students to the Console.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
using System.Collections.Generic;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
List<string> studentnames = new List<string>();
int studentcount = 0;
string morestudents;
do
{
Console.Write("Enter Student Name: ");
studentnames.Add(Console.ReadLine());
studentcount++;
Console.Write("More Students (yes/no): ");
morestudents = Console.ReadLine();
} while ( morestudents == "yes" );
Console.WriteLine($"You entered {studentcount} students.");
_ = Console.ReadLine();
}
}
}
Sets: Arrays
Description:
The homework from the Lesson 7, Sets: Arrays, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to create an array of 3 names. Ask the user which number to select. When the user gives you a number, return that name.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
string[] names = new string[] { "Tim", "Sue", "Bob" };
Console.Write("Pick a number from 1 to 3: ");
string numbertext = Console.ReadLine();
bool isvalidnumber = int.TryParse(numbertext, out int number);
if ( !isvalidnumber || number < 1 || number > 3 )
{
Console.WriteLine("That is not a valid number.");
_ = Console.ReadLine();
return;
}
Console.WriteLine($"The name in position {number} is {names[number - 1]}.");
_ = Console.ReadLine();
}
}
}
Do/While
Description:
The homework from the Lesson 6, Do/While, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to ask for the user's name. If their name is Tim, say "Hello Professor". Otherwise, say "Hi __". Do this until they type "exit".
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
string name;
do
{
Console.Write("What is your name: ");
name = Console.ReadLine();
if ( name.ToLower() == "tim" )
{
Console.WriteLine("Hello Professor");
}
else if ( name.ToLower() != "exit" )
{
Console.WriteLine($"Hi {name}");
}
} while ( name.ToLower() != "exit" );
}
}
}
Mini-Project
Description:
The homework from the Lesson 5, Mini-Project, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to plan and build a Console Application that asks a user for their name and their age. If their name is Bob or Sue, address them as professor. If the person is under 21, recommend they wait X years to start this class.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
Console.Write("What is your first name: ");
string firstname = Console.ReadLine();
Console.Write("How old are you: ");
string agetext = Console.ReadLine();
bool isagevalid = int.TryParse(agetext, out int age);
if ( firstname.ToLower() == "bob" || firstname.ToLower() == "sue" )
{
Console.WriteLine($"Hello Professor {firstname}");
}
else
{
Console.WriteLine($"Hello {firstname}");
}
if ( isagevalid )
{
if ( age < 21 )
{
int yearstowait = 21 - age;
Console.WriteLine($"I recommend you wait {yearstowait} years before starting this class");
}
}
else
{
Console.WriteLine("You must enter your age in digits");
}
_ = Console.ReadLine();
}
}
}
Type Conversion
Description:
The homework from the Lesson 4, Type Conversion, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to capture a user's age from the Console and then identify how old they were in the year 2000. If they were not born yet, tell them that instead.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/CommonSyntax-TypeConversion
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
Console.Write("How old are you: ");
string agetext = Console.ReadLine();
bool isagevalid = int.TryParse(agetext, out int age);
if ( isagevalid )
{
age -= 21;
if ( age < 0 )
{
Console.WriteLine("You were not born yet in the year 2000!");
}
else
{
Console.WriteLine($"You were {age} years old in the year 2000.");
}
}
else
{
Console.WriteLine("Please enter your age using digits.");
}
_ = Console.ReadLine();
}
}
}
Conditionals
Description:
The homework from the Lesson 3, Conditionals, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Console Application that asks the user for their name. Welcome Tim as professor or anyone else as a student.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
Console.Write("What is your first name: ");
string firstname = Console.ReadLine();
if ( firstname.ToLower() == "tim" )
{
Console.WriteLine("Hello Professor!");
}
else
{
Console.WriteLine("Hello Student!");
}
_ = Console.ReadLine();
}
}
}
Basic Variables
Description:
The homework from the Lesson 2, Basic Variables, of Module 2, Common Syntax, of the Complete Foundation in C# Course Series from Tim Corey. We are to create a Console Application that has variables to hold a person's name, age, if they are alive, and their phone number.
Technologies Used:
- .NET;
- .NET Framework;
- .NET Framework 4.8;
- C#;
- Console Application;
Find the Project here:
https://github.com/Spartan-CSharp/CommonSyntax-BasicVariables
Code Snippet:
using System;
namespace ConsoleUI
{
internal class Program
{
private static void Main()
{
string firstname = "Pierre";
string lastname = "Plourde";
string fullname = $"{firstname} {lastname}";
int age = 47;
bool isalive = true;
string phonenumber = "905-439-7645";
Console.WriteLine($"Hi, {fullname}, you are {age} years old, your phone number is {phonenumber}, and you are alive? {isalive}.");
_ = Console.ReadLine();
}
}
}