CRUD with MVP pattern, C#, WinForms and SQL Server

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello this time i will show you how to make a crud application using the mvp pattern the database is a simple table of bets in the application we can search by id or filter by name add a new bet edit or delete it we will also do data validation that is do not allow empty data string length or format well the most important in this tutorial is to show them the advantages solutions and how to implement the mvp pattern in their projects honestly using the mvp pattern freed me from a lot of headaches how easy it was to maintain scale and develop a project in addition to having a much cleaner and more structured code well before we start the tutorial we need to understand the basics of this pattern the mvp pattern or model view presenter is one of the many software patterns that exist this pattern derives from the mvc pattern like the mbvm pattern the mvc pattern is more suitable for web and mobile applications while mvp and mvvm can be used on any platform however mvp is the only pattern that is best suited for windows forms these patterns can be called design or architecture patterns depending on the scope and how it is being used for example if the pattern is only used for the structure of an project it would be an architectural pattern but if it is used for the structure of the presentation layer would be a design pattern since it changes the granularity level and perspective however that doesn't matter because it's still a software pattern but usually in projects with data access the mvc or mvp pattern is used in the presentation layer as it is gui oriented and aims to provide a cleaner separation of concerns between view and logic so this pattern can be used in conjunction with layered architecture be it the traditional the proposal by eric evans in his book ddd onion hexagonal or among other variations of layers while now focusing on mvp the goal of this pattern is to separate the ui and mechanisms from the business logic there are three main components that accomplish this which are model view and presenter the model represents the domain objects that is business entities that encapsulate data and implement business logic the view is responsible for displaying the content of the model on the screen and interacting with user events the view should be as dumb as possible that is it should not do anything except display the data and raise the events the presenter is the main component it is responsible for interpreting user events refresh the view and the communication with the model it is basically the mediator between the view and the model passing the user input from the view to the model and passing the output from the model to the view to make that possible implement the view interface to read and write the form data in addition to subscribing to the event handler methods now you may be wondering how to implement it with the layered architecture well as i said before the mvp pattern is implemented in the presentation layer however the model would become part of the domain layer and to display the model in the view you can either use data transfer objects or create dedicated anemic models for the view which would be a copy of the domain model properties and in addition to adding other custom fields maybe i'll do a tutorial on this later but since the application that we will create in this tutorial will access the database it is necessarily required to add the data access layer in order to keep the responsibilities separate we will also apply the dependency inversion principle at the architectural level that is the model will define the abstractions and the detail implements the abstractions in this way the model will be independent of low-level modules to make this possible we define and implement interfaces well said all the above let's start with the tutorial we have a fairly simple database a pets table with an auto-incrementing id field that starts at 100 000 to be six characters then a field name type and color of bet finally the insertion of some data for display them on the screen i'll leave the script download link in the video description okay now let's move on to visual studio we create a windows form project in c-sharp you can choose any version of net framework we can delete this form as we will not be using it all right first we add folders for the model the view and the presenter [Music] in the model component we add a class for the pet model [Music] here we simply define the respective fields and generate the properties you can create the interface of this model i will not do it because this will be an anemic model that is it does not implement business logic services since the application that we will make will only perform read operations and data writing doing that will take care of the repositories as i said in the introduction [Music] once the properties are defined we will do the data validation for example do not allow numbers or empty values we can either validate the data from the set accessor or make life easier and use the data annotation validators for this we need to add a reference to the component model's data annotation namespace [Music] we implement the component model data annotations in the class header this namespace provides attribute classes that are used to define metadata that allow validation by simply adding one or more attributes such as the required or string length attribute we can also define attributes to specify how it should be displayed in the user interface for example i want the column id to display as peta id this field is auto-incrementing so no need to do data validation let's pass to the name property in the same way we specify the name to display and indicate that the field can't be empty optionally we can specify the error message for example the pet name is required we can also specify the minimum and maximum length of the string for example the pet's name must be between 3 and 50 characters and so on we can keep adding more attributes for example the field must be in email only numbers letters and among other regular expressions [Music] all right that's it on the pet model now in the model we will add the abstraction of the repository for this we add an interface and define the public behaviors of the repository for example add edit delete get all and perform searches as i said in the introduction the dependency inversion principle states that the details must depend on the abstractions in this case speaking in terms of architecture the data access layer should depend on the domain model but not the other way around that's why we define this interface of the repository in the model and the data access layer will be the one who implements the detail this will allow loose coupling between the model and data access and the model does not depend on the data access layer the interfaces are used in most architecture and design patterns so i would recommend reading up on the importance and benefits of using interfaces all right once we've defined the behaviors for the repository we go to the view component and add an interface for the pet view [Music] similar to the above we define the properties of the pet view such as the pet id name type and color we'll also define other properties for the search value edit state successful operation and a result message [Music] we then define the events for user actions for example the event for search add edit delete save changes and cancel these events will be generated when the user performs some action for example a click on a button finally we define the methods in this case a method to set the pet list binding source with the parameter of type binding source this class belongs to the windows forms namespace it has many benefits as it creates a bind between a data control and the data source i'll explain later when we bind the data to the data grid view optionally we also define the show method alright now we add a form for the pet view [Music] we start designing the form [Music] [Music] we add a tab control and dock it in the remaining space of the form in this first tab we add controls to show the pet list and also perform searches in the second tab we add controls to edit or add data you can use user controls instead of tabs or form but i think in this case the tab control is the best option if you want fast and uncomplicated development all right once the view is designed we begin to implement the functionality of the form for this we go to the code first and foremost we implement the view interface [Music] well we already have defined all the properties events and methods of the view but we still need to implement the operation it has to perform let's start to implement the detail of the setpetlist bindingsource method here we simply set the pet list parameter to the data source of the data grid as for the events will be associated with the click events of the buttons which we will do later now let's continue with the implementation of the properties in the get and set accessors of the message property we return and set the message field this field does not exist so we generate it this is optional you can define and implement the property in a single line using auto implemented properties however i personally like to do it this way define the fields and generate the properties the code looks much more elegant and tidy as well as being able to include some validation or logic in the accessors [Music] well in the case of the search value property you don't need to define the field because that's what the search text box is responsible for so we implement the text property of the search text box we do the same for pet color type and name this is the interesting part of the mvp pattern thanks to the implementation of the interface we will be able to manipulate and update the view data from the presenter without having a direct dependency on the view due to the contract that exists between the pet view interface and the pet view concrete class they'll understand better when we inject the interface dependencies into the presenter [Music] [Music] all right now that we're done implementing the view properties now we associate and generate the view events by user actions let's start with the search event to do this in the constructor we can call a method for example associate and raise the view events [Music] the search event should be raised or executed when the user clicks the search button so we subscribe to the click event of the search button and raise the search event we can do it by an event handler method or we can do it directly in a single line or block using lambda expression or using a delegate so we access the search event check that it's non-null and finally invoke the event sending the sender object and argument parameters in this case this form and an empty event argument okay we'll also raise the search event when the enter key is pressed since it's much more interactive and we don't have the hassle of clicking the search button so similarly we subscribe the key down event of the search text box in this case we use lambda expression since it will be necessary to get the argument of the event we define a condition if the key code of the event argument is the enter key we raise the search event this line of code is a short version of raise the event the long version would look like this the null conditional operator appeared in c sharp 6 in 2014 so it's not of new feature it's been around for eight years all right so we do the same thing for the ad edit and delete event to keep things simple we'll do that later in due course for now we'll just do the option to search and show the list of bets and we'll also hide the second tab as this should only be displayed when the add new pet or edit pet button is clicked okay so far we have the model and the view still not displaying anything this is where the most important component of the mvp pattern comes into play the presenter the presenter is the mediator or bind between the model and the view it orchestrates everything where it passes the user input from the view to the model and passes the output from the model to the view so to make it all work we add the pet presenter first we add the reference to the model in the view [Music] then we define the following fields a private field for the view using the views abstract interface in the same way for the model in this case the abstract interface of the repository since my app is only going to execute commands for data storage and retrieval and i am going to include the data access layer that will depend on the model so it is not so necessary to define the model abstraction at least not in the way i plan to do it although i would recommend doing it mainly if you want to apply the dependency inversion principle between classes we also define a field for the binding source of the pet list and another field of type enumerable interface to store the list of bets then we generate the constructor with parameters for the view and repository interface defining the constructor in this way will allow dependency injection as well as making unit testing easier well we initialize the bonding source of the pet list then we subscribe the handler event methods to the view events that is to say we implement what should be done when an event is generated for example when the search event is invoked we search for the pet in the database and return the result to the view we will implement the functionality of this method in a moment now let's continue subscribing the methods to the remaining events of the view talking a bit about the presenter we had said that the presenter is responsible for interpreting user events communication with model and view objects moving things from one component to another as needed that's basically what we're doing right now in this class this is achieved because the presenter accepts as parameters the interfaces that implement the view and repository in such a way that the presenter can operate and manipulate them however the presenter does not touch the view or repository directly rather it does so through abstractions the idea is that a class should not depend on or create concrete instances of another class rather it should depend on an abstract interface that class implements and into which a concrete instance is injected basically that is the dependency inversion principle and dependency injection is about how one object meets another dependent object through the interface we will do that when we create the presenter instance and inject it with the concrete class of the view and the repository all right then we set the binding source of the pet list using the method defined and implemented in the view [Music] now we load the data to the list of all bets for this we create a method finally we show the view it is worth mentioning that the show method already exists in the form so it was not necessary to implement it when we implemented the view interface okay now we implement the functionality of the method load pet list so the pet list field will be equal to the return value of the get all from repository method we then set the list to the data source of the pet's binding source by doing this the data grid view can now display the data from the list of pets and it is updated automatically every time the data binding changes note that in the implementation of the method in the view the pet lists binding sources sets the data source of the data grid view all right we do similarly for the pet search however we check that the views search value is not null empty or white space so if the search value is not empty we perform the search using the repository's get by value method and assign the result to the pet list here i forgot to define the parameter for the search value [Music] now if the search value is empty we simply get the list of all bets finally we refresh the data source of the pet binding source if you want you can call the loadpet list method here since it does the same thing well that's all for now this concludes the basic tutorial on how to implement the model view presenter pattern the application still does not work since it is necessary to implement the data access component as well as to associate and subscribe the events of adding editing deleting and saving changes well we will do those details in the following videos the tutorial lasts approximately one hour so i will upload it in three parts so in the next video we will implement the repositories to be able to do searches and show the pet list also the dependency injection issue is pending and also create a main presenter and view well until the next tutorial
Info
Channel: RJ Code Advance EN
Views: 110,060
Rating: undefined out of 5
Keywords: Windows Form, C#, VB, .NET, Software, HTML, Modern Forms, software, computer, technology, design of modern user interfaces, visual basic, php, java, design flat login, software development, web programming, information systems development, JavaScript, Visual Basic, Software Patterns, Architecture Patterns, Design Patterns, Language Patterns, Software Engineering, Systems, Web pages, mvc, layers, objects, POO, object-oriented programming, mysql, mariadb, .Net Framework, Custom Controls, SQL
Id: WSBy_Ypgk38
Channel Id: undefined
Length: 23min 35sec (1415 seconds)
Published: Sun Apr 10 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.