2. План на курса
Обща информация, определения
Сценарий за разработка
Разработка на базата данни и обектния домейн
Създаване на функционалностите за работа със
студентски данни
• Разработка на функционалностите за работа с
оценки
4. Изходен код на проекта
• Изтеглете: http://www.uni-ruse.bg/info-sys/lab-2.zip
• Премахнете блокировката
• Десен бутон -> Properties -> Unblock
• Разархивирайте
• Премахнете ограничението „само за четене“
• Отворете във Visual Studio
• Разкачете проекта от системата за контрол на
изходния код
6. Обектът „Оценка“
Public Class Score
Inherits DomainObject
Private ReadOnly theStudent As Student = Nothing
Public ReadOnly Property Student As Student
Get
Return theStudent
End Get
End Property
Private theSubject As Subject
Public Property Subject As Subject
Get
Return theSubject
End Get
Protected Set(value As Subject)
theSubject = value
End Set
End Property
Public Property Value As Double
Public Sub New(aStudent As Student, aSubject As Subject, aValue As Double)
theStudent = aStudent
theSubject = aSubject
Value = aValue
End Sub
End Class
7. Обектът „Нова оценка“
Public Class NewScore
Inherits Score
Public Shadows Property Subject As Subject
Get
Return MyBase.Subject
End Get
Set(value As Subject)
MyBase.Subject = value
End Set
End Property
Public Sub New(aStudent As Student)
MyBase.New(aStudent, Nothing, 0)
End Sub
End Class
10. План на упражнението
• Шаблони за проектиране
• Шаблонът „Model-View-ViewModel”
• Разработка на модел
• Разработка на модел на гледка за списъчен
изглед
• Разработка на списъчен изглед
• Разработка на модел на гледка за редакция на
студентски данни
• Разработка на формуляр за редакция на
студентски данни
11. Шаблони за проектиране
• a.k.a. Design patterns
• Рецепти за проектиране
• Независими от езика или платформата за
програмиране
• Най-известните:
• Model-View-Controller – MVC
• Adapter
• Façade
• Command
• Abstract factory
• Singleton
14. ILabDBAModel
Public Interface ILabDBAModel
Function GetStudents() As IList(Of Domain.Student)
Function GetSubjects() As IList(Of Domain.Subject)
Sub SaveStudent(theStudent As Domain.Student)
Sub SaveScore(theScore As Domain.Score)
Sub DeleteStudent(student As Domain.Student)
Sub DeleteScore(score As Domain.Score)
End Interface
18. GetStudents
Public Function GetStudents() As IList(Of Domain.Student) Implements ILabDBAModel.GetStudents
Using orm As New InfoSysEntityModel(theConnectionString)
Dim dbResult As IList(Of Student) = orm.Students.ToList()
Dim methodResult As New List(Of Domain.Student)()
For Each aStudent As Student In dbResult
Dim translatedStudent As New Domain.Student(aStudent.StudentID)
translatedStudent.FirstName = aStudent.FirstName
translatedStudent.LastName = aStudent.FamilyName
translatedStudent.PhotoURL = aStudent.PhotoURL
Dim scores As List(Of Score) = aStudent.Scores.ToList()
For Each Score As Score In scores
Dim translatedSubject As New Domain.Subject(Score.Subject.SubjectName)
Dim translatedScore As New Domain.Score(translatedStudent, translatedSubject,
Score.Value)
translatedStudent.Scores.Add(translatedScore)
Next
methodResult.Add(translatedStudent)
Next
Return methodResult
End Using
End Function
19. Извличане на данни за студенти
Dim dbResult As IList(Of Student) = orm.Students.ToList()
20. SaveStudent
Public Sub SaveStudent(theStudent As Domain.Student) Implements ILabDBAModel.SaveStudent
Using orm As New InfoSysEntityModel(theConnectionString)
Dim aStudent As Student
Dim isNew As Boolean = False
If TypeOf theStudent Is Domain.NewStudent Then
aStudent = New Student()
isNew = True
Else
aStudent = orm.Students.FirstOrDefault(Function(s) s.StudentID = theStudent.StudentID)
isNew = False
End If
aStudent.StudentID = theStudent.StudentID
aStudent.FirstName = theStudent.FirstName
aStudent.FamilyName = theStudent.LastName
aStudent.PhotoURL = theStudent.PhotoURL
If isNew Then
orm.Students.AddObject(aStudent)
End If
orm.SaveChanges()
End Using
End Sub
21. Извличане на запис по ключ
aStudent = orm.Students.FirstOrDefault(
Function(s) s.StudentID = theStudent.StudentID
)
22. DeleteStudent
Public Sub DeleteStudent(student As Domain.Student) Implements
ILabDBAModel.DeleteStudent
Using orm As New InfoSysEntityModel(theConnectionString)
Dim theStudent As Student =
orm.Students.FirstOrDefault(Function(dbStudent) dbStudent.StudentID
= student.StudentID)
If theStudent IsNot Nothing Then
orm.Students.DeleteObject(theStudent)
orm.SaveChanges()
Else
Throw New ObjectNotFoundException("Студент с такъв
факултетен номер не е намерен в базата данни.")
End If
End Using
End Sub
25. Базов модел на гледка
Imports System.ComponentModel
Imports InfoSys.Lab.Models
Public Class ViewModelBase
Implements INotifyPropertyChanged
Public Event PropertyChanged(sender As Object, e As PropertyChangedEventArgs) Implements
INotifyPropertyChanged.PropertyChanged
Private ReadOnly theModel As ILabDBAModel
Protected ReadOnly Property Model As ILabDBAModel
Get
Return theModel
End Get
End Property
Public Sub New(aModel As ILabDBAModel)
theModel = aModel
End Sub
Protected Sub DoNotify(aPropertyName As String)
RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(aPropertyName))
End Sub
End Class
26. Модел на списъчната гледка
Imports InfoSys.Lab.Domain
Public Interface IStudentsListViewModel
Property StudentsList As IList(Of Student)
Property SelectedStudent As Student
ReadOnly Property RefreshStudentsListCommand As
ICommand
ReadOnly Property NewStudentCommand As ICommand
ReadOnly Property DeleteStudentCommand As ICommand
End Interface
27. Свойството StudenstList
Public Property StudentsList As IList(Of Domain.Student)
Implements IStudentsListViewModel.StudentsList
Get
Return theStudentsList
End Get
Set(value As IList(Of Domain.Student))
theStudentsList = value
DoNotify("StudentsList")
End Set
End Property
28. Свойството SelectedStudent
Public Property SelectedStudent As Domain.Student
Implements IStudentsListViewModel.SelectedStudent
Get
Return theSelectedStudent
End Get
Set(value As Domain.Student)
theSelectedStudent = value
DoNotify("SelectedStudent")
DoNotify("IsSelected")
theMediator.SetStudent(theSelectedStudent)
End Set
End Property
30. Обработчици на командите
Private Function canDelete() As Boolean
Return IsSelected AndAlso Not TypeOf
SelectedStudent Is NewStudent
End Function
31. Обработчици на командите
Private Sub whenDelete()
If SelectedStudent IsNot Nothing Then
Model.DeleteStudent(SelectedStudent)
theMediator.DoRefresh()
End If
End Sub
39. Application.xaml.vb
Private Sub WhenStart() Handles Me.Startup
Dim theModel As New LabDBModel(“vader", "InfoSys.Lab.1",
"InfoSys.Lab", "@Test-2012")
Dim theMediator As New MainWindowMediator()
Dim theMainWindowViewModel As New MainWindowViewModel(
Nothing,
Nothing,
Nothing,
Nothing
)
Dim theMainWindow As New MainWindow(theMainWindowViewModel)
theMainWindow.Show()
Me.MainWindow = theMainWindow
End Sub
40. Бази данни
InfoSys.Lab.DB.1-1
.
.
.
InfoSys.Lab.DB.3-9
41. Добавяне на списъчната гледка
Dim theStudenstListViewModel As New StudentsListViewModel(
theModel,
theMediator
)
theMediator.RegisterCanRefresh(theStudenstListViewModel)
Dim theStudentsListView As New StudentsListView(
theStudenstListViewModel
)
42. Инжектиране в основния прозорец
Dim theMainWindowViewModel As New MainWindowViewModel (
Nothing,
Nothing,
Nothing,
theStudentsListView
)
45. Модел на формуляра
Imports InfoSys.Lab.Domain
Public Interface IStudentEditViewModel
Property StudentID As String
Property FirstName As String
Property LastName As String
Property PhotoURL As String
ReadOnly Property isNew As Boolean
Property isChanged As Boolean
ReadOnly Property SaveStudent As ICommand
End Interface
46. Свойството Student
Protected Property Student As Domain.Student
Get
Return theStudent
End Get
Set(value As Domain.Student)
theStudent = value
isChanged = False
DoNotify("FirstName")
DoNotify("LastName")
DoNotify("StudentID")
DoNotify("PhotoURL")
DoNotify("isNew")
DoNotify("IsSelected")
End Set
End Property
50. Поле за факултетен номер
<TextBox
Text="{Binding Path=StudentID, Mode=TwoWay}"
IsEnabled="{Binding Path=isNew}"
Grid.Column="1" Margin="8"
TextWrapping="Wrap" MinWidth="60" />
51. Поле за собствено име
<TextBox
Text="{Binding Path=FirstName, Mode=TwoWay}"
Grid.Column="1" Margin="8"
TextWrapping="Wrap"
Grid.Row="1" Grid.ColumnSpan="2" />
52. Поле за фамилия
<TextBox
Text="{Binding Path=LastName, Mode=TwoWay}"
Grid.Column="1" Margin="8"
TextWrapping="Wrap"
Grid.Row="2" Grid.ColumnSpan="2" />
55. Application.xaml.vb
Dim theStudentEditViewModel As New StudentEditViewModel(
theModel,
theMediator
)
theMediator.RegisterInterestedInStudent(
theStudentEditViewModel
)
Dim theStudentEditView As New StudentEditView(
theStudentEditViewModel
)
56. Инжектиране в основния прозорец
Dim theMainWindowViewModel As New
MainWindowViewModel (
Nothing,
Nothing,
theStudentEditView,
theStudentsListView
)
57. КРАЙ НА
УПРАЖНЕНИЕ № 2
Създаване на функционалностите за
работа със студентски данни