Henrik Høltzer (heho)
Software Construction - SWC 1.2 2C

Semester: 2.sem., forår 2019
Email: heho@zealand.dk

Materialer generelt:

Noter:

Object-Oriented Programming with C# (findes på GitHub her)


Opgaver:

C# Programming Exercises (findes på GitHub her)

Unsolved exercise projects

Solved exercise projects


Supplerende materiale:

Microsoft Visual C# Step by Step (8th ed.), by John Sharp (ISBN: 9781509301041)

NB: Bogen er IKKE pensum

 

Video

Lynda.com (Gratis adgang; tilmeld med EASJ e-mail konto: https://www.lynda.com/email-signup) (SWC Lynda.com Playlist)

MS Academy: C# Fundamentals for absolute beginners

 

 

Andet:

Studieordning Datamatiker

Opgave-Oversigten

Læse-Oversigten

Wiki C# : Gr1 Gr2 Gr3 Gr4 Gr5 Gr6 Gr7


Link til 1. semester: Software Construction - SWC 1.1 1C

Uge Emner Materialer Opgaver
5 Brush Up


O1: EventMaker

The MVVM-CookBook & Dictionary

Solutions:
EventMakerV2.zip

6
Brush Up (cont.),
Inheritance
Polymorphism
Interface

Error/Exception
Unit Test
(flyttes til uge 9)




Inheritance (Arv), Interface + Abstract class:
Noter: s.111-122

(Bog: Kap. 12, 13, 6 (i den orden))

Slides: Inheritance and Polymofism


Exceptions:
Noter: s.129-133 (MSVC#: Chap. 6 )
Exceptions and Exception Handling in C#

MSDN: Best Practices for Exceptions

Exercise:
O2: BrushUp

O3: ISpeak (Philosopher)

O4: OOP.2.7
O5: Exceptions-Stack
O6 Exceptions-UnitTest (flyttes til uge 9)





Solutions:
ISpeak.zip
Exceptions-UnitTest (flyttes til uge 9)

7

Stack ADT (Abstract Data Type)
Generics
Queue (ADT) Using Collections

IComparable / IComparer
Equals( ) / GetHashCode( )

Generics:
Noter: s.194-207 (
MSVC#
: Chap. 17p. 369-375)

Collections:
Noter: s.223-227 (MSVC#:
Chap 18. 399-411)

Collections-Overview
An Overview Of System.Collections.Generic
MSDN: IComparable
MSDN: IComparer

Video:

What is IEnumerable,IComparable And IComparer Interfaces in C#?
Visualization and Comparison of Sorting Algorithms

Exercise:
O7: MyGenericStack

C#-Projects:
MyStack.zip

Exercise:
O8: Circular List
O9: CollectionsSort
O10: GenericCollectionsAndDictionarys

C#-Projects:
CollectionSortTest.zip

Solutions:
CircularList
CollectionsSort.zip

8 Ingen UV i SWC    
9-10

Predicate Deligates
Anonymous functions
Lambda-expressions
IEnumerable / IEnumerator

LINQ

Functions as parameters (Delegates, Predicates and Lambda):
Noter: s.208-218

Bemærk:

Predicate deligates og anonyme funktioner er lidt "tungt" stof ;)

CodeProject: Understanding Predicate Delegates

Videos:
Anonymous methods in c#

Lambda expression in c#
Func delegate in c# ** bemærk extra !! **


MSDN: Anonymous Methods
MSDN: Delegates
MSDN: Predicate <T> Delegate
MSDN: Lambda expressions
DotnetPerls: C# Lambdas

LINQ:
Noter: s.232-241 (Bogen: MSVC#
: Chap. 21p.469-481)
WizIQ : LINQ - Language INtegrated Query (slides)
MSDN: Introduction to LINQ
MSDN: 101 LINQ Samples

Videos:
LINQ
Part 1 What is LINQ
Part 2 Writing LINQ queries
Part 3 Extensions Methods in C#
Part 4 LINQ Aggregate Functions

Exercise:
O11: LambdaExpressions
O12: LinqHotelExercice.zip

C#-Projects:
DeligateTest.zip
PredicateDeligateTest.zip
LinqTest.zip

Solutions:
LinqHotels.zip
LambdaExpressions.zip

10
Entity Framework

Web API 2

MSDN: Entity Framework Development Workflows
Channel9-MSDN: Code First to Existing Database
MSDN: Code First to a New Database

Daniel Børger: Guide til Azure (pdf)


Exercise: O13
Code First - Existing Database
Create your own DB using Visual Studio
(eg a TradeDB with the following tables: Product, Customer, Order and Orderline)
Insert som data.
Watch the video:
Code First to Existing Database

Use ADO.NET Entity Data Model -> Code First From Database to generate your model clases.
Use LINQ to query and manipulate the database.

Test all CRUD - operations (Create/Add, Read/query, Update, Delete/Remove)

Exercise: O14
Create a wiew in the Database eg. Customer.Id, Customer.Name, Product.Name, Orderline.Count

Use Entity framework to generate classes and DBContext to the wiew and test it in the console.


Exercise: O15
Get an Azure-account from Imagine/Dreamspark.
Create a DB in Azure and test if you can get access from your console application


Exercise: (O16 - extra)
Code First - New Database

Watch the video:
Code First to a New Database

And look at this: http://evang.dk/softwareconstruction-2nd-semester/entity-framework-6-code-first-to-new-database/

Create your Model classes in a new project.
Create a class that inherit from DbContext with DbSet properties of your classes.
Verify that your DB is automatic generated and use LINQ to query and manipulate your DB.

 

11

 

Web API 2.2 client


Demonstrates how to create a restfull webservice that provides access to our HotelDB
Screencast: WebServiceEntityFrameworkDemo1 (Part1)

Demonstrates how to use the webservice from a client application (console)
Screencast: WebServiceEntityFrameworkDemo2 (Part2)

Demonstrates how to create a database view and how to provide the view by using a webservice controller.
Screencast: WebServiceView (Part3)

Exercise O17:

Webservice - rest
In this exercise you have to create a restfull webservice to the HotelDB, then fetch
the data from the HotelDB by using the service - and print the result in the console.

Start createing a new Console project (HotelWebserviceRest) and follow
the steps I demonstrate in the screencast.

Notice:
When using the DbContext API for Code First you have to add:
base.Configuration.ProxyCreationEnabled = false in the DbContext-class

public class MyClass : DbContext
{
public MyClass(){base.Configuration.ProxyCreationEnabled = false;} }
see: https://stackoverflow.com/questions/3372895/datacontractserializer

Hint to the client-site:

const string ServerUrl = "http://localhost:50000";

HttpClientHandler handler = new HttpClientHandler();
handler.UseDefaultCredentials = true;

using (var client = new HttpClient(handler))
{
client.BaseAddress = new Uri(ServerUrl);
client.DefaultRequestHeaders.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
try
{

var response = client.GetAsync("api/Hotels").Result;

if (response.IsSuccessStatusCode)
{
IEnumerable<Hotel> hotelData = response.Content.ReadAsAsync<IEnumerable<Hotel>>().Result;
foreach (var hotel in hotelData)
{
Console.WriteLine(hotel);
}

}


Notice:
When using Web API Client library (HttpClient) it can be nessesary to change the DefaultCredentials

HttpClientHandler handler = new HttpClientHandler();  
handler.UseDefaultCredentials = true;  
HttpClient client = new HttpClient(handler);
see: http://social.msdn.microsoft.com/forums/windowsapps

 

Exercise O18: (Windows Store App - Event)

Tag udgangspunkt i EventMaker fra uge 5.

  • Lav en Database EventDB med en tabel Event, - tabellen skal have samme attributter (navn/type) som properties fra class Event i EventMaker.
  • Tilføj et nyt ASP.net - projekt (EventWS) til EventMaker solution og generer Context og Controller til projektet, så databasen kan tilgås via webservice.
    (Husk: No-authentication og base.Configuration.ProxyCreationEnabled = false;)
  • Test i Browser at WS virker.
  • Opret et Consolprojekt og test, at der kan tilgås fra klient-side
    (Husk: Nuget: Web API client Lib 2.2).
  • Ændre i EventMakers PersistensService så der benyttes en Database i stedet for at seriealisere til filer - der skal tilføjes en ny metode til PersistencyService: DeleteEventAsync som kaldes fra EventSingleton i stedet for SaveEventsAsJsonAsync (før blev filen overskrevet, nu skal der bare slettes en event fra DB). Ellers er det kun PersistencyService der skal opdateres (LoadEventsAsJsonAsync og SaveEventsAsJsonAsync) da vi benytter lagdelt arkitektur (og følger retningslinierne fra Larmann :)).

C#-Projects:
EventMaker.zip (version 2, med EventDB)
WebserviceTest.zip (Code demonstrated in the class)

 

12-13
Web API 2 (Cont.)

Advanced Stuff:
In ASP.NET Web API, a controller is a class that handles HTTP requests. The public methods of the controller are called action methods or simply actions. When the Web API framework receives a request, it routes the request to an action. For more information read:
Routing in ASP.NET Web API
Routing and Action Selection
Create a REST API with Attribute Routing in Web API 2

Web API: Mixing Traditional & Verb-Based Routing ***
MVC web API with more then one Get method



(It's about - Rest isn't just CRUD actions, and how to invoke the non-CRUD actions)

Other interresting links:
RESTful HTTP in practice




Exercise O19: (Windows Store App - Hotel)

Make a front-end (windows store app) to your Hotel webservice, so you can do the CRUD and non-CRUD operations on the HotelDB (eg. display hotel/room information, create new guest and bookings, display current bookings on a selected hotel ....).

Use ICommand/RelayCommand - not code-behind event-handling. (look at the new EventTriggerBehavior/InvokeCommandAction)

Use GridView/ListView (ItemSource, ItemTemplate) and DataTemplates

Notice:
If you have used "Windows Authentification" to your back-end Webservice - you will get an 401 error when trying to get access from win 10 store app. Create a new web-service with "No Authentification" (or find out - how to change by configuration?)

For saving an object in the DB, you must use PostAsync( ) and convert the c#-object to a Json-object:

string postBody = JsonConvert.SerializeObject(hotel);
var response = client.PostAsync("api/Hotels",new StringContent(postBody, Encoding.UTF8, "application/json")).Result;

But you have to install the NuGet Package: Json.Net first.

OR use PostAsJsonAsync see: Calling a Web API From a .NET Client in ASP.NET Web API 2 (C#)

If You want to insert a new hotel:

1) In the DB - change the primary key to be auto generated (set column Hotel_No to identity)
2) In class Hotel - change the Annotation for Hotel_No to:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Hotel_No { get; set; }



C#-Projects:

WSRestHotels.zip (code demonstrated in class)
HotelDbtest2.mdf (zip-fil)

 

14

Design Patterns

  • Decorator
  • Factory
  • Observer
  • Adapter
  • State
  • mm.

Lynda.com:
Foundations-Programming-Design-Patterns

Design patterns explained 
Illustrated designpatterns: 1 2 3 4 5

Code-project: Strategy Pattern-C#


DesignPatterns (Note)

Larman: Kap. 26

Exercise O20:

PizzaShop

C#-Projects:
PizzaDesignPatterns (løsning til PizzaShop)

15.1 Dokumentation Code Documentation with Doxygen


Exercise O21:




15.2
Task, Thread, Asynchron

Microsoft:

Task-based Asynchronous Programming
Asynchronous programming


CodeProject: Asynchronous Programming in C# 5.0 using async and await

Async/Await - Best Practices in Asynchronous Programming

Slides: ProcessesAndThreads (PowerPoint)
Slides: AsynchronousProgramming (PowerPoint)

 


Joseph Albahari Threading in C#, part 1
Threads in C# (slides)

Example: TryThread | WriteToArray

Joseph Albahari Threading in C#, part 2

Synchronization: Threads + monitors (slides)

Example: ThreadBank



C#-Projects:
WSRestHotels.zip (ver. 2 - HotelApp/HotelWS)
WSRestHotels.zip (ver. 3 - HotelApp/HotelWS)


C#-Projects:
GuiExampleAsyncAwait


Notice:

"Blend always launches with "We're preparing for first use" dialog"



Exercise
O22:
First thread | Solution
O23: Adding threads to an existing program | Solution
O24: Producer-Consumer | solution
16 Påskeferie    
17-22 Projektarbejde Projektaflevering: Wiseflow d. 28. maj kl. 11.00
Præsentation (Demodag): d. 29. maj kl. 900-13.00 (program følger)
Eksempler på tidligere opgaver:
Flygo og DriversApp (zip)
23-24 Eksamenslæsning Repetition/Spørgetimer:
25 Eksamen 17-19. juni 2019 Eksamensliste
Pensumsliste