115
SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽBE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica Radosav SADRŽAJ: I DEO OSNOVE 1. OBLAST UML PROVERA ZNANJA: grupni rad (dokumentovanje softvera) 2. OBLAST C# sintaksa 3. OBLAST OBJEKTNO ORJENTISANO PROGRAMIRANJE u C# PROVERA ZNANJA: Test poznavanja osnovnih pojmova II DEO RAZVOJ APLIKACIJA 4. OBLAST KLASE ZA RAD SA PODACIMA BAZA PODATAKA, TEKSTUALNE DATOTEKE, XML, FILE/FOLDER 5. OBLAST RAZVOJ WINDOWS I WEB APLIKACIJA 6. OBLAST RAZVOJ VIŠESLOJNE APLIKACIJE PROVERA ZNANJA: 1. KOLOKVIJUM 7. OBLAST MVC PRISTUP I ENTITY FRAMEWORK PROVERA ZNANJA: 2. KOLOKVIJUM PROVERA ZNANJA - OBAVEZNI SEMINARSKI RAD: OBJEDINJENA PRIMENA CELOKUPNOG ZNANJA III DEO NAPREDNE TEHNIKE informativno ovde, detaljnije: SOFTVERSKO INZENJERSTVO 2 7. DESIGN GUIDELINES uputstva za pravilno osmišljavanje klasa 8. DESIGN PATTERNS šabloni opšteprihvaćenih industrijskih rešenja klasa 9. REFACTORING reorganizovanje koda radi unapređenja kvaliteta koda (čitljivosti, brzine rada, fleksibilnosti…) ----------------------- 10. KONKURENTNO PROGRAMIRANJE niti, sinhronizacija OSNOVNA TROSLOJNA ARHITEKTURA PREZENTACIONI SLOJ KORISNICKI INTERFEJS = WINDOWS APP, WEB APP, MOBILNA APP SLOJ POSLOVNE LOGIKE BIBLIOTEKE KLASA (DLL) ILI WEB SERVISI VIŠESLOJNI PRISTUP – VIŠE BIBLIOTEKA KLASA SA PODELOM ZADUŽENJA SLOJ PODATAKA BAZA PODATAKA, XML FAJLOVI, JSON FAJLOVI, EXCEL FAJLOVI…. LITERATURA: OSNOVNI DEO I RAZVOJ APLIKACIJA: 1. Grady Booch, James Rumbaugh, Ivar Jacobson: “The Unified Modeling Language User Guide”,Addison-Wesley, 1999. 2. Robin A. Reynolds Haertle: “OOP sa Microsoft tehnologijama Visual Basic.NET I Visual C#. NET”, CET, 2002. 3. Jesse Liberty: “Programiranje na jeziku C#”, Mikro knjiga, 2007. 4. Microsoft: “Programming with C#”, MSDN training workbook, Microsoft, 2002. NAPREDNI DEO: 1. Arthur J. Riel: “Heuristike objektno-orjentisanog dizajna”, CET, 2003. 2. Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides: “Design Patterns”, Addison-Wesley, 1995. 3. Martin Fowler: “Refactoring – Improving the Design of Existing Code”, Addison-Wesley, 1999.

SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Embed Size (px)

Citation preview

Page 1: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽBE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica Radosav SADRŽAJ: I DEO – OSNOVE 1. OBLAST – UML PROVERA ZNANJA: grupni rad (dokumentovanje softvera) 2. OBLAST – C# sintaksa 3. OBLAST – OBJEKTNO ORJENTISANO PROGRAMIRANJE u C# PROVERA ZNANJA: Test poznavanja osnovnih pojmova II DEO – RAZVOJ APLIKACIJA 4. OBLAST – KLASE ZA RAD SA PODACIMA – BAZA PODATAKA, TEKSTUALNE DATOTEKE, XML, FILE/FOLDER 5. OBLAST – RAZVOJ WINDOWS I WEB APLIKACIJA 6. OBLAST – RAZVOJ VIŠESLOJNE APLIKACIJE PROVERA ZNANJA: 1. KOLOKVIJUM 7. OBLAST – MVC PRISTUP I ENTITY FRAMEWORK PROVERA ZNANJA: 2. KOLOKVIJUM PROVERA ZNANJA - OBAVEZNI SEMINARSKI RAD: OBJEDINJENA PRIMENA CELOKUPNOG ZNANJA III DEO – NAPREDNE TEHNIKE – informativno ovde, detaljnije: SOFTVERSKO INZENJERSTVO 2 7. DESIGN GUIDELINES – uputstva za pravilno osmišljavanje klasa 8. DESIGN PATTERNS – šabloni opšteprihvaćenih industrijskih rešenja klasa 9. REFACTORING – reorganizovanje koda radi unapređenja kvaliteta koda (čitljivosti, brzine rada, fleksibilnosti…) ----------------------- 10. KONKURENTNO PROGRAMIRANJE – niti, sinhronizacija OSNOVNA TROSLOJNA ARHITEKTURA

PREZENTACIONI SLOJ KORISNICKI INTERFEJS = WINDOWS APP, WEB APP, MOBILNA APP

SLOJ POSLOVNE LOGIKE BIBLIOTEKE KLASA (DLL) ILI WEB SERVISI VIŠESLOJNI PRISTUP – VIŠE BIBLIOTEKA KLASA SA PODELOM ZADUŽENJA

SLOJ PODATAKA BAZA PODATAKA, XML FAJLOVI, JSON FAJLOVI, EXCEL FAJLOVI….

LITERATURA: OSNOVNI DEO I RAZVOJ APLIKACIJA: 1. Grady Booch, James Rumbaugh, Ivar Jacobson: “The Unified Modeling Language User Guide”,Addison-Wesley, 1999. 2. Robin A. Reynolds – Haertle: “OOP sa Microsoft tehnologijama Visual Basic.NET I Visual C#. NET”, CET, 2002. 3. Jesse Liberty: “Programiranje na jeziku C#”, Mikro knjiga, 2007. 4. Microsoft: “Programming with C#”, MSDN training workbook, Microsoft, 2002. NAPREDNI DEO: 1. Arthur J. Riel: “Heuristike objektno-orjentisanog dizajna”, CET, 2003. 2. Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides: “Design Patterns”, Addison-Wesley, 1995. 3. Martin Fowler: “Refactoring – Improving the Design of Existing Code”, Addison-Wesley, 1999.

Page 2: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

1. OBLAST – UML Teorija

Case alat

Primer UML dijagrama sa vežbi

Generisanje programskog koda biblioteke klasa na osnovu modela u okviru CASE alata

Teorija UML (Unified Modeling Language) predstavlja prvenstveno grafički jezik modelovanja u svim fazama razvoja softvera, počev od specifikacije zahteva, sistemske analize, dizajna, dokumentovanja itd. Najčešća primena UML je u specifikaciji zahteva korisnika (use case dijagram) i dizajnu (dijagram komponenti, dijagram razmeštaja, dijagram klasa). Prva verzija UML 1.0 uključuje 9 vrsta dijagrama: use case dijagram, class dijagram, object dijagram, sequence dijagram, communication dijagram, activity dijagram, statechart dijagram, dijagram komponenti (component), dijagram razmeštaja (deployment). Druga verzija UML (UML 2.0) uključuje Package dijagram, interaction overview, composite structure.

Use case diagram (Dijagram slučajeva korišćenja) – Namena: prikaz osnovnih funkcija koju sistem nudi korisniku, sa aspekta vrednosti ili radnih aktivnosti koje sistem rešava. Elementi: actor (profil korisnika), slučaj korišćenja, veze između actora I slučaja korišćenja, veze između samih slučajeva korišćenja. Pored samog dijagrama, radi detaljnijeg opisa koriste se I specifikacije pojedinih slučajeva korišćenja koje obuhvataju: preduslove (potrebno stanje sistema pre početka rada slučaja korišćenja), postuslove (rezultate rada), action steps (uključuje pseudokod opisa interakcije korisnika I sistema uz različite scenarije), exceptions (obrada grešaka), extension points (tačke proširenja na druge slučajeve korišćenja).

Component diagram (Dijagram komponenti) – Namena: predstavlja osnovne elemente softverskog sistema I njihove međusobne zavisnosti, Elementi: paketi, komponente, fajlovi, veze zavisnosti

Deployment diagram (Dijagram razmeštaja) – Namena: predstavlja raspored softverskih komponenti po čvorovima (serverima) u računarskoj mreži (iako se pod pojmom server podrazumeva zapravo računarski program koji obavlja određeni servis – obradu i fizički sve te komponente: serveri i ostale komponente softvera mogu biti na jednom računaru), elementi: čvorovi, softverske komponente, veze zavisnosti

Class diagram (Dijagram klasa) – Namena: predstavlja klase softverskog rešenja i njihove zavisnosti, Elementi: Klase (atributi, metode), veze između klasa (asocijacija, agregacija, kompozicija, nasleđivanje). Kod opisa klasa bitno je podesiti modifikatore pristupa na nivou klase, atributa I metoda (private, public, protected, internal). Kod atributa važno je podesiti naziv I tip. Bitno je razlikovati “suštinske attribute” – polja (promenljive u okviru klase koje kod konkretnog objekta čuvaju vrednosti) i “svojstva” (javno dostupne “predstavnike” polja – samo za ona polja koja želimo da budu javno dostupna I to se realizuje putem get-set metoda). Obratićemo pažnju na veličinu slova u nazivima atributa, metoda I parametara metoda (camelCasing – prvo slovo malo, ostala prva slova reci velika,a ostala mala: privatni atributi (polja), parametri metoda, promenljive deklarisane unutar metoda; PascalCasing – Svako prvo slovo reci je veliko, ostala mala: naziv klase, metode…). Zaglavlje metode (naziv I lista parametara) naziva se signature (potpis) metode. Kod parametara metoda obratićemo pažnju da li su ulazni, izlazni ili ulazno-izlazni. Kod podešavanja karakteristika veza, bitno je u CASE alatu pravilno podesiti tip veze i osobine Navigable i Container Type.

Sequence diagram (Dijagram sekvenci) – Namena: predstavlja vremenski sled komunikacije objekata klasa u realizaciji jednog slučaja korišćenja (odnosno jednog scenarija u okviru jednog slučaja korišćenja). Elementi: actor (može biti čovek ili drugi automatizovani-softverski sistem), objekti klasa, poruke (pozivi metoda klasa), aktivacija (vertikalni pravougaonik kojim se predstavlja dužina trajanja “života” jednog objekta, odnosno interacije putem razmene poruka).

Ostale vrste dijagrama:

Object diagram – predstavlja objekte klasa sa konkretnim vrednostima atributa radi ilustracije I objašnjenja značenja klasa

State chart diagram – predstavlja različita stanja koje objekat jedne klase može da ima. Stanje objekta određeno je vrednostima njegovih atributa u svakom trenutku.

Communication diagram – slično dijagramu sekvenci, predstavlja objekte klasa i razmenu poruka, bez prikaza vremenske dimenzije toka razmene poruka (prikazuje se samo redni broj poruke).

Page 3: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Activity diagram - može se koristiti u fazi specifikacije toka poslovnih procesa (sistemska analiza), predstavljanju action steps kod specifikacije jednog slučaja korišćenja ili predstavljanju načina realizacije neke metode jedne klase.

CASE Alat U okviru razvoja softvera radi povezivanja različitih faza razvoja, ubrzavanja I povećanja kvaliteta, koriste se posebni alati – CASE (Computer Aided Software Engineering) alati. Najčešće uključuju u sebe više alata koji mogu da razmenjuju podatke rezultata, kako bi naredna faza razvoja mogla efikasnije da se nastavi. Tako se na osnovu jedne vrste modela mogu generisati druge vrste modela ili čak upotrebljivi elementi prototipa rešenja: s jedne strane baze podataka, s druge strane izvorni kod programa. U okviru CASE alata Sybase Power Designer, u primeni UML modela koristi se Object Oriented Model, gde se može birati univerzalni-apstraktni objektni jezik Analysis ili konkretan programski jezik (npr. C#), kao I različite vrste dijagrama.

PRIMER UML DIJAGRAMA SA VEŽBI Analiziran je primer aplikacije koja uključuje 2 nezavisna projekta koji mogu biti smešteni I aktivni na različitim računarima na Internetu: ASPX web aplikaciju i Web servis (SOAP/XML) , čime se ilustruje aktuelni pristup razvoju softvera: servisno-orjentisana arhitektura, tj. razvoj softvera kao servis (“Software as service”). Navedeni pristup se zasniva na konceptu da jedna firma ne mora da razvija kompletan softver, već koristi usluge (besplatno ili plaća) realizovanog I javno dostupnog softvera druge firme putem interneta (pozivanjem odgovarajućeg URL gde se nalazi navedeni softverski servis). U toku izvršavanja softvera navedene firme, u određenom trenutku se poziva softverska funkcija udaljenog servisa, izvršava I dobija rezultat rada, a zatim navedeni softver dalje nastavlja sa radom. U okviru dokumentovanja postojećeg softverskog rešenja realizovani su sledeći dijagrami: USE CASE DIJAGRAM

Page 4: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

DIJAGRAM KLASA

DIJAGRAM KOMPONENTI

DIJAGRAM RAZMEŠTAJA

Page 5: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

DOPUNJENI DIJAGRAM KLASA

DIJAGRAM SEKVENCI

0..1

0..*

0..1

0..*

<<web stranica korisnickog interfejsa>>

_Default

- prezime : String

-

-

#

#

NapuniCombo ()

SnimiPodatke (String brojIndeksa, String prezime, String ime, String nazivSmera)

Page_Load (object sender, EventArgs e)

btnSnimi_Click (object sender, EventArgs e)

: void

: boolean

: void

: void

<<klasa iz web servisa>>

Service1

+

+

+

DajSifruSmera (String nazivSmera)

DajDataSetSmerovi ()

DajNazivStavkeIzRb (int redniBrojStavke)

: String

: DataSet

: String

<<klasa iz standardne biblioteke>>

System.Web.UI.Page<<klasa iz standardne biblioteke>>

System.Web.Services.WebService

RAcun

Stavke racuna

MEsto

-

-

ptt

nazivMesta

: String

: String

Page 6: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

GENERISANJE PROGRAMSKOG KODA BIBLIOTEKE KLASA NA OSNOVU MODELA U OKVIRU CASE ALATA SLOJ KLASA 1. Kreirati CDM model. Racun -(1:M dependent) - stavke - roba Racun - kupac Kupac is a firma, osoba.

SequenceDiagram_1

Sifra smera

<<DajSifruSmera(NazivSmera)>>

DajSifruSmera

<<btn Snimi Click>>

Izbor opcije za snimanje podataka

Unos podataka u text boxove

<<Page Load>>

Ucitavanje stranice

<<_Default>>

Stranica za unos

<<Service 1>>

objKlasaSmer

Korisnik web aplikacije

Sifra smera

<<DajSifruSmera(NazivSmera)>>

DajSifruSmera

<<btn Snimi Click>>

Izbor opcije za snimanje podataka

Unos podataka u text boxove

<<Page Load>>

Ucitavanje stranice

Page 7: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

2. Generisati dijagram klasa iz CDM modela (Tools – Generate object oriented model). Podesiti karakteristike relacija: - asocijacija (obicna relacija) – podesiti Navigable, ukloniti ArrayList ako ima. - nasledjivanje (od is-a) - kompozicija (celina - deo) Dodati set/get metode.

Redni broj stavke brisemo,

pravimo slozeni primarni

kljuc od broja racuna

i oznake robe.

Tip kupca

je dobio

sadrzi

je izabrana

JEDNINA U

NAZIVU

SVAKOG

ENTITETA!!!

Racun

BrojRacuna

Datum

UkupanIznos

<pi> Variable characters (20)

Date

Float

<M>

Identifier_1 <pi>

Kupac

IDKupca

Adresa

Telefon

Email

<pi> Long integer

Variable characters (100)

Variable characters (50)

Variable characters (50)

<M>

Identifier_1 <pi>

Firma

NazivFirme Variable characters (100)Osoba

Prezime

Ime

Variable characters (50)

Variable characters (40)

Stavka racuna

Kolicina Float

Roba

OznakaRobe

NazivRobe

Cena

JedinicaMere

<pi> Variable characters (10)

Variable characters (100)

Float

Variable characters (30)

<M>

Identifier_1 <pi>

Page 8: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

3. Iz dijagrama klasa generisati C# kod biblioteke klasa.

1..1

0..*

1..1

1..*

1..1

0..*

Racun

-

-

-

+

+

+

<<PropertyImplementation>>

<<PropertyImplementation>>

<<PropertyImplementation>>

<<Property>>

<<Property>>

<<Property>>

pBrojRacuna

pDatum

pUkupanIznos

BrojRacuna

Datum

UkupanIznos

: string

: DateTime

: float

: string

: DateTime

: float

+

+

+

+

+

+

<<Setter>>

<<Getter>>

<<Setter>>

<<Getter>>

<<Setter>>

<<Getter>>

set_BrojRacuna (string value)

get_BrojRacuna ()

set_Datum (DateTime value)

get_Datum ()

set_UkupanIznos (float value)

get_UkupanIznos ()

: void

: string

: void

: DateTime

: void

: float

Kupac

-

-

-

-

+

+

+

+

<<PropertyImplementation>>

<<PropertyImplementation>>

<<PropertyImplementation>>

<<PropertyImplementation>>

<<Property>>

<<Property>>

<<Property>>

<<Property>>

pIDKupca

pAdresa

pTelefon

pEmail

IDKupca

Adresa

Telefon

Email

: long

: string

: string

: string

: long

: string

: string

: string

+

+

+

+

+

+

+

+

<<Setter>>

<<Getter>>

<<Setter>>

<<Getter>>

<<Setter>>

<<Getter>>

<<Setter>>

<<Getter>>

set_IDKupca (long value)

get_IDKupca ()

set_Adresa (string value)

get_Adresa ()

set_Telefon (string value)

get_Telefon ()

set_Email (string value)

get_Email ()

: void

: long

: void

: string

: void

: string

: void

: string

Firma

-

+

<<PropertyImplementation>>

<<Property>>

pNazivFirme

NazivFirme

: string

: string

+

+

<<Setter>>

<<Getter>>

set_NazivFirme (string value)

get_NazivFirme ()

: void

: string

Osoba

-

-

+

+

<<PropertyImplementation>>

<<PropertyImplementation>>

<<Property>>

<<Property>>

pPrezime

pIme

Prezime

Ime

: string

: string

: string

: string

+

+

+

+

<<Setter>>

<<Getter>>

<<Setter>>

<<Getter>>

set_Prezime (string value)

get_Prezime ()

set_Ime (string value)

get_Ime ()

: void

: string

: void

: string

Stavka racuna

-

+

<<PropertyImplementation>>

<<Property>>

pKolicina

Kolicina

: float

: float

+

+

<<Setter>>

<<Getter>>

set_Kolicina (float value)

get_Kolicina ()

: void

: float

Roba

-

-

-

-

+

+

+

+

<<PropertyImplementation>>

<<PropertyImplementation>>

<<PropertyImplementation>>

<<PropertyImplementation>>

<<Property>>

<<Property>>

<<Property>>

<<Property>>

pOznakaRobe

pNazivRobe

pCena

pJedinicaMere

OznakaRobe

NazivRobe

Cena

JedinicaMere

: string

: string

: float

: string

: string

: string

: float

: string

+

+

+

+

+

+

+

+

<<Setter>>

<<Getter>>

<<Setter>>

<<Getter>>

<<Setter>>

<<Getter>>

<<Setter>>

<<Getter>>

set_OznakaRobe (string value)

get_OznakaRobe ()

set_NazivRobe (string value)

get_NazivRobe ()

set_Cena (float value)

get_Cena ()

set_JedinicaMere (string value)

get_JedinicaMere ()

: void

: string

: void

: string

: void

: float

: void

: string

Page 9: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

OBICNA KLASA, GET I SET ZA REALIZACIJU PROPERTY public class Roba { private string POznakaRobe; private string PNazivRobe; private float PCena; private string PJedinicaMere; public string OznakaRobe { get { return POznakaRobe; } set { if (this.POznakaRobe != value) this.POznakaRobe = value; } }

Objasnjenje za sva 3 najvaznija tipa veze sa dijagrama klasa – KAKO SE TO REALIZUJE U KODU: NASLEDJIVANJE public class Osoba : Kupac ASOCIJACIJA public class StavkaRacuna { public Roba roba; private float PKolicina; KOMPOZICIJA public class Racun { public System.Collections.ArrayList stavkaRacuna; public void AddStavkaRacuna(StavkaRacuna newStavkaRacuna) { ..

Page 10: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

public void RemoveStavkaRacuna(StavkaRacuna oldStavkaRacuna) {

Dodati namespace – DODAJEMO UZ NAZIV PROJEKTA ZA SVAKU KLASU, DA BI BILA UKLJUCENA U PROJEKAT I VIDLJIVA SPOLJA KAO DEO BIBLIOTEKE KLASA.

Generisati dll (Dynamic Link Library).

PREZENTACIONI SLOJ

1. KREIRATI KORISNICKI INTERFEJS WINDOWS APLIKACIJE sa formom za unos podataka o robi: OZNAKA, NAZIV, CENA, JEDINICA MERE, Tasteri za navigaciju: PRVI, PRETHODNI, SLEDECI, POSLEDNJI , Tasteri za azuriranje: UNOS, BRISANJE, IZMENA, SNIMI, ODUSTANI Povezati korisnicki interfejs sa kreiranom bibliotekom DLL.

Page 11: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

2. OBLAST – C# SINTAKSA OSNOVE SINTAKSE

Komentari

// za svaki red ili /* */ za blok

Na kraju svake naredbe ;

Case sensitive – nije isto naziv i Naziv

Oblast { }, Oblast važenja promenljivih, početak I kraj bloka naredbi, početak I kraj metode, klase, namespace TIPOVI PODATAKA prosti, Standardni - strukture - promenljive tipa vrednosti (promenljiva ukazuje direktno na lokaciju gde se nalaze podaci): Integer, real, bool, enum, struct promenljive tipa reference (promenljiva sadrzi pokazivac na memorijsku lokaciju gde se nalaze podaci): klasa, interfejs, niz, string, objekat, delegat The variables in C#, are categorized into the following types:

Value types

Reference types

Pointer types Value Type Value type variables can be assigned a value directly. They are derived from the class System.ValueType. The value types directly contain data. Some examples are int, char, and float, which stores numbers, alphabets, and floating point numbers, respectively. When you declare an int type, the system allocates memory to store the value. The following table lists the available value types in C# 2010:

Type Represents Range Default Value

bool Boolean value True or False False

byte 8-bit unsigned integer 0 to 255 0

char 16-bit Unicode character U +0000 to U +ffff '\0'

decimal 128-bit precise decimal values with 28-29 significant digits

(-7.9 x 1028

to 7.9 x 1028

) / 100 to 28

0.0M

double 64-bit double-precision floating point type (+/-)5.0 x 10-324

to (+/-)1.7 x 10308

0.0D

float 32-bit single-precision floating point type -3.4 x 1038

to + 3.4 x 1038

0.0F

int 32-bit signed integer type -2,147,483,648 to 2,147,483,647 0

long 64-bit signed integer type -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

0L

sbyte 8-bit signed integer type -128 to 127 0

short 16-bit signed integer type -32,768 to 32,767 0

uint 32-bit unsigned integer type 0 to 4,294,967,295 0

ulong 64-bit unsigned integer type 0 to 18,446,744,073,709,551,615 0

ushort 16-bit unsigned integer type 0 to 65,535 0

To get the exact size of a type or a variable on a particular platform, you can use the sizeof method. The expression sizeof(type) yields the storage size of the object or type in bytes. Following is an example to get the size of int type on any machine:

using System; namespace DataTypeApplication

Page 12: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

{ class Program { static void Main(string[] args) { Console.WriteLine("Size of int: {0}", sizeof(int)); Console.ReadLine(); } } } When the above code is compiled and executed, it produces the following result:

Size of int: 4 Reference Type The reference types do not contain the actual data stored in a variable, but they contain a reference to the variables. In other words, they refer to a memory location. Using multiple variables, the reference types can refer to a memory location. If the data in the memory location is changed by one of the variables, the other variable automatically reflects this change in value. Example of built-in reference types are: object, dynamic, and string.

Object Type The Object Type is the ultimate base class for all data types in C# Common Type System (CTS). Object is an alias for System.Object class. The object types can be assigned values of any other types, value types, reference types, predefined or user-defined types. However, before assigning values, it needs type conversion. When a value type is converted to object type, it is called boxing and on the other hand, when an object type is converted to a value type, it is called unboxing.

object obj; obj = 100; // this is boxing Dynamic Type You can store any type of value in the dynamic data type variable. Type checking for these types of variables takes place at run-time. Syntax for declaring a dynamic type is:

dynamic <variable_name> = value; For example,

dynamic d = 20; Dynamic types are similar to object types except that type checking for object type variables takes place at compile time, whereas that for the dynamic type variables takes place at run time.

String Type The String Type allows you to assign any string values to a variable. The string type is an alias for the System.String class. It is derived from object type. The value for a string type can be assigned using string literals in two forms: quoted and @quoted. For example,

String str = "Tutorials Point"; A @quoted string literal looks as follows:

@"Tutorials Point"; The user-defined reference types are: class, interface, or delegate. We will discuss these types in later chapter.

Pointer Type Pointer type variables store the memory address of another type. Pointers in C# have the same capabilities as the pointers in C or C++. Syntax for declaring a pointer type is:

type* identifier; For example,

char* cptr;

int* iptr;

Razlikovati string i String. String je klasa , System.String

Properties

Name Description

Chars[Int32] Gets the Char object at a specified position in the current String object.

Length Gets the number of characters in the current String object.

Methods

Name Description

Clone()

Returns a reference to this instance of String.

Compare(String, Int32, String, Int32, Int32)

Compares substrings of two specified String objects and returns an integer that indicates their relative

position in the sort order.

Compare(String, Int32, String, Int32, Compares substrings of two specified String objects, ignoring or honoring their case, and returns an integer

that indicates their relative position in the sort order.

Page 13: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Int32, Boolean)

Compare(String, Int32, String, Int32, Int32, Boolean, CultureInfo)

Compares substrings of two specified String objects, ignoring or honoring their case and using culture-specific information to influence the comparison, and returns an integer that indicates their relative position

in the sort order.

Compare(String, Int32, String, Int32, Int32, CultureInfo, CompareOptions)

Compares substrings of two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the

two substrings to each other in the sort order.

Compare(String, Int32, String, Int32, Int32, StringComparison)

Compares substrings of two specified String objects using the specified rules, and returns an integer that

indicates their relative position in the sort order.

Compare(String, String) Compares two specified String objects and returns an integer that indicates their relative position in the sort

order.

Compare(String, String, Boolean) Compares two specified String objects, ignoring or honoring their case, and returns an integer that indicates

their relative position in the sort order.

Compare(String, String, Boolean, CultureInfo)

Compares two specified String objects, ignoring or honoring their case, and using culture-specific

information to influence the comparison, and returns an integer that indicates their relative position in the sort

order.

Compare(String, String, CultureInfo, CompareOptions)

Compares two specified String objects using the specified comparison options and culture-specific information to influence the comparison, and returns an integer that indicates the relationship of the two

strings to each other in the sort order.

Compare(String, String, StringComparison)

Compares two specified String objects using the specified rules, and returns an integer that indicates their

relative position in the sort order.

CompareOrdinal(String, Int32, String, Int32, Int32)

Compares substrings of two specified String objects by evaluating the numeric values of the

corresponding Char objects in each substring.

CompareOrdinal(String, String) Compares two specified String objects by evaluating the numeric values of the corresponding Charobjects in

each string.

CompareTo(Object)

Compares this instance with a specified Object and indicates whether this instance precedes, follows, or

appears in the same position in the sort order as the specified Object.

CompareTo(String)

Compares this instance with a specified String object and indicates whether this instance precedes, follows,

or appears in the same position in the sort order as the specified string.

Concat(IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String.

Concat(Object) Creates the string representation of a specified object.

Concat(Object, Object) Concatenates the string representations of two specified objects.

Concat(Object, Object, Object) Concatenates the string representations of three specified objects.

Concat(Object, Object, Object, Object) Concatenates the string representations of four specified objects and any objects specified in an optional

variable length parameter list.

Concat(Object[]) Concatenates the string representations of the elements in a specified Object array.

Concat(String, String) Concatenates two specified instances of String.

Page 14: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Concat(String, String, String) Concatenates three specified instances of String.

Concat(String, String, String, String) Concatenates four specified instances of String.

Concat(String[]) Concatenates the elements of a specified String array.

Concat<T>(IEnumerable<T>) Concatenates the members of an IEnumerable<T> implementation.

Contains(String)

Returns a value indicating whether a specified substring occurs within this string.

Copy(String) Creates a new instance of String with the same value as a specified String.

CopyTo(Int32, Char[], Int32, Int32)

Copies a specified number of characters from a specified position in this instance to a specified position in an

array of Unicode characters.

EndsWith(String)

Determines whether the end of this string instance matches the specified string.

EndsWith(String, Boolean, CultureInfo)

Determines whether the end of this string instance matches the specified string when compared using the

specified culture.

EndsWith(String, StringComparison)

Determines whether the end of this string instance matches the specified string when compared using the specified comparison option.

Equals(Object)

Determines whether this instance and a specified object, which must also be a String object, have the same

value.(Overrides Object.Equals(Object).)

Equals(String)

Determines whether this instance and another specified String object have the same value.

Equals(String, String) Determines whether two specified String objects have the same value.

Equals(String, String, StringComparison) Determines whether two specified String objects have the same value. A parameter specifies the culture, case, and sort rules used in the comparison.

Equals(String, StringComparison)

Determines whether this string and a specified String object have the same value. A parameter specifies the culture, case, and sort rules used in the comparison.

Format(IFormatProvider, String, Object) Replaces the format item or items in a specified string with the string representation of the corresponding

object. A parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, Object, Object)

Replaces the format items in a specified string with the string representation of two specified objects. A

parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, Object, Object, Object)

Replaces the format items in a specified string with the string representation of three specified objects. An parameter supplies culture-specific formatting information.

Format(IFormatProvider, String, Object[]) Replaces the format items in a specified string with the string representations of corresponding objects in a specified array. A parameter supplies culture-specific formatting information.

Format(String, Object) Replaces one or more format items in a specified string with the string representation of a specified object.

Format(String, Object, Object) Replaces the format items in a specified string with the string representation of two specified objects.

Format(String, Object, Object, Object) Replaces the format items in a specified string with the string representation of three specified objects.

Page 15: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Format(String, Object[]) Replaces the format item in a specified string with the string representation of a corresponding object in a specified array.

GetEnumerator()

Retrieves an object that can iterate through the individual characters in this string.

GetHashCode()

Returns the hash code for this string.(Overrides Object.GetHashCode().)

GetType()

Gets the Type of the current instance.(Inherited from Object.)

GetTypeCode()

Returns the TypeCode for class String.

IndexOf(Char)

Reports the zero-based index of the first occurrence of the specified Unicode character in this string.

IndexOf(Char, Int32)

Reports the zero-based index of the first occurrence of the specified Unicode character in this string. The search starts at a specified character position.

IndexOf(Char, Int32, Int32)

Reports the zero-based index of the first occurrence of the specified character in this instance. The search

starts at a specified character position and examines a specified number of character positions.

IndexOf(String)

Reports the zero-based index of the first occurrence of the specified string in this instance.

IndexOf(String, Int32)

Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts at a specified character position.

IndexOf(String, Int32, Int32)

Reports the zero-based index of the first occurrence of the specified string in this instance. The search starts

at a specified character position and examines a specified number of character positions.

IndexOf(String, Int32, Int32, StringComparison)

Reports the zero-based index of the first occurrence of the specified string in the current String object. Parameters specify the starting search position in the current string, the number of characters in the current

string to search, and the type of search to use for the specified string.

IndexOf(String, Int32, StringComparison)

Reports the zero-based index of the first occurrence of the specified string in the current String object.

Parameters specify the starting search position in the current string and the type of search to use for the specified string.

IndexOf(String, StringComparison)

Reports the zero-based index of the first occurrence of the specified string in the current String object. A

parameter specifies the type of search to use for the specified string.

IndexOfAny(Char[])

Reports the zero-based index of the first occurrence in this instance of any character in a specified array of Unicode characters.

IndexOfAny(Char[], Int32)

Reports the zero-based index of the first occurrence in this instance of any character in a specified array of

Unicode characters. The search starts at a specified character position.

IndexOfAny(Char[], Int32, Int32)

Reports the zero-based index of the first occurrence in this instance of any character in a specified array of

Unicode characters. The search starts at a specified character position and examines a specified number of character positions.

Insert(Int32, String)

Returns a new string in which a specified string is inserted at a specified index position in this instance.

Intern(String) Retrieves the system's reference to the specified String.

IsInterned(String) Retrieves a reference to a specified String.

IsNormalized()

Indicates whether this string is in Unicode normalization form C.

IsNormalized(NormalizationForm)

Indicates whether this string is in the specified Unicode normalization form.

Page 16: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

IsNullOrEmpty(String) Indicates whether the specified string is null or an Empty string.

IsNullOrWhiteSpace(String) Indicates whether a specified string is null, empty, or consists only of white-space characters.

Join(String, IEnumerable<String>) Concatenates the members of a constructed IEnumerable<T> collection of type String, using the specified separator between each member.

Join(String, Object[]) Concatenates the elements of an object array, using the specified separator between each element.

Join(String, String[]) Concatenates all the elements of a string array, using the specified separator between each element.

Join(String, String[], Int32, Int32) Concatenates the specified elements of a string array, using the specified separator between each element.

Join<T>(String, IEnumerable<T>) Concatenates the members of a collection, using the specified separator between each member.

LastIndexOf(Char)

Reports the zero-based index position of the last occurrence of a specified Unicode character within this instance.

LastIndexOf(Char, Int32)

Reports the zero-based index position of the last occurrence of a specified Unicode character within this

instance. The search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(Char, Int32, Int32)

Reports the zero-based index position of the last occurrence of the specified Unicode character in a substring

within this instance. The search starts at a specified character position and proceeds backward toward the

beginning of the string for a specified number of character positions.

LastIndexOf(String)

Reports the zero-based index position of the last occurrence of a specified string within this instance.

LastIndexOf(String, Int32)

Reports the zero-based index position of the last occurrence of a specified string within this instance. The

search starts at a specified character position and proceeds backward toward the beginning of the string.

LastIndexOf(String, Int32, Int32)

Reports the zero-based index position of the last occurrence of a specified string within this instance. The search starts at a specified character position and proceeds backward toward the beginning of the string for a

specified number of character positions.

LastIndexOf(String, Int32, Int32, StringComparison)

Reports the zero-based index position of the last occurrence of a specified string within this instance. The

search starts at a specified character position and proceeds backward toward the beginning of the string for the specified number of character positions. A parameter specifies the type of comparison to perform when

searching for the specified string.

LastIndexOf(String, Int32, StringComparison)

Reports the zero-based index of the last occurrence of a specified string within the current Stringobject. The

search starts at a specified character position and proceeds backward toward the beginning of the string. A

parameter specifies the type of comparison to perform when searching for the specified string.

LastIndexOf(String, StringComparison)

Reports the zero-based index of the last occurrence of a specified string within the current Stringobject. A

parameter specifies the type of search to use for the specified string.

LastIndexOfAny(Char[])

Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array.

LastIndexOfAny(Char[], Int32)

Reports the zero-based index position of the last occurrence in this instance of one or more characters

specified in a Unicode array. The search starts at a specified character position and proceeds backward

toward the beginning of the string.

LastIndexOfAny(Char[], Int32, Int32)

Reports the zero-based index position of the last occurrence in this instance of one or more characters specified in a Unicode array. The search starts at a specified character position and proceeds backward

toward the beginning of the string for a specified number of character positions.

Page 17: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Normalize()

Returns a new string whose textual value is the same as this string, but whose binary representation is in

Unicode normalization form C.

Normalize(NormalizationForm)

Returns a new string whose textual value is the same as this string, but whose binary representation is in the

specified Unicode normalization form.

PadLeft(Int32)

Returns a new string that right-aligns the characters in this instance by padding them with spaces on the left, for a specified total length.

PadLeft(Int32, Char)

Returns a new string that right-aligns the characters in this instance by padding them on the left with a

specified Unicode character, for a specified total length.

PadRight(Int32)

Returns a new string that left-aligns the characters in this string by padding them with spaces on the right, for a specified total length.

PadRight(Int32, Char)

Returns a new string that left-aligns the characters in this string by padding them on the right with a specified

Unicode character, for a specified total length.

Remove(Int32)

Returns a new string in which all the characters in the current instance, beginning at a specified position and

continuing through the last position, have been deleted.

Remove(Int32, Int32)

Returns a new string in which a specified number of characters in the current instance beginning at a

specified position have been deleted.

Replace(Char, Char)

Returns a new string in which all occurrences of a specified Unicode character in this instance are replaced

with another specified Unicode character.

Replace(String, String)

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

Split(Char[])

Splits a string into substrings that are based on the characters in an array.

Split(Char[], Int32)

Splits a string into a maximum number of substrings based on the characters in an array. You also specify the

maximum number of substrings to return.

Split(Char[], Int32, StringSplitOptions)

Splits a string into a maximum number of substrings based on the characters in an array.

Split(Char[], StringSplitOptions)

Splits a string into substrings based on the characters in an array. You can specify whether the substrings

include empty array elements.

Split(String[], Int32, StringSplitOptions)

Splits a string into a maximum number of substrings based on the strings in an array. You can specify whether the substrings include empty array elements.

Split(String[], StringSplitOptions)

Splits a string into substrings based on the strings in an array. You can specify whether the substrings include

empty array elements.

StartsWith(String)

Determines whether the beginning of this string instance matches the specified string.

StartsWith(String, Boolean, CultureInfo)

Determines whether the beginning of this string instance matches the specified string when compared using

the specified culture.

StartsWith(String, StringComparison)

Determines whether the beginning of this string instance matches the specified string when compared using

the specified comparison option.

Substring(Int32)

Retrieves a substring from this instance. The substring starts at a specified character position and continues to

the end of the string.

Substring(Int32, Int32)

Retrieves a substring from this instance. The substring starts at a specified character position and has a

specified length.

ToCharArray()

Copies the characters in this instance to a Unicode character array.

Page 18: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

ToCharArray(Int32, Int32)

Copies the characters in a specified substring in this instance to a Unicode character array.

ToLower()

Returns a copy of this string converted to lowercase.

ToLower(CultureInfo)

Returns a copy of this string converted to lowercase, using the casing rules of the specified culture.

ToLowerInvariant()

Returns a copy of this String object converted to lowercase using the casing rules of the invariant culture.

ToString()

Returns this instance of String; no actual conversion is performed.(Overrides Object.ToString().)

ToString(IFormatProvider)

Returns this instance of String; no actual conversion is performed.

ToUpper()

Returns a copy of this string converted to uppercase.

ToUpper(CultureInfo)

Returns a copy of this string converted to uppercase, using the casing rules of the specified culture.

ToUpperInvariant()

Returns a copy of this String object converted to uppercase using the casing rules of the invariant culture.

Trim()

Removes all leading and trailing white-space characters from the current String object.

Trim(Char[])

Removes all leading and trailing occurrences of a set of characters specified in an array from the current String object.

TrimEnd(Char[])

Removes all trailing occurrences of a set of characters specified in an array from the current Stringobject.

TrimStart(Char[])

Removes all leading occurrences of a set of characters specified in an array from the current Stringobject.

Fields

Name Description

Empty Represents the empty string. This field is read-only.

Enumeracija Enum Temperatura { TempSmrzavanja=0, TempKljucanja=100 } Koriscenje: (Int) Temperatura.TempSmrzavanja… transformacija tipova podataka

- Utvrdjivanje tipa: TypeOf( – implicitna transformacija (npr. dodela byte vrednosti u integer ili integer u long…automatski je prihvaceno)

- Eksplicitna: type casting Int.Parse ()…. Ili (int)Promenljiva… PROMENLJIVE

Deklaracija promenljive - Tip NazivPromenljive;

Inicijalizacija promenljive- NazivPromenljive = PocetnaVrednost;

Definicija promenljive = Deklaracija + Inicijalizacija KONSTANTA

Page 19: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Const int nazivkonstante=vrednost; OPERATORI I FUNKCIJE

= dodela vrednosti

== upoređivanje vrednosti ( ... ==null) C# provides many operators, which are symbols that specify which operations (math, indexing, function call, etc.) to perform in an expression. You

can overload many operators to change their meaning when applied to a user-defined type.

Operations on integral types (such as ==, !=, <, >, &, |) are generally allowed on enumeration (enum) types.

The sections lists the C# operators starting with the highest precedence to the lowest. The operators within each section share the same precedence

level.

Primary Operators

These are the highest precedence operators. NOTE, you can click on the operators to go the detailed pages with examples.

x.y – member access.

x?.y – null conditional member access. Returns null if the left hand operand is null.

f(x) – function invocation.

a[x] – aggregate object indexing.

a?[x] – null conditional indexing. Returns null if the left hand operand is null.

x++ – postfix increment. Returns the value of x and then updates the storage location with the value of x that is one greater (typically adds the integer

1).

x-- – postfix decrement. Returns the value of x and then updates the storage location with the value of x that is one less (typically subtracts the integer

1).

New – type instantiation.

Typeof – returns the System.Type object representing the operand.

Checked – enables overflow checking for integer operations.

Unchecked – disables overflow checking for integer operations. This is the default compiler behavior.

default(T) – returns the default initialized value of type T, null for reference types, zero for numeric types, and zero/null filled in members for struct

types.

Delegate – declares and returns a delegate instance.

Sizeof – returns the size in bytes of the type operand.

-> – pointer dereferencing combined with member access.

Unary Operators

These operators have higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operators

to go the detailed pages with examples.

+x – returns the value of x.

-x – numeric negation.

!x – logical negation.

~x – bitwise complement.

++x – prefix increment. Returns the value of x after updating the storage location with the value of x that is one greater (typically adds the integer 1).

--x – prefix decrement. Returns the value of x after updating the storage location with the value of x that is one less (typically adds the integer 1).

(T)x – type casting.

Await – awaits a Task.

&x – address of.

*x – dereferencing.

Multiplicative Operators

These operators have higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operators

to go the detailed pages with examples.

x * y – multiplication.

x / y – division. If the operands are integers, the result is an integer truncated toward zero (for example, -7 / 2 is -3).

x % y – modulus. If the operands are integers, this returns the remainder of dividing x by y. If q = x / y and r = x % y, then x = q * y + r.

Additive Operators

These operators have higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operators

to go the detailed pages with examples.

x + y – addition.

x – y – subtraction.

Shift Operators

These operators have higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operators

to go the detailed pages with examples.

x << y – shift bits left and fill with zero on the right.

x >> y – shift bits right. If the left operand is int or long, then left bits are filled with the sign bit. If the left operand is uint or ulong, then left bits

are filled with zero.

Relational and Type-testing Operators

These operators have higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operators

to go the detailed pages with examples.

x < y – less than (true if x is less than y).

x > y – greater than (true if x is greater than y).

x <= y – less than or equal to.

x >= y – greater than or equal to.

Is – type compatibility. Returns true if the evaluated left operand can be cast to the type specified in the right operand (a static type).

Page 20: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

As – type conversion. Returns the left operand cast to the type specified by the right operand (a static type), but as returns null where (T)x would

throw an exception.

Equality Operators

These operators have higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operators

to go the detailed pages with examples.

x == y – equality. By default, for reference types other than string, this returns reference equality (identity test). However, types can overload ==, so

if your intent is to test identity, it is best to use the ReferenceEquals method on object.

x != y – not equal. See comment for ==. If a type overloads ==, then it must overload !=.

Logical AND Operator

This operator has higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operator to go

the details page with examples.

x & y – logical or bitwise AND. Use with integer types and enum types is generally allowed.

Logical XOR Operator

This operator has higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operator to go

the details page with examples.

x ^ y – logical or bitwise XOR. You can generally use this with integer types and enum types.

Logical OR Operator

This operator has higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operator to go

the details page with examples.

x | y – logical or bitwise OR. Use with integer types and enum types is generally allowed.

Conditional AND Operator

This operator has higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operator to go

the details page with examples.

x && y – logical AND. If the first operand is false, then C# does not evaluate the second operand.

Conditional OR Operator

This operator has higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operator to go

the details page with examples.

x || y – logical OR. If the first operand is true, then C# does not evaluate the second operand.

Null-coalescing Operator

This operator has higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operator to go

the details page with examples.

x ?? y – returns x if it is non-null; otherwise, returns y.

Conditional Operator

This operator has higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operator to go

the details page with examples.

t ? x : y – if test t is true, then evaluate and return x; otherwise, evaluate and return y.

Assignment and Lambda Operators

These operators have higher precedence than the next section and lower precedence than the previous section. NOTE, you can click on the operators

to go the detailed pages with examples.

x = y – assignment.

x += y – increment. Add the value of y to the value of x, store the result in x, and return the new value. If x designates an event, then y must be an

appropriate function that C# adds as an event handler.

x -= y – decrement. Subtract the value of y from the value of x, store the result in x, and return the new value. If x designates an event, then y must

be an appropriate function that C# removes as an event handler

x *= y – multiplication assignment. Multiply the value of y to the value of x, store the result in x, and return the new value.

x /= y – division assignment. Divide the value of x by the value of y, store the result in x, and return the new value.

x %= y – modulus assignment. Divide the value of x by the value of y, store the remainder in x, and return the new value.

x &= y – AND assignment. AND the value of y with the value of x, store the result in x, and return the new value.

x |= y – OR assignment. OR the value of y with the value of x, store the result in x, and return the new value.

x ^= y – XOR assignment. XOR the value of y with the value of x, store the result in x, and return the new value.

x <<= y – left-shift assignment. Shift the value of x left by y places, store the result in x, and return the new value.

x >>= y – right-shift assignment. Shift the value of x right by y places, store the result in x, and return the new value.

=> – lambda declaration.

PROGRAMSKE STRUKTURE SEKVENCA – naredba; {blok naredbi} SELEKCIJA –

- if (uslov) {} else {} - switch (izraz) { Case konstanta: Naredba; Naredbaskoka; NPR BREAK;

Page 21: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Default : AKO NIJE NIJEDAN OD IZBORA }

ITERACIJA

– while, While (uslov) { }

- do while Do { } while (i<10),

- for, for (int i=0; i<100, i++) { }

foreach SKOK - goto, break, continue LABELA: … GOTO LABELA; STRUKTURE Enumeracija, struct Stek, red, Niz, lista, uredjena lista OBRADA GREŠAKA System.ApplicationException Tačka prekida – Debugger Try-catch –finally Try { DEO KODA KOJI JE OSETLJIV I MOZE DA NAPRAVI GRESKU } Catch (Exception greska) { OBRADA GRESKE – PRIKAZ TEKSTA GRESKE NPR. MessageBox.Show (Greska.Message); } Finally { BLOK KOJI SE SVAKAKO IZVRSAVA, BILO GRESKE ILI NE } Throw new Exception…

Page 22: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

3. OBLAST – OBJEKTNO-ORJENTISANO PROGRAMIRANJE u C# Teorija Klasa je osnovni gradivni element objektno-orjentisanog programa. Opisuje se svojstvima (atributima) i ponašanjem (metodama). Objekat je konkretna pojava neke klase. Objekat se može smatrati promenljivom čiji je tip klasa. Da bi se kreirao objekat u memoriji, potrebno je da se prvo deklariše da je određenog tipa (da pripada klasi, tj. Da je objekat te klase), a zatim instancira (pozivom konstruktora klase) – pripremi prostor u memoriji za smeštaj njegovih atributa, čime se istovremeno i inicijalizuju svi atributi na početnu vrednost. Stanje objekta opisano je vrednostima njegovih atributa u svakom trenutku. Objekat može da menja stanje. Preporučljivo je da se objektu menja stanje na osnovu poziva odgovarajućih metoda, a ne direktnim pristupom atributima.

OOP u C# Standardne biblioteke klasa Using NazivBibliotekeKlasa;

Klasa:

Class NazivKlase { }

Konstruktor klase: Class NazivKlase { // konstruktor

public NazivKlase () { } }

Polje klase: Class NazivKlase { // privatni atribut, tj. polje private string m_prezime; // konstruktor public NazivKlase () { } }

Svojstvo klase (javni atribut) – readonly ima samo get, writeonly ima samo set:

Class NazivKlase { // privatni atribut, tj. polje private string m_prezime; // javni atribut, tj. svojstvo public string Prezime { get { return m_prezime;

} set { m_prezime=value; }

Page 23: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} // konstruktor public NazivKlase () { } }

Proširenje konstruktora inicijalizacijom promenljivih, tj. Privatnih atributa

Class NazivKlase { // privatni atribut, tj. polje private string m_prezime; // javni atribut, tj. svojstvo public string Prezime { get { return m_prezime;

} Set { m_prezime=value; }

} // konstruktor public NazivKlase () { } m_prezime=””; }

Kreiranje objekta: NazivKlase objNovaKlasa = new NazivKlase (); - deklaracija + instanciranje (poziv konstruktora ukljucuje i inicijalizaciju promenljivih, tj. privatnih atributa, polja). Uništavanje objekta objNovaKlasa.Dispose(); Destruktor – ne poziva se eksplicitno u kodu ~NovaKlasa(){ //naredbe } Korišćenje objekta – postavljanje vrednosti atributu: objNovaKlasa.Prezime = “Markovic”; OVDE SE POZIVA U SUSTINI METODA SET Dodavanje metode – modifikatori pristupa: private, public, protected, internal

Class NazivKlase { // privatni atribut, tj. polje Private string m_prezime; Private string m_ime; // javni atribut, tj. svojstvo Public string Prezime {

Page 24: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

get { return m_prezime;

} Set { m_prezime=value; }

} Public string Ime { get { return m_ime;

} Set { m_ime=value; }

} // konstruktor public NazivKlase () { } m_prezime=””; m_ime=””; }

public string DajPrezimeIme() { return this.m_prezime + “ “ + this.m_ime; } KLJUČNA REČ THIS – ukazuje na trenutni objekat sa kojim se radi Korišćenje klase – poziv metode String PrezimeIme = objNovaKlasa.DajPrezimeIme(); Konstruktor sa parametrima

// konstruktor public NazivKlase (string pocetnoPrezime, string pocetnoIme) { } m_prezime=pocetnoPrezime; m_ime=pocetnoIme; }

Parametri metode Prosledjivanje po reference ili po vrednosti (ulazni, izlazni) – ref int Prom, in int prom, out int prom Poziv: ref Prom, out prom, in prom… Preopterećene(preklapajuće – OVERLOADING) metode – metode u okviru iste klase koje imaju isti naziv, a različite parametre public string DajPrezimeIme() { return this.m_prezime + “ “ + this.m_ime; }

Page 25: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

public string DajPrezimeIme(bool prvoPrezime) { return this.m_prezime + “ “ + this.m_ime; } Nasleđivanje Public class DrugaKlasa: PrvaKlasa { } Poziv konstruktora osnovne klase: Public DrugaKlasa (): base () { } Zaštita osnovne klase – protected modifikator pristupa za atribute i metode Nadjačavanje (OVERRIDE) svojstava i metoda u izvedenoj klasi U osnovnoj klasi: Virtual public string ID... U izvedenoj klasi: Override public string ID Specifične varijante – sealed (zapečaćena) class ( ne može da se nasledi), new public void Metod (naglašava se da nije nadjačana metoda, ne ponaša se polimorfno), abstract (klasa, metoda, atribut) – mora biti nasleđena, nema objekte Polimorfizam – objektu osnovne klase dodeliti referencu na izvedenu klasu i tada treba da bude primenjena metoda izvedene klase. Može se videti kod kolecija (niz, liste) kada se napravi niz elemenata osnovne klase, a dodele kao reference elementi izvedenih klasa. Svaka treba da prilikom poziva istih naziva metoda da dobije svoj rezultat, kao rezultat nadjacavanja metoda. Statičke klase – imaju statičke atribute i metode. Ne instanciraju se, koriste se direktno putem naziva klase. Public static int Broj =5;

STRUKTURE SA OBJEKTIMA KLASA

NIZ, UREĐENA LISTA (LIST, ARRAY LIST) NazivKlase [] nizklasa = {new NazivKlase(), new NazivKlase() }; List ArrayList Indekser

INTERFEJSI – usluge jedne ili više klasa, sakriva implementaciju, ugovor da ce klasa koja implementira interfejs da

se ponasa na odredjeni nacin Public Interface imeinterfejsa { } Svojstvo: Int Imesvojstva { Get; Set; }

Page 26: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Metod Void NazivMetode (parameter…); Klasa koja implementira interfejs Public class KlasaInterfejsa: NazivInterfejsa { }

NAPREDNI NIVO UPRAVLJANJE DOGAĐAJIMA (EVENTS, ADD HANDLER, SYSTEM.EVENTARGS, DELEGATI)

META PODACI O KLASAMA

DINAMIČKO POVEZIVANJE DLL, PROGRAMSKI SKLOP (ASSEMBLY – MANIFEST)

GARBAGE COLLECTION – UPRAVLJANJE MEMORIJOM

SERIJALIZACIJA – SNIMANJE KLASA U FAJLOVIMA ----------------------------------------------------------------- --------------------------------------------------------------------------- KONVENCIJE NAZIVANJA:

Casing: camelCasing – privatni atributi, parametri metoda, promeljive unutar metoda, PascalCasing – sve ostalo

Privatni atributi- prefix m_, Property bez prefiksa RAD SA STRUKTURAMA

NIZ An array stores a fixed-size sequential collection of elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an array as a collection of variables of the same type stored at contiguous memory locations. Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent individual variables. A specific element in an array is accessed by an index. All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Declaring Arrays To declare an array in C#, you can use the following syntax: datatype[] arrayName;

where,

datatype is used to specify the type of elements in the array.

[ ] specifies the rank of the array. The rank specifies the size of the array.

arrayName specifies the name of the array. For example, double[] balance;

Initializing an Array Declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array. Array is a reference type, so you need to use the new keyword to create an instance of the array. For example, double[] balance = new double[10];

Assigning Values to an Array You can assign values to individual array elements, by using the index number, like: double[] balance = new double[10]; balance[0] = 4500.0;

You can assign values to the array at the time of declaration, as shown: double[] balance = { 2340.0, 4523.69, 3421.0};

You can also create and initialize an array, as shown: int [] marks = new int[5] { 99, 98, 92, 97, 95};

You may also omit the size of the array, as shown: int [] marks = new int[] { 99, 98, 92, 97, 95};

You can copy an array variable into another target array variable. In such case, both the target and source point to the same memory location: int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks;

Page 27: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

When you create an array, C# compiler implicitly initializes each array element to a default value depending on the array type. For example, for an int array all elements are initialized to 0. Accessing Array Elements An element is accessed by indexing the array name. This is done by placing the index of the element within square brackets after the name of the array. For example, double salary = balance[9];

The following example, demonstrates the above-mentioned concepts declaration, assignment, and accessing arrays: using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ int i,j; /* initialize elements of array n */ for ( i = 0; i < 10; i++ ) { n[ i ] = i + 100; } /* output each array element's value */ for (j = 0; j < 10; j++ ) { Console.WriteLine("Element[{0}] = {1}", j, n[j]); } Console.ReadKey(); } } }

When the above code is compiled and executed, it produces the following result: Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104 Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109

Using the foreach Loop In the previous example, we used a for loop for accessing each array element. You can also use a foreach statement to iterate through an array. using System; namespace ArrayApplication { class MyArray { static void Main(string[] args) { int [] n = new int[10]; /* n is an array of 10 integers */ /* initialize elements of array n */ for ( int i = 0; i < 10; i++ ) { n[i] = i + 100; } /* output each array element's value */ foreach (int j in n ) { int i = j-100; Console.WriteLine("Element[{0}] = {1}", i, j); } Console.ReadKey(); } } }

ARRAY LIST

Page 28: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

It represents an ordered collection of an object that can be indexed individually. It is basically an alternative to an array.

However, unlike array you can add and remove items from a list at a specified position using an index and the array resizes itself

automatically. It also allows dynamic memory allocation, adding, searching and sorting items in the list.

Methods and Properties of ArrayList Class

The following table lists some of the commonly used properties of the ArrayList class:

Property Description

Capacity Gets or sets the number of elements that the ArrayList can contain.

Count Gets the number of elements actually contained in the ArrayList.

IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly Gets a value indicating whether the ArrayList is read-only.

Item Gets or sets the element at the specified index.

The following table lists some of the commonly used methods of the ArrayList class:

Sr.No. Methods

1 public virtual int Add(object value);

Adds an object to the end of the ArrayList.

2 public virtual void AddRange(ICollection c);

Adds the elements of an ICollection to the end of the ArrayList.

3 public virtual void Clear();

Removes all elements from the ArrayList.

4 public virtual bool Contains(object item);

Determines whether an element is in the ArrayList.

5 public virtual ArrayList GetRange(int index, int count);

Page 29: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Returns an ArrayList which represents a subset of the elements in the source ArrayList.

6 public virtual int IndexOf(object);

Returns the zero-based index of the first occurrence of a value in the ArrayList or in a portion

of it.

7 public virtual void Insert(int index, object value);

Inserts an element into the ArrayList at the specified index.

8 public virtual void InsertRange(int index, ICollection c);

Inserts the elements of a collection into the ArrayList at the specified index.

9 public virtual void Remove(object obj);

Removes the first occurrence of a specific object from the ArrayList.

10 public virtual void RemoveAt(int index);

Removes the element at the specified index of the ArrayList.

11 public virtual void RemoveRange(int index, int count);

Removes a range of elements from the ArrayList.

12 public virtual void Reverse();

Reverses the order of the elements in the ArrayList.

13 public virtual void SetRange(int index, ICollection c);

Copies the elements of a collection over a range of elements in the ArrayList.

14 public virtual void Sort();

Sorts the elements in the ArrayList.

15 public virtual void TrimToSize();

Sets the capacity to the actual number of elements in the ArrayList.

Example

The following example demonstrates the concept:

Page 30: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

using System;

using System.Collections;

namespace CollectionApplication

{

class Program

{

static void Main(string[] args)

{

ArrayList al = new ArrayList();

Console.WriteLine("Adding some numbers:");

al.Add(45);

al.Add(78);

al.Add(33);

al.Add(56);

al.Add(12);

al.Add(23);

al.Add(9);

Console.WriteLine("Capacity: {0} ", al.Capacity);

Console.WriteLine("Count: {0}", al.Count);

Console.Write("Content: ");

foreach (int i in al)

{

Console.Write(i + " ");

}

Console.WriteLine();

Console.Write("Sorted Content: ");

al.Sort();

foreach (int i in al)

{

Console.Write(i + " ");

}

Console.WriteLine();

Console.ReadKey();

Page 31: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

}

}

}

When the above code is compiled and executed, it produces the following result:

Adding some numbers: Capacity: 8 Count: 7 Content: 45 78 33 56 12 23 9 Content: 9 12 23 33 45 56 78

TIPIZIRANA LISTA You have already learned about ArrayList in the previous section. An ArrayList resizes automatically as it grows. The List<T> collection is the same as an ArrayList except that List<T> is a generic collection whereas ArrayList is a non-generic collection.

List<T> can be initialized in the following two ways.

Example: List<T> Initialization

List<int> intList = new List<int>(); //Or IList<int> intList = new List<int>();

In the above example, the first statement uses List type variable, whereas the second statement uses IList type variable to initialize List. List<T> is a concreate implementation of IList<T> interface. In the object-oriented programming, it is advisable to program to interface rather than concreate class. So use IList<T> type variable to create an object of List<T>.

List<T> includes more helper methods than IList<T> interface. The table shown below lists important properties and methods of List<T>, which are initialized using a List<T>:

Property Usage

Items Gets or sets the element at the specified index

Count Returns the total number of elements exists in the List<T>

Method Usage

Add Adds an element at the end of a List<T>.

AddRange Adds elements of the specified collection at the end of a List<T>.

BinarySearch Search the element and returns an index of the element.

Clear Removes all the elements from a List<T>.

Contains Checks whether the speciied element exists or not in a List<T>.

Page 32: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Property Usage

Find Finds the first element based on the specified predicate function.

Foreach Iterates through a List<T>.

Insert Inserts an element at the specified index in a List<T>.

InsertRange Inserts elements of another collection at the specified index.

Remove Removes the first occurence of the specified element.

RemoveAt Removes the element at the specified index.

RemoveRange Removes all the elements that match with the supplied predicate function.

Sort Sorts all the elements.

TrimExcess Sets the capacity to the actual number of elements.

TrueForAll Determines whether every element in the List<T> matches the conditions defined by the specified predicate.

Add Elements into List:

Use the Add() method to add an element into a List collection. The following example adds int value into a List<T> of int type.

Add() signature: void Add(T item)

Example: Adding elements into List

IList<int> intList = new List<int>(); intList.Add(10); intList.Add(20); intList.Add(30); intList.Add(40); IList<string> strList = new List<string>(); strList.Add("one"); strList.Add("two"); strList.Add("three"); strList.Add("four"); strList.Add("four"); strList.Add(null); strList.Add(null); IList<Student> studentList = new List<Student>(); studentList.Add(new Student()); studentList.Add(new Student()); studentList.Add(new Student());

Try it

You can also add elements at the time of initialization using object initializer syntax as below:

Page 33: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Example: Add elements using object initializer syntax

IList<int> intList = new List<int>(){ 10, 20, 30, 40 }; //Or IList<Student> studentList = new List<Student>() { new Student(){ StudentID=1, StudentName="Bill"}, new Student(){ StudentID=2, StudentName="Steve"}, new Student(){ StudentID=3, StudentName="Ram"}, new Student(){ StudentID=1, StudentName="Moin"} };

Try it

AddRange:

The AddRange() method adds all the elements from another collection.

AddRange() signature: void AddRange(IEnumerable<T> collection)

Example: AddRange

IList<int> intList1 = new List<int>(); intList1.Add(10); intList1.Add(20); intList1.Add(30); intList1.Add(40); List<int> intList2 = new List<int>(); intList2.AddRange(intList1);

Try it

Note :The AddRange() method will only be applicable if you initialized with a List<T> variable. IList<T> doesn't include the

AddRange() method.

Access List collection:

Use a foreach or for loop to iterate a List<T> collection.

Example: Accessing List

List<int> intList = new List<int>() { 10, 20, 30 }; intList.ForEach(el => Console.WriteLine(el));

Try it

If you have initialized the List<T> with an IList<T> interface then use seperate foreach statement with implicitly typed variable:

Example: Accessing List

IList<int> intList = new List<int>() { 10, 20, 30, 40 }; foreach (var el in intList) Console.WriteLine(el);

Try it

Page 34: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Output:

10

20

30

40

Access individual items by using an indexer (i.e., passing an index in square brackets):

Example: Accessing List

IList<int> intList = new List<int>() { 10, 20, 30, 40 }; int elem = intList[1]; // returns 20

Use the Count property to get the total number of elements in the List.

Example: Access List elements

IList<int> intList = new List<int>() { 10, 20, 30, 40 }; Console.Write("Total elements: {0}", intList.Count); Output:

Total elements: 4

Use for loop to access list as shown below:

Example: Accessing List using for loop example:

IList<int> intList = new List<int>() { 10, 20, 30, 40 }; for (int i = 0; i < intList.Count; i++) Console.WriteLine(intList[i]);

Try it

Output:

10

20

Page 35: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

30

40

List<T> implements IList<T>, so List<T> implicitly type cast to IList<T>.

Example: Access List

static void Print(IList<string> list) { Console.WriteLine("Count: {0}", list.Count); foreach (string value in list) { Console.WriteLine(value); } } static void Main(string[] args) { string[] strArray = new string[2]; strArray[0] = "Hello"; strArray[1] = "World"; Print(strArray); List<string> strList = new List<string>(); strList.Add("Hello"); strList.Add("World"); Print(strList); }

Try it

Output:

Hello

World

Hello

World

Insert into List:

The Insert() method inserts an element into a List<T> collection at the specified index.

Insert() signature:void Insert(int index, T item);

Example: Insert elements into List

IList<int> intList = new List<int>(){ 10, 20, 30, 40 }; intList.Insert(1, 11);// inserts 11 at 1st index: after 10. foreach (var el in intList)

Page 36: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Console.Write(el);

Try it

Output:

10

11

20

30

40

Remove Elements from List:

The Remove() and RemoveAt() methods remove items from a List<T> collection.

Remove() signature: bool Remove(T item)

RemoveAt() signature: void RemoveAt(int index)

Example: Remove elements from List

IList<int> intList = new List<int>(){ 10, 20, 30, 40 }; intList.Remove(10); // removes the 10 from a list intList.RemoveAt(2); //removes the 3rd element (index starts from 0) foreach (var el in intList) Console.Write(el);

OBRADA GRESAKA

An exception is a problem that arises during the execution of a program. A C# exception is a response to an exceptional

circumstance that arises while a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to another. C# exception handling is built upon four

keywords: try, catch, finally, and throw.

try: A try block identifies a block of code for which particular exceptions is activated. It is followed by one or more catch

blocks.

catch: A program catches an exception with an exception handler at the place in a program where you want to handle

the problem. The catch keyword indicates the catching of an exception.

Page 37: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

finally: The finally block is used to execute a given set of statements, whether an exception is thrown or not thrown. For

example, if you open a file, it must be closed whether an exception is raised or not.

throw: A program throws an exception when a problem shows up. This is done using a throw keyword.

Syntax

Assuming a block raises an exception, a method catches an exception using a combination of the try and catch keywords. A

try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as

protected code, and the syntax for using try/catch looks like the following:

try

{

// statements causing exception

}

catch( ExceptionName e1 )

{

// error handling code

}

catch( ExceptionName e2 )

{

// error handling code

}

catch( ExceptionName eN )

{

// error handling code

}

finally

{

// statements to be executed

}

You can list down multiple catch statements to catch different type of exceptions in case your try block raises more than one

exception in different situations.

Exception Classes in C#

C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from

the System.Exception class. Some of the exception classes derived from the System.Exception class are

the System.ApplicationException and System.SystemException classes.

The System.ApplicationException class supports exceptions generated by application programs. Hence the exceptions defined

by the programmers should derive from this class.

Page 38: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

The System.SystemException class is the base class for all predefined system exception.

The following table provides some of the predefined exception classes derived from the Sytem.SystemException class:

Exception Class Description

System.IO.IOException Handles I/O errors.

System.IndexOutOfRangeException Handles errors generated when a method refers to an array index out of range.

System.ArrayTypeMismatchException Handles errors generated when type is mismatched with the array type.

System.NullReferenceException Handles errors generated from deferencing a null object.

System.DivideByZeroException Handles errors generated from dividing a dividend with zero.

System.InvalidCastException Handles errors generated during typecasting.

System.OutOfMemoryException Handles errors generated from insufficient free memory.

System.StackOverflowException Handles errors generated from stack overflow.

Handling Exceptions

C# provides a structured solution to the exception handling in the form of try and catch blocks. Using these blocks the core

program statements are separated from the error-handling statements.

These error handling blocks are implemented using the try, catch, and finallykeywords. Following is an example of throwing an

exception when dividing by zero condition occurs:

using System;

namespace ErrorHandlingApplication

{

class DivNumbers

{

int result;

DivNumbers()

{

result = 0;

}

Page 39: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

public void division(int num1, int num2)

{

try

{

result = num1 / num2;

}

catch (DivideByZeroException e)

{

Console.WriteLine("Exception caught: {0}", e);

}

finally

{

Console.WriteLine("Result: {0}", result);

}

}

static void Main(string[] args)

{

DivNumbers d = new DivNumbers();

d.division(25, 0);

Console.ReadKey();

}

}

}

When the above code is compiled and executed, it produces the following result:

Exception caught: System.DivideByZeroException: Attempted to divide by zero. at ... Result: 0

Creating User-Defined Exceptions

You can also define your own exception. User-defined exception classes are derived from the Exception class. The following

example demonstrates this:

using System;

namespace UserDefinedException

{

class TestTemperature

{

static void Main(string[] args)

{

Temperature temp = new Temperature();

Page 40: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

try

{

temp.showTemp();

}

catch(TempIsZeroException e)

{

Console.WriteLine("TempIsZeroException: {0}", e.Message);

}

Console.ReadKey();

}

}

}

public class TempIsZeroException: Exception

{

public TempIsZeroException(string message): base(message)

{

}

}

public class Temperature

{

int temperature = 0;

public void showTemp()

{

if(temperature == 0)

{

throw (new TempIsZeroException("Zero Temperature found"));

}

else

{

Console.WriteLine("Temperature: {0}", temperature);

}

}

}

When the above code is compiled and executed, it produces the following result:

TempIsZeroException: Zero Temperature found

Throwing Objects

Page 41: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

You can throw an object if it is either directly or indirectly derived from the System.Exception class. You can use a throw

statement in the catch block to throw the present object as:

Catch(Exception e)

{

...

Throw e

}

OSNOVNI KONCEPTI OBJEKTNO – ORJENTISANOG PROGRAMIRANJA

Osnovni koncepti objektno-orjentisanog programiranja – enkapsulacija, nasleđivanje, polimorfizam

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Calculators { // NASLEDJIVANJE u odnosu na opstu klasu Exception public class clsCustomException: Exception { // ENKAPSULACIJA - SAKRIVANJE IMPLEMENTACIJE - ATRIBUTI SU PRIVATNI private string mTipGreske; private string mTekstGreske; // ENKAPSULACIJA - SAKRIVANJE IMPLEMENTACIJE - METODA JE PRIVATNA private string DajTekstGreske() { string tekstGreske=""; switch (mTipGreske) { case "OperacijaBezOperanda": tekstGreske="Operacija bez operanda";

Page 42: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

break; } return tekstGreske; } // KONSTRUKTOR SA PARAMETROM public clsCustomException(string noviTipGreske) { mTipGreske = noviTipGreske; mTekstGreske = DajTekstGreske(); } // NADJACAVANJE SVOJSTVA public override string Message { get { return mTekstGreske; // NE IDE PORUKA OD OPSTE KLASE EXCEPTION //return base.Message; } } } }

OBRADA GRESAKA

private void btnSimbolDeljenje_Click(object sender, EventArgs e) { if (sadrzajDispleja.Length == 0) { // instanciranje custom klase upisom u objekat opste klase // prikazuje se specificna custom greska - polimorfizam Exception greska = new clsCustomException("OperacijaBezOperanda"); MessageBox.Show("Greska:" + greska.Message); } else { char chrKarakter = '/'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } }

RAD SA NIZOVIMA, LISTAMA I TIPIZIRANIM LISTAMA

Page 43: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

IZMENA POCETNE STRANICE – Program.cs

NIZ:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Calculators { public partial class frmNiz : Form { // atributi - globalne promenljive vidljive na nivou cele klase //private string sadrzajDispleja = ""; //private String sadrzajDispleja = ""; // 6. cas - rad sa nizovima - niz ima fiksan broj karaktera private char[] sadrzajDispleja = new char[10]; private int brojacKaraktera=0; // METODE // konstruktor

Page 44: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

public frmNiz() { InitializeComponent(); } // nase metode // 1. varijanta - globalna promenljiva ulazi ... neocekivano... //private void PrikaziSadrzajDispleja() //{ // txbDisplej.Text = sadrzajDispleja; //} // 2. varijanta - procedura sa parametrom ulaza - kontrola ulaza private void PrikaziSadrzajDispleja(string noviSadrzaj) { txbDisplej.Text = noviSadrzaj; } //3.varijanta - niz - OVDE ZADRZAVAMO OBE VERZIJE I PROGRAM SE NE BUNI, // TO JE OVERLOADING - preklapanje/preopterecivanje private void PrikaziSadrzajDispleja(char[] noviSadrzaj) { txbDisplej.Text = ""; for (int i = 0; i < 10; i++) { txbDisplej.Text = txbDisplej.Text + noviSadrzaj[i]; } } private void IsprazniSadrzajDispleja(char[] stariSadrzaj) { for (int i = 0; i < 10; i++) { stariSadrzaj[i]=' '; } } // dogadjaji private void btnSimbol7_Click(object sender, EventArgs e) { //1. nacin //txbDisplej.Text = "7"; // 2. nacin //sadrzajDispleja = sadrzajDispleja + "7"; //txbDisplej.Text = "7"; //3. nacin bolji... //sadrzajDispleja = sadrzajDispleja + "7"; //PrikaziSadrzajDispleja(); // 4. nacin //sadrzajDispleja = sadrzajDispleja + "7"; //PrikaziSadrzajDispleja(sadrzajDispleja); // 5. nacin - niz // ----- string u karakter //string strKarakter = "7"; //char chrKarakter = strKarakter[0]; // ----- direktno karakter char chrKarakter = '7'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++;

Page 45: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbol8_Click(object sender, EventArgs e) { //sadrzajDispleja = sadrzajDispleja + "8"; //PrikaziSadrzajDispleja(sadrzajDispleja); char chrKarakter = '8'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbol9_Click(object sender, EventArgs e) { char chrKarakter = '9'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbolDeljenje_Click(object sender, EventArgs e) { if (sadrzajDispleja.Length == 0) { // instanciranje custom klase upisom u objekat opste klase // prikazuje se specificna custom greska - polimorfizam Exception greska = new clsCustomException("OperacijaBezOperanda"); MessageBox.Show("Greska:" + greska.Message); } else { char chrKarakter = '/'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } } private void btnSimbol4_Click(object sender, EventArgs e) { char chrKarakter = '4'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbol5_Click(object sender, EventArgs e) { char chrKarakter = '5'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++;

Page 46: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbol6_Click(object sender, EventArgs e) { char chrKarakter = '6'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbolMnozenje_Click(object sender, EventArgs e) { char chrKarakter = '8'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbol1_Click(object sender, EventArgs e) { char chrKarakter = '1'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbol2_Click(object sender, EventArgs e) { char chrKarakter = '2'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbol3_Click(object sender, EventArgs e) { char chrKarakter = '3'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbolMinus_Click(object sender, EventArgs e) { char chrKarakter = '-'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbol0_Click(object sender, EventArgs e) { char chrKarakter = '0';

Page 47: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbolZarez_Click(object sender, EventArgs e) { char chrKarakter = ','; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnSimbolPlus_Click(object sender, EventArgs e) { char chrKarakter = '+'; sadrzajDispleja[brojacKaraktera] = chrKarakter; // stavljamo kasnije jer krece od 0, pa za sledeci da je spremno brojacKaraktera++; PrikaziSadrzajDispleja(sadrzajDispleja); } private void btnObrisi_Click(object sender, EventArgs e) { //1. nacin //sadrzajDispleja = ""; //txbDisplej.Text = ""; //2.nacin //sadrzajDispleja = ""; //txbDisplej.Text = sadrzajDispleja; //3. nacin - otprilike IsprazniSadrzajDispleja(sadrzajDispleja); PrikaziSadrzajDispleja(sadrzajDispleja); } private void Form1_Load(object sender, EventArgs e) { } } }

LISTA (ARRAYLIST)

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; // - DODATO: using System.Collections;

Page 48: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

namespace Calculators { public partial class frmLista : Form { // ATRIBUTI ArrayList lista = new ArrayList(); // METODE // konstruktor public frmLista() { InitializeComponent(); } // nase metode // prikaz iz ARRAY LISTE private void PrikaziSadrzajDispleja(ArrayList noviSadrzaj) { string strNoviSadrzaj = ""; // OVO SE MOZE PRERADITI NA WHILE ILI REPEAT (DO-WHILE) for (int i = 0; i < noviSadrzaj.Count; i++) { strNoviSadrzaj = strNoviSadrzaj + noviSadrzaj[i]; } txbDisplej.Text = strNoviSadrzaj; } private void IsprazniSadrzajDispleja(ArrayList stariSadrzaj) { // BRISE SADRZAJ IZ POSTOJECIH ELEMENATA, TJ. POSTAVLJA NA BLANKO for (int i = 0; i < stariSadrzaj.Count; i++) { stariSadrzaj[i] = ' '; } // UKLANJA ELEMENTE // ovako on kada ponovo uradimo add dodaje ispocetka elemente stariSadrzaj.Clear(); } // dogadjaji private void frmLista_Load(object sender, EventArgs e) { } private void btnSimbol7_Click(object sender, EventArgs e) { lista.Add("7"); PrikaziSadrzajDispleja(lista); } private void btnSimbol8_Click(object sender, EventArgs e) { lista.Add("8");

Page 49: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

PrikaziSadrzajDispleja(lista); } private void btnSimbol9_Click(object sender, EventArgs e) { lista.Add("9"); PrikaziSadrzajDispleja(lista); } private void btnSimbolDeljenje_Click(object sender, EventArgs e) { lista.Add("/"); PrikaziSadrzajDispleja(lista); } private void btnSimbol4_Click(object sender, EventArgs e) { lista.Add("4"); PrikaziSadrzajDispleja(lista); } private void btnSimbol5_Click(object sender, EventArgs e) { lista.Add("5"); PrikaziSadrzajDispleja(lista); } private void btnSimbol6_Click(object sender, EventArgs e) { lista.Add("6"); PrikaziSadrzajDispleja(lista); } private void btnSimbolMnozenje_Click(object sender, EventArgs e) { lista.Add("*"); PrikaziSadrzajDispleja(lista); } private void btnSimbol1_Click(object sender, EventArgs e) { lista.Add("1"); PrikaziSadrzajDispleja(lista); } private void btnSimbol2_Click(object sender, EventArgs e) { lista.Add("2"); PrikaziSadrzajDispleja(lista); } private void btnSimbol3_Click(object sender, EventArgs e) { lista.Add("3"); PrikaziSadrzajDispleja(lista); } private void btnSimbolMinus_Click(object sender, EventArgs e) { lista.Add("-"); PrikaziSadrzajDispleja(lista); } private void btnSimbol0_Click(object sender, EventArgs e) { lista.Add("0");

Page 50: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

PrikaziSadrzajDispleja(lista); } private void btnSimbolZarez_Click(object sender, EventArgs e) { lista.Add(","); PrikaziSadrzajDispleja(lista); } private void btnSimbolPlus_Click(object sender, EventArgs e) { lista.Add("+"); PrikaziSadrzajDispleja(lista); } private void btnObrisi_Click(object sender, EventArgs e) { IsprazniSadrzajDispleja(lista); PrikaziSadrzajDispleja(lista); } } }

TIPIZIRANA LISTA

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Calculators { public partial class frmTipiziranaLista : Form { // ATRIBUTI List<char> chrLista = new List<char>(); // METODE // konstruktor public frmTipiziranaLista() { InitializeComponent(); } // nase metode private void PrikaziSadrzajDispleja(List<char> noviSadrzaj) { string strNoviSadrzaj = ""; // OVO SE MOZE PRERADITI NA WHILE ILI REPEAT (DO-WHILE) for (int i = 0; i < noviSadrzaj.Count; i++) { strNoviSadrzaj = strNoviSadrzaj + noviSadrzaj[i]; } txbDisplej.Text = strNoviSadrzaj; }

Page 51: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

private void IsprazniSadrzajDispleja(List<char> stariSadrzaj) { // BRISANJE SADRZAJA SAMIH ELEMENATA for (int i = 0; i < stariSadrzaj.Count; i++) { stariSadrzaj[i] = ' '; } // BRISANJE LISTE - PROSLEDJENA JE PO REFERENCI // bez ovog bi stalno dodavao nove, a imao prazne na pocetku // ovako on kada ponovo uradimo add dodaje ispocetka elemente stariSadrzaj.Clear(); } // dogadjaji private void frmTipiziranaLista_Load(object sender, EventArgs e) { } private void btnSimbol7_Click(object sender, EventArgs e) { chrLista.Add('7'); PrikaziSadrzajDispleja(chrLista); } private void btnObrisi_Click(object sender, EventArgs e) { IsprazniSadrzajDispleja(chrLista); PrikaziSadrzajDispleja(chrLista); } private void btnSimbol8_Click(object sender, EventArgs e) { chrLista.Add('8'); PrikaziSadrzajDispleja(chrLista); } private void btnSimbol9_Click(object sender, EventArgs e) { chrLista.Add('9'); PrikaziSadrzajDispleja(chrLista); } private void btnSimbolDeljenje_Click(object sender, EventArgs e) { chrLista.Add('/'); PrikaziSadrzajDispleja(chrLista); } } }

Nasledjivanje

public class clsOsoba {

Page 52: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

// ATRIBUTI private string mPrezime; private string mIme; private string mAdresa; // SVOJSTVA public virtual string Prezime { get { return mPrezime; } set { mPrezime = value; } } public virtual string Ime { get { return mIme; } set { mIme = value; } } public virtual string Adresa { get { return mAdresa; } set { mAdresa = value; } } // METODE // konstruktor public clsOsoba() { } // javna metoda public virtual string DajLicnePodatke() { return mPrezime + " " + mIme; } }

public class clsOsobaSrbija: clsOsoba { // ATRIBUTI private string mJMBG; // SVOJSTVA public virtual string JMBG { get { return mJMBG;

Page 53: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} set { mJMBG = value; } } // METODE // konstruktor public clsOsobaSrbija() { } public override string DajLicnePodatke() { return base.Prezime + " " + base.Ime + " JMBG:" + mJMBG; }

public class clsOsobaSvet: clsOsoba { // ATRIBUTI private string mZemlja; // SVOJSTVA public virtual string Zemlja { get { return mZemlja; } set { mZemlja = value; } } // METODE // konstruktor public clsOsobaSvet() { } public override string DajLicnePodatke() { return base.Prezime + " " + base.Ime + " Zemlja:" + mZemlja; }

Primena nasledjivanja – ima sve attribute I metode bazne klase I dodatne specificne attribute I metode:

Page 54: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Tipizirana lista objekata Klase

List<clsOsoba> ListaOsoba = new List<clsOsoba>();

Polimorfizam

Page 55: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

clsOsoba objOsoba1 = new clsOsoba(); objOsoba1.Prezime = "Kazi"; objOsoba1.Ime = "Ljubica"; objOsoba1.Adresa = "4. juli 45"; clsOsobaSrbija objOsoba2 = new clsOsobaSrbija(); objOsoba2.Prezime = "Eremic"; objOsoba2.Ime = "Ivana"; objOsoba2.Adresa = "Majska 5"; objOsoba2.JMBG = "11111"; clsOsobaSvet objOsoba3 = new clsOsobaSvet(); objOsoba3.Prezime = "Markov"; objOsoba3.Ime = "Marko"; objOsoba3.Adresa = "Markova ulica bb"; objOsoba3.Zemlja = "Francuska"; objOsoba3. List<clsOsoba> ListaOsoba = new List<clsOsoba>(); ListaOsoba.Add(objOsoba1); ListaOsoba.Add(objOsoba2); ListaOsoba.Add(objOsoba3); for (int i = 0; i < ListaOsoba.Count; i++) { lbxListaStudenata.Items.Add(ListaOsoba[i].DajLicnePodatke()); }

Page 56: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Predlog pitanja za test poznavanja osnovnih pojmova: SOFTVERSKE ARHITEKTURE

1. Koja su tri osnovna sloja troslojne arhitekture softvera? 2. Koje su komponente sloja poslovne logike? 3. Kako se realizuje višeslojni pristup u okviru sloja poslovne logike? 4. Šta je server? 5. Šta znači servisno-orjentisana arhitektura softvera? 6. Koje su prednosti korišćenja CASE alata?

UML 7. Šta je UML? 8. Koje su vrste dijagrama uključene u UML 1.0? 9. Namena i elementi use case dijagrama? 10. Namena i elementi dijagrama komponenti? 11. Namena i elementi dijagrama razmeštaja? 12. Namena i elementi dijagrama klasa? 13. Koje su vrste veza na dijagramu klasa? 14. Koja je razlika između agregacije I kompozicije? 15. Koja je razlika između asocijacije i kompozicije? 16. Koji su elementi klase? 17. Namena i elementi dijagrama sekvenci? 18. Šta je poruka?

KONVENCIJE 19. Koji načini imenovanja elemenata klase postoje i kada se koriste (tipovi Casing-a)?

OPŠTI POJMOVI PROGRAMIRANJA

1. Koja je razlika izmedju promenljive tipa vrednosti i promenljive tipa reference? 2. Šta znaci type casting? 3. Koja je razlika izmedju deklaracije, incijalizacije, definicije promenljive?

OBJEKTNO ORJENTISANO PROGRAMIRANJE

4. Koji su najčešće korišćeni modifikatori pristupa klase i elemenata klase, objasniti značenje? 5. Šta je signatura metode? 6. Koji je uobičajeni modifikator pristupa za polja (suštinske atribute) klase? 7. Šta predstavlja I kako se realizuje svojstvo (property)? Koja je razlika u odnosu na polja klase? 8. Kako se realizuje u programskom kodu odnos nasleđivanja? 9. Kako se realizuje u programskom kodu odnos asocijacije? 10. Kako se realizuje u programskom kodu odnos kompozicije? 11. Šta je konstruktor? Koja je njegova uloga? 12. Ako je konstruktor nema parametara i nijedna naredba ne piše u bloku naredbi u okviru konstruktora, da li

konstruktor nešto izvršava? Šta? 13. Koja je razlika atributa(polja) i svojstva? Kako se svojstvo implementira? 14. Koja je razlika set i get metode? Čemu služe? Da li uvek moraju obe da se pišu u paru? 15. Šta naslednik može da vidi i koristi u odnosu na baznu klasu? 16. Šta znači nasleđivanje? 17. Kako se implementira enkapsulacija? 18. Kako se implementira polimorfizam? 19. Da li može pokazivač na nasledničku klasu da bude smešten u objektu bazne klase? 20. Šta znači statička klasa? 21. Šta je interfejs klasa? 22. Razlika Overloading (preklapanje) i Overriding (redefinisanje)? 23. Šta je apstraktna klasa? Da li se može nasleđivati? Da li se može instancirati?

Page 57: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

SINTAKSA C# JEZIKA I OBJEKTNO PROGRAMIRANJE U C# 24. Šta je namespace? 25. Šta znači skraćenica dll? 26. Kako povezujemo biblioteku klasa sa korisničkim interfejsom? 27. Koji su tipovi podataka u C# za celobrojne vrednosti I realne brojeve? 28. Kako se spajaju stringovi u C#? 29. Da li je obavezna inicijalizacija promenljivih u C#? Šta znači incijalizacija? 30. Koja su 2 tipa transformacija tipova podataka? 31. Koja su 2 tipa eksplicitnog type castinga u C# - navesti primer? 32. Koji simbol se koristi za dodelu vrednosti promenljive, a koji za proveru da li promenljiva ima neku vrednost? 33. Sta znaci “PROMENLJIVA++”? 34. Kako se oznacava NEGACIJA u C#? Sta znaci “!”? 35. Kako označavamo kada procedura ne vraća vrednost? 36. Kojom naredbom u kodu procedure (koja vraća vrednost) zapravo omogućavamo vraćanje vrednosti? 37. Koji simboli se koristi u C# za logicko AND (2 vrste) iza logicko OR (2 vrste)? Objasniti razliku izmedju 2 vrste za

svaku od ovih operacija. 38. Kako se uslov u C# navodi u if delu kod uslovnog grananja? Navesti primer. 39. Kako se pise u u C# case struktura – višestruko grananje? Navesti primer. 40. Kako se piše ciklus sa preduslovom (while), a kako ciklus sa postuslovom (repeat until)? Navesti primer. 41. Kako se piše for i koja je razlika između for i foreach? Navesti primer. 42. Kako se piše blok za obradu grešaka? Navesti primer. 43. Šta znači finally u try-catch bloku? 44. Kako se uništava objekat? 45. Šta znači this? 46. Šta znači base? 47. Kako označavamo nasleđivanje? 48. Koja je razlika između niza, Array Liste I Tipizirane liste? 49. Koja je bazna klasa za sve klase?

DOPUNA GRADIVA – OSNOVNE PROGRAMSKE STRUKTURE U C# I OBRADA GRESAKA DORADITI KORISNICKI INTERFEJS – dodati labelu, tekst box I dugme za testiranje TYPE CASTINGA

Page 58: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

50. Da li je obavezna inicijalizacija promenljivih u C#?

51. Šta znaci type casting? IZMENA TIPA PODATKA PROMENLJIVE 52. Koja su 2 tipa transformacija tipova podataka? Implicitna, eksplicitna

There is a predefined implicit conversion from byte to short, ushort, int, uint, long, ulong, float, double,

or decimal.

PRIMER IMPLICITNOG: string Ulaz = txtVrednost.Text;

int Duzina = Ulaz.Length; long LongDuzina = Duzina;

PRIMER EKSPLICITNOG: String DuzinaStr = LongDuzina.ToString();

53. Koja su 2 tipa eksplicitnog type castinga u C# - navesti primer?

Eksplicitno: 1. tip int VrednostInt = int.Parse(Ulaz);

MessageBox.Show("Vrednost unetog stringa uvecana za 1:" + (VrednostInt+1).ToString ());

2. tip string Ulaz = txtVrednost.Text;

int Duzina = Ulaz.Length; long LongDuzina = (long)Duzina; MessageBox.Show("Duzina unetog stringa uvecana za 1:" + (LongDuzina+1).ToString ());

3. tip String DuzinaStr = LongDuzina.ToString(); 4. tip long LongDuzina = Convert.ToInt64(Ulaz);

private void btnTransformisi_Click(object sender, EventArgs e) { string Ulaz = txtVrednost.Text; int Duzina = Ulaz.Length; //long LongDuzina = Duzina; long LongDuzina = (long)Duzina; //string DuzinaStr =LongDuzina.ToString(); int VrednostInt = int.Parse(Ulaz); MessageBox.Show("Duzina unetog stringa uvecana za 1:" + (LongDuzina+1).ToString ()); }

-------------------------------------------------------------

1. Sta znaci “PROMENLJIVA++”? INKREMENT 2. Kako se oznacava NEGACIJA u C#? Sta znaci “!”? ! = NEGACIJA 3. Kojom naredbom u kodu procedure (koja vraća vrednost) zapravo omogućavamo vraćanje vrednosti? RETURN 4. Koji simboli se koristi u C# za logicko AND (2 vrste) iza logicko OR (2 vrste)? Objasniti razliku izmedju 2 vrste za

svaku od ovih operacija. &&,|| IMA I SA JEDNOSTRUKIM SIMBOLOM, PROCESIRA SAMO PRVI OPERAND 5. Kako se uslov u C# navodi u if delu kod uslovnog grananja? Navesti primer. SA ZAGRADOM () 6. Kako se pise u u C# case struktura – višestruko grananje? Navesti primer. SWITCH 7. Kako se piše ciklus sa preduslovom (while), a kako ciklus sa postuslovom (repeat until)? Navesti primer. WHILE

(USLOV) {}, DO { } WHILE 8. Kako se piše for i koja je razlika između for i foreach? Navesti primer. FOREACH NE NAVODIMO BROJAC 9. Kako se piše blok za obradu grešaka? Navesti primer. TRY CATCH FINALLY

Page 59: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

10. Šta znači finally u try-catch bloku? SVAKAKO SE IZVRSAVA, POSLE TRY ILI POSLE CATCH DELA ------------------------------------------------------------------------------------------------------------------------

11. Razlika Overloading (preklapanje) – kod iste klase, isto ime metode, razliciti parametri Overriding (redefinisanje) – kod naslednika, isto ime metode, isti parametri ------------------------------------------------------------------------------------------------------------------------

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace StudentskaSluzba { public partial class Form1 : Form { // atributi // METODE // konstruktor public Form1() { InitializeComponent(); } // nase metode private int DajDuzinu(string Rec) { return Rec.Length; } private bool DuzinaVecaOdGranicneVrednosti(string Rec, int GranicnaDuzina) { return DajDuzinu(Rec) > GranicnaDuzina; } private string DuzinaManjaOdGranicneVrednostiObradaGreske(string Rec, int GranicnaDuzina) { bool ispravno = false; string tekstIspravnosti = ""; try { ispravno = DajDuzinu(Rec) < GranicnaDuzina; if (ispravno) { tekstIspravnosti = "MANJE OD GRANICNE VREDNOSTI"; } else { tekstIspravnosti = "VECE ILI JEDNAKO GRANICNOJ VREDNOSTI"; } } catch (Exception ex) { tekstIspravnosti = "greska:" + ex.Message.ToString(); } finally // ovo se uvek svakako izvrsava, bez obzira na to da li ide kroz try redovno ili kroz catch, mora proci i kroz ovo na kraju svakog od ovih prethodnih { tekstIspravnosti = "PROVERA:" + tekstIspravnosti; } return tekstIspravnosti; } private bool DuzinaUIntervalu(string Rec, int DonjaGranicnaDuzina, int GornjaGranicnaDuzina) { // ovde koristimo za logicno AND simbol & gde oba izraza levo i desno moraju da se provere // postoji i && gde se proverava samo prvi levo operand, pa ako je false, drugi se ni ne proverava return ((DajDuzinu(Rec) > DonjaGranicnaDuzina) & (DajDuzinu(Rec) < GornjaGranicnaDuzina)); } private bool DuzinaJednaOd(string Rec, int PrvaDuzina, int DrugaDuzina) { // ovde koristimo za logicno ILI simbol | gde oba izraza levo i desno moraju da se provere // postoji i || gde se proverava samo prvi levo operand, pa ako je true, drugi se ni ne proverava return ((DajDuzinu(Rec) == PrvaDuzina) || (DajDuzinu(Rec) == DrugaDuzina));

Page 60: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} private bool DuzinaJednaOd(string Rec, int PrvaDuzina, int DrugaDuzina, int TrecaDuzina) { // ovde koristimo za logicno ILI simbol | gde oba izraza levo i desno moraju da se provere // postoji i || gde se proverava samo prvi levo operand, pa ako je true, drugi se ni ne proverava return ((DajDuzinu(Rec) == PrvaDuzina) || (DajDuzinu(Rec) == DrugaDuzina) || (DajDuzinu(Rec) == TrecaDuzina)); } // dogadjaji private void btnDodaj_Click(object sender, EventArgs e) { // KREIRANJE OBJEKATA clsOsoba objOsoba1 = new clsOsoba(); objOsoba1.Prezime = "Markovic"; objOsoba1.Ime = "Marko"; objOsoba1.Adresa = "Ivanova 22"; clsOsobaSrbija objOsoba2 = new clsOsobaSrbija(); objOsoba2.Prezime = "Jovanic"; objOsoba2.Ime = "Jovan"; objOsoba2.Adresa = "Majska 5"; objOsoba2.JMBG = "11111"; clsOsobaSvet objOsoba3 = new clsOsobaSvet(); objOsoba3.Prezime = "Markov"; objOsoba3.Ime = "Marko"; objOsoba3.Adresa = "Markova ulica bb"; objOsoba3.Zemlja = "Francuska"; // KREIRANJE TIPIZIRANE LISTE OBJEKATA List<clsOsoba> ListaOsoba = new List<clsOsoba>(); // DODAVANJE ELEMENATA U LISTU ListaOsoba.Add(objOsoba1); ListaOsoba.Add(objOsoba2); ListaOsoba.Add(objOsoba3); // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM FOR lbxListaStudenata.Items.Add("DODAVANJE KORISCENJEM FOR"); for (int i = 0; i < ListaOsoba.Count; i++) { lbxListaStudenata.Items.Add(ListaOsoba[i].DajLicnePodatke()); } // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM FOREACH lbxListaStudenata.Items.Add("DODAVANJE KORISCENJEM FOREACH"); foreach (clsOsoba osoba in ListaOsoba) { lbxListaStudenata.Items.Add(osoba.DajLicnePodatke()); } // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM WHILE (preduslov) lbxListaStudenata.Items.Add("DODAVANJE KORISCENJEM WHILE"); int j = 0; while (j < ListaOsoba.Count) { lbxListaStudenata.Items.Add(ListaOsoba[j].DajLicnePodatke()); j++; } // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM do WHILE (postuslov) lbxListaStudenata.Items.Add("DODAVANJE KORISCENJEM DO - WHILE"); int k = 0; do { lbxListaStudenata.Items.Add(ListaOsoba[k].DajLicnePodatke()); k++; } while (k < ListaOsoba.Count); // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM do WHILE (postuslov) sa proverom uslova IF lbxListaStudenata.Items.Add("DODAVANJE KORISCENJEM DO - WHILE i IF provera uslova"); int a = 0; do { string sadrzaj=ListaOsoba[a].DajLicnePodatke(); if (sadrzaj.Length > 15) { lbxListaStudenata.Items.Add("DUZE OD 15 KARAKTERA"); } else { lbxListaStudenata.Items.Add(sadrzaj); } a++;

Page 61: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} while (a < ListaOsoba.Count); // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM CASE lbxListaStudenata.Items.Add("DODAVANJE KORISCENJEM CASE provera uslova"); int b = 0; do { string sadrzaj = ListaOsoba[b].DajLicnePodatke(); int duzina = sadrzaj.Length; bool duzeOd15karaktera= (duzina>15); switch (duzeOd15karaktera) { case true: { lbxListaStudenata.Items.Add("case true - DUZE OD 15 KARAKTERA"); break; } default: // ovo je else u odnosu na sve ostale opcije { lbxListaStudenata.Items.Add(sadrzaj); break; } } b++; } while (b < ListaOsoba.Count); // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM NEGACIJA lbxListaStudenata.Items.Add("NEGACIJA"); int c = 0; do { string sadrzaj = ListaOsoba[c].DajLicnePodatke(); int duzina = sadrzaj.Length; bool NijeDuzeOd15karaktera = !(duzina > 15); switch (NijeDuzeOd15karaktera) { case true: { lbxListaStudenata.Items.Add("NIJE DUZE OD 15 KARAKTERA"); break; } default: // ovo je else u odnosu na sve ostale opcije { lbxListaStudenata.Items.Add(sadrzaj); break; } } c++; } while (c < ListaOsoba.Count); // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM PROCEDURE lbxListaStudenata.Items.Add("PROCEDURA"); int d = 0; do { string sadrzaj = ListaOsoba[d].DajLicnePodatke(); bool DuzinaOdgovara = DuzinaVecaOdGranicneVrednosti (sadrzaj, 15); switch (DuzinaOdgovara) { case true: { lbxListaStudenata.Items.Add("Duzina veca od 15:" + sadrzaj); break; } default: // ovo je else u odnosu na sve ostale opcije { lbxListaStudenata.Items.Add("Duzina nije veca od 15:" + sadrzaj); break; } } d++; } while (d < ListaOsoba.Count); // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM OBRADE GRESAKA lbxListaStudenata.Items.Add("OBRADA GRESAKA"); int f = 0; do { string sadrzaj = ListaOsoba[f].DajLicnePodatke(); //string tekstIspravnosti = DuzinaManjaOdGranicneVrednostiObradaGreske(sadrzaj, 15); string tekstIspravnosti = DuzinaManjaOdGranicneVrednostiObradaGreske(sadrzaj, 0); switch (tekstIspravnosti) { case "PROVERA:MANJE OD GRANICNE VREDNOSTI": { lbxListaStudenata.Items.Add("Duzina manja od granicne vrednosti:" + tekstIspravnosti + "- SADRZAJ:" + sadrzaj); break; } case "PROVERA:VECE ILI JEDNAKO GRANICNOJ VREDNOSTI":

Page 62: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

{ lbxListaStudenata.Items.Add("Duzina veca od granicne vrednosti:" + tekstIspravnosti + "- SADRZAJ:" + sadrzaj); break; } default: // ovo je else u odnosu na sve ostale opcije { lbxListaStudenata.Items.Add("GRESKA:" + tekstIspravnosti + "- SADRZAJ:" + sadrzaj); break; } } f++; } while (f < ListaOsoba.Count); // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM AND OPERATORA lbxListaStudenata.Items.Add("INTERVAL - primena AND OPERATORA"); int g = 0; do { string sadrzaj = ListaOsoba[g].DajLicnePodatke(); bool intervalDuzina = DuzinaUIntervalu(sadrzaj, 15, 60); switch (intervalDuzina) { case true: { lbxListaStudenata.Items.Add("U intervalu - SADRZAJ:" + sadrzaj); break; } default: // ovo je else u odnosu na sve ostale opcije { lbxListaStudenata.Items.Add("NIJE U INTERVALU - SADRZAJ:" + sadrzaj); break; } } g++; } while (g < ListaOsoba.Count); // IZLISTAVANJE I PRIKAZIVANJE KORISCENJEM OR OPERATORA lbxListaStudenata.Items.Add("VREDNOSTI KONKRETNE - primena OR OPERATORA"); int H = 0; do { string sadrzaj = ListaOsoba[H].DajLicnePodatke(); //bool intervalDuzina = DuzinaJednaOd(sadrzaj, 15, 40); bool intervalDuzina = DuzinaJednaOd(sadrzaj, 15, 40, 50); switch (intervalDuzina) { case true: { lbxListaStudenata.Items.Add("JESTE jedna od duzina - SADRZAJ:" + sadrzaj); break; } default: // ovo je else u odnosu na sve ostale opcije { lbxListaStudenata.Items.Add("NIJE jedna od duzina - SADRZAJ:" + sadrzaj); break; } } H++; } while (H < ListaOsoba.Count); } } }

Page 63: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

SOFTVERSKO INZENJERSTVO 1, CAS 9

4. OBLAST – RAD SA BAZAMA PODATAKA I XML, WINDOWS APP

PREZENTACIONI SLOJ Windows aplikacija

SLOJ POSLOVNE LOGIKE Klase: - Standardne

SLOJ PODATAKA Baza podataka + Stored procedure XML

1. KREIRANJE BAZE PODATAKA SA STORED PROCEDURAMA

Rad sa stored procedurama omogucava osnovne operacije sa podacima da se izvrsavaju u okviru same baze podataka,

cime se ubrzava rad cele aplikacije.

##################################################### PRVI DEO ##################################################### USE [master] GO CREATE DATABASE [GEOGRAFIJASE1] GO USE [GEOGRAFIJASE1] GO CREATE TABLE [dbo].[MESTO]( [PTT] [nvarchar](5) NOT NULL PRIMARY KEY, [Naziv] [nvarchar](40) NOT NULL, [OznakaDrzave] [nvarchar](3) NOT NULL ) GO CREATE TABLE [dbo].[DRZAVA]( [OZNAKA] [nvarchar](3) NOT NULL PRIMARY KEY, [Naziv] [nvarchar](100) NOT NULL, [UkupnoMesta] int NOT NULL ) GO ALTER TABLE [dbo].[MESTO] ADD CONSTRAINT FK_PRIPADA FOREIGN KEY (OznakaDrzave) REFERENCES [dbo].[DRZAVA] (OZNAKA) ON UPDATE CASCADE ON DELETE NO ACTION; GO ##################################################### DRUGI DEO ##################################################### USE [GEOGRAFIJASE1] GO CREATE PROCEDURE [DodajNovuDrzavu]( @OZNAKA nvarchar(3), @Naziv nvarchar(100), @UkupnoMesta int) AS BEGIN Insert into Drzava(Oznaka, Naziv, UkupnoMesta) values (@OZNAKA, @Naziv, @UkupnoMesta) END

Page 64: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

GO CREATE PROCEDURE [ObrisiDrzavu] (@OZNAKA nvarchar(3)) AS BEGIN Delete from Drzava where Oznaka=@OZNAKA END GO CREATE PROCEDURE [IzmeniDrzavu]( @StaraOZNAKA nvarchar(3), @OZNAKA nvarchar(3), @Naziv nvarchar(100), @UkupnoMesta int) AS BEGIN Update Drzava set Oznaka=@OZNAKA, Naziv=@Naziv, UkupnoMesta=@UkupnoMesta where Oznaka=@StaraOZNAKA END GO CREATE PROCEDURE [DajSveDrzave] AS BEGIN Select * from Drzava END GO CREATE PROCEDURE [DajDrzavuPremaOznaci] (@OZNAKA nvarchar(3)) AS BEGIN Select * from Drzava where Oznaka=@OZNAKA END GO

2. KORISNIČKI INTERFEJS – WINDOWS APLIKACIJA

Page 65: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

3. PROGRAMSKI KOD ZA RAD SA PODACIMA - upiti u stored procedurama u bazi podataka - u okviru korisnickog interfejsa - u okviru klasa (zasebni projekat tipa class library - dll ili u okviru istog projekta sa korisnickim interfejsom) VARIJANTE:

- Sa stored procedurama - Sa standardnim klasama za rad sa SQL server bazom podataka (System.Data.SQLClient) - Sa sopstvenim klasama u projektu tipa class library koje su bazirane na standardnim (SQLDBUtils.dll) - Višeslojno, više biblioteka klasa tipa dll - Klase generisane nad SQL Server bazom podataka – Entity Framework

Menjamo u fajlu Program.cs koja stranica je prva:

UREĐUJEMO PROGRAMSKI KOD SVAKE FORME:

Page 66: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

PROGRAMSKI KOD KORISNIČKOG INTERFEJSA ZA RAD SA STORED PROCEDURAMA

- UNOS, TABELARNI PRIKAZ, FILTER, EKSPORT PODATAKA

Dodajemo STATIČKU klasu u projektu korisnickog interfejsa koju smo nazvali Global, postavljamo public static atribute

koji predstavljaju konstante u programu:

CEO PROGRAMSKI KOD U OKVIRU FORME KORISNICKOG INTERFEJSA:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; // using System.Data.SqlClient; namespace KorisnickiInterfejs { public partial class frmSaStoredProcedurom : Form { // ------------ ATRIBUTI // ################################################# private DataTable podaciTabelarni; // ------------ METODE // ################################################# // -----------------NASE PROCEDURE private void IsprazniKontrole() { txtOznaka.Text = ""; txtNaziv.Text = ""; } private int SnimiPodatke() { int brojslogova = 0; SqlConnection Veza = new SqlConnection(Global.stringKonekcije); Veza.Open(); SqlCommand Komanda = new SqlCommand("DodajNovuDrzavu", Veza); Komanda.CommandType = CommandType.StoredProcedure; Komanda.Parameters.Add("@OZNAKA", SqlDbType.NVarChar).Value = txtOznaka.Text; Komanda.Parameters.Add("@Naziv", SqlDbType.NVarChar).Value = txtNaziv.Text; Komanda.Parameters.Add("@UkupnoMesta", SqlDbType.Int).Value = 0; brojslogova = Komanda.ExecuteNonQuery(); Veza.Close(); Veza.Dispose(); return brojslogova;

Page 67: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} private DataTable UcitajSve() { DataTable TabelaPodataka = new DataTable(); SqlConnection Veza = new SqlConnection(Global.stringKonekcije); Veza.Open(); // preuzimanje podataka SqlCommand Komanda = new SqlCommand("DajSveDrzave", Veza); Komanda.CommandType = CommandType.StoredProcedure; SqlDataReader dr = Komanda.ExecuteReader(); // transformacija datareader u data table // - ne mora, u web aplikaciji se moze povezati direktno // grid sa data readerom, ali postoji problem zbog zatvaranja konekcije // pa je bolje ipak da se podati postave u datatable, koji nije direktno povezan sa bazom if (dr.HasRows) { TabelaPodataka.Load(dr); } dr.Close(); Veza.Close(); Veza.Dispose(); return TabelaPodataka; } private DataTable UcitajFiltrirano(string Filter) { DataTable TabelaPodataka = new DataTable(); SqlConnection Veza = new SqlConnection(Global.stringKonekcije); Veza.Open(); // preuzimanje podataka SqlCommand Komanda = new SqlCommand("DajDrzavuPremaOznaci", Veza); Komanda.Parameters.Add("@OZNAKA", SqlDbType.NVarChar).Value = Filter; Komanda.CommandType = CommandType.StoredProcedure; SqlDataReader dr = Komanda.ExecuteReader(); // transformacija datareader u data table // - ne mora, u web aplikaciji se moze povezati direktno // grid sa data readerom, ali postoji problem zbog zatvaranja konekcije // pa je bolje ipak da se podati postave u datatable, koji nije direktno povezan sa bazom if (dr.HasRows) { TabelaPodataka.Load(dr); } dr.Close(); Veza.Close(); Veza.Dispose(); return TabelaPodataka; } private void PrikaziTabeluPodataka(DataTable TabelaPodataka) { dgvSpisakDrzava.DataSource = TabelaPodataka; dgvSpisakDrzava.Refresh(); } private void SnimiXML(DataTable podaci, string putanja) { DataSet dsPodaciEksport = new DataSet(); dsPodaciEksport.Tables.Add(podaci); dsPodaciEksport.WriteXml(putanja); }

Page 68: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

//----------------- KONSTRUKTOR public frmSaStoredProcedurom() { InitializeComponent(); } //----------------DOGADJAJI private void btnUnos_Click(object sender, EventArgs e) { IsprazniKontrole(); txtOznaka.Focus(); } private void btnSnimi_Click(object sender, EventArgs e) { string poruka = ""; int ukupnoSnimljeno = SnimiPodatke(); if (ukupnoSnimljeno > 0) { poruka = "Uspesno snimljeno!"; } else { poruka = "Nije uspesno snimljeno!"; } MessageBox.Show(poruka); } private void btnOdustani_Click(object sender, EventArgs e) { IsprazniKontrole(); } private void btnSve_Click(object sender, EventArgs e) { podaciTabelarni = UcitajSve(); PrikaziTabeluPodataka(podaciTabelarni); } private void btnFiltriraj_Click(object sender, EventArgs e) { podaciTabelarni = UcitajFiltrirano(txtFilter.Text); PrikaziTabeluPodataka(podaciTabelarni); } private void btnExportXML_Click(object sender, EventArgs e) { SnimiXML(podaciTabelarni, Global.putanjaXML); MessageBox.Show("Uspesno realizovan eksport podataka!"); } } }

Page 69: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

SOFTVERSKO INZENJERSTVO 1, CAS 11 – RAD SA STANDARDNIM I SOPSTVENIM KLASAMA, VIŠESLOJNA APLIKACIJA

Odgovori na dodatna pitanja: 1. Kako se uništava objekat? Dispose 2. Koja je bazna klasa za sve klase? Object 3. Kako povezujemo biblioteku klasa sa korisničkim interfejsom? References, Add reference

------------------------------------------------------------ 4. Šta znači statička klasa? Sadrzi staticke attribute (konstante) I metode, ne instancira se, poziva se direktno

navodjenjem imena klase I atributa.

PREZENTACIONI SLOJ Windows aplikacija

SLOJ POSLOVNE LOGIKE Klase: - Standardne

- Sopstvene (DLL), Viseslojno (Vise DLL) - Entity Framework

SLOJ PODATAKA Baza podataka + Stored procedure XML

1. KREIRANJE BAZE PODATAKA

USE [master] GO CREATE DATABASE [GEOGRAFIJASE1] GO USE [GEOGRAFIJASE1] GO CREATE TABLE [dbo].[MESTO]( [PTT] [nvarchar](5) NOT NULL PRIMARY KEY, [Naziv] [nvarchar](40) NOT NULL, [OznakaDrzave] [nvarchar](3) NOT NULL ) GO CREATE TABLE [dbo].[DRZAVA]( [OZNAKA] [nvarchar](3) NOT NULL PRIMARY KEY, [Naziv] [nvarchar](100) NOT NULL, [UkupnoMesta] int NOT NULL ) GO ALTER TABLE [dbo].[MESTO] ADD CONSTRAINT FK_PRIPADA FOREIGN KEY (OznakaDrzave) REFERENCES [dbo].[DRZAVA] (OZNAKA) ON UPDATE CASCADE ON DELETE NO ACTION; GO

2. KORISNIČKI INTERFEJS – WINDOWS APLIKACIJA

Page 70: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

3.1. RAD SA STANDARDNIM KLASAMA

CEO PROGRAMSKI KOD U OKVIRU FORME KORISNICKOG INTERFEJSA (deo se izvrsava u okviru standardnih klasa koje

su date u Visual Studio NET):

Dodavanje „Enabled=false” u okviru Properties za text box.

Sredjivanje Tab Index redom od unosa, text boxova, taster snimi, taster odustani…

Dodavanje koda za aktiviranje i deaktiviranje kontrola – enabled = true/false.

Izmena public static klase sa konstantama da se zove Parametri.cs umesto Global.cs (standardni naziv ne treba

koristiti).

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; //

Page 71: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

using System.Data; using System.Data.SqlClient; namespace KorisnickiInterfejs { public partial class frmSaStandardnimKlasama : Form { // ------------ ATRIBUTI // ################################################# private DataTable podaciTabelarni; // ------------ METODE // ################################################# // -----------------NASE PROCEDURE private void IsprazniKontrole() { txtOznaka.Text = ""; txtNaziv.Text = ""; } private void AktivirajKontrole() { txtOznaka.Enabled=true; txtNaziv.Enabled = true; } private void DeaktivirajKontrole() { txtOznaka.Enabled = false; txtNaziv.Enabled = false; } private int SnimiPodatke() { int brojslogova = 0; // preuzimanje iz korisnickog interfejsa // radi preglednosti koda postavljamo promenljive string Oznaka = txtOznaka.Text; string Naziv = txtNaziv.Text; string UkupnoMesta = "0"; SqlConnection Veza = new SqlConnection(Parametri.stringKonekcije); Veza.Open(); string SQLNaredba = "Insert into Drzava (Oznaka, Naziv, UkupnoMesta) Values ('" + Oznaka + "', '" + Naziv + "'," + UkupnoMesta + ")"; SqlCommand Komanda = new SqlCommand(SQLNaredba, Veza); brojslogova = Komanda.ExecuteNonQuery(); Veza.Close(); Veza.Dispose(); return brojslogova; } private DataTable UcitajSve() { DataTable TabelaPodataka = new DataTable(); SqlConnection Veza = new SqlConnection(Parametri.stringKonekcije); Veza.Open(); // preuzimanje podataka string SQLNaredba = "select * from Drzava"; SqlCommand Komanda = new SqlCommand(SQLNaredba, Veza); SqlDataReader dr = Komanda.ExecuteReader(); // transformacija datareader u data table // - ne mora, u web aplikaciji se moze povezati direktno // grid sa data readerom, ali postoji problem zbog zatvaranja konekcije // pa je bolje ipak da se podati postave u datatable, koji nije direktno povezan sa bazom if (dr.HasRows) { TabelaPodataka.Load(dr);

Page 72: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} dr.Close(); Veza.Close(); Veza.Dispose(); return TabelaPodataka; } private DataTable UcitajFiltrirano(string Filter) { DataTable TabelaPodataka = new DataTable(); SqlConnection Veza = new SqlConnection(Parametri.stringKonekcije); Veza.Open(); // preuzimanje podataka string SQLNaredba = "select * from Drzava where Oznaka='" + Filter + "'"; SqlCommand Komanda = new SqlCommand(SQLNaredba, Veza); SqlDataReader dr = Komanda.ExecuteReader(); // transformacija datareader u data table // - ne mora, u web aplikaciji se moze povezati direktno // grid sa data readerom, ali postoji problem zbog zatvaranja konekcije // pa je bolje ipak da se podati postave u datatable, koji nije direktno povezan sa bazom if (dr.HasRows) { TabelaPodataka.Load(dr); } dr.Close(); Veza.Close(); Veza.Dispose(); return TabelaPodataka; } private void PrikaziTabeluPodataka(DataTable TabelaPodataka) { dgvSpisakDrzava.DataSource = TabelaPodataka; dgvSpisakDrzava.Refresh(); } private void SnimiXML(DataTable podaci, string putanja) { DataSet dsPodaciEksport = new DataSet(); dsPodaciEksport.Tables.Add(podaci); dsPodaciEksport.WriteXml(putanja); } // KONSTRUKTOR public frmSaStandardnimKlasama() { InitializeComponent(); } // DOGADJAJ private void frmSaStandardnimKlasama_Load(object sender, EventArgs e) { } private void btnFiltriraj_Click(object sender, EventArgs e) { podaciTabelarni = UcitajFiltrirano(txtFilter.Text); PrikaziTabeluPodataka(podaciTabelarni); } private void btnSve_Click(object sender, EventArgs e) { podaciTabelarni = UcitajSve(); PrikaziTabeluPodataka(podaciTabelarni); }

Page 73: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

private void btnUnos_Click(object sender, EventArgs e) { IsprazniKontrole(); AktivirajKontrole(); txtOznaka.Focus(); } private void btnSnimi_Click(object sender, EventArgs e) { string poruka = ""; int ukupnoSnimljeno = SnimiPodatke(); if (ukupnoSnimljeno > 0) { poruka = "Uspesno snimljeno!"; } else { poruka = "Nije uspesno snimljeno!"; } DeaktivirajKontrole(); MessageBox.Show(poruka); } private void btnOdustani_Click(object sender, EventArgs e) { IsprazniKontrole(); DeaktivirajKontrole(); } private void btnExportXML_Click(object sender, EventArgs e) { SnimiXML(podaciTabelarni, Parametri.putanjaXML); MessageBox.Show("Uspesno realizovan eksport podataka!"); } } }

Page 74: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

3.2. RAD SA SOPSTVENIM KLASAMA (SQL DB UTILS. DLL)

PROGRAMSKI KOD KLASE SQLDBUTILS.DLL (POGLEDATI POSEBAN WORD DOKUMENT – OSNOVNA BIBLIOTEKA KLASA I KORIGOVANA BIBLIOTEKA KLASA sa preklapajucim metodama)

UKLJUČUJEMO DLL U REFERENCES GLAVNOG PROGRAMA:

PROGRAMSKI KOD U OKVIRU FORME KORISNICKOG INTERFEJSA Dodajemo u using delu samo: // using System.Data; using SqlDBUtils;

Definisemo promenljivu (objekat tipa clsSqlKonekcija), prilikom poziva konstruktora mozemo birati 2 varijante konstruktura:

S obzirom da u Parametri.cs imamo vec ceo string konekcije, koristimo prvu varijantu.

Kreiramo objekat klase clsSqlTabela, imamo 2 preklapajuce metode za izvrsavanje aktivnih upita:

Testiranje aplikacije – primer PROMENLJIVE TIPA REFERENCE

Page 75: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Izmene:

private void SnimiXML(DataTable podaci, string putanja) { DataSet dsPodaciEksport = new DataSet(); // s obzirom da smo dobili kroz parametar poziva ove procedure "podaci" // zapravo samo promenljivu koja sadrzi memorijsku lokaciju, pokazivac // ka podacima, javlja se problem kada ovaj isti DataTable "podaci" // vezemo sa drugim datasetom "dsPodaciExport" jer je taj DataTable // vec povezan sa dsPodaci u okviru procedure UcitajSve i UcitajTabelarno. // Zato moramo da radimo Copy, da kopiramo strukturu i podatke u NOVI DataTable. DataTable podaciZaEksport = new DataTable(); podaciZaEksport = podaci.Copy(); dsPodaciEksport.Tables.Add(podaciZaEksport); dsPodaciEksport.WriteXml(putanja); }

CEO PROGRAMSKI KOD:

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; // using System.Data; using SqlDBUtils; namespace KorisnickiInterfejs { public partial class frmSaSopstvenomBibliotekomDBUtils : Form { // ------------ ATRIBUTI // ################################################# private DataTable podaciTabelarni; // ------------ METODE // ################################################# // -----------------NASE PROCEDURE private void IsprazniKontrole() {

Page 76: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

txtOznaka.Text = ""; txtNaziv.Text = ""; } private void AktivirajKontrole() { txtOznaka.Enabled = true; txtNaziv.Enabled = true; } private void DeaktivirajKontrole() { txtOznaka.Enabled = false; txtNaziv.Enabled = false; } private int SnimiPodatke() { int brojslogova = 0; // preuzimanje iz korisnickog interfejsa // radi preglednosti koda postavljamo promenljive string Oznaka = txtOznaka.Text; string Naziv = txtNaziv.Text; string UkupnoMesta = "0"; clsSqlKonekcija objKonekcija = new clsSqlKonekcija(Parametri.stringKonekcije); objKonekcija.OtvoriKonekciju(); clsSqlTabela objTabela = new clsSqlTabela(objKonekcija, "Drzava"); string SQLNaredba = "Insert into Drzava (Oznaka, Naziv, UkupnoMesta) Values ('" + Oznaka + "', '" + Naziv + "'," + UkupnoMesta + ")"; bool uspeh = objTabela.IzvrsiAzuriranje(SQLNaredba); if (uspeh) { brojslogova = 1; } else { brojslogova = 0; } objKonekcija.ZatvoriKonekciju(); return brojslogova; } private DataTable UcitajSve() { DataTable TabelaPodataka = new DataTable(); clsSqlKonekcija objKonekcija = new clsSqlKonekcija(Parametri.stringKonekcije); objKonekcija.OtvoriKonekciju(); clsSqlTabela objTabela = new clsSqlTabela(objKonekcija, "Drzava"); string SQLNaredba = "select * from Drzava"; DataSet dsPodaci = objTabela.DajPodatke(SQLNaredba); TabelaPodataka = dsPodaci.Tables[0]; objKonekcija.ZatvoriKonekciju(); return TabelaPodataka; } private DataTable UcitajFiltrirano(string Filter) { DataTable TabelaPodataka = new DataTable(); clsSqlKonekcija objKonekcija = new clsSqlKonekcija(Parametri.stringKonekcije);

Page 77: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

objKonekcija.OtvoriKonekciju(); clsSqlTabela objTabela = new clsSqlTabela(objKonekcija, "Drzava"); string SQLNaredba = "select * from Drzava where Oznaka='" + Filter + "'"; DataSet dsPodaci = objTabela.DajPodatke(SQLNaredba); TabelaPodataka = dsPodaci.Tables[0]; objKonekcija.ZatvoriKonekciju(); return TabelaPodataka; } private void PrikaziTabeluPodataka(DataTable TabelaPodataka) { dgvSpisakDrzava.DataSource = TabelaPodataka; dgvSpisakDrzava.Refresh(); } private void SnimiXML(DataTable podaci, string putanja) { DataSet dsPodaciEksport = new DataSet(); // s obzirom da smo dobili kroz parametar poziva ove procedure "podaci" // zapravo samo promenljivu koja sadrzi memorijsku lokaciju, pokazivac // ka podacima, javlja se problem kada ovaj isti DataTable "podaci" // vezemo sa drugim datasetom "dsPodaciExport" jer je taj DataTable // vec povezan sa dsPodaci u okviru procedure UcitajSve i UcitajTabelarno. // Zato moramo da radimo Copy, da kopiramo strukturu i podatke u NOVI DataTable. DataTable podaciZaEksport = new DataTable(); podaciZaEksport = podaci.Copy(); dsPodaciEksport.Tables.Add(podaciZaEksport); dsPodaciEksport.WriteXml(putanja); } // KONSTRUKTOR public frmSaSopstvenomBibliotekomDBUtils() { InitializeComponent(); } // DOGADJAJI private void btnUnos_Click(object sender, EventArgs e) { IsprazniKontrole(); AktivirajKontrole(); txtOznaka.Focus(); } private void btnSnimi_Click(object sender, EventArgs e) { string poruka = ""; int ukupnoSnimljeno = SnimiPodatke(); if (ukupnoSnimljeno > 0) { poruka = "Uspesno snimljeno!"; } else { poruka = "Nije uspesno snimljeno!"; } DeaktivirajKontrole(); MessageBox.Show(poruka); } private void btnOdustani_Click(object sender, EventArgs e) { IsprazniKontrole(); DeaktivirajKontrole(); } private void btnFiltriraj_Click(object sender, EventArgs e)

Page 78: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

{ podaciTabelarni = UcitajFiltrirano(txtFilter.Text); PrikaziTabeluPodataka(podaciTabelarni); } private void btnSve_Click(object sender, EventArgs e) { podaciTabelarni = UcitajSve(); PrikaziTabeluPodataka(podaciTabelarni); } private void btnExportXML_Click(object sender, EventArgs e) { SnimiXML(podaciTabelarni, Parametri.putanjaXML); MessageBox.Show("Uspesno realizovan eksport podataka!"); } private void frmSaSopstvenomBibliotekomDBUtils_Load(object sender, EventArgs e) { } } }

Page 79: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

6.OBLAST - VISESLOJNE APLIKACIJE - RAD SA SOPSTVENIM KLASAMA

(TEHNOLOSKE KLASE, KLASE PODATAKA)

PROGRAMSKI KOD KLASE SQLDBUTILS.DLL – TEHNOLOSKE KLASE

PROGRAMSKI KOD KLASA PODATAKA

PROGRAMSKI KOD KLASA POSLOVNE LOGIKE – ENTITETI, DOKUMENTI, PROCESI, POSLOVNA PRAVILA, RADNI TOKOVI

KLASE UZ KORISNICKI INTERFEJS

PROGRAMSKI KOD U OKVIRU FORME KORISNICKOG INTERFEJSA

Kreiranje novog projekta tipa Class Library da bibliotekom klasa KLASE PODATAKA

Za svaku tabelu iz baze podataka u biblioteci KLASE PODATAKA moze da se napravi 3 klase:

1. Klasa pojedinac – ima samo set i get metode

2. Klasa Tipizirana liste pojedinaca

3. Klasa DB sa upitima koji se odnose na rad sa tom tabelom u bazi podataka.

Biblioteka KLASA PODATAKA moze da koristi u okviru DB klase - standardne klase za pristup bazi podataka ili da koristi

sopstvenu TEHNOLOSKU klasu, npr. SQL DB UTILS, kao u ovom slucaju.

KLASA POJEDINAC

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace KlasePodataka { public class clsDrzava {

Page 80: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

//-------------ATRIBUTI // polja - sustinski atributi private string pOznaka; private string pNaziv; private int pUkupnoMesta; // public property public string Oznaka { get { return pOznaka; } set { if (this.pOznaka != value) this.pOznaka = value; } } public string Naziv { get { return pNaziv; } set { if (this.pNaziv != value) this.pNaziv = value; } } public int UkupnoMesta { get { return pUkupnoMesta; } set { if (this.pUkupnoMesta != value) this.pUkupnoMesta = value; } } // --------- METODE //konstruktor public clsDrzava() { // inicijalizacija polja pOznaka=""; pNaziv=""; pUkupnoMesta=0; } } }

KLASA LISTA POJEDINACA

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace KlasePodataka { public class clsListaDrzava { // ATRIBUTI

Page 81: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

// polja - sustinski atributi private List<clsDrzava> pListaDrzava; // public property public List<clsDrzava> ListaDrzava { get { return pListaDrzava; } set { if (this.pListaDrzava != value) this.pListaDrzava = value; } } // --------- METODE //konstruktor public clsListaDrzava() { pListaDrzava = new List<clsDrzava>(); } // javne metode public void DodajNoviElement(clsDrzava objNovaDrzava) { pListaDrzava.Add(objNovaDrzava); } public void ObrisiElement(clsDrzava objDrzavaZaBrisanje) { pListaDrzava.Remove(objDrzavaZaBrisanje); } public void ObrisiElementNaPoziciji(int pozicija) { pListaDrzava.RemoveAt(pozicija); } } }

KLASA DB

using System; using System.Collections.Generic; using System.Linq; using System.Text; // using System.Data; using SqlDBUtils; namespace KlasePodataka { public class clsDrzavaDB { // atributi private string pStringKonekcije=""; // metode // konstruktor public clsDrzavaDB(string noviStringKonekcije) { pStringKonekcije = noviStringKonekcije; }

Page 82: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

// javne metode public int SnimiPodatke(clsDrzava objNovaDrzava) { int brojslogova = 0; // preuzimanje iz korisnickog interfejsa // radi preglednosti koda postavljamo promenljive string Oznaka = objNovaDrzava.Oznaka ; string Naziv = objNovaDrzava.Naziv ; string UkupnoMesta = objNovaDrzava.UkupnoMesta.ToString () ; clsSqlKonekcija objKonekcija = new clsSqlKonekcija(pStringKonekcije); objKonekcija.OtvoriKonekciju(); clsSqlTabela objTabela = new clsSqlTabela(objKonekcija, "Drzava"); string SQLNaredba = "Insert into Drzava (Oznaka, Naziv, UkupnoMesta) Values ('" + Oznaka + "', '" + Naziv + "'," + UkupnoMesta + ")"; bool uspeh = objTabela.IzvrsiAzuriranje(SQLNaredba); if (uspeh) { brojslogova = 1; } else { brojslogova = 0; } objKonekcija.ZatvoriKonekciju(); return brojslogova; } public DataTable UcitajSve() { DataTable TabelaPodataka = new DataTable(); clsSqlKonekcija objKonekcija = new clsSqlKonekcija(pStringKonekcije ); objKonekcija.OtvoriKonekciju(); clsSqlTabela objTabela = new clsSqlTabela(objKonekcija, "Drzava"); string SQLNaredba = "select * from Drzava"; DataSet dsPodaci = objTabela.DajPodatke(SQLNaredba); TabelaPodataka = dsPodaci.Tables[0]; objKonekcija.ZatvoriKonekciju(); return TabelaPodataka; } public DataTable UcitajFiltrirano(string Filter) { DataTable TabelaPodataka = new DataTable(); clsSqlKonekcija objKonekcija = new clsSqlKonekcija(pStringKonekcije); objKonekcija.OtvoriKonekciju(); clsSqlTabela objTabela = new clsSqlTabela(objKonekcija, "Drzava"); string SQLNaredba = "select * from Drzava where Oznaka='" + Filter + "'"; DataSet dsPodaci = objTabela.DajPodatke(SQLNaredba); TabelaPodataka = dsPodaci.Tables[0]; objKonekcija.ZatvoriKonekciju(); return TabelaPodataka; } // metoda } // klasa } // namespace

Page 83: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

PROGRAMSKI KOD KORISNIČKOG INTERFEJSA – OSLOBOĐEN BILOKAKVE VEZE SA BAZOM

PODATAKA

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; // using System.Data; using KlasePodataka; namespace KorisnickiInterfejs { public partial class frmSaViseslojnimSopstvenimKlasama : Form { // ------------ ATRIBUTI // ################################################# private DataTable podaciTabelarni; private clsDrzavaDB objDrzavaDB; // ------------ METODE // ################################################# // -----------------NASE PROCEDURE private void IsprazniKontrole() { txtOznaka.Text = ""; txtNaziv.Text = ""; } private void AktivirajKontrole() { txtOznaka.Enabled = true; txtNaziv.Enabled = true; } private void DeaktivirajKontrole() { txtOznaka.Enabled = false; txtNaziv.Enabled = false; } private void PrikaziTabeluPodataka(DataTable TabelaPodataka) { dgvSpisakDrzava.DataSource = TabelaPodataka; dgvSpisakDrzava.Refresh(); } private void SnimiXML(DataTable podaci, string putanja) { DataSet dsPodaciEksport = new DataSet(); // s obzirom da smo dobili kroz parametar poziva ove procedure "podaci" // zapravo samo promenljivu koja sadrzi memorijsku lokaciju, pokazivac // ka podacima, javlja se problem kada ovaj isti DataTable "podaci" // vezemo sa drugim datasetom "dsPodaciExport" jer je taj DataTable // vec povezan sa dsPodaci u okviru procedure UcitajSve i UcitajTabelarno. // Zato moramo da radimo Copy, da kopiramo strukturu i podatke u NOVI DataTable. DataTable podaciZaEksport = new DataTable(); podaciZaEksport = podaci.Copy(); dsPodaciEksport.Tables.Add(podaciZaEksport); dsPodaciEksport.WriteXml(putanja); } // KONSTRUKTOR public frmSaViseslojnimSopstvenimKlasama()

Page 84: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

{ InitializeComponent(); } // DOGADJAJI private void frmSaViseslojnimSopstvenimKlasama_Load(object sender, EventArgs e) { // inicijalizacija globalne promenljive objDrzavaDB = new clsDrzavaDB(Parametri.stringKonekcije); } private void btnUnos_Click(object sender, EventArgs e) { IsprazniKontrole(); AktivirajKontrole(); txtOznaka.Focus(); } private void btnSnimi_Click(object sender, EventArgs e) { string poruka = ""; // preuzimanje vrednosti sa korisnickog interfejsa clsDrzava objNovaDrzava = new clsDrzava(); objNovaDrzava.Oznaka = txtOznaka.Text; objNovaDrzava.Naziv = txtNaziv.Text; objNovaDrzava.UkupnoMesta = 0; // snimanje int ukupnoSnimljeno = objDrzavaDB.SnimiPodatke(objNovaDrzava); if (ukupnoSnimljeno > 0) { poruka = "Uspesno snimljeno!"; } else { poruka = "Nije uspesno snimljeno!"; } DeaktivirajKontrole(); MessageBox.Show(poruka); } private void btnOdustani_Click(object sender, EventArgs e) { IsprazniKontrole(); DeaktivirajKontrole(); } private void btnFiltriraj_Click(object sender, EventArgs e) { podaciTabelarni = objDrzavaDB.UcitajFiltrirano(txtFilter.Text); PrikaziTabeluPodataka(podaciTabelarni); } private void btnSve_Click(object sender, EventArgs e) { podaciTabelarni = objDrzavaDB.UcitajSve(); PrikaziTabeluPodataka(podaciTabelarni); } private void btnExportXML_Click(object sender, EventArgs e) { SnimiXML(podaciTabelarni, Parametri.putanjaXML); MessageBox.Show("Uspesno realizovan eksport podataka!"); } } }

Page 85: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

IZMENJENA BIBLIOTEKA KLASA SQL DB UTILS

DODATO PREKLAPANJE KONSTRUKTORA U KLASI KONEKCIJA

DODATO PREKLAPANJE METODE IZVRSI AZURIRANJE U KLASI TABELA

KLASA KONEKCIJA

using System; using System.Collections.Generic; using System.Linq; using System.Text; // using System.Data.SqlClient; namespace SqlDBUtils { public class clsSqlKonekcija { /* ODGOVORNOST: Konekcija na celinu baze podataka, SQL server tipa */ #region Atributi private SqlConnection pKonekcija; // private string pPutanjaSQLBaze; private string pNazivBaze; private string pNazivSQL_DBMSinstance; private string pStringKonekcije; #endregion #region Konstruktor public clsSqlKonekcija(string nazivSQL_DBMSInstance, string putanjaSqlBaze, string NazivBaze) { pPutanjaSQLBaze = putanjaSqlBaze; pNazivBaze = NazivBaze; pNazivSQL_DBMSinstance = nazivSQL_DBMSInstance; } // preklapajuci konstruktor, kada dobijemo spolja string konekcije public clsSqlKonekcija(string noviStringKonekcije) { pStringKonekcije = noviStringKonekcije; } #endregion #region Privatne metode private string DajStringKonekcije() { string mStringKonekcije=pStringKonekcije; if (mStringKonekcije.Length == 0) { if (pPutanjaSQLBaze.Length.Equals(0) || pPutanjaSQLBaze == null) { mStringKonekcije = "Data Source=" + pNazivSQL_DBMSinstance + " ;Initial Catalog=" + pNazivBaze + ";Integrated Security=True"; } else { mStringKonekcije = "Data Source=.\\" + pNazivSQL_DBMSinstance + ";AttachDbFilename=" + pPutanjaSQLBaze + "\\" + pNazivBaze + ";Integrated Security=True;Connect Timeout=30;User Instance=True"; }

Page 86: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} return mStringKonekcije; } #endregion #region Javne metode public bool OtvoriKonekciju() { bool uspeh; pKonekcija = new SqlConnection(); pKonekcija.ConnectionString = DajStringKonekcije(); try { pKonekcija.Open(); uspeh = true; } catch { uspeh = false; } return uspeh; } public SqlConnection DajKonekciju() { return pKonekcija; } public void ZatvoriKonekciju() { pPutanjaSQLBaze = ""; pKonekcija.Close(); pKonekcija.Dispose(); } #endregion } }

KLASA TABELA

using System; using System.Collections.Generic; using System.Linq; using System.Text; // using System.Data.SqlClient; namespace SqlDBUtils { public class clsSqlTabela { #region Atributi private string pNazivTabele; private clsSqlKonekcija pKonekcija; private SqlDataAdapter pAdapter; private System.Data.DataSet pDataSet; #endregion #region Konstruktor public clsSqlTabela(clsSqlKonekcija Konekcija, string NazivTabele)

Page 87: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

{ pKonekcija = Konekcija; pNazivTabele = NazivTabele; } #endregion #region Privatne metode private void KreirajAdapter(string SelectUpit, string InsertUpit, string DeleteUpit, string UpdateUpit) { SqlCommand mSelectKomanda, mInsertKomanda, mDeleteKomanda, mUpdateKomanda; mSelectKomanda = new SqlCommand(); mSelectKomanda.CommandText = SelectUpit; mSelectKomanda.Connection = pKonekcija.DajKonekciju(); mInsertKomanda = new SqlCommand(); mInsertKomanda.CommandText = InsertUpit; mInsertKomanda.Connection = pKonekcija.DajKonekciju(); mDeleteKomanda = new SqlCommand(); mDeleteKomanda.CommandText = DeleteUpit; mDeleteKomanda.Connection = pKonekcija.DajKonekciju(); mUpdateKomanda = new SqlCommand(); mUpdateKomanda.CommandText = UpdateUpit; mUpdateKomanda.Connection = pKonekcija.DajKonekciju(); pAdapter = new SqlDataAdapter(); pAdapter.SelectCommand = mSelectKomanda; pAdapter.InsertCommand = mInsertKomanda; pAdapter.UpdateCommand = mUpdateKomanda; pAdapter.DeleteCommand = mDeleteKomanda; } private void KreirajDataset() { pDataSet = new System.Data.DataSet(); pAdapter.Fill(pDataSet, pNazivTabele); } private void ZatvoriAdapterDataset() { pAdapter.Dispose(); pDataSet.Dispose(); } #endregion #region Javne metode public System.Data.DataSet DajPodatke(string SelectUpit) // izdvaja podatke u odnosu na dat selectupit { KreirajAdapter(SelectUpit, "", "", ""); KreirajDataset(); return pDataSet; } public int DajBrojSlogova() { int BrojSlogova = pDataSet.Tables[0].Rows.Count; return BrojSlogova;

Page 88: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} public bool IzvrsiAzuriranje(string Upit) // izvrzava azuriranje unos/brisanje/izmena u odnosu na dati i upit { // bool uspeh = false; SqlConnection mKonekcija; SqlCommand Komanda; SqlTransaction mTransakcija = null; try { mKonekcija = pKonekcija.DajKonekciju(); // aktivan kod // povezivanje Komanda = new SqlCommand(); Komanda.Connection = mKonekcija; Komanda = mKonekcija.CreateCommand(); // pokretanje // NE TREBA OPEN JER DOBIJAMO OTVORENU KONEKCIJU KROZ KONSTRUKTOR // mKonekcija.Open(); mTransakcija = mKonekcija.BeginTransaction(); Komanda.Transaction = mTransakcija; Komanda.CommandText = Upit; Komanda.ExecuteNonQuery(); mTransakcija.Commit(); uspeh = true; } catch { mTransakcija.Rollback(); uspeh = false; } return uspeh; } // preklapajuca metoda kada dobijemo vise upita da se izvrsi u transakciji public bool IzvrsiAzuriranje(List<string> ListaUpita) // izvrzava azuriranje unos/brisanje/izmena // moze se dodeliti kao parametar lista od vise upita // sada transakcija ima smisla, jer izvrsava vise upita u paketu { // bool uspeh = false; SqlConnection mKonekcija; SqlCommand Komanda; SqlTransaction mTransakcija = null; try { mKonekcija = pKonekcija.DajKonekciju(); // aktivan kod // povezivanje Komanda = new SqlCommand(); Komanda.Connection = mKonekcija; Komanda = mKonekcija.CreateCommand(); // pokretanje // NE TREBA OPEN JER DOBIJAMO OTVORENU KONEKCIJU KROZ KONSTRUKTOR // mKonekcija.Open(); string Upit=""; mTransakcija = mKonekcija.BeginTransaction(); Komanda.Transaction = mTransakcija; for (int i = 0; i < ListaUpita.Count(); i++)

Page 89: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

{ Upit = ListaUpita[i]; Komanda.CommandText = Upit; Komanda.ExecuteNonQuery(); } mTransakcija.Commit(); uspeh = true; } catch { mTransakcija.Rollback(); uspeh = false; } return uspeh; } #endregion } }

Page 90: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

7. OBLAST - MVC – DESIGN PATTERN I ENTITY FRAMEWORK

TEORIJSKI DEO

- Model (entiteti poslovnog problema, poslovna pravila, jezgro funkcionalnosti sistema, ukljucuje i deo koji se

odnosi na klase koje se bave resursima, tj. Podacima iz baze podataka – osnovne rutine pristupa I azuriranja )

- View (graficki prikaz podataka, ali moze biti I pogled bez grafike)

- Controller (odgovara na ulaz - korisnikove zahteve, upucuje zahteve modelu da treba da izmeni stanje u

podacima, upucuje zahtev view da prikaze izmenu na pogledu na grafickom displeju

ZA ISTE PODATKE (Model) moze biti vise prikaza (VIEW). Preuzimanje I tumacenje akcija od strane korisnika (ulaz) I

usmeravanje modela da izvrsi izmene, kao I usmeravanje view da prikaze izmene radi CONTROLLER.

Page 91: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica
Page 92: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

PRAKTICNI DEO

PREZENTACIONI SLOJ KORISNIČKI INTERFEJS

- VIEW : PRIKAZ PODATAKA I STANJA PROGRAMA

1. Kontrole korisničkog interfejsa

2. Klase View

- CONTROLLER: ULAZ OD KORISNIKA, TUMAČENJE, TRANSFORMACIJE U KOMANDE PREMA VIEW I KOMANDE PREMA MODELU

1. Kao događaji (event, delegati)

2. Kao klase Kontroleri

POSLOVNA LOGIKA MODEL KLASE

- LOGIKA FUNKCIONALNOSTI PROGRAMA

- SUŠTINSKI ENTITETI I PODRŠKA POSLOVNIM PROCESIMA, poslovna pravila

SLOJ PODATAKA MODEL - KLASE ZA PRISTUP PODACIMA

DBMS + BAZA PODATAKA (tabele, relacije, pogledi, stored procedure, trigeri) DATOTEKE – XML, TXT, JSON…

RAD SA KLASAMA ENTITY FRAMEWORKA

1. KREIRANJE PROJEKTA TIPA CLASS LIBRARY

Kreiramo projekat tipa Class Library (moze se sve ovo dalje realizovati I u okviru projekta korisnickog interfejsa, ali

ovde odvajamo poseban projekat za klase modela):

Page 93: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

DOBIJAMO:

2. DODAVANJE KONEKCIJE NA BAZU PODATAKA

Server Explorer, Data Connections, Add Connection

Unosimo naziv server, biramo naziv baze podataka. Testiramo konekciju “TEST CONNECTION”.

Page 94: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

3. DODAVANJE IZVORA PODATAKA

Ako izaberemo DATABASE:

Page 95: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Ako izaberemo SERVICE:

Ako izaberemo Object:

Ako izaberemo Share Point:

Page 96: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

4. KREIRANJE ENTITY DATA MODEL KLASA

1. Ako izaberemo Dataset, bice kreirani dataset objekti koji su povezani sa bazom podataka.

2. Ako izaberemo Entity Data Model:

Biramo GENERATE FROM DATABASE:

Page 97: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Biramo tabele i stored procedure koje zelimo da ukljuci u klase modela, kao i podesavamo PLURALIZE AND

SINGULARIZE OBJECT NAMES.

Page 98: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Dobijamo:

Detaljnije, kreiran je App.Config, dodate reference potrebne za rad u References:

Page 99: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

APP.CONFIG <?xml version="1.0" encoding="utf-8"?> <configuration> <connectionStrings> <add name="GEOGRAFIJASE1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=BUBILIS;initial catalog=GEOGRAFIJASE1;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> </configuration>

Dodati su u references: - System.Data.Entity - System.Runtime.Serialization - System.Security

Detalje kreiranog Entity modela mozemo pogledati koristeci link MODEL BROWSER:

Detalji:

Page 100: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Generisani programski kod Entity Data Modela:

#region EDM Relationship Metadata

Page 101: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

[assembly: EdmRelationshipAttribute("GEOGRAFIJASE1Model", "FK_PRIPADA", "DRZAVA", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(EntityFrameworkKlase.DRZAVA), "MESTO", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(EntityFrameworkKlase.MESTO), true)] #endregion

REGION CONTEXTS

REGION ENTITETI

CEO KOD:

Page 102: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.ComponentModel; using System.Data.EntityClient; using System.Data.Objects; using System.Data.Objects.DataClasses; using System.Linq; using System.Runtime.Serialization; using System.Xml.Serialization; [assembly: EdmSchemaAttribute()] #region EDM Relationship Metadata [assembly: EdmRelationshipAttribute("GEOGRAFIJASE1Model", "FK_PRIPADA", "DRZAVA", System.Data.Metadata.Edm.RelationshipMultiplicity.One, typeof(EntityFrameworkKlase.DRZAVA), "MESTO", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, typeof(EntityFrameworkKlase.MESTO), true)] #endregion namespace EntityFrameworkKlase { #region Contexts /// <summary> /// No Metadata Documentation available. /// </summary> public partial class GEOGRAFIJASE1Entities : ObjectContext { #region Constructors /// <summary> /// Initializes a new GEOGRAFIJASE1Entities object using the connection string found in the 'GEOGRAFIJASE1Entities' section of the application configuration file. /// </summary> public GEOGRAFIJASE1Entities() : base("name=GEOGRAFIJASE1Entities", "GEOGRAFIJASE1Entities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } /// <summary> /// Initialize a new GEOGRAFIJASE1Entities object. /// </summary> public GEOGRAFIJASE1Entities(string connectionString) : base(connectionString, "GEOGRAFIJASE1Entities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated(); } /// <summary> /// Initialize a new GEOGRAFIJASE1Entities object. /// </summary> public GEOGRAFIJASE1Entities(EntityConnection connection) : base(connection, "GEOGRAFIJASE1Entities") { this.ContextOptions.LazyLoadingEnabled = true; OnContextCreated();

Page 103: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} #endregion #region Partial Methods partial void OnContextCreated(); #endregion #region ObjectSet Properties /// <summary> /// No Metadata Documentation available. /// </summary> public ObjectSet<DRZAVA> DRZAVAs { get { if ((_DRZAVAs == null)) { _DRZAVAs = base.CreateObjectSet<DRZAVA>("DRZAVAs"); } return _DRZAVAs; } } private ObjectSet<DRZAVA> _DRZAVAs; /// <summary> /// No Metadata Documentation available. /// </summary> public ObjectSet<MESTO> MESTOes { get { if ((_MESTOes == null)) { _MESTOes = base.CreateObjectSet<MESTO>("MESTOes"); } return _MESTOes; } } private ObjectSet<MESTO> _MESTOes; #endregion #region AddTo Methods /// <summary> /// Deprecated Method for adding a new object to the DRZAVAs EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead. /// </summary> public void AddToDRZAVAs(DRZAVA dRZAVA) { base.AddObject("DRZAVAs", dRZAVA); } /// <summary> /// Deprecated Method for adding a new object to the MESTOes EntitySet. Consider using the .Add method of the associated ObjectSet&lt;T&gt; property instead. /// </summary> public void AddToMESTOes(MESTO mESTO) { base.AddObject("MESTOes", mESTO); }

Page 104: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

#endregion } #endregion #region Entities /// <summary> /// No Metadata Documentation available. /// </summary> [EdmEntityTypeAttribute(NamespaceName="GEOGRAFIJASE1Model", Name="DRZAVA")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class DRZAVA : EntityObject { #region Factory Method /// <summary> /// Create a new DRZAVA object. /// </summary> /// <param name="oZNAKA">Initial value of the OZNAKA property.</param> /// <param name="naziv">Initial value of the Naziv property.</param> /// <param name="ukupnoMesta">Initial value of the UkupnoMesta property.</param> public static DRZAVA CreateDRZAVA(global::System.String oZNAKA, global::System.String naziv, global::System.Int32 ukupnoMesta) { DRZAVA dRZAVA = new DRZAVA(); dRZAVA.OZNAKA = oZNAKA; dRZAVA.Naziv = naziv; dRZAVA.UkupnoMesta = ukupnoMesta; return dRZAVA; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.String OZNAKA { get { return _OZNAKA; } set { if (_OZNAKA != value) { OnOZNAKAChanging(value); ReportPropertyChanging("OZNAKA"); _OZNAKA = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("OZNAKA"); OnOZNAKAChanged(); } } } private global::System.String _OZNAKA; partial void OnOZNAKAChanging(global::System.String value); partial void OnOZNAKAChanged(); /// <summary>

Page 105: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

/// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Naziv { get { return _Naziv; } set { OnNazivChanging(value); ReportPropertyChanging("Naziv"); _Naziv = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Naziv"); OnNazivChanged(); } } private global::System.String _Naziv; partial void OnNazivChanging(global::System.String value); partial void OnNazivChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.Int32 UkupnoMesta { get { return _UkupnoMesta; } set { OnUkupnoMestaChanging(value); ReportPropertyChanging("UkupnoMesta"); _UkupnoMesta = StructuralObject.SetValidValue(value); ReportPropertyChanged("UkupnoMesta"); OnUkupnoMestaChanged(); } } private global::System.Int32 _UkupnoMesta; partial void OnUkupnoMestaChanging(global::System.Int32 value); partial void OnUkupnoMestaChanged(); #endregion #region Navigation Properties /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()] [EdmRelationshipNavigationPropertyAttribute("GEOGRAFIJASE1Model", "FK_PRIPADA", "MESTO")] public EntityCollection<MESTO> MESTOes { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedCollection<MESTO>("GEOGRAFIJASE1Model.FK_PRIPADA", "MESTO");

Page 106: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedCollection<MESTO>("GEOGRAFIJASE1Model.FK_PRIPADA", "MESTO", value); } } } #endregion } /// <summary> /// No Metadata Documentation available. /// </summary> [EdmEntityTypeAttribute(NamespaceName="GEOGRAFIJASE1Model", Name="MESTO")] [Serializable()] [DataContractAttribute(IsReference=true)] public partial class MESTO : EntityObject { #region Factory Method /// <summary> /// Create a new MESTO object. /// </summary> /// <param name="pTT">Initial value of the PTT property.</param> /// <param name="naziv">Initial value of the Naziv property.</param> /// <param name="oznakaDrzave">Initial value of the OznakaDrzave property.</param> public static MESTO CreateMESTO(global::System.String pTT, global::System.String naziv, global::System.String oznakaDrzave) { MESTO mESTO = new MESTO(); mESTO.PTT = pTT; mESTO.Naziv = naziv; mESTO.OznakaDrzave = oznakaDrzave; return mESTO; } #endregion #region Primitive Properties /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)] [DataMemberAttribute()] public global::System.String PTT { get { return _PTT; } set { if (_PTT != value) { OnPTTChanging(value); ReportPropertyChanging("PTT"); _PTT = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("PTT"); OnPTTChanged();

Page 107: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

} } } private global::System.String _PTT; partial void OnPTTChanging(global::System.String value); partial void OnPTTChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String Naziv { get { return _Naziv; } set { OnNazivChanging(value); ReportPropertyChanging("Naziv"); _Naziv = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("Naziv"); OnNazivChanged(); } } private global::System.String _Naziv; partial void OnNazivChanging(global::System.String value); partial void OnNazivChanged(); /// <summary> /// No Metadata Documentation available. /// </summary> [EdmScalarPropertyAttribute(EntityKeyProperty=false, IsNullable=false)] [DataMemberAttribute()] public global::System.String OznakaDrzave { get { return _OznakaDrzave; } set { OnOznakaDrzaveChanging(value); ReportPropertyChanging("OznakaDrzave"); _OznakaDrzave = StructuralObject.SetValidValue(value, false); ReportPropertyChanged("OznakaDrzave"); OnOznakaDrzaveChanged(); } } private global::System.String _OznakaDrzave; partial void OnOznakaDrzaveChanging(global::System.String value); partial void OnOznakaDrzaveChanged(); #endregion #region Navigation Properties /// <summary> /// No Metadata Documentation available. /// </summary> [XmlIgnoreAttribute()] [SoapIgnoreAttribute()] [DataMemberAttribute()]

Page 108: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

[EdmRelationshipNavigationPropertyAttribute("GEOGRAFIJASE1Model", "FK_PRIPADA", "DRZAVA")] public DRZAVA DRZAVA { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<DRZAVA>("GEOGRAFIJASE1Model.FK_PRIPADA", "DRZAVA").Value; } set { ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<DRZAVA>("GEOGRAFIJASE1Model.FK_PRIPADA", "DRZAVA").Value = value; } } /// <summary> /// No Metadata Documentation available. /// </summary> [BrowsableAttribute(false)] [DataMemberAttribute()] public EntityReference<DRZAVA> DRZAVAReference { get { return ((IEntityWithRelationships)this).RelationshipManager.GetRelatedReference<DRZAVA>("GEOGRAFIJASE1Model.FK_PRIPADA", "DRZAVA"); } set { if ((value != null)) { ((IEntityWithRelationships)this).RelationshipManager.InitializeRelatedReference<DRZAVA>("GEOGRAFIJASE1Model.FK_PRIPADA", "DRZAVA", value); } } } #endregion } #endregion }

5. KREIRANJE KLASE U OKVIRU BIBLIOTEKE KLASE KOJA KORISTI GENERISANE

KLASE ENTITY MODELA

- Omogucava unos i tabelarni prikaz sa filterom

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

Page 109: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

namespace EntityFrameworkKlase

{

public class DrzavaEntDB

{

private GEOGRAFIJASE1Entities pKontekst;

// konstruktor

public DrzavaEntDB(GEOGRAFIJASE1Entities noviKontekst)

{

pKontekst = noviKontekst;

}

public void DodajNovuDrzavu(DRZAVA novaDrzava)

{

using (pKontekst)

{

DRZAVA drzavaTabela = new DRZAVA();

drzavaTabela.OZNAKA = novaDrzava.OZNAKA ;

drzavaTabela.Naziv = novaDrzava.Naziv;

drzavaTabela.UkupnoMesta = novaDrzava.UkupnoMesta;

pKontekst.DRZAVAs.AddObject(drzavaTabela);

pKontekst.SaveChanges();

} // kraj using

} // kraj procedure

public List<DRZAVA> UcitajSveDrzave()

{

List<DRZAVA> izlaznaListaDrzava = new List<DRZAVA>();

using (pKontekst)

{

// izdvajanje podataka iz baze podataka

var ListaDrzavaEntBaza = from skupDrzava in pKontekst.DRZAVAs select skupDrzava;

// presipanje u listu

List<DRZAVA> lista = ListaDrzavaEntBaza.ToList<DRZAVA>();

foreach (DRZAVA objDrzava in lista)

{

DRZAVA novaDrzava = new DRZAVA();

novaDrzava.OZNAKA = objDrzava.OZNAKA;

novaDrzava.Naziv = objDrzava.Naziv;

novaDrzava.UkupnoMesta = objDrzava.UkupnoMesta;

izlaznaListaDrzava.Add(novaDrzava);

}

}

return izlaznaListaDrzava;

} // kraj metode

Page 110: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

public List<DRZAVA> UcitajDrzavePremaOznaci(string novaOznaka)

{

List<DRZAVA> izlaznaListaDrzava = new List<DRZAVA>();

using (pKontekst)

{

// izdvajanje podataka iz baze podataka

var ListaDrzavaEntBaza = from skupDrzava in pKontekst.DRZAVAs where skupDrzava.OZNAKA

==novaOznaka select skupDrzava;

// presipanje u listu

List<DRZAVA> lista = ListaDrzavaEntBaza.ToList<DRZAVA>();

foreach (DRZAVA objDrzava in lista)

{

DRZAVA novaDrzava = new DRZAVA();

novaDrzava.OZNAKA = objDrzava.OZNAKA;

novaDrzava.Naziv = objDrzava.Naziv;

novaDrzava.UkupnoMesta = objDrzava.UkupnoMesta;

izlaznaListaDrzava.Add(novaDrzava);

}

}

return izlaznaListaDrzava;

} // kraj metode

} // kraj klase

} // kraj namespace

6. POVEZIVANJE KORISNIČKOG INTERFEJSA SA BIBLIOTEKOM KLASA KOJA SADRŽI KLASE ENTITY DATA MODELA Prekopirati App.Config na osnovni folder aplikacije.

Dodajemo u projekat – Naziv projekta, Add, Existing Item.

Page 111: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

Dodati reference na potrebne standardne dll biblioteke klasa koje omogućavaju rad sa Entity modelom: C:/ProgramFiles/ReferenceAssemblies/Microsoft/Framework/.NetFramework/4.0/

Izgled korisničkog interfejsa:

Ubacujemo reference na novi dll koji smo kreirali I dodajemo u using:

Page 112: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

CEO KOD: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; // using EntityFrameworkKlase; namespace KorisnickiInterfejs { public partial class frmSaKlasamaEntityFrameworka : Form { // ATRIBUTI GEOGRAFIJASE1Entities objKontekst; List<DRZAVA> listaDrzava = new List<DRZAVA>(); // -----------------NASE PROCEDURE private void IsprazniKontrole() { txtOznaka.Text = ""; txtNaziv.Text = ""; } private void AktivirajKontrole() { txtOznaka.Enabled = true; txtNaziv.Enabled = true; } private void DeaktivirajKontrole() { txtOznaka.Enabled = false; txtNaziv.Enabled = false; } private void PrikaziTabeluPodataka(List<DRZAVA> novaListaDrzava) {

Page 113: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

dgvSpisakDrzava.Rows.Clear(); for (int i = 0; i < novaListaDrzava.Count; i++) { dgvSpisakDrzava.Rows.Add(); dgvSpisakDrzava.Rows[i].Cells["Oznaka"].Value = novaListaDrzava[i].OZNAKA; dgvSpisakDrzava.Rows[i].Cells["Naziv"].Value = novaListaDrzava[i].Naziv; dgvSpisakDrzava.Rows[i].Cells["UkupnoMesta"].Value = novaListaDrzava[i].UkupnoMesta; } } // KONSTRUKTOR public frmSaKlasamaEntityFrameworka() { InitializeComponent(); // RUCNO DEFINISEMO STRUKTURU DATA GRID VIEW KONTROLE dgvSpisakDrzava.Columns.Add("Oznaka", "Oznaka"); dgvSpisakDrzava.Columns.Add("Naziv", "Naziv"); dgvSpisakDrzava.Columns.Add("UkupnoMesta", "Ukupno mesta"); } //DOGADJAJI private void frmSaKlasamaEntityFrameworka_Load(object sender, EventArgs e) { objKontekst = new GEOGRAFIJASE1Entities(); } private void btnUnos_Click(object sender, EventArgs e) { IsprazniKontrole(); AktivirajKontrole(); txtOznaka.Focus(); } private void btnSnimi_Click(object sender, EventArgs e) { string poruka = ""; try { // preuzimanje vrednosti sa korisnickog interfejsa DRZAVA objNovaDrzava = new DRZAVA(); objNovaDrzava.OZNAKA = txtOznaka.Text; objNovaDrzava.Naziv = txtNaziv.Text; objNovaDrzava.UkupnoMesta = 0; // dodavanje nove drzave u kolekciju i snimanje // 1. nacin - DIREKTNO KORISCENJE KLASA GENERISANIH U ENTITY MODELU //objKontekst.DRZAVAs.AddObject(objNovaDrzava); //objKontekst.SaveChanges(); //2. nacin - POSREDNA KLASA DrzavaEntDB DrzavaEntDB objDrzavaEntDB = new DrzavaEntDB(objKontekst); objDrzavaEntDB.DodajNovuDrzavu(objNovaDrzava); poruka = "Uspesno snimljeno!"; }

Page 114: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica

catch (Exception ex) { poruka = "Nije uspesno snimljeno! Greska:" + ex.Message; } DeaktivirajKontrole(); MessageBox.Show(poruka); } private void btnOdustani_Click(object sender, EventArgs e) { IsprazniKontrole(); DeaktivirajKontrole(); } private void btnFiltriraj_Click(object sender, EventArgs e) { // ucitavanje podataka iz baze preko entity modela u listu DrzavaEntDB objDrzavaEntDB = new DrzavaEntDB(objKontekst); listaDrzava = objDrzavaEntDB.UcitajDrzavePremaOznaci(txtFilter.Text); // prikaz u gridu PrikaziTabeluPodataka(listaDrzava); } private void btnSve_Click(object sender, EventArgs e) { // ucitavanje podataka iz baze preko entity modela u listu DrzavaEntDB objDrzavaEntDB = new DrzavaEntDB(objKontekst); listaDrzava = objDrzavaEntDB.UcitajSveDrzave(); // prikaz u gridu PrikaziTabeluPodataka(listaDrzava); } } }

OSTAJE: 1. RAD SA WEB APLIKACIJAMA 2. POJMOVI:

Šta je interfejs klasa?

Šta je apstraktna klasa? Da li se može nasleđivati? Da li se može instancirati?

Global

ObjectSet

Partial

EntityCollection

Page 115: SKRIPTA ZA VEŽE (radna verzija) - tfzr.rs SOFTVERSKO INZENJERSTVO 1... · SOFTVERSKO INŽENJERSTVO 1 – SKRIPTA ZA VEŽE (radna verzija) Autori: Doc dr Ljubica Kazi, prof. dr Dragica