Weekplan Software Construction SWC1.2

Semester: 2.sem., spring 2017
Teacher: Henrik Høltzer
Email: heho@easj.dk

Literature/Material:
MSVC#: Microsoft Visual C# - Step by step, John Sharp, Microsoft 2015, Eighth Edition

C#-note: Note by Per Laursen
Exercises: SWC1 Exercise Set
NewBoston: Video tutorial

Vejledningsliste
Opgave-Oversigten 2. semester
DMU-Ordbogen - GR1, GR2, GR3, GR4, GR5, GR6
Weekplan Software Construction SWC1.1 1.sem

NB: The plan is preliminary and will properly be changed during the semester! (Last updated: 2. juni 2017)

Week Topics Literature/Material Exercises
5 Brush Up


Exercise:
O1: EventMaker

Solutions:
EventMaker.zip

6
Brush Up (cont.),
Inheritance
Polymorphism
Interface

Error/Exception
IO/File
Unit Test




Inheritance (Arv):
MSVC#: Chap. 12 + C#-note: p.55-59

Interface + Abstract class:
MSVC#: Chap. 13 + C#-note: p.59-60

Slides: Inheritance and Polymofism

InheritanceDemo

Exceptions:
MSVC#: Chap. 6 + C#-note: p.61-68
Exceptions and Exception Handling in C#

MSDN: Best Practices for Exceptions


Exercise:
O2: BrushUp

O3: ISpeak (Philosopher)
O4 Exceptions-UnitTest

Repetition - exercices from last semester:
O5: Exceptions-Stack

O6: SerializationTest
O7: ExceptionTextFiles

HomeExercice:
O8: Exercises: nr. 26
O9: Exercises: nr. 27
O10: The Bank Job


C#-Projects:

Company_v1
Company_v2

The Bank Job Steps 1 to 3

Solutions:
Ex 26 (Company_v1Solved)
Ex 27 (Company_v2Solved)
ISpeak.zip
Exceptions-UnitTest


7

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

IComparable / IComparer
Equals( ) / GetHashCode( )

MSVC#: Chap. 17p. 369-375 (Generics )
MSVC#:
Chap 18. 399-411 (Collection)

Collections-Overview
An Overview Of System.Collections.Generic
MSDN: IComparable
MSDN: IComparer
MSDN: Guidelines for Overloading Equals()

Video:

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

Exercise:
O11: MyGenericStack

C#-Projects:
MyStack.zip

Exercise:

O12: Circular List
O13: CollectionsSort
O14: GenericCollectionsAndDictionarys

C#-Projects:
CollectionSortTest.zip

Solutions:
CircularList
CollectionsSort.zip

8-9

Predicate Deligates
Anonymous functions
Lambda-expressions
IEnumerable / IEnumerator

LINQ

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

MSVC#
: Chap. 21p.469-481 (LINQ)
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:
O15: LambdaExpressions
O16: 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) New!


Exercise: O17
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: O18
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: O19
Get an Azure-account from Imagine/Dreamspark.
Create a DB in Azure and test if you can get access from your console application


Exercise: (O20 - 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


MSDN: How to: Install Sample Databases
(look at: Connecting to a Database file)


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 O21:

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 O22: (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
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 O23: (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 8.1 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; }


Hint:
Install the NuGet Package: MVVM Helpers for Windows 8.1 Store app
Include e.g setting the focus to a TextBox control see: http://www.julmar.com/blog/programming/managing-focus-with-mvvm-in-windows-store-apps/



C#-Projects:

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

 

13-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 O24:

PizzaShop (opdateret 14-04-2015 kl. 18.05)

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

14 Dokumentation Code Documentation with Doxygen


Exercise O25:

  • Download and install Doxygen
  • Document some of your previons projects and try to extract documentation using Doxygen




15 Easter holidays  
16-17
Task, Thread, Asynchron
MSDN: Asynchronous Programming with Async and Await
CodeProject: Asynchronous Programming in C# 5.0 using async and await

Don't Block on Async Code

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
SimpleBrowserAsync



Exercise
O26:
First thread | Solution
O27: Adding threads to an existing program | Solution
O28: Producer-Consumer | solution
18-22 Exam Project
Hand-in (wiseflow) : 31. maj kl. 11.00
Presentation: 2. juni program
Bemærk: Morgenbrød kl. 9 fredag d. 2. juni i klassen
Eksempler på tidligere opgaver:
Flygo og DriversApp (zip)
23-24 Exam preparation Spørgetime: mandag d. 12. juni kl. 12.15 ->  
25 Exam: 19-20 juni

Pensumliste

Mødeliste