C# Fundamental Muhammad Bagir M.T.I
Profile
Muhammad Bagir M.T.I
Phone : 08998152784 / 08118625231
Mail :
[email protected]
Pin : 29137131
Experience :
Trainer Badiklat Kemhan, Corporate, Binus Centre
Lecturer CCIT FT UI, STT NF, I-TECH, Binus
Application & Web Developer with OOP Language.
Daily Contents Management
Day 1 : C# Fundamental
Day 2 : C# with ADO.Net
Day 3 : HTML, JSCRIPT & ASP.Net
Day 4 : ASP.Net with ADO.Net & Linq
Day 5 : Application & Web Deployment
Contents
OOP & C# Introduction
C# CUI and I/O
C# GUI
User Interface
Working with SQL Server 2008
CRUD Operation
Data Set
Linq
Generic & Collection
Reflection, Thread & Graph
Deployment
C# & OOP
C# is a modern object-oriented, general-purpose programming language, created and developed by Microsoft together with the .NET platform. There is highly diverse software developed with C# and on the .NET platform: office applications, web applications, websites, desktop applications, mobile applications, games and many others.
C# is a high-level language that is similar to Java and C++ and, to some extent, languages like Delphi, VB.NET and C. All C# programs are objectoriented. They consist of a set of definitions in classes that contain methods and the methods contain the program logic – the instructions which the computer executes.
Programming Concept Input
Process
Output
Oil, Egg, Salt
Fry
Scramble Egg
Number
Prime Number Checking
True or False
SELECTION
IF Clause
IF Clause
IF..ELSE IF…ELSE
IF..ELSE
NESTED IF
Tugas I (If Clause)
Buatlah sebuah aplikasi sederhana untuk menghitung nilai akhir dari siswa. Untuk menghitung nilai akhir, user harus memasukkan jumlah absen, nilai UTS, UAS, dan Tugas dari siswa. Ketentuan pemberian nilai adalah :
Nilai akhir = 35% UTS + 20% Tugas + 45% UAS
Setelah nilai akhir di dapatkan, tetapkan grade siswa :
0 – 50 : E
51 – 64 : D
65 – 74 : C
75 – 84 : B
85 – 100 : A
Apabila absen siswa lebih dari tiga, maka siswa akan otomatis mendapat nilai F, dan dinyatakan gagal.
Output terakhir di layar hanya grade saja. Tidak perlu nilainya.
Contoh : “Selamat, anda mendapatkan grade A!”
LOOPING
Looping Construct • FOR dengan Increment
• While….loop
• FOR dengan Decrement
• Do. …While
Tugas II (Loop)
Buatlah sebuah program untuk menampilkan deret bilangan Fibonacci. Mintalah user untuk memasukkan jumlah bilangan yang ingin ditampilkan. Validasikan bahwa user hanya boleh mengetikkan angka dari 3 – 10!
Contoh :
Input : 4 Output : 1 1 2 3
Input : 6 Output : 1 1 2 3 5
BREAK
Digunakan untuk keluar dari perulangan
0 1 2 3
0 1 2 … 9
GOTO
Digunakan untuk menunjukan suatu langkah
0 1 2 Hasil goto
0 1 2 … 9
CONTINUE
Menspesifikasikan kapan suatu aksi harus dilakukan
Looping forever
0 1 2 … 9
Encapsulation
Membatasi akses user lain terhadap data dan member class anda
Melindungi data dari perubahan yang disengaja maupun tidak oleh fungsi lain
Mengurangi coupling antar objek
Meningkatkan maintainability dari code anda
Access-Identifier Sealed • membuat class tidak bisa disinherit oleh class lain.
Private • hanya bisa diakses di dalam/oleh class itu sendiri
Protected • bisa diakses oleh class itu sendiri dan turunannya
Internal • Hanya bisa diakses dan terlihat dalam satu assembly yang sama
Public • bisa diakses oleh siapapun di dalam maupun di luar class itu
Ways to Do Encapsulation
Getter & Settter
Properties
Ways to Do Encapsulation
Read-Only Properties
Write-Only Properties
Inheritance
Memungkinkan anda mereuse code
Menurunkan "sifat" dari Base Class (class induk) ke Derived Class (class anak)
Gunakan simbol titik dua [:] untuk menginherit suatu class
Contoh Inheritance
Polymorphism
Mengizinkan sebuah definisi (function) untuk dipakai pada beberapa tipe data yang berbeda.
Kemampuan dari object yang berbeda tipe (class) untuk merespon method dengan nama yang sama, namun mungkin menjalankan action yang berbeda.
Polymorphism berarti jika class B merupakan subclass dari class A, class B tidak harus memiliki semua method dari class A. Mungkin saja ada method di class B yang melakukan action yang berbeda dari method di class A.
Override Method
Overload Method
Override Method
Suatu method bisa menghasilkan hasil yang berbeda pada class anak yang berbeda
Method pada base class yang akan di override harus diberi keyword virtual
Overload Method
Nama method sama namun isi berbeda-beda dalam satu class
Contohnya adalah pada saat pembuat constructor dengan dan tanpa operator
Recursion
Fungsi yang memanggil dirinya sendiri
Struct
Digunakan untuk membuat "tipe data" baru
Class menghasilkan "tipe data" reference, sedangkan struct membuat "tipe data" value
Struct juga memiliki field, method, dan property namun struct tidak mengenal inheritance
Interface
Gambaran apa yang harus dimiliki oleh class
Interface bukanlah sebuah class
Interface memiliki properties dan method tapi tidak memiliki fields
interface tidak bisa dibuat object, harus diinherit dulu oleh sebuah class agar bisa digunakan
C# tidak mengenal multiple inheritance, oleh karena itu interface dibuat untuk menanggulangi masalah ini
Abstract Class
Class yang belum lengkap
Terdiri dari satu atau lebih method abstract method
Abstract class tidak bisa diinisialisasi langsung
Class yang menginherit dan mengimplementasi seluruh abstract methodnya disebut concrete class
Problem Statement: Furniture and Fittings Company (FFC) manufactures domestic furniture. Customers provide their specifications to the company for the furniture they want. To cope with the received customer’s orders, FFC decides to computerize the order-processing system. The system should accept the values of furniture items, such as a bookshelf and a chair. You need to develop the hierarchy of these items.
Solution
Interface Vs Abstract Class Fitur Multiple Inheritance
Interface Class bisa menginherit lebih dari 1 Interface
Abstract Class 1 Class hanya bisa menginherit satu abstract class
Default
Interface tidak memprovide code, hanya
Abstract class bisa berisi code yang lengkap
Implementation
signature
sebagai defaultnya dan bisa di override
Access Modifiers
Interface tidak memiliki access modifiers,
Access Modifier dari abstract class bisa
seluruh member dan interface itu sendiri akan didefinisikan dideteksi sebagai public Core Vs Prepheral
Interface digunakan untuk menjelaskan
Abstract class mendefinisikan identitas dasar
kemampuan standar dari suatu class
yang harus dimiliki oleh suatu class dan digunakan oleh object dengan tipe yang sama
Kecepatan
Memerlukan waktu yang cukup lama untuk
Cepat
mendapatkan method pada class yang bersangkutan
Fields & Constanta
Fields tidak bisa didefinisikan di dalam interface
Abstract class bisa memiliki field dan constanta
Enumeration
Enum digunakan untuk menyimpan sebuah set konstanta Enum NamaEnumeration { konstanta1, konstanta2, …., konstanta-n}
Array
Sekumpulan variabel yang memiliki tipe data yang sama
Index array dimulai dari 0
Ada 3 jenis array berdasarkan dimensinya : One-dimensional
array
Multi-dimensional Jagged
array
array
One-Dimensional Array
Inisialisasi Array langsung tipedata[] namaArray = { nilai1, nilai2, ……., nilai-n };
Inisialisasi Array tidak langsung tipedata[] namaArray = new tipedata[n]
Multi-Dimensional Array
Inisialisasi Array langsung tipedata[,] namaArray = { {nilai1a, nilai1b}, ……., {nilai-na, nilai-nb};
Inisialisasi Array tidak langsung tipedata[,] namaArray = new tipedata[n,z]
Jagged Array
“Array di dalam array”
Digunakan jika jumlah index pada setiap row berbeda
Inisialisasi jagged array
TipeData[][] NamaArray = new Tipedata[n1][n2]
Manipulasi Array
Mengakses Array NamaArray[index] = nilai; NamaArray[index1,index2] = nilai;
Mengetahui Panjang Array NamaArray.Length;
Menghapus Elemen Array Array.Clear(NamaArray, IndexMulai, BanyakElemen)
Manipulasi Array (Cont.)
Sort
Array.Sort(NamaArray)
Reverse Array.Reverse(NamaArray)
For…Each
Perulangan untuk mengakses setiap elemen array foreach (datatype namavariabel in namaarray) { //do something here }
ArrayList
Sama seperti array, namun tipe data tidak perlu didefinisikan
Sangat fleksible, ArrayList resize terjadi secara dinamis
Terdapat dalam System.Collections
Inisialisasi ArrayList : ArrayList namaArrayList = New ArrayList();
Manipulasi ArrayList
Menambah Data(add) NamaArrayList.Add(object)
Menambah Data (insert) NamaArrayList.Insert(index, object)
Manipulasi ArrayList (cont.)
Menghapus Data NamaArrayList.Remove(object);
Menghapus Data Pada Index tertentu NamaArrayList.RemoveAt(index);
Menghapus seluruh elemen dalam ArrayList NamaArrayList.Clear();
Manipulasi ArrayList (cont.)
Meresize ArrayList NamaArrayList.TrimToSize();
Mengecek ada tidaknya suatu elemen di ArrayList NamaArrayList.RemoveAt(index);
Mencari letak object dalam ArrayList NamaArrayList.IndexOf(object);
Manipulasi ArrayList (cont.)
Mengetahui kapasitas ArrayList NamaArrayList.Capacity;
Mengetahui jumlah elemen yang ada dalam ArrayList NamaArrayList.Count;
Handling Exceptions In exception handling, the application is divided into blocks of code. A block that shows the probability of raising an error contains one or more exception handlers. The exception handlers follow a control structure and a uniform way of handling the system level and application level errors. The blocks for exception-handling can be implemented using the following keywords: try catch finally
Try … catch … finally The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown:
try { //statements that may cause an exception } catch (…) { //error handling code
} finally {
//statements to be executed }
Demo: Handling Exception for Arrays Beyond Limit Problem Statement: David is working on a project where he is calculating the sum of values in an integer array. David needs to handle the exceptions, which can occur while he is working with the arrays. If any exceptional condition is reached when David is executing the application, the application needs to display an exception message. Help David to handle the exceptions.
Solution To develop a console-based application, David need to perform the following tasks: 1.
Create a console-based application.
2.
Build and execute an application
Consider the following code snippet: using System; namespace ex{ class exc_demo{ int x=0; public void div(int a,int b) { try{x = a/b;} catch(DivideByZeroException e) {Console.WriteLine("exception {0}",e);}} public static void Main(String[] args){ exc_demo obj = new exc_demo(); obj.div(0,10); Console.ReadLine();}}}
Identify the output of the preceding code snippet. Will handle the exception occurred and display the result Will not be able to handle the exception generated Will display result = 0 It will compile but will not display any result.
Implementing Threads A thread is defined as the execution path of a program. You can define a unique flow of a control in a program, using a thread. Threads are used to run applications that perform large and complex computations. A process that is executed using one thread is known as a single-threaded process, where the process is a running instance of a program. Single-threaded application can perform only one task at a time. You have to wait for one task to complete before another task can start.
Working with Threads In C#, you create a thread by creating an object of type Thread, giving its constructor a ThreadStart reference, and calling the new thread’s Start() method. The new thread starts executing asynchronously with an invocation of the thread’s method. There are various methods available with the Thread class. Using these methods, you can control the execution of threads. Few of these methods are: Start(): Starts a thread.
Sleep(): Makes the thread to pause for a period of time. Abort(): Terminates the thread. Suspend(): Suspends a thread. If the thread is already suspended it has no effect. Resume(): Resumes the suspended thread.
Creating Threads You can create threads by extending the Thread class. The extended thread class calls the Start() method to begin the child thread execution. Following is an example of creating threads:
ThreadStart ChildRef = new ThreadStart(ChildThreadCall); Thread ChildThread = new Thread(ChildRef); ChildThread.Start();
Thread Life Cycle The lifecycle of a thread starts when an object of the System.Threading.Thread class is created. The life cycle of the thread ends with task execution. There are various states in the life cycle of a thread. These states are: The Unstarted state The Runnable state
The Not Runnable state The Dead state
Let us understand the life cycle of the thread with the help of the following figure.
Thread Life Thread Life CycleCycle (Contd.) Start()
Started
Work Completed
Stopped
Thread Life Thread Life CycleCycle (Contd.)
Start()
Started
Suspend()
Suspended
Resume()
Thread Life Thread Life CycleCycle (Contd.) Start()
Started
Sleep()
Wait/Join Sleep
Interrupt()
Time Expires
Thread Life Thread Life CycleCycle (Contd.) Start()
Started
Abort()
Stop Request
Thread Responds to Stop Request
Stopped
The Unstarted State When an instance of the Thread class is created, the thread enters the unstarted state. A new thread is an empty object of the Thread class, and no system resources such as memory are allocated to it.
The Runnable State The thread remains in the unstarted state until the program calls the Start() method of the Thread class, which places the thread in the runnable state and immediately returns control to the calling thread. This state is also called as the ready or started state. The newly started thread and any other threads in the program execute concurrently. The Not Runnable State : A thread is not in the runnable state if it is: Sleeping
Waiting Blocked
The Dead State A running thread enters the dead state when the statements of the threads method are complete. This state is also called the terminated state.
A program can force a thread into the dead state by calling the Abort() method of the Thread class on the appropriate thread object.
Demo: Hangman Game Problem Statement: The next door children request you to create the Hangman game for them. The game asks a user to enter a category as Book or Movie. Based on the category, a book name or movie name is extracted and the user is asked to guess the name by giving the character and its position in a string. A user will get 60 seconds to play the game. Develop the Hangman game application.
I/O
FileStream
Digunakan untuk membaca dan menulis data dari dan ke suatu file secara biner
semua karakter akan dianggap bukan sebagai teks, tapi kode-kode ASCII
Constructor filestream yang paling sering digunakan adalah :
FileStream namafstream = new FileStream(filepath, FileMode.PilihMode, FileAccess);
StreamReader
Digunakan untuk membaca data dari suatu file
Pembacaan dilakukan dengan menggunakan method : Read
: Satu karakter
ReadLine
: Sampai EOL
ReadToEnd
: Sampai EOF
StreamWriter
Digunakan untuk menuliskan output ke suatu file Penulisan dilakukan dengan menggunakan method :
Write WriteLine
Tutup stream jika sudah selesai agar perubahan tersimpan
Tanpa FileStream
Dengan FileStream
Challenge Mary needs to write code in C# that displays the names of all the files within a specified directory. Identify the correct code snippet that would enable Mary to accomplish this task. DirectoryInfo MydirInfo = new DirectoryInfo(@"c:\WINDOWS"); FileInfo FilesInDir = MydirInfo.GetFiles ( ); foreach (FileInfo file in FilesInDir) {Console.WriteLine ("File Name :{0}", file.Name);} DirectoryInfo MydirInfo = new DirectoryInfo(@"c:\WINDOWS"); FileInfo [] FilesInDir = MydirInfo.GetFiles ( ); foreach (FileInfo file in FilesInDir) {Console.WriteLine ("File Name :{0}", file.Name);} DirectoryInfo MydirInfo = new DirectoryInfo(@"c:\WINDOWS"); FileInfo [] FilesInDir = MydirInfo.GetFiles ( ); foreach (FileInfo file in MydirInfo) {Console.WriteLine ("File Name :{0}", file.Name);} DirectoryInfo MydirInfo = new DirectoryInfo(@"c:\WINDOWS"); FileInfo [] FilesInDir = DirectoryInfo.GetFiles(); foreach (FileInfo file in FilesInDir) {Console.WriteLine ("File Name :{0}", file.Name);}
Answer: DirectoryInfo MydirInfo = new DirectoryInfo(@"c:\WINDOWS"); FileInfo [] FilesInDir = MydirInfo.GetFiles ( ); foreach (FileInfo file in FilesInDir) { Console.WriteLine ("File Name :{0}", file.Name);}