Tuesday, December 31, 2013

When to use MVC and when to use Web Forms: an ASP.NET MVC-WebForms Comparison

         By Carmel Schvartzman

In this post we'll discuss when to use ASP.NET MVC and when to use ASP.NET Web Forms, performing an MVC-WebForms comparison

This is an MVC View:

Compare it with the Web Forms markup:

Web Forms are based on pre-built building stones called HTML Controls and Server Controls.
On the other side, MVC is based in the Model-View-Controller Pattern, that is reflected in the MVC folders architecture:



For those who until now have been working with traditional ASP.NET Web Forms, the following remarks about the Web Forms will not be new at all:

                                    ASP.NET Web Forms

Separation between UI Design (HTML) and Application Logic
ViewState:  exists, and usually is a heavy weight upon rendering HTML markup
Postback:  YES
Event-Driven Development: YES
Controls:  large library of drag-and-drop pre-built milestones that help you but limite you
SEO: Search Engine Optimization: limited by the pre-built controls
RAD: Rapid Application Development based on a rich variety of HTML and Server Controls
Test-Driven Development: no


                                       ASP.NET MVC

Separation between UI Design (View) - Data Bussiness Logic (Model) - Application Logic (Controller)
ViewState: NO (stateless model)
Postback: NO
Event-Driven: NO
Controls:   do not exist: there is complete control on the generated HTML
SEO: Search Engine Optimization: enhanced by the complete control on the generated HTML
RAD: Rapid Application Development is not the priority
Test-Driven Development: optimized for it

Based on the previous considerations, we could use the following table for deciding between MVC-WEBFORMS:

Needs
MVC
Web Forms





 SEO optimizations
 
YES
NO
Development Speed

NO
YES
Control over rendered HTML

YES
NO
Intranet Applications

NO
YES
Internet Applications

YES
MAYBE




Test-Driven Development

YES
NO
HTML5 skills

YES
NO

















Following the previous rough considerations, you could consider which ASP.NET development options to use.


That's all!! 
Happy programming.....


כתב: כרמל שוורצמן

Sunday, December 29, 2013

Step By Step How to add Model Data Validation (Code First) to an ASP.NET MVC 4 application

         By Carmel Schvartzman


In this tutorial we'll learn how  to add Model Data Validation to an ASP.NET MVC4 application, while using the Code First approach of the Entity Framework


Concerning the Model in a MVC application, there are two kinds of errors that can happen: data type errors and bussiness logic errors. The later are usually handled in special classes which extend the DAL of the application. Remember that when you use the Entity Framework as the DAL (Data Access Layer) of your MVC, every time you update the conceptual data model to reflect changes made to the data store, the Model classes are regenerates by a tool, meaning that everything that's in it is erased and rewriten. Therefore the Bussiness Rules are coded in partial classes which extends the Model classes.

For that reason, decorating entities's fields with Data Annotaions will not work while using the Database First approach of the Entity Framework. Every time you refresh the conceptual Model, your annotations will be overriden. In this tutorial we'll use Data Annotations with the  the Code First approach.

The MVC Data Model created automatically by the Entity Framework captures the data type errors caused by incompatibility between data types, and throws exceptions notificating the user about the problems.

This kind of errors can be easily handled using Data Annotations, by decorating the entity's fields with attributes. That way, custom validation rules will be enforced not only while persisting data to the store, but whenever MODEL-BINDING OPERATIONS are performed by MVC.
The  following validator attributes are supported:
   Range – checks if the value of a property is between a specified range.
   ReqularExpression – checks whether the value matches a specified regular expression.
   Required – sets a property as required.
   StringLength –  checks whether a maximum length for a string property is legal.
   
There is also the option of inheriting from the base class "Validation" in order to enforce custom validation.
First think we must do is adding the System.ComponentModel.DataAnnotations namespace to the entity class we want to validate:


Let's say we have an entity named "User" with the following properties:



We want to ensure the FirstName and LastName have been typed in, therefore we'll use the "Required" attribute:


Next, we can force the user to enter an address fullfilling certain requirements, and for that we can use the StringLenght attribute:


The Annotation will end as follows, and also we can set what the message error will be:



For the Phone property, we'll use the DataType attribute to specify which type must be entered (currently with .Net Framework 4.5 there are 17 valid predefined types allowed, such as "EmailAddress" or "PostalCode", but also you can use CUSTOM TYPES defining your own class):



We'll choose the "PhoneNumber" type, and some Error Message to be presented to the user:


Finally, we'll want to validate the user's Credit Card number, and in this case we could use a RegularExpression to enforce some specific type of Credit card, as follows:



Or also use the DataType attibute as follows:



These Data Annotations will enforce the user to enter valid input, but also will protect the system from dangerous input like sql injections.


That's all!! 
Happy programming.....


כתב: כרמל שוורצמן

Thursday, December 26, 2013

Step By Step How to create a Data Repository with Data Caching in ASP.NET MVC 4

         By Carmel Schvartzman

In this tutorial we'll learn how to create a Data Repository with Data Caching in ASP.NET MVC 4. The MVC C# code for this step-by-step tutorial is available for download on GitHub at :
https://github.com/CarmelSoftware/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4
Its GitHub Wiki page is:
https://github.com/CarmelSoftware/Data-Repository-with-Data-Caching-in-ASP.NET-MVC-4/wiki

The Data Repository is a class which is designed to implement the Repository Pattern. This software pattern was created in order to access, cache in memory and persist in the database the application data. That means, the Repository will fetch the data ONLY IF IT'S NOT AVAILABLE IN MEMORY. 
There are, however, Repository implementations with no use of caching. The caching only stands to avoid unnecesary round trips to the SQL server. But when scalability of the sites is on the stage, may be we don't want to choke our web server's memory. Then, caching is not only redundant, but also dangerous as a waste of the web server resources. Of course using the Cache or the Application storages is less wasteful than using the Session ASP.NET storage, but even then the RAM memory of the web server should be taken into account and preserved as much as possible.
In this tutorial we'll add a Repository functionality with caching support to a new ASP.NET MVC 4 app.
Let's say we have an MVC internet application with an Entity Data Model mapped to an SQL server database. This EDM maps just two entities: Blog and Comment:

Our Repository will be added to the Model folder, which holds all the bussiness logic of the MVC application. Therefore focus the Model folder and create a new class: MyDataRepository.

Next, we'll create our Data Context, using the class created by the Entity Framework, inheriting DbContext: this class will be located under the Entity Data Model .edmx node: just open it until you see the XXX.Context.cs file:

 open it to see the name of your data context class which inherits from DbContext:

 This is your Data context and you'll add it to the Repository:

 Also add a null check to be sure your DbContext is there:

 Enclose the properties in a region:

 Take a look at the DbContext: you'll see that the Blog and Comment entities are represented by generic collections with a type DbSet<> :


 DbSet class provides the CRUD (Create Retrieve Update Delete) functionality we'll need to persist data changes to the database:


 The first method we'll add to our Repository will be the Save method. We separate this functionality so then we could make several changes all together and, just when done, we'll call the Repository Save method:



Now is time of designing the caching mechanism to store in memory the data. We'll use the caching infraestructure from the System.Runtime.Caching library, therefore add the pertinent reference:



Now focusing on the Model folder, create a new class named MyCachingProvider:



The class will use the ObjectCache, so add a private property to provide it. Implement the Get function instantiating the MemoryCache:



The first method we'll implement in our caching facility will be the Add functionality,and we'll take advantage of a MemoryCache aspect which puts this kind of storage far before from another storages like Application or Session: the caching policy. Later we'll state a caching expiration of a whole hour:




Now add the Remove functionality:



Also append the IsInMemory(key) method to check whether the required data is in memory:


Finally code the FetchData() method to get the data stored in memory:




 Next, we'll add all CRUD functionality to our Repository, as follows:



Notice that every C_UD (Create Update Delete) operation evicts the Comments from the Cache: that is because when a Comment is updated, created or deleted, the cached list remains in a async state with the actual data persisted in the database. We can either use the Sql Cache Dependencies functionality of the framework, or just evict the data from cache every time it is changed. For simplicity, we'll choose this later option.

 Finally, add the Retrieve functionality also for ALL the Comments and for just ONE selected Comment:


In the code you'll notice the use of the Caching functionality: first we check whether the data is in memory: if so we use the cache; elsewhere we fetch the data from the database and refresh the cache.


The RetrieveComment(id) method makes use of the previous RetrieveComment() method to get the List<> from memory:



 Now, let's check how our Repository works. On the server view, check the Comments table:


 Open the table contents, and clear them:




 Now, create a Testing class to run tests against the Repository. Inside the class, instantiate the Repository and create a new Comment:


 Next, call the Repository's AddComment() method, and Save() it all:


 Finally, in the HomeController make a call to our Test class:

 Build and debug the MVC application:



 As you can see, the original Comment has been instantiated.

 When finished the run, refresh the Comments table:



 The new record has been persisted by the Repository to the database.
Do it all again, adding the Retrieve part of the testing, fetching two comments to verify that the SECOND time we try to get data, it is loaded from the cache and not from database:


We get the Comment with CommentID = 2, as required:


Finally, test the Update method of the Repository, adding the code to change the Comment data:




Set a breakpoint inside the RetrieveComment() method to see how the "IF" clause causes to fetch data from the cache instead of from the database:





We've seen how to create a Data Repository with Data Caching in ASP.NET MVC 4 with support for all CRUD operations.
That's all!! 

Happy programming.....


כתב: כרמל שוורצמן

Wednesday, December 25, 2013

Step By Step How to create a Data Repository in ASP.NET MVC 4

         By Carmel Schvartzman

In this tutorial we'll learn how to create a Data Repository in ASP.NET MVC 4
The Data Repository is a class which tries to implement the Repository Pattern. This software pattern was designed in order to access, cache in memory and persist in the database the application data. That means, the Repository will fetch the data ONLY IF IT'S NOT AVAILABLE IN MEMORY. Thus the repository will support all CRUD operations (Create Retrieve Update Delete) enhancing a clear separation between data domain and database.
There are, however, Repository implementations with no use of caching. The caching only stands to avoid unnecesary round trips to the SQL server. But when scalability of the sites is on the stage, may be we don't want to choke our web server's memory. Then, caching is not only redundant, but also dangerous as a waste of the web server resources.
In this tutorial we'll add Repository functionality (no caching) to a new ASP.NET MVC 4 app.
Let's say we have an MVC internet application with an Entity Data Model mapped to an SQL server database. This EDM maps just two entities: Blog and Comment:


Our Repository will be added to the Model folder, which holds all the bussiness logic of the MVC application. Therefore focus the Model folder and create a new class:



Next, we'll create our Data Context, using the class created by the Entity Framework, inheriting DbContext: this class will be located under the Entity Data Model .edmx node: just open it until you see the XXX.Context.cs file:


 open it to see the name of your data context class which inherits from DbContext:




This is your Data context and you'll add it to the Repository:


Also add a null check to be sure your DbContext is there:


Enclose the properties in a region:


Take a look at the DbContext: you'll see that the Blog and Comment entities are represented by generic collections with a type DbSet<> :



 DbSet class provides the CRUD (Create Retrieve Update Delete) functionality we'll need to persist data changes to the database:


The first method we'll add to our Repository will be the Save method. We separate this functionality so then we could make several changes all together and, just when done, we'll call the Repository Save method:


Next, we'll add all CRUD functionality, as follows:



Finally, add the Retrieve functionality also for ALL the Comments and for just ONE selected Comment:


Now, let's check our Repository. On the server view, check the Comments table:


Open the table contents, and clear them:


Now, create a Testing class to run tests against the Repository. Inside the class, instantiate the Repository and create a new Comment:




Next, call the Repository's AddComment() method, and Save() it all:



Finally, in the HomeController make a call to our Test class:



Build and debug the MVC application:


As you can see, the original Comment has been instantiated:


When finished the run, refresh the Comments table:

The new record has been persisted by the Repository to the database.
Do it all again, adding the Retrieve part of the testing:



We get the Comment with CommentID = 2, as required:


Finally, test the Update method of the Repository, adding the code to change the Comment data:


Check the Comments table, which by now shall look like this:


We are updating the fields of the Comment with ID = 2. Build and run, and check the Comments table again to see the changes:




We've built a complete Data Repository with support for all CRUD operations.
That's all!! 
Happy programming.....


כתב: כרמל שוורצמן